`. Opens the resolved DB read-only via the SDK (never
+ writes) and respects `--db`, so you can inspect any split-brain store that
+ `sibyl status` surfaces. (big-patch PKG-4) Regression test:
+ `tests/test_memory_cmd_2026_06_16.py` (6 cases).
+
+## [0.3.14] — 2026-06-11
+
+### Added
+
+- **`sibyl status` now lists every memory store on the machine + warns on
+ split-brain divergence** (beta report, 2026-06-11). A new read-only
+ `_discover_stores()` enumerates the SDK/CLI/MCP default
+ (`~/.sibyl-memory/memory.db`), the Hermes adapter
+ (`$HERMES_HOME/sibyl/memory.db`), per-profile DBs
+ (`$HERMES_HOME/sibyl/profiles//memory.db`), and any `SIBYL_MEMORY_DB`
+ override, listing each with path + size. When more than one store holds data,
+ a warning explains that memory is not shared across entry points and how to
+ point them at one path. Discovery creates and moves nothing — path
+ unification is a separate, migration-gated change. Regression test:
+ `tests/test_status_stores_2026_06_11.py` (4 cases). (big-patch PKG-2/PKG-3)
+
+## [0.3.13] — 2026-06-11
+
+### Fixed
+
+- **Corrupt `~/.claude/settings.json` was silently replaced with a sibyl-only
+ file (data loss).** `_write_settings_with_sibyl` swallowed JSON parse errors
+ (`except Exception: cfg = {}`) and the subsequent atomic replace destroyed the
+ user's other `mcpServers`, `permissions`, `hooks`, and `env`. Setup now fails
+ fast with a clear error (file untouched, backup path reported) on invalid JSON
+ or a non-object top level; an empty file is still treated as legitimately
+ empty. The same fail-fast applies to a valid-but-non-mapping Hermes YAML
+ config. `current_state()` now surfaces `settings_parse_error` instead of
+ swallowing it. (bugflow)
+- **`sibyl status` crashed with a TypeError whenever a tier cache existed.**
+ `cmd_status` sliced `checked_at` with `[:19]`, but `_capcheck` writes
+ `checked_at` as epoch seconds (float), so every `sibyl status` run with a
+ populated `~/.sibyl-memory/tier_cache.json` raised
+ `TypeError: 'float' object is not subscriptable`. The value is now rendered
+ via `time.strftime` when numeric and passed through (truncated to 19 chars)
+ when it is already an ISO string; missing or null renders as `?`. Validated
+ against float, ISO-string, missing, null, and zero inputs. (bugflow)
+
+## [0.3.12] — 2026-06-05
+
+### Fixed
+
+- **`sibyl migrate --force` (onboarding dead-end).** When a detected harness
+ already had a non-sibyl memory provider, the wirer refused with
+ "Use --force to overwrite." but `run_guided_setup` called `wire()` with no
+ `force`, and `sibyl migrate` had no `--force` flag to pass, leaving the user
+ with no way forward. Added `--force` to `sibyl migrate`, threaded through
+ `cmd_migrate` → `run_guided_setup(force=)` → `wire(force=force)`, so migration
+ can overwrite an existing provider when the user explicitly opts in.
+ Regression coverage: `tests/test_migrate_force_2026_06_05.py`. (bugflow)
+
+## [0.3.11] — 2026-06-01
+
+### Fixed
+
+- **`sibyl init` left a pre-existing `~/.sibyl-memory` world-readable.**
+ `mkdir(mode=0o700)` is a no-op when the directory already exists, so a dir
+ created earlier at 0755 kept loose permissions on the credentials directory.
+ `os.chmod(~/.sibyl-memory, 0o700)` is now applied explicitly after mkdir.
+ (security; beta report dor_alpha)
+- **Claude Code MCP registration could report false success.**
+ `claude mcp add --scope user` returning exit 0 did not guarantee the server
+ showed up in `claude mcp list`. The wirer now verifies via `claude mcp get`
+ after adding; if the server is absent it returns an error with concrete
+ remediation instead of a false "wired". (beta report)
+
+## [0.3.10] — 2026-06-01
+
+### Fixed
+
+- **`sibyl setup hermes` raised a TypeError on every first-run wiring.**
+ `HermesWirer._install_plugin()` called `install()` with only `hermes_home`
+ (as a `str`), but `sibyl_memory_hermes.install_plugin.install()` requires
+ `(hermes_home: Path, force: bool, dry_run: bool)` with no defaults, so it
+ raised `TypeError` before the plugin could install. Now calls
+ `install(hermes_home=Path(self.hermes_home), force=False, dry_run=False)`.
+
+## [0.3.9] — 2026-05-31
+
+Guided migration plus first-class Codex support and the real fix for Claude
+Code MCP discovery.
+
+### Added
+
+- **`sibyl migrate` — guided onboarding.** One command takes a user from
+ "memory scattered across CLAUDE.md / AGENTS.md / config files" to "memory in
+ Sibyl." It (1) backs up every existing memory/agent file FIRST to a
+ timestamped, byte-verified folder with a collision-free layout (a home file
+ and a same-named project file never clobber each other), (2) auto-wires Sibyl
+ into every detected harness, (3) hands the semantic extraction to the user's
+ OWN agent — the agent reads only from the backup and writes via the
+ `sibyl-memory` MCP tool, so Sibyl Labs never sees the user's files or memory
+ (local/private by construction), (4) verifies what actually landed in the DB,
+ and (5) optionally trims the originals — only on an explicit confirm and only
+ because a verified backup exists. New `migrate.py` module + orchestrator.
+- **Codex is now a first-class wiring target.** New `CodexWirer` edits
+ `~/.codex/config.toml` (`[mcp_servers.sibyl_memory]`) atomically with a `.bak`
+ backup and an idempotent guard, writing the RESOLVED absolute binary path
+ (matching codex's own `codex mcp add` behavior). `sibyl setup codex` now
+ works — previously the parser offered `codex` but `ALL_WIRERS` lacked it, so
+ it errored.
+
+### Fixed
+
+- **Claude Code MCP registration.** Wiring now goes through
+ `claude mcp add --scope user` — where Claude Code actually discovers MCP
+ servers — instead of writing `~/.claude/settings.json`, which Claude Code does
+ NOT read for MCP discovery. This was the root cause of "configured but never
+ connects." Detection now uses `claude mcp get`; the settings.json path remains
+ a fallback only for environments without the `claude` CLI.
+- **Absolute-path registration (both Claude and Codex).** User-scope / config
+ servers are launched from the harness's own environment, not the interactive
+ shell, so a bare `sibyl-memory-mcp` could fail to resolve (Claude showed
+ "✗ Failed to connect"; Codex would not spawn). Both wirers now register the
+ resolved absolute path.
+
+### Tested
+
+- 82 tests including adversarial inputs and a 60-iteration fuzz of the migration
+ flow. Live MCP connection verified end-to-end against Claude Code
+ (`--scope user` → ✓ Connected) and Codex (initialize handshake + ListTools),
+ and a real headless agent extraction wrote structured entities into an
+ isolated DB.
+
+## [0.3.8] — 2026-05-24
+
+Fix: `sibyl setup claude-code` wired the MCP config but never ensured the
+`sibyl-memory-mcp` binary existed, causing ENOENT on every Claude Code
+reconnect. Same defect in the Codex wirer path.
+
+### Fixed
+
+- `ClaudeCodeWirer.wire()` now calls `shutil.which("sibyl-memory-mcp")`
+ before writing config. If the binary is absent, it auto-installs
+ `sibyl-memory-mcp` via `pip install` (mirroring `HermesWirer._install_plugin`).
+ If auto-install fails, the outcome downgrades to `error` with the exact
+ `pip install sibyl-memory-mcp` command instead of false success.
+- `current_state()` now includes `mcp_binary_found`. The `wired_with_sibyl`
+ flag is only True when both the config block matches AND the binary is on
+ PATH. Previously, re-running `sibyl setup` reported "already wired" even
+ when the binary was missing, hiding the problem on every retry.
+- Config-present-but-binary-missing is now a distinct path in `wire()`:
+ it installs the binary without re-writing the config block, then reports
+ `wired` (not `already`).
+
+### Added
+
+- **Post-wire MCP verification.** After wiring (or confirming "already"),
+ `cmd_setup` spawns `sibyl-memory-mcp` briefly and confirms it doesn't
+ crash on startup (catches ImportError, missing deps, bad credentials).
+ Reports `✓ MCP server verified` on success or `✗ Server crashed on
+ startup (exit N): ` on failure, with a non-zero exit code so
+ CI and scripts can detect the problem.
+- Claude Code reconnect instructions print after verification: tells
+ the user to type `/mcp` and reconnect `sibyl-memory`, or restart.
+- `[mcp]` optional extra in pyproject.toml: `pip install "sibyl-memory-cli[mcp]"`
+ now pulls in `sibyl-memory-mcp>=0.1.2` transitively.
+
+### Root cause
+
+`sibyl-memory-mcp` ships in a separate opt-in PyPI package. `sibyl setup`
+wrote a config entry pointing at the binary without checking it existed.
+The Hermes wirer had self-heal (`_install_plugin()`); the Claude Code and
+Codex wirers did not.
+
+## [0.3.5] — 2026-05-21
+
+Permanent fix for the silent-success activation foot-gun. 0.3.4 raised the
+CLI poll to 30min and the server pairing TTL to 30min so the two windows
+matched. Operator pushed back: matching constants is a temporary fix that
+re-opens the moment either side moves. The structural fix is one source of
+truth.
+
+### Changed
+
+- The CLI no longer carries its own activation deadline. The `/session-init`
+ response already includes `pairing_ttl_seconds` (it always did — the CLI
+ was just throwing it away). The CLI now captures that value and uses it
+ as the poll deadline.
+- `INIT_TIMEOUT_SEC` removed. Replaced by `INIT_TIMEOUT_FALLBACK_SEC`,
+ used only when `/session-init` fails entirely or the response is missing
+ the field. Drift between CLI and server is now impossible by
+ construction.
+
+### Why this is permanent
+
+If the server-side TTL ever changes again, every CLI install in the wild
+adopts the new value on the next `sibyl init` automatically. No CLI
+re-publish required. No `bumped constant on one side` failure mode. The
+server is the single source of truth; the CLI defers.
+
+## [0.3.4] — 2026-05-21
+
+Silent-success activation foot-gun. Multi-user reports of "email auth doesn't
+work, no error message." Root cause: CLI `INIT_TIMEOUT_SEC` was 10min while
+the server-side `PAIRING_TTL_SECONDS` was 15min. Users who took 10-15min to
+find the pairing code in their inbox would hit the gap: server accepted the
+bind, browser showed the success modal, but the local CLI had already exited
+and `credentials.json` was never written. No error surfaced anywhere — the
+plugin just failed to load on the next run.
+
+### Changed
+
+- `INIT_TIMEOUT_SEC` raised from `10 * 60` to `30 * 60` (cli.py:61). Matches
+ the server's new 30min pairing-code TTL — the two windows now never
+ disagree.
+- `UPGRADE_TIMEOUT_SEC` raised to `30 * 60` for the same alignment reason on
+ the upgrade flow.
+- Activation-timeout terminal message now explicitly calls out the
+ silent-success failure mode and tells the user to run
+ `sibyl init --force`. Earlier message just said "Re-run sibyl init."
+
+### Companion changes (same session)
+
+- `api-sibyllabs/api/plugin/session-init.js`: `PAIRING_TTL_SECONDS` 15min →
+ 30min.
+- `api-sibyllabs/api/plugin/email-bind.js`: error message for expired code
+ updated from "15 min limit" to "30 min limit" + `sibyl init --force`.
+- `sibyllabs/plugin/activate.html`: success modal gains a callout that
+ prompts the user to run `sibyl init --force` if their terminal already
+ showed the timeout message before they bound.
+
+## [0.3.3] — 2026-05-20
+
+Auth subdomain migration. Operator directive: "make sure the temp links are
+being generated at install.sibyllabs.com/plugin/auth or something like this,
+and not sibyllabs.org/install." Surfaced as a trust + phishing-resistance ask
+for the URL that appears in the user's terminal at activation time.
+
+### Changed
+
+- `ACTIVATE_BASE` default changed from `https://sibyllabs.org/plugin/activate`
+ to `https://auth.sibyllabs.org`. Activation URL shape moved from
+ query-string (`?session=`) to bare path (`/`). The terminal
+ output now reads `Opening https://auth.sibyllabs.org/` —
+ shorter, line-wraps less on narrow terminals, easier to verify visually.
+- The Vercel rewrite on `auth.sibyllabs.org` serves the same `/plugin/activate`
+ page but preserves the user-visible URL, so the wallet popup's "X wants you
+ to sign in" header matches the URL bar. Phishing-conscious wallets (Rabby,
+ MetaMask in security mode) skip the domain-mismatch warning.
+- Companion api-sibyllabs change (same session): `bind.js` SIWE
+ `expectedDomains` allowlist now includes `auth.sibyllabs.org` alongside
+ `sibyllabs.org` and `sibylcap.com`.
+
+### Backward compatibility
+
+The legacy `https://sibyllabs.org/plugin/activate?session=` URL still
+resolves and works identically. Anyone on cli 0.3.2 or earlier keeps a
+functioning activation flow until they upgrade. The new URL works on cli
+0.3.3+ automatically with no env-var changes needed.
+
+Override via `SIBYL_ACTIVATE_BASE` env var still works for staging /
+self-hosted setups. The CLI auto-detects path-vs-query URL shape from the
+base hostname (sibyllabs.org subdomain → path; everything else → query).
+
+## [0.3.2] — 2026-05-20
+
+Branding pass on the banner. Operator directive: "beneath the large
+SIBYL title it needs to say underneath the memory you can hold in
+your hand tagline, 'a Sibyl Labs LLC Product. Agentic Infrastructure
+and Memory Products' or something similar."
+
+### Changed
+
+- `_banner.py` now emits a third line under the wordmark + tagline:
+ `a Sibyl Labs LLC Product. Agentic Infrastructure and Memory Products`.
+ Rendered in the same deepest-gold (`_GRADIENT[-1]` = `(106, 79, 31)`)
+ as the tagline but with ANSI dim (`\033[2m`) applied so the visual
+ hierarchy reads SIBYL > tagline > attribution at a glance. Plain-text
+ fallback also includes the line for non-color terminals.
+
+Preview captures at https://sibylcap.com/hud-2026-05-20 (scene 09
+isolates the banner; scenes 01 + 05 show it inline with the rest of
+the activation and install ceremonies).
+
+## [0.3.1] — 2026-05-20
+
+Operator-directed tuning: "typical app patterns — heavy menus on
+install window and initial setup, light on dashboards etc." v0.3.0
+applied the full section_header treatment uniformly across every
+subcommand. v0.3.1 lightens the daily-use dashboards and keeps the
+ceremony reserved for activation moments.
+
+### Changed
+
+- `sibyl status`, `sibyl whoami`, `sibyl devices`, `sibyl logout`,
+ `sibyl health` — dropped the section_header opener. Same convention
+ as `git status`, `ls -la`, `gh auth status`, `pg_isready`,
+ `redis-cli ping`: utilitarian dashboards present data, not chrome.
+ Eyebrow labels + kv rows + status lines remain.
+
+### Unchanged
+
+- `sibyl init` — keeps the full SIBYL gradient banner + section
+ headers + numbered next-steps. This IS the install moment; it earns
+ the ceremony.
+- `sibyl upgrade` — keeps section header + KV. Mid-weight: tier-flip
+ moment is install-ish but not first-run.
+- `_aesthetic.py` library — unchanged. Applied differently across
+ commands per the heavy/light convention.
+
+## [0.3.0] — 2026-05-20
+
+Visual identity pass across every subcommand. The `sibyl init` brand
+moment (the SIBYL ASCII wordmark with pale-gold → deep-ochre vertical
+gradient) was the only command with serious typography; every other
+subcommand was plain text + ANSI 16-color. v0.3.0 brings the lab face
+to the whole surface.
+
+### Added
+
+- New `_aesthetic.py` module — shared visual library for the entire CLI.
+ Brand palette derived from the rule 46 creme paper face (PAPER, INK,
+ ACCENT, JADE, PULSE, RULE, etc.). 24-bit truecolor → 256-color → plain
+ text degradation cascade. Letter-spaced eyebrows, gradient titles,
+ ASCII rule dividers, key/value rows, status chips with success/warn/
+ error glyphs, multi-stop char-by-char gradient interpolation.
+- `SIBYL_FORCE_COLOR=1` env override for non-tty rendering (CI logs,
+ doc captures, harness inspection). Honors `NO_COLOR` as the wider
+ precedence override per the standard.
+
+### Changed
+
+- `sibyl init`, `sibyl upgrade`, `sibyl status`, `sibyl whoami`,
+ `sibyl devices`, `sibyl logout`, `sibyl health` all now open with a
+ styled section header (gradient command-name + creme rule lines +
+ dim subtitle), use eyebrow labels for sub-sections (uppercase
+ letter-spaced ochre), and render key/value rows + status lines with
+ the brand palette. Success states (Activated, Upgraded, Logged out)
+ flow with a pulse → jade gradient. Cap warnings and errors use the
+ measured warm-ochre / red palette tokens, not generic ANSI 31/33.
+- `sibyl init` waiting spinner now reads "watching the network for your
+ bind" in pulse-jade, aligned with the wallet-bind-watcher service
+ language users see in their browser.
+- `sibyl devices` list rendering: current device marked with `▶` in
+ pulse + the device label flows in gold gradient; other devices show
+ in calm ink with dim metadata. Index chips in pulse for "this device"
+ or muted gray for the rest.
+
+### Compatibility
+
+- Backward compat preserved: existing `dim/bold/green/yellow/red/cyan`
+ helpers stay in `cli.py` (the legacy `print_status` path they served
+ was removed later, in 0.5.0). New `_aesthetic.a.*`
+ helpers layer on top.
+- All visual choices honor `NO_COLOR`. Plain text fallback is
+ visually clean (no garbage escapes leak).
+- Terminal capability detection identical to `_banner.py` for
+ consistency (COLORTERM=truecolor, TERM_PROGRAM whitelist, TERM
+ pattern match for kitty/alacritty/256color).
+
+## [0.2.0] — 2026-05-19
+
+Auth-redesign wave 2 — account-surface CLI commands. Adds `sibyl whoami`
+for a one-line account summary (masked by default, `--full` opt-in) and
+`sibyl devices` for listing active bearer tokens with per-device revoke.
+
+### Added
+
+- `sibyl whoami` — one-line summary: short account_id, tier, masked email
+ (`a***@e***.tld`), masked wallet (`0xabcd…1234`), this device label.
+ `--full` flag shows unmasked email + wallet for ops scenarios.
+- `sibyl devices` — list active (non-revoked) bearer tokens for the
+ account in issued_at DESC order. Marks current device with `▶` and
+ shows revoke command for each other device.
+- `sibyl devices revoke ` — POST `/api/plugin/devices` with the
+ bearer_id at that index. Refuses to revoke the calling device.
+
+### Server companion (deployed)
+
+- `GET /api/plugin/devices?account_id=` — lists bearer_tokens.
+- `POST /api/plugin/devices { bearer_id }` — revokes the bearer.
+- Both auth via `Authorization: Bearer `; caller must
+ own the account.
+
+## [0.1.4] — 2026-05-18
+
+Maximum-efficiency onboarding release. New `sibyl setup` command auto-detects
+agent frameworks on the user's machine and wires SIBYL as the memory provider
+in one command. Replaces the prior three-step Hermes flow (`pip install
+sibyl-memory-hermes` + `sibyl-memory-hermes install-plugin` + manual
+`config.yaml` edit) with `sibyl setup`. Also handles Claude Code MCP wiring.
+
+### Added
+
+- **`sibyl setup`** — new subcommand. Auto-detects Hermes (`$HERMES_HOME` or
+ `~/.hermes/` or `hermes` on PATH) and Claude Code (`~/.claude/settings.json`
+ or `claude` on PATH). Prompts per stack with explicit confirmation:
+ - Fresh add: `Set SIBYL as default memory provider in Hermes? [Y/n]` (default Y)
+ - Overwrite existing: `Hermes currently uses 'mem0' as memory provider. Overwrite with SIBYL? [y/N]` (default N, never destroys user state without explicit y)
+ - Already wired: noop with green status
+ - Multi-framework: `Wire which? [h]ermes, [c]laude, [a]ll, [n]one (default: all)`
+- **`sibyl setup hermes`** / **`sibyl setup claude-code`** — explicit targeting
+ for power users (skips detection, wires only the named stack).
+- **Flags**: `--yes` (accept all defaults, still respects destructive-default-N
+ unless `--force` is also passed), `--force` (overwrite existing non-SIBYL
+ configs), `--dry-run` (print intent without writing), `--hermes-home`,
+ `--claude-settings` (override autodetect).
+- **Atomic writes + backups**: every config edit creates a `.bak` sibling
+ (`config.yaml.bak`, `settings.json.bak`) before atomic rename via tmpfile.
+ Defensive against partial writes + user mistake recovery.
+- **`HermesWirer`, `ClaudeCodeWirer`** classes in new `sibyl_memory_cli.setup`
+ module. Composable wirer protocol (`is_present()` / `current_state()` /
+ `wire()` / `WireOutcome`) ready for v0.1.5 addition of Codex / Cursor /
+ Continue wirers.
+- **33 new tests** in `tests/test_setup.py` covering: detection logic, prompt
+ helpers, Hermes fresh / existing-sibyl / existing-other / force-overwrite /
+ dry-run / config-preservation, Claude Code fresh / existing-other-mcps /
+ existing-sibyl / mismatched-sibyl / force / dry-run.
+
+### Changed
+
+- **Dependencies**: added `pyyaml>=6.0` for Hermes `config.yaml` editing.
+ Already a transitive dep for any Hermes user; small (~250 KB) for
+ Claude-Code-only users.
+
+### Notes
+
+- Replaces the prior canonical three-step Hermes flow. Docs `install.html`
+ Step 4 collapses from three commands to two: `pip install sibyl-memory-cli`
+ + `sibyl setup`. The old `sibyl-memory-hermes install-plugin` path stays
+ documented as a manual fallback for advanced users who want fine-grained
+ control over each step.
+- Codex / Cursor / Continue MCP wirers are scoped for v0.1.5. The wirer
+ protocol in `setup.py` is ready to take them as drop-in classes.
+- The shell installer (`curl ... | sh`) remains on the roadmap; combined with
+ `sibyl setup` it collapses the full onboarding to a single curl line.
+
+
+
+## [0.1.3] — 2026-05-18
+
+External-tester remediation release. Family-wide alignment with the
+v0.4.0 client + v0.3.2 hermes (external-test fixes: exception export
+path, db file perms, identifier validation, FTS5 error surfacing). No CLI
+code changes in this release.
+
+### Changed
+
+- `sibyl-memory-client` pin: `>=0.3.3` → `>=0.4.0`.
+- `sibyl-memory-hermes` pin: `>=0.3.1` → `>=0.3.2`.
+
+### Notes
+
+- `sibyl init / upgrade / status / health` surface is unchanged from
+ v0.1.2. The external tester's fixes flow through transparently via the dependency
+ bump.
+
+---
+
+## [0.1.2] — 2026-05-18
+
+Audit-remediation release. v0.3.0 plugin-family pre-ship audit (2026-05-18T05:05Z)
+surfaced 10 critical findings; this release lands the CLI-side fixes.
+Companion releases: `sibyl-memory-client` v0.3.3 (engine + schema v3 +
+cross-tier search), `sibyl-memory-hermes` v0.3.1, `sibyl-memory-mcp` v0.1.1.
+
+### Fixed
+
+- **C3** — `__version__` no longer hardcoded. Now sourced from
+ `importlib.metadata.version("sibyl-memory-cli")` with `+source` fallback.
+ Same pattern as sibyl-memory-hermes v0.3.0+. Wheel and `__init__.py`
+ can't drift.
+- **C3** — HTTP User-Agent header now built from the runtime
+ `_client_version()` helper instead of the hardcoded `"sibyl-memory-cli/0.1.0"`.
+ Server telemetry will see real versions, not the stale literal.
+- **C3** — `/api/plugin/session-init` payload's `client_version` field
+ similarly switched from `__import__("sibyl_memory_cli").__version__` to
+ the helper. Telemetry will accurately reflect 0.1.2+.
+- **C4** — post-activation message rewritten. Removed the fictional
+ `from hermes_agent import Agent; agent = Agent(memory=SibylMemoryProvider())`
+ quickstart (the API never existed in any Hermes release). Replaced with:
+ the real Hermes install flow (`sibyl-memory-hermes install-plugin` +
+ config.yaml edit), the MCP install hint for Claude Code / Codex / Cursor /
+ Continue users, and the direct-SDK path for any Python orchestration.
+
+### Security
+
+- **SEC-2** — `write_credentials_atomic` now creates files at mode 0o600
+ set by the kernel at file-creation time via `os.open(O_WRONLY|O_CREAT|
+ O_EXCL|O_NOFOLLOW, 0o600)`. Previously used `write_text()` then
+ `os.chmod(0o600)`, leaving a world-readable window between syscalls every
+ credential save. No race.
+- **SEC-1** (CLI-side mitigation) — the URL parameter handed to the
+ browser is now treated as an opaque pairing-session identifier, not as
+ the long-lived bearer. After activation completes, the CLI prefers a
+ server-issued `bearer_token` field from `/check` (post-fix server flow);
+ if absent, falls back to the legacy session-echo flow. Full fix requires
+ the api-sibyllabs server-side change to issue a separate bearer; this
+ release prepares the CLI to consume it when the server-side lands.
+ Internal variable renamed `session_token` → `session_id` in `cmd_init`
+ to reflect the corrected meaning.
+- **SEC-11** — `read_credentials` refuses to follow symlinks.
+
+### Dependencies
+
+- `sibyl-memory-client>=0.3.3` (was `>=0.3.0`)
+- `sibyl-memory-hermes>=0.3.1` (was `>=0.2.0`) — picks up the fictional-API
+ removal in the hermes package; earlier versions are structurally broken.
+
+## [0.1.1] — 2026-05-17
+
+### Added
+
+- **SIBYL wordmark banner** at the top of `sibyl init`. ANSI Shadow boxchars,
+ 24-bit truecolor vertical gradient flowing cream/white at the top through
+ warm gold to deep ochre at the bottom — aligned with the lab visual identity
+ per the operator's brand-discipline rule (creme palette, `--accent #8a6a2a`).
+ Plus a tagline: "memory you can hold in your hand".
+
+### Implementation notes
+
+- New module `sibyl_memory_cli._banner` with `render_banner()` and
+ `print_banner()` helpers. Truecolor support is detected via `COLORTERM`,
+ `TERM_PROGRAM`, and `TERM` — modern terminals (iTerm2, Alacritty, Kitty,
+ wezterm, Ghostty, Windows Terminal, VS Code, Tabby) light up automatically.
+- Gracefully degrades to plain text (still readable, no escape junk) when
+ `NO_COLOR` is set, when stdout is not a TTY, or when `TERM=dumb`.
+- Wired into `cmd_init` only — `status` / `health` / `upgrade` stay banner-free
+ so they don't add noise to scripted invocations.
+- Banner palette is encoded as 6 RGB tuples (one per row) in the module
+ rather than computed at runtime — easier to tune and audit.
+
+## [0.1.0] — 2026-05-16
+
+### Changed (same-day revision before publish): terminal pairing code
+
+`sibyl init` now generates a 6-digit pairing code locally (via
+`secrets.randbelow`), prints it in the terminal, and POSTs only its
+sha256 hash to `/api/plugin/session-init` BEFORE opening the browser.
+The code itself never leaves the user's machine until they type it
+into the browser's email panel. Replaces the earlier Resend-backed
+email magic-code flow, removing the external dependency entirely.
+
+The wallet (SIWE) path is unchanged — the pairing code only matters
+for the email panel.
+
+
+
+Initial release. Operator directive 2026-05-16: build the user-facing
+CLI + upgrade page so the SDK + payment-auth machinery has a front door.
+
+### Added
+
+- **`sibyl init`** — browser activation. Generates a session UUID,
+ opens `sibyllabs.org/plugin/activate?session=...` in the user's
+ browser, polls `api.sibyllabs.org/api/plugin/check` every 3s with a
+ 10-min timeout. On bind, writes `~/.sibyl-memory/credentials.json`
+ atomically at mode 0600.
+- **`sibyl upgrade`** — opens `sibyllabs.org/plugin/upgrade?session=...`
+ with the existing session token. Polls `/api/plugin/access` every 3s
+ with a 15-min timeout until `tier` changes from the local value.
+ On change: rewrites credentials.json, clears `tier_cache.json` so
+ the next write picks up the new entitlement immediately.
+- **`sibyl status`** — shows local credentials, DB size, tier cache
+ state, plus the server's view of tier (subscription / staker /
+ free). Flags local↔server tier drift.
+- **`sibyl health`** — wraps `SibylMemoryProvider.health()`. Prints
+ the JSON diagnostic dict.
+
+### Design
+
+- Pure stdlib HTTP via `urllib`. No `requests`, no `httpx`. The wheel
+ installs in seconds.
+- `session_token` printed only as short slice (`first8…last4`). Never
+ full-length to stdout.
+- Polling has explicit timeouts. No infinite loops. Ctrl-C exits 130.
+- All endpoint URLs configurable via env (`SIBYL_API_BASE`,
+ `SIBYL_ACTIVATE_BASE`, `SIBYL_UPGRADE_BASE`) for staging tests.
+
+### Depends on
+
+- `sibyl-memory-client>=0.3.0` (cap gate)
+- `sibyl-memory-hermes>=0.2.0` (provider + credentials loader)
+
+### Entry point
+
+`pip install sibyl-memory-cli` installs the `sibyl` binary via the
+`[project.scripts]` block in pyproject.
diff --git a/sibyl-memory-cli/LICENSE b/sibyl-memory-cli/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..ec17a86a156882e7351814ef54a31c3a5bae9433
--- /dev/null
+++ b/sibyl-memory-cli/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Sibyl Labs LLC
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/sibyl-memory-cli/README.md b/sibyl-memory-cli/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8f4b5675547637bb96801987f80fdbf77b48a87f
--- /dev/null
+++ b/sibyl-memory-cli/README.md
@@ -0,0 +1,313 @@
+# sibyl-memory-cli
+
+Command-line interface for the **Sibyl Memory Plugin**.
+
+```bash
+pip install sibyl-memory-cli
+```
+
+Sibyl Memory runs on Linux, macOS (Apple Silicon and Intel), and Windows through WSL2. Native Windows is not supported.
+
+This pulls in `sibyl-memory-client` (the local SDK) and `sibyl-memory-hermes` (the Hermes provider) automatically.
+
+**Upgrading.** The packages ship as one release train (client 0.10.0, mcp 0.4.2, hermes 0.6.0, cli 0.7.0), and each one requires the client of its own release. Upgrade them together, never one alone:
+
+```bash
+sibyl update --apply
+# or, without the CLI:
+pip install -U sibyl-memory-client sibyl-memory-mcp sibyl-memory-hermes sibyl-memory-cli
+```
+
+## Commands
+
+```
+sibyl --version Print the installed versions: cli, client, mcp, hermes, langgraph.
+sibyl init Open the browser activation page. Writes ~/.sibyl-memory/credentials.json.
+ Afterwards it offers to add or confirm your email (terminal only).
+sibyl init --no-email Activate without the email prompt.
+sibyl init --replace Re-activate this computer in place of its earlier sign-in (re-activation
+ never uses a second computer slot). At the account's computer limit
+ (Free: one computer) init lists the computers signed in and offers to
+ sign one out on the account page.
+sibyl refresh Check your account now (an upgrade, a staking unlock or a plan change
+ lands at once), refresh the procedures, shims and hooks, and say what
+ changed. Exits 0 with no account (it says what to do), 2 when offline.
+sibyl autosave [on|off|every N]
+ Pro automatic save: every N minutes of active work (30 to 240, default
+ 60). On the free plan the setting is kept for the day you upgrade.
+sibyl email Show your account email: confirmed, not confirmed, or none.
+sibyl email add Send a code to a new address, then confirm it.
+sibyl email verify Send a code to the address you activated with, then confirm it.
+sibyl email confirm Confirm a code from the email (for scripts and non-interactive shells).
+sibyl claim Link a card purchase from sibyllabs.org/pro to this account.
+sibyl migrate Guided onboarding: back up your existing memory/agent files, wire Sibyl
+ into every detected harness, populate Sibyl Memory from the backup, and
+ optionally slim the instruction files it found (CLAUDE.md, AGENTS.md,
+ .cursorrules, ...). Backup-first, never destructive.
+sibyl setup [target] Wire Sibyl as the memory provider for Hermes, Claude Code, Codex, Cursor,
+ Grok Bot and/or DeepSeek Harness, and install the save and debloat
+ procedures for each. target is one of: hermes | claude-code | codex |
+ cursor | grokbot | deepseek (alias dsh) (default: detect all).
+ DeepSeek Harness: --dsh-home, --dsh-profile .
+sibyl save Save: --fact "" writes one fact; --status shows the last save; bare
+ prints how to run the save procedure in your agent. --capsule on Pro.
+sibyl debloat Measure the instruction files your agent loads every start (--fyi, --json);
+ plan | apply [] | auto | manual | undo [].
+sibyl skills install | status | reset | uninstall (run it before pip uninstall).
+sibyl reminders on | off | quiet (save and debloat reminders; quiet silences Pro reports).
+sibyl status Show local credentials, DB size, this computer's access, and the server's
+ view of your tier.
+sibyl whoami One-line account summary (masked by default).
+sibyl devices List the devices (active tokens) bound to your account, with the
+ account's computer limit when the api sends it (Free 1, Pro up to 2).
+sibyl devices revoke N Revoke a device by index (run `sibyl devices` to see the indexes).
+sibyl dashboard Open the account page at account.sibyllabs.org (no token in the URL; you
+ sign in there). Shows `sibyl status` while the page is not open yet.
+sibyl upgrade Open the tier/billing flow: the account billing page when the server offers
+ it, otherwise the stake / USDC page through a one-time link.
+sibyl update Check PyPI for newer releases of the installed Sibyl packages: cli, client,
+ hermes, the MCP server, and langgraph when installed.
+sibyl update --apply Update the installed Sibyl packages in place (pip install -U), the MCP server
+ included; never installs one you do not have. This is the
+ canonical way to update the plugin, distinct from `sibyl upgrade` (which is
+ the tier/billing flow, not a package update).
+sibyl health Run the SibylMemoryProvider self-check (schema version, DB path, tenant,
+ entitlement state, pinned key ids).
+sibyl logout Sign this computer out: revoke it on the server, remove credentials.json and
+ entitlement.json (your memory.db is left untouched).
+sibyl memory list [category] List stored entities, optionally filtered by category (--limit N).
+ `sibyl memory` never needs an account: your local data is always yours to read.
+sibyl memory search Full-text search across entities, state, reference, and journal (--limit N).
+sibyl memory recall
+ Recall a single entity by category + name.
+sibyl memory adopt [--yes] Move memory written on this computer before sign-in into your account
+ (local, one transaction, nothing deleted; asks first if the store has
+ held another account). `sibyl init` does this on the first sign-in.
+```
+
+## Migrate (guided onboarding)
+
+```bash
+$ sibyl migrate
+```
+
+`sibyl migrate` moves your accumulated agent memory into Sibyl without risking
+your existing files:
+
+1. **Back up first.** Every memory/agent file it finds (`CLAUDE.md`,
+ `AGENTS.md`, `.codex/config.toml`, `.hermes/*`, and similar) is copied to a
+ timestamped backup folder and byte-verified before anything else happens.
+2. **Wire Sibyl** into every detected harness — Claude Code (via
+ `claude mcp add --scope user`), Codex (via `~/.codex/config.toml`), Hermes.
+3. **Extract** — it prints a prompt you run in your own agent. The agent reads
+ only from the backup and writes structured memory through the `sibyl-memory`
+ tool. The extraction runs locally on your machine; Sibyl Labs never sees your
+ files or memory.
+4. **Verify** the new entries that landed in your local DB.
+5. **Optionally trim** the instruction files it found (`CLAUDE.md`, `AGENTS.md`,
+ `.cursorrules`, ...), one question per file, only if you confirm and only because
+ a verified backup of that file exists. Configuration files are never trimmed. Your
+ full pre-migration files are always preserved.
+
+Flags: `--backup-dir PATH` (default: home), `--no-debloat` (skip the trim
+step), `--yes` (skip the initial confirm; the trim step still asks separately).
+
+> No warranty. Keep your backup until you've confirmed everything migrated.
+> Sibyl Labs is not responsible for data loss.
+
+## Activation
+
+```bash
+$ sibyl init
+
+─ activation ───────────────────────────────────────────────
+two paths · pick whichever fits your device
+
+ Session a1b2c3d4…e5f6
+ Code 437 480 (use this in the email panel)
+ Opening https://auth.sibyllabs.org/a1b2c3d4-…
+
+ desktop wallet · or email + code
+ this terminal will pick up automatically when you bind.
+
+ ⠙ watching the network for your bind … 9:59 left
+```
+
+The browser opens the sign-in page. Sign in with your email and the code shown in the terminal, or with a desktop wallet (when the server offers it, a third path sends a small USDC amount from a mobile wallet). If you already have an account, `sibyl init` also prints an approve link on `account.sibyllabs.org`: open it on a computer that is already signed in and type the same code. The terminal picks up the moment the binding lands. Credentials are written to `~/.sibyl-memory/credentials.json` at mode 0600, and this computer's signed access file to `~/.sibyl-memory/entitlement.json` (0600).
+
+An account is required for agents to use memory (MCP, Hermes, LangGraph, the SDK). `sibyl init` is the sign-in; there is no separate login command. The access pass is re-checked about once a day (and at the end of a paid plan) and keeps working offline for up to 14 days. Memory written on this computer before you signed in moves into your account at that first sign-in (on this computer only); if the store has held another account, `sibyl init` leaves it and `sibyl memory adopt` asks first.
+
+## Email
+
+Every account needs a confirmed email for receipts, security notices, purchases and recovery.
+Your local memory works either way. Wallet activation stays available.
+
+```bash
+$ sibyl email add you@example.com
+ code sent to y***@e***.com. it expires in 10 minutes.
+ code from the email: 123456
+ ✓ Email confirmed. Your account is complete.
+```
+
+`sibyl email verify` confirms the address you activated with. Confirming from the terminal keeps
+this computer signed in and signs out any other computer that was set up with the address before
+you confirmed it.
+
+## Upgrade
+
+Free is 5 MB of local memory. Pro removes the cap: $12/month or $108/year (plus applicable tax by card), bought at
+`sibyllabs.org/checkout` or through `sibyl upgrade`. Holding 100,000 $SIBYL staked also gives Pro.
+
+```bash
+$ sibyl upgrade
+```
+
+`sibyl upgrade` shows your account and current tier, then opens the purchase page in your
+browser: the account billing page (`https://account.sibyllabs.org/billing`; sign in there and buy
+Pro) when the server offers it, otherwise a one-time exchange link. No token ever rides the URL.
+It then waits for the plan change. A card purchase made elsewhere can be linked with
+`sibyl claim `.
+
+When the tier changes, the CLI rewrites `credentials.json` and clears `tier_cache.json` so your next write picks up the new entitlement without delay.
+
+## Status
+
+```bash
+$ sibyl status
+
+P L U G I N
+ Version cli 0.5.0 · client 0.9.0
+L O C A L
+ Credentials ~/.sibyl-memory/credentials.json
+ Account a1b2c3d4-e5f6-4789-8abc-def012345678
+ Tier Free
+ Wallet 0xa1b2c3d4e5f60718293a4b5c6d7e8f9012345678
+ Email you@example.com
+ Issued 2026-05-16 18:12 UTC
+ Platform Linux (x86_64)
+ DB path ~/.sibyl-memory/memory.db
+ DB size 1,247,300 bytes (1.19 MB · 23.8% of free cap)
+
+A C C E S S
+ Access active · re-checks in 24h
+ Tier cache free (checked 2026-05-16 18:12 UTC)
+
+S E R V E R
+ Tier Free
+ Source free
+ Cap bytes 5,242,880
+ Email not confirmed · run sibyl email verify
+ Dashboard https://account.sibyllabs.org
+
+L I F E C Y C L E
+ save last never · 0 writes since · manual (automatic on Pro)
+ context no always-load files found here
+ skills not installed · sibyl skills install
+ reminders on
+```
+
+`$SIBYL held`, `Threshold` and `Qualified` rows appear under `SERVER` when the server reports staking details.
+
+`Email`, `Account` and `Dashboard` rows appear when the server reports them. On a paid plan a `Plan` row under `Access` shows the billing date when the server sends it: `Pro · renews 8 Oct 2027` for a renewing card plan, `Pro · ends 8 Oct 2027` when the plan is set to end (a cancellation, or a fixed term). The `Tier` rows always show the tier of this computer's current access pass.
+
+`sibyl status` runs one access check-in when online (the check-in is the status). The `Access` row reads one of:
+
+| Row | Meaning | What to do |
+|---|---|---|
+| `active · re-checks in h` | this computer is signed in; the access pass is checked again in about hours (not a billing date) | nothing |
+| `offline · days of grace left · connect once to renew` | not reached the server lately | connect to the internet once |
+| `paused · offline too long · connect to the internet, or run sibyl init` | offline more than 14 days | connect; if it stays paused, `sibyl init` |
+| `setup not finished · connect to the internet once to finish setup` | credentials from before 0.9.0 and no check-in yet | connect once |
+| `signed out · run sibyl init` | signed out, revoked, or the sign-in expired | `sibyl init` |
+| `under review · email sibyl@sibyllabs.org` | the account is under review | email us |
+
+When the server cannot be reached, the account rows come from the last check-in, labeled `as of `. With no credentials at all, `sibyl status` says so and that agents cannot use memory until you run `sibyl init`; your local data is kept.
+
+If `LOCAL` and `SERVER` tiers diverge, run `sibyl refresh` to pick up the server plan (or `sibyl init --force` to re-activate).
+
+## Environment overrides
+
+For internal testing only:
+
+```bash
+SIBYL_API_BASE=https://staging.sibyllabs.org sibyl init
+SIBYL_ACTIVATE_BASE=https://staging.sibyllabs.org/plugin/activate sibyl init
+SIBYL_UPGRADE_BASE=https://staging.sibyllabs.org/plugin/upgrade sibyl upgrade
+SIBYL_ACCOUNT_BASE=https://account.staging.sibyllabs.org sibyl dashboard
+SIBYL_NONINTERACTIVE=1 sibyl init # never prompt (same as a non-TTY shell)
+```
+
+The CLI sends your sign-in only to an https `*.sibyllabs.org` address or a loopback address (for example `http://127.0.0.1:8787`); any other `SIBYL_API_BASE` or `SIBYL_UPGRADE_BASE` gets no session token.
+
+## Security
+
+- `credentials.json` and `entitlement.json` are written atomically at mode 0600.
+- The access file is verified offline against a public key pinned in `sibyl-memory-client`; it is never printed.
+- `session_token` is never printed in full: only a short slice.
+- No token rides a browser URL: `sibyl dashboard` opens the account page bare, and `sibyl upgrade`
+ uses a one-time exchange link.
+- No memory content ever transits these endpoints. `sibyl status` reads only the size of `memory.db`; `sibyl memory list|search|recall|adopt` read your memory locally and send none of it anywhere.
+- Wallet operations happen in the browser. The CLI sees only the resulting tier change.
+
+## Save and debloat
+
+**Save.** At the end of a session, or after a big block of work, your agent writes what happened
+into Sibyl Memory through the plugin's own tools: the decisions made and why (journal), the
+people, projects and products touched (entities), what to pick up next time and the open
+warnings (session state), the ranked priorities, and it closes what died (archive). A delta
+marker means a second save in the same day captures only what changed. It may offer to turn a
+repeated pattern into a reusable skill; that is offered, never forced. Nothing in a save leaves
+your machine.
+
+**Debloat.** Sibyl measures the files your agent loads on every session start (`CLAUDE.md`,
+`AGENTS.md`, `.cursorrules` and the rest of the scan set), deterministically (`chars/4`,
+labeled `MEASURED~`), and when they are heavy, trims the accreted history out of them without
+losing a byte: the history moves out and a one-line pointer stays. On the free plan the history
+moves to a sibling `*-history` file. On Pro it is stored in Sibyl Memory as a reference document,
+so it stays searchable, and the measurement and trim run by themselves under a policy you set
+once.
+
+| | Free (activated account) | Pro |
+|---|---|---|
+| The procedures in `~/.sibyl-memory/skills/` (`SAVE.md`, `DEBLOAT.md`), `/sibyl-save` and `/sibyl-debloat` in Claude Code, skills in Hermes and Codex, a block in Codex's `AGENTS.md`, the `save` and `debloat` MCP prompts | yes | yes |
+| `sibyl save`, `sibyl debloat` (measure, plan, apply, undo) | yes | yes |
+| Reminders (one quiet line; `sibyl reminders off`) | yes | replaced by a one-line report of what ran |
+| Where trimmed history goes | a sibling `*-history` file | Sibyl Memory, plus a byte-verified backup |
+| Automatic debloat | no | yes: `propose` by default; a file is trimmed by itself only after you run `sibyl debloat auto ` (that file at its path, never the same name elsewhere) |
+| Automatic save by active time: once early (after 5 memory writes or a compaction), then about every 60 minutes of active work, only when there is something to save, at most 8 a session and 12 a day (`sibyl autosave every <30-240>` or `sibyl autosave off`). Claude Code: the Stop hook asks your agent to run the save procedure headless (a scripted `claude -p` run is never asked); Cursor, Codex and other MCP hosts: a `notice` on the next tool result; Hermes: a note in the next prefetch. A session capsule (counts only) at compaction and session end. Each automatic save is one extra model turn that reads and writes memory | no | yes |
+| Skill proposals: Sibyl finds repeated work in your journal (locally, no network), names up to 3 at a session start at most once a day, and creates nothing without a yes (`/sibyl-save curate`, or `sibyl skills proposals accept `, which writes the skill for Claude Code, Codex and Hermes) | no (`/sibyl-save` still offers skills when you run it) | yes |
+| Skill signals (0.10): Sibyl also notices a tool sequence your agent repeats (in Claude Code the whole workflow, for example `Read -> Edit -> Bash`; in Codex, Cursor and Hermes the memory tools only) and an entity rewritten again and again, and proposes a skill for it the same way. It keeps one small local file, `~/.sibyl-memory/signals.json`: tool and MCP server names in plain text, argument names and entity names only as hashes, never a value, never a prompt or a file path; nothing leaves your computer. `sibyl skills signals` shows its size, `clear` deletes it, `off` stops it. In Claude Code a proposal from the workflow appears at the next session start at the earliest | no (nothing is recorded) | yes |
+
+The procedures are vendored, with attribution, from the public MIT repos
+[sibyl-save](https://github.com/Sibyl-Labs/sibyl-save) and
+[debloat](https://github.com/Sibyl-Labs/debloat); both stay standalone and account-free.
+
+Uninstalling: run `sibyl skills uninstall` first. It removes the Claude Code hooks in
+`~/.claude/settings.json`, the skill shims and the Codex block (files you edited are kept); then
+`pip uninstall` the packages. The hooks call this package's `sibyl` command: if the package goes
+first they exit quietly, but they stay in your settings until you reinstall and run
+`sibyl skills uninstall`, or delete the five `sibyl hook` entries by hand.
+
+Privacy: the lifecycle reads your instruction files to measure and trim them locally; no file
+content and no conversation content ever leaves your machine.
+
+Forks: a gate-stripped fork can run the lifecycle code locally (MIT allows it). It gains nothing
+hosted, and its trims land in a store the official path cannot recognize as Pro. No file, flag
+or environment variable turns the automation on for a free account.
+
+Commands: `sibyl save` (`--fact`, `--status`, `--capsule` on Pro), `sibyl debloat` (`--fyi`,
+`--json`, `plan`, `apply []`, `auto `, `manual `, `undo []`),
+`sibyl skills install|status|reset|uninstall`, `sibyl skills proposals [show|accept|reject|mute|unmute]`
+(Pro), `sibyl skills signals [status|clear|off|on]` (Pro; `off` and `clear` on any plan), `sibyl autosave [on|off|every ]`, `sibyl reminders on|off|quiet`. `sibyl setup`
+installs the procedures and wires them: Claude Code gets the two skills plus five hooks in
+`~/.claude/settings.json` (`sibyl hook `, installed by setup, not for manual use; any
+other hook you have is left alone; each hook exits 0 quietly if the `sibyl` it names is gone),
+Codex gets a marked block in `~/.codex/AGENTS.md` and two skills in `~/.codex/skills/`, Hermes
+gets two skills in `$HERMES_HOME/skills/`. `sibyl debloat auto ` authorizes that one file
+at its path. On Pro the Stop hook asks the agent to save once early (after 5 memory writes or a
+compaction), then about every hour of active work (`sibyl autosave`). `sibyl migrate` now slims the instruction files it
+found (`CLAUDE.md`, `AGENTS.md`, `.cursorrules`, ...), one question per file.
+
+## License
+
+MIT.
diff --git a/sibyl-memory-cli/pyproject.toml b/sibyl-memory-cli/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..6f33db63857566cb2093e63189b10f7ebee7e558
--- /dev/null
+++ b/sibyl-memory-cli/pyproject.toml
@@ -0,0 +1,53 @@
+[build-system]
+requires = ["setuptools>=61.0", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "sibyl-memory-cli"
+version = "0.7.0"
+description = "Command-line interface for the Sibyl Memory Plugin. `sibyl init` activates, `sibyl upgrade` opens the Pro / Elite upgrade flow, `sibyl status` shows current tier and DB stats, `sibyl whoami` gives a one-line account summary, `sibyl devices` lists active devices and supports per-device revoke."
+authors = [{ name = "SIBYL, Sibyl Labs LLC", email = "sibyl@sibyllabs.org" }]
+license = { text = "MIT" }
+readme = "README.md"
+requires-python = ">=3.10"
+keywords = ["sibyl", "memory", "cli", "agent", "hermes", "deepseek"]
+classifiers = [
+ "Development Status :: 4 - Beta",
+ "Intended Audience :: Developers",
+ "License :: OSI Approved :: MIT License",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Environment :: Console",
+ "Topic :: Software Development :: Libraries :: Python Modules",
+ "Operating System :: POSIX :: Linux",
+ "Operating System :: MacOS",
+]
+dependencies = [
+ "sibyl-memory-client>=0.10.0",
+ "sibyl-memory-hermes>=0.6.0",
+ "pyyaml>=6.0,<7",
+ # The Codex config proof parses TOML; tomllib is stdlib only from 3.11.
+ 'tomli>=2; python_version < "3.11"',
+]
+
+[project.optional-dependencies]
+mcp = [
+ "sibyl-memory-mcp>=0.4.0",
+]
+dev = [
+ "pytest>=7.0",
+]
+
+[project.scripts]
+sibyl = "sibyl_memory_cli._entry:main"
+
+[project.urls]
+Homepage = "https://sibyllabs.org/plugin"
+Documentation = "https://docs.sibyllabs.org/memory/"
+Repository = "https://github.com/Sibyl-Labs/Sibyl-Memory"
+
+[tool.setuptools.packages.find]
+where = ["src"]
+include = ["sibyl_memory_cli*"]
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/__init__.py b/sibyl-memory-cli/src/sibyl_memory_cli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dca86412fc51544fd951a7e72f0ecd09b8936b66
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/__init__.py
@@ -0,0 +1,40 @@
+"""sibyl-memory-cli: command-line interface for the Sibyl Memory Plugin.
+
+Entry point: `sibyl` (installed via [project.scripts] in pyproject).
+`sibyl --help` lists every command; a few to start with:
+
+ sibyl init sign in (email + code, or a wallet) and write
+ ~/.sibyl-memory/credentials.json
+ sibyl setup wire Claude Code, Codex, Cursor, Hermes and
+ DeepSeek Harness
+ sibyl status show current tier, DB size, expiry, account
+ sibyl upgrade open the upgrade flow: Pro by card or USDC, or by
+ staking $SIBYL
+
+Account calls go to https://api.sibyllabs.org (SIBYL_API_BASE overrides);
+`sibyl update` also asks pypi.org for the latest releases.
+"""
+# Lazy (PEP 562): `main` and `__version__` resolve on first access, so the
+# `sibyl hook ` fast path (_entry.py -> hooks.py) imports neither the
+# whole CLI nor importlib.metadata. `from sibyl_memory_cli import main` and
+# `sibyl_memory_cli.__version__` work as before.
+
+
+def __getattr__(name: str):
+ if name == "main":
+ from .cli import main
+ return main
+ if name == "__version__":
+ # Single-sourced from installed metadata so wheel + code can't drift
+ # (C3 audit fix v0.1.2). Same pattern as sibyl-memory-hermes v0.3.0+.
+ from importlib.metadata import PackageNotFoundError, version as _pkg_version
+ try:
+ v = _pkg_version("sibyl-memory-cli")
+ except PackageNotFoundError: # pragma: no cover - source-tree dev only
+ v = "0.0.0+source"
+ globals()["__version__"] = v
+ return v
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+__all__ = ["main", "__version__"]
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/_account_gate.py b/sibyl-memory-cli/src/sibyl_memory_cli/_account_gate.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a83efe0ebff78cf51120d3540ebb7a336fcae27
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/_account_gate.py
@@ -0,0 +1,545 @@
+"""CLI side of the account gate (spec account-gated-plugin 2026-09-27, 3.4 and 5.6).
+
+The gate itself lives in sibyl-memory-client (``_entitlement``). This module is
+the CLI's thin layer over it:
+
+ * write / remove ``entitlement.json`` beside the credentials file
+ (``sibyl init``, ``sibyl email confirm``, ``sibyl logout``);
+ * the ``X-Sibyl-Entitlement`` header the CLI adds to every
+ session-authenticated call (only a token that verifies, is bound to this
+ computer and is inside ``exp + og``; never a token it knows the api would
+ refuse);
+ * the ``access`` status row and the ``health`` line;
+ * one-line copy for the api's 403 ``entitlement_invalid`` / ``client_too_old``.
+
+Nothing here prints or logs a token or a session value.
+"""
+from __future__ import annotations
+
+import time
+from pathlib import Path
+from typing import Any
+
+try: # the CLI stays importable without the client (update / setup paths)
+ from sibyl_memory_client import _entitlement as _E
+except Exception: # pragma: no cover - client absent or pre-0.9.0
+ _E = None
+
+ENTITLEMENT_FILENAME = "entitlement.json"
+HEADER = "X-Sibyl-Entitlement"
+
+CLIENT_TOO_OLD_LINE = ("update the plugin: pip install -U sibyl-memory-client sibyl-memory-mcp "
+ "sibyl-memory-hermes sibyl-memory-cli")
+ENTITLEMENT_INVALID_LINE = ("this computer's sign-in file is damaged, expired or belongs to "
+ "another computer. run sibyl init to sign in again. your local "
+ "memory is kept.")
+NO_ACCOUNT_MEMORY_LINE = "reading local data without an account. agents need sibyl init."
+# 403 client_too_old while this computer holds no usable token: the plugin is
+# current, the api refused an ABSENT token (after the min_client_version
+# cutoff) because setup never finished. Same words as the setup_incomplete
+# access row.
+SETUP_INCOMPLETE_LINE = ("setup is not finished on this computer. connect to the internet once "
+ "to finish setup. nothing was deleted.")
+
+
+# Follow-up D1 (2026-11-14): the CLI refused to send the sign-in because
+# SIBYL_API_BASE is not https *.sibyllabs.org or a loopback address
+# (cli.http_request raises HttpError(0, code untrusted_api_base); the client
+# gate's refresh answers transient with the same code). Not a network fault:
+# never "retry" and never "connect to the internet".
+UNTRUSTED_BASE_CODE = "untrusted_api_base"
+UNTRUSTED_BASE_LINE = "sign-in not sent: SIBYL_API_BASE is not a Sibyl address."
+UNTRUSTED_BASE_HUMAN = ("SIBYL_API_BASE points at a host Sibyl will not send your sign-in to; "
+ "unset it")
+UNTRUSTED_UPGRADE_HUMAN = ("SIBYL_UPGRADE_BASE points at a host Sibyl will not send your sign-in "
+ "to; unset it")
+
+
+def untrusted_base_handoff() -> tuple[str, str | None]:
+ return ("done", UNTRUSTED_BASE_HUMAN)
+
+
+def _unsafe_url_chars(url: str) -> bool:
+ return any(c == "\\" or c.isspace() or ord(c) < 0x20 or ord(c) == 0x7F for c in url)
+
+
+def bearer_url_safe(url: Any) -> bool:
+ """Follow-up D3: the extra refusals the CLI applies before the client's
+ host rule, so cli 0.7.0 is protected with client 0.10.0 installed. A URL
+ with a backslash, whitespace or a control character, or with userinfo
+ (``https://evil.com\\@sibyllabs.org/x`` parses with hostname sibyllabs.org
+ while some HTTP stacks connect to evil.com), never gets the bearer."""
+ import urllib.parse
+ if not isinstance(url, str) or _unsafe_url_chars(url):
+ return False
+ try:
+ parsed = urllib.parse.urlparse(url)
+ if parsed.username is not None or parsed.password is not None:
+ return False
+ except ValueError:
+ return False
+ return True
+
+
+def _guarded_refresh(account_id: str, session_token: str):
+ """The client's /entitlement transport behind the CLI's own URL check
+ (D3): the client gate's own rule alone accepts a userinfo URL."""
+ if not bearer_url_safe(_E._api_base() + _E.ENTITLEMENT_PATH):
+ return _E.RefreshOutcome("transient", code=UNTRUSTED_BASE_CODE)
+ return _E.http_refresh(account_id, session_token)
+
+
+# F-1 (contract C1): the api's 401 ``code`` for a computer that was signed
+# out when the account's email was confirmed on the account page.
+SIGNED_OUT_ON_CLAIM = "signed_out_on_claim"
+SIGNED_OUT_ON_CLAIM_NEXT = "sibyl init --force"
+
+
+def signed_out_on_claim_line(signed_out_at: Any = None) -> str:
+ """'signed out: this computer was signed out when your email was confirmed
+ on the account page (2026-10-08 18:34 UTC). run: sibyl init --force'. The
+ parenthesis is left out when the api sent no usable time."""
+ from ._timefmt import utc_minute
+ when = utc_minute(signed_out_at) if isinstance(signed_out_at, str) else None
+ at = f" ({when})" if when else ""
+ return ("signed out: this computer was signed out when your email was confirmed on the "
+ f"account page{at}. run: {SIGNED_OUT_ON_CLAIM_NEXT}")
+
+
+def entitlement_path(cred_path: Path) -> Path:
+ return Path(cred_path).expanduser().parent / ENTITLEMENT_FILENAME
+
+
+def _shape_ok(token: Any) -> bool:
+ """Cheap shape check before writing (spec 9.5 item 24): a string, at most
+ 4096 bytes, printable ASCII, three segments, SE1 prefix. The signature is
+ verified by the gate on every use, never trusted from here."""
+ if not isinstance(token, str) or not token or len(token) > 4096:
+ return False
+ try:
+ raw = token.encode("ascii")
+ except UnicodeEncodeError:
+ return False
+ if any(b < 0x21 or b > 0x7E for b in raw):
+ return False
+ parts = token.split(".")
+ return len(parts) == 3 and parts[0] == "SE1" and all(parts[1:])
+
+
+def write_entitlement_atomic(token: Any, cred_path: Path) -> Path | None:
+ """Write entitlement.json (0600, mkstemp + os.replace, symlink-refusing)
+ beside ``cred_path``. Returns the path, or None when the token is
+ malformed (ignored, nothing written) or the write was refused."""
+ if _E is None or not _shape_ok(token):
+ return None
+ store = _E.EntitlementStore(entitlement_path(cred_path))
+ now = time.time()
+ ok = store.store({"token": token, "received_at": now, "hwm": now})
+ return store.path if ok else None
+
+
+def remove_entitlement(cred_path: Path) -> list[str]:
+ """Delete entitlement.json (and a leftover lock). Returns what was removed."""
+ removed: list[str] = []
+ for name in (ENTITLEMENT_FILENAME, "entitlement.lock"):
+ p = Path(cred_path).expanduser().parent / name
+ try:
+ if p.is_symlink() or p.exists():
+ p.unlink()
+ if name == ENTITLEMENT_FILENAME:
+ removed.append(str(p))
+ except OSError:
+ pass
+ return removed
+
+
+def gate_for(cred_path: Path, *, background: bool = False):
+ if _E is None:
+ return None
+ return _E.EntitlementGate(Path(cred_path).expanduser(), background_refresh=background,
+ refresh_fn=_guarded_refresh)
+
+
+def header_token(cred_path: Path) -> str | None:
+ """The token to present on a session-authenticated call, or None.
+
+ Read-only: no refresh here. A token past exp + og, unverifiable, or bound
+ to another session is never sent (the api would answer 403
+ entitlement_invalid); with no token the api accepts the call until
+ min_client_version is set."""
+ gate = gate_for(cred_path)
+ if gate is None:
+ return None
+ try:
+ return gate.peek_token()
+ except Exception:
+ return None
+
+
+def has_account_access(cred_path: Path) -> bool:
+ """True when an agent on this computer could use memory right now
+ (fresh, stale or bootstrap grace), judged locally with no network."""
+ gate = gate_for(cred_path)
+ if gate is None:
+ return False
+ try:
+ return gate.peek().state in ("fresh", "stale", "bootstrap")
+ except Exception:
+ return False
+
+
+def ensure_fresh_token(cred_path: Path) -> str | None:
+ """Security calls (logout revoke, device revoke): when there is no usable
+ token, try one blocking /entitlement refresh first, then return whatever
+ usable token exists (possibly None: the caller proceeds without it)."""
+ tok = header_token(cred_path)
+ if tok is not None:
+ return tok
+ gate = gate_for(cred_path)
+ if gate is None:
+ return None
+ try:
+ gate.refresh(blocking=True)
+ return gate.peek_token()
+ except Exception:
+ return None
+
+
+def gate_http_line(status: int, code: str | None, *, cred_path: Path | None = None,
+ body: Any = None) -> str | None:
+ """One-line copy for the api's account-gate answers on CLI calls (5.6).
+
+ ``client_too_old`` with ``cred_path`` given and no usable token on this
+ computer (the client present) means the call went out WITHOUT a token and
+ was refused for that: the plugin is current, setup is not finished, so the
+ line is the setup one, not "update the plugin".
+
+ F-1: a 401 whose ``code`` is ``signed_out_on_claim`` gets its own
+ line, with the ``signed_out_at`` from ``body`` (the HttpError body)."""
+ if status == 0 and code == UNTRUSTED_BASE_CODE:
+ return UNTRUSTED_BASE_LINE
+ if status == 401 and code == SIGNED_OUT_ON_CLAIM:
+ return signed_out_on_claim_line(body.get("signed_out_at") if isinstance(body, dict) else None)
+ if status == 403 and code == "entitlement_invalid":
+ return ENTITLEMENT_INVALID_LINE
+ if status == 403 and code == "client_too_old":
+ if cred_path is not None and _E is not None and header_token(cred_path) is None:
+ return SETUP_INCOMPLETE_LINE
+ return CLIENT_TOO_OLD_LINE
+ return None
+
+
+def status_info(cred_path: Path, *, refresh: bool) -> dict[str, Any] | None:
+ """The gate's view for `sibyl status` / `sibyl health`. With ``refresh``,
+ one blocking refresh attempt first (the refresh IS the status check).
+ Returns the gate's token-free status dict plus ``refreshed`` (the attempt's
+ outcome status) or None when the client is unavailable."""
+ gate = gate_for(cred_path)
+ if gate is None:
+ return None
+ outcome = None
+ if refresh:
+ try:
+ outcome = gate.refresh(blocking=True)
+ except Exception:
+ outcome = None
+ info = gate.status()
+ info["refreshed"] = getattr(outcome, "status", None)
+ info["refresh_code"] = getattr(outcome, "code", None)
+ return info
+
+
+def _read_only_row(info: dict[str, Any]) -> str:
+ """R1 (plan 4.2): read-only because of the computer limit
+ (``acct.devices.over``) or, otherwise, the email."""
+ try:
+ from sibyl_memory_client.exceptions import SECURITY_URL, device_limit_info
+ d = device_limit_info(info.get("acct"))
+ except Exception:
+ d = None
+ if d is not None and d["over"]:
+ page = SECURITY_URL.split("://", 1)[-1]
+ return ("read only on this computer · more computers signed in than the plan allows: sign "
+ f"the others out at {page} (sibyl devices) or get Pro")
+ return "read only · confirm your email: sibyl email add you@example.com"
+
+
+def has_valid_pass(info: dict[str, Any] | None) -> bool:
+ """A verified, bound pass this computer may use (fresh or stale)."""
+ return bool(info) and info.get("state") in ("fresh", "stale") and isinstance(info.get("tier"), str)
+
+
+def display_tier(info: dict[str, Any] | None, saved: Any) -> Any:
+ """Shown-tier fix (2026-10-08): the tier every user-facing line shows. The current
+ verified pass's tier (as enforced: an unrecognised label is Free) when
+ there is a valid pass, else the saved credentials tier. One source per
+ screen, so two lines never show two tiers."""
+ if has_valid_pass(info):
+ return info.get("tier_effective") or info.get("tier")
+ return saved
+
+
+def peek_tier(cred_path: Path, saved: Any) -> Any:
+ """display_tier with no network (init, whoami, upgrade). With no
+ entitlement file there is no pass, so nothing is evaluated (an evaluation
+ could leave a bookkeeping-only entitlement.json behind)."""
+ try:
+ p = entitlement_path(cred_path)
+ if p.is_symlink() or not p.is_file():
+ return saved
+ info = status_info(cred_path, refresh=False)
+ except Exception:
+ info = None
+ return display_tier(info, saved)
+
+
+_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
+
+
+def _short_date(value: Any) -> str | None:
+ """'2027-10-08T12:00:00.000Z' -> '8 Oct 2027' in this computer's local
+ time, or None when the value is not an ISO timestamp."""
+ import calendar
+ import re
+ if not isinstance(value, str):
+ return None
+ m = re.match(r"^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})", value.strip())
+ if not m:
+ return None
+ try:
+ y, mo, d, hh, mi, ss = (int(x) for x in m.groups())
+ epoch = calendar.timegm((y, mo, d, hh, mi, ss, 0, 0, 0))
+ lt = time.localtime(epoch)
+ except (ValueError, OverflowError, OSError):
+ return None
+ return f"{lt.tm_mday} {_MONTHS[lt.tm_mon - 1]} {lt.tm_year}"
+
+
+def plan_row(info: dict[str, Any] | None) -> str | None:
+ """Plan-end fix (2026-10-08): the `Plan` value, 'Pro · ends 8 Oct 2027' (a
+ scheduled or completed cancellation, or a fixed term) or 'Pro · renews
+ 8 Oct 2027' (a renewing card plan), from the pass's acct.plan. None when
+ there is no valid pass or the server sent no date (older servers, free,
+ staker, Lifetime). The tier word is the same one the Tier row shows."""
+ if not has_valid_pass(info):
+ return None
+ plan = info.get("plan")
+ if not isinstance(plan, dict):
+ return None
+ try:
+ from sibyl_memory_client.tiers import display
+ word = display(display_tier(info, None))
+ except Exception: # pragma: no cover - client absent
+ word = str(display_tier(info, None) or "").capitalize()
+ for key, verb in (("ends_at", "ends"), ("renews_at", "renews")):
+ when = _short_date(plan.get(key))
+ if when:
+ return f"{word} \u00b7 {verb} {when}"
+ return None
+
+
+TIER_UNKNOWN = "tier_unknown"
+
+
+def _tier_unknown_row(info: dict[str, Any]) -> str | None:
+ """Tier convention (2026-10-05): the two ``tier_unknown`` rows, or None.
+
+ * the server answered 503 ``tier_unknown`` to the renewal: the last valid
+ token is kept and this computer keeps working on it;
+ * the signed label is not one this version recognises: treated as Free
+ until the plugin is updated."""
+ if info.get("state") not in ("fresh", "stale", "bootstrap"):
+ return None
+ if info.get("refresh_code") == TIER_UNKNOWN:
+ return f"renewal paused · access label check ({TIER_UNKNOWN}) · keep working; it retries on its own"
+ if info.get("state") == "fresh" and info.get("tier_known") is False:
+ raw = str(info.get("tier") or "")[:32]
+ return (f'active · access label "{raw}" is not recognised by this version, treated as Free '
+ f"({TIER_UNKNOWN}) · run sibyl update")
+ return None
+
+
+def _untrusted_offline(info: dict[str, Any]) -> bool:
+ """D1: the last refresh was not sent (untrusted SIBYL_API_BASE) and the
+ state is one whose copy would otherwise say "connect to the internet"."""
+ return (info.get("refresh_code") == UNTRUSTED_BASE_CODE
+ and (info.get("state") in ("stale", "bootstrap")
+ or info.get("code") in ("expired_offline", "setup_incomplete")))
+
+
+def access_row(info: dict[str, Any]) -> str:
+ """The `access` eyebrow value (spec 3.4, 8.2-8.5)."""
+ state = info.get("state")
+ code = info.get("code")
+ tier_row = _tier_unknown_row(info)
+ if tier_row is not None:
+ return tier_row
+ if _untrusted_offline(info):
+ return "not checked · " + UNTRUSTED_BASE_LINE
+ if state == "fresh":
+ secs = info.get("renews_in_seconds") or 0
+ hours = max(0, int(round(secs / 3600)))
+ if info.get("mem") == "read_only":
+ # Reads work, writes are refused (policy_read_only): say why.
+ return _read_only_row(info) + f" · re-checks in {hours}h"
+ # Plan-end fix (2026-10-08): this is the pass re-check, not a billing renewal
+ # (the billing date is the Plan row).
+ return f"active · re-checks in {hours}h"
+ if state in ("stale", "bootstrap"):
+ left = info.get("grace_left_seconds") or 0
+ days = max(0, int(-(-left // 86400)))
+ return f"offline · {days} days of grace left · connect once to renew"
+ if state == "no_account":
+ return "signed out · run sibyl init"
+ if code == "policy_read_only":
+ return _read_only_row(info)
+ if code == "signed_out" and info.get("cause") == SIGNED_OUT_ON_CLAIM:
+ return signed_out_on_claim_line(info.get("signed_out_at"))
+ return {
+ "expired_offline": "paused · offline too long · connect to the internet, or run sibyl init",
+ "setup_incomplete": "setup not finished · connect to the internet once to finish setup",
+ "signed_out": "signed out · run sibyl init",
+ "under_review": "under review · email sibyl@sibyllabs.org",
+ "account_deleted": "account deleted · run sibyl init",
+ "invalid_entitlement": "sign-in file damaged · run sibyl init",
+ "wrong_device": "sign-in file damaged · run sibyl init",
+ "client_too_old": "update needed · " + CLIENT_TOO_OLD_LINE,
+ "policy_read_only": "read only · confirm your email: sibyl email add you@example.com",
+ "policy_none": "paused · confirm your email: sibyl email add you@example.com",
+ }.get(code or "", "signed out · run sibyl init")
+
+
+def _devices_over(info: dict[str, Any]) -> bool:
+ try:
+ from sibyl_memory_client.exceptions import device_limit_info
+ d = device_limit_info(info.get("acct"))
+ except Exception:
+ d = None
+ return d is not None and d["over"]
+
+
+def code_handoff(code: str | None) -> tuple[str, str | None]:
+ """(next, human) for an entitlement code (client table rows C1 to C11)."""
+ try:
+ from sibyl_memory_client.exceptions import ENTITLEMENT_HUMAN_ACTION, ENTITLEMENT_NEXT
+ except Exception: # pragma: no cover - client absent or pre-0.9.0
+ return ("sibyl init", None)
+ code = code if code in ENTITLEMENT_NEXT else "invalid_entitlement"
+ return ENTITLEMENT_NEXT[code], ENTITLEMENT_HUMAN_ACTION[code]
+
+
+def _read_only_handoff(info: dict[str, Any]) -> tuple[str, str | None]:
+ if _devices_over(info):
+ try:
+ from sibyl_memory_client.exceptions import (DEVICES_READ_ONLY_HUMAN_ACTION,
+ DEVICES_READ_ONLY_NEXT)
+ return DEVICES_READ_ONLY_NEXT, DEVICES_READ_ONLY_HUMAN_ACTION
+ except Exception: # pragma: no cover
+ return "sibyl devices", None
+ return code_handoff("policy_read_only")
+
+
+def access_handoff(info: dict[str, Any] | None) -> tuple[str, str | None]:
+ """The agent handoff for an access state (spec 2026-10-03 section 1.7):
+ (next, human). Kept beside ``access_row`` so status, refresh, health and
+ the gate lines agree (rows S3 to S8, R3, R4, H3c)."""
+ if not info:
+ return ("sibyl init", None)
+ state = info.get("state")
+ code = info.get("code")
+ if _untrusted_offline(info):
+ return untrusted_base_handoff()
+ if state in ("fresh", "stale", "bootstrap"):
+ if info.get("refresh_code") == TIER_UNKNOWN:
+ return ("done", None)
+ if state == "fresh" and info.get("tier_known") is False:
+ return ("sibyl update", None)
+ if state == "fresh":
+ if info.get("mem") == "read_only":
+ return _read_only_handoff(info)
+ return ("done", None)
+ if state in ("stale", "bootstrap"):
+ left = info.get("grace_left_seconds") or 0
+ days = max(0, int(-(-left // 86400)))
+ return ("sibyl refresh",
+ f"connect this computer to the internet once; memory keeps working {days} more days")
+ if state == "no_account":
+ return code_handoff("no_account")
+ if code == "policy_read_only":
+ return _read_only_handoff(info)
+ if code == "signed_out" and info.get("cause") == SIGNED_OUT_ON_CLAIM:
+ return (SIGNED_OUT_ON_CLAIM_NEXT, None)
+ return code_handoff(code or "signed_out")
+
+
+def gate_http_handoff(status: int, code: str | None, *, cred_path: Path | None = None,
+ body: Any = None) -> tuple[str, str | None] | None:
+ """The handoff for the api's 403 gate answers (rows E23, K3, V4): the same
+ branch choice as ``gate_http_line``."""
+ line = gate_http_line(status, code, cred_path=cred_path, body=body)
+ if line is None:
+ return None
+ if line == UNTRUSTED_BASE_LINE:
+ return untrusted_base_handoff()
+ if status == 401 and code == SIGNED_OUT_ON_CLAIM:
+ return (SIGNED_OUT_ON_CLAIM_NEXT, None)
+ if line == ENTITLEMENT_INVALID_LINE:
+ return code_handoff("invalid_entitlement")
+ if line == SETUP_INCOMPLETE_LINE:
+ return code_handoff("setup_incomplete")
+ return code_handoff("client_too_old")
+
+
+ADOPT_HINT = "run sibyl memory adopt to move them into your account"
+
+
+def _creds_tenant(cred_path: Path) -> str | None:
+ import json
+ try:
+ p = Path(cred_path).expanduser()
+ if p.is_symlink() or not p.is_file():
+ return None
+ raw = json.loads(p.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ if not isinstance(raw, dict):
+ return None
+ return (raw.get("tenant_id") or "") or (raw.get("account_id") or "") or None
+
+
+def adopt_pre_signin(db_path: Path, cred_path: Path, *, trigger: str,
+ confirm_other_accounts: bool = False):
+ """Move the rows written before sign-in (DEFAULT_TENANT) of ``db_path``
+ into the signed-in account's tenant (client ``_adopt``): one local
+ transaction, never deletes, no network of its own. Requires a verified
+ entitlement for the credentials at ``cred_path`` (``gate.require`` may do
+ the one blocking refresh a device without a token needs). Raises
+ ``EntitlementError`` when there is no verified sign-in and
+ ``_adopt.AdoptionRefused`` when the move is not allowed. Returns the
+ ``AdoptionResult``, or None when there is no store."""
+ from sibyl_memory_client import _adopt
+ from sibyl_memory_client.storage import Storage
+ db_path = Path(db_path).expanduser()
+ if not db_path.exists():
+ return None
+ gate = gate_for(cred_path)
+ ent = gate.require("adopt")
+ tenant = _creds_tenant(cred_path)
+ if ent is None or tenant is None:
+ raise _adopt.AdoptionRefused("not_verified",
+ "No verified sign-in on this computer. Run sibyl init first.")
+ storage = Storage(db_path)
+ try:
+ return _adopt.adopt_default_tenant(storage, tenant, ent, trigger=trigger,
+ confirm_other_accounts=confirm_other_accounts)
+ finally:
+ storage.close()
+
+
+def pinned_kids() -> list[str]:
+ if _E is None:
+ return []
+ try:
+ return sorted(_E.TRUSTED_KEYS)
+ except Exception:
+ return []
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/_aesthetic.py b/sibyl-memory-cli/src/sibyl_memory_cli/_aesthetic.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f35e19a6f52a9cdc45c9a36b784d7caab3e4371
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/_aesthetic.py
@@ -0,0 +1,251 @@
+"""Shared visual identity for the sibyl CLI surface.
+
+Sister module to `_banner.py`. Where the banner is the identity-reveal
+moment for `sibyl init`, this module supplies the granular building
+blocks every subcommand uses to share one coherent look:
+
+ - 24-bit-truecolor → 256-color → plain-text degradation cascade
+ - Brand palette derived from the lab creme paper face (rule 46)
+ - Letter-spaced eyebrow labels, gradient titles, ASCII rule dividers
+ - Key/value rows, status chips, success/warn/error glyphs
+ - Pulsing accents for live states (activation, upgrade, watching)
+
+Voice constraint: precise, editorial, restrained. Gradients flow over
+2–3 stops max. No rainbow. The terminal is paper.
+"""
+from __future__ import annotations
+
+import os
+import sys
+
+# ─── Palette (RGB · derived from rule 46 creme-paper tokens) ─────────
+# Names map 1:1 to CSS custom properties on lab artifacts.
+
+PAPER = (245, 241, 230) # --paper — foreground accent on dark
+PAPER_DEEP = (237, 230, 211) # --paper-deep — depth on creme
+CARD = (253, 251, 245) # --card — slightly lifted creme
+INK = (21, 17, 10) # --ink — main text on creme
+INK_SOFT = (44, 39, 29) # --ink-soft — body text
+INK_MUTE = (106, 99, 86) # --ink-mute — secondary text
+INK_FAINT = (152, 145, 127) # --ink-faint — tertiary text
+RULE = (216, 208, 187) # --rule — hairline
+RULE_STRONG = (184, 174, 147) # --rule-strong — emphasised hairline
+ACCENT = (138, 106, 42) # --accent — ochre highlight
+ACCENT_WARM = (160, 132, 56) # --accent-warm — softer ochre
+ACCENT_GOLD = (224, 194, 119) # mid gold — gradient bridge
+ACCENT_PALE = (244, 229, 184) # pale gold — gradient top
+JADE = (45, 110, 106) # --jade — cool counterpoint
+PULSE = (29, 138, 130) # --pulse — brighter jade (live signal)
+ERROR = (162, 58, 42) # --error — measured red
+
+# Status glyphs (Unicode, terminal-safe in modern fonts)
+GLYPH_OK = "✓"
+GLYPH_WARN = "⚠"
+GLYPH_ERR = "✗"
+GLYPH_DOT = "·"
+GLYPH_ARROW = "→"
+GLYPH_BULLET = "▸"
+
+
+# ─── Terminal capability detection ────────────────────────────────────
+
+def supports_truecolor() -> bool:
+ """24-bit RGB ANSI. Same heuristic as _banner.py."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("TERM", "").lower() == "dumb":
+ return False
+ # SIBYL_FORCE_COLOR=1 — explicit override for non-tty rendering
+ # (CI logs, doc captures, dev inspection inside the Claude harness).
+ if os.environ.get("SIBYL_FORCE_COLOR") == "1":
+ return True
+ if not sys.stdout.isatty():
+ return False
+ colorterm = os.environ.get("COLORTERM", "").lower()
+ if "truecolor" in colorterm or "24bit" in colorterm:
+ return True
+ term_program = os.environ.get("TERM_PROGRAM", "").lower()
+ if term_program in {"iterm.app", "wezterm", "ghostty", "vscode", "tabby"}:
+ return True
+ term = os.environ.get("TERM", "").lower()
+ if any(k in term for k in ("256color", "kitty", "alacritty", "xterm-direct")):
+ return True
+ return False
+
+
+def supports_color() -> bool:
+ """Any color at all (3/4-bit fallback)."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("TERM", "").lower() == "dumb":
+ return False
+ if os.environ.get("SIBYL_FORCE_COLOR") == "1":
+ return True
+ return sys.stdout.isatty()
+
+
+_TC = supports_truecolor()
+_C = supports_color()
+RESET = "\033[0m" if _C else ""
+
+
+def rgb(r: int, g: int, b: int) -> str:
+ """24-bit foreground escape (no-op if color disabled)."""
+ if not _TC:
+ return ""
+ return f"\033[38;2;{r};{g};{b}m"
+
+
+def color(text: str, c: tuple[int, int, int]) -> str:
+ if not _TC:
+ return text
+ return f"{rgb(*c)}{text}{RESET}"
+
+
+# ─── Gradient · char-by-char RGB interpolation ────────────────────────
+
+def _interp(a: int, b: int, t: float) -> int:
+ return round(a + (b - a) * t)
+
+
+def gradient(text: str, *stops: tuple[int, int, int]) -> str:
+ """Color a string with a gradient across N stops, one char at a time.
+
+ Plain-text fallback: returns the input unchanged when color is off.
+ Whitespace is preserved (uncolored to keep terminals consistent).
+ """
+ if not _TC or len(stops) < 2 or not text:
+ return text
+ out = []
+ chars = list(text)
+ # Distribute char index across stop segments
+ n = max(1, len(chars) - 1)
+ segs = len(stops) - 1
+ for i, ch in enumerate(chars):
+ if ch == " ":
+ out.append(ch)
+ continue
+ seg_f = (i / n) * segs
+ seg_i = min(int(seg_f), segs - 1)
+ t = seg_f - seg_i
+ a = stops[seg_i]
+ b = stops[seg_i + 1]
+ r = _interp(a[0], b[0], t)
+ g = _interp(a[1], b[1], t)
+ bb = _interp(a[2], b[2], t)
+ out.append(f"\033[38;2;{r};{g};{bb}m{ch}")
+ return "".join(out) + RESET
+
+
+def gradient_gold(text: str) -> str:
+ """Pale-gold → deep-ochre flow. The brand's headline gradient."""
+ return gradient(text, ACCENT_PALE, ACCENT_GOLD, ACCENT)
+
+
+def gradient_jade(text: str) -> str:
+ """Pulse → jade. Used for success states + live indicators."""
+ return gradient(text, PULSE, JADE)
+
+
+# ─── Style primitives ─────────────────────────────────────────────────
+
+def dim(s: str) -> str:
+ return color(s, INK_FAINT)
+
+
+def muted(s: str) -> str:
+ return color(s, INK_MUTE)
+
+
+def soft(s: str) -> str:
+ return color(s, INK_SOFT)
+
+
+def ink(s: str) -> str:
+ return color(s, INK)
+
+
+def ok(s: str) -> str:
+ return color(s, PULSE)
+
+
+def warn(s: str) -> str:
+ return color(s, ACCENT_WARM)
+
+
+def err(s: str) -> str:
+ return color(s, ERROR)
+
+
+def accent(s: str) -> str:
+ return color(s, ACCENT)
+
+
+def bold(s: str) -> str:
+ if not _C:
+ return s
+ return f"\033[1m{s}{RESET}"
+
+
+# ─── Composite primitives ─────────────────────────────────────────────
+
+def eyebrow(label: str) -> str:
+ """Uppercase letter-spaced ochre label. Editorial section marker."""
+ spaced = " ".join(label.upper())
+ return color(spaced, ACCENT)
+
+
+def section_header(name: str, *, subtitle: str | None = None, width: int = 60) -> str:
+ """The standard subcommand opener.
+
+ ─ ────────────────────────────────────────
+
+ """
+ name_part = f" {gradient_gold(name)} "
+ # Stripped-color length for visible width calc
+ visible_name_len = len(f" {name} ")
+ rule_left = "─"
+ rule_right = "─" * max(3, width - 1 - visible_name_len)
+ head = color(rule_left, RULE) + name_part + color(rule_right, RULE)
+ if subtitle:
+ return head + "\n" + dim(subtitle)
+ return head
+
+
+def chip(text: str, *, palette: str = "accent") -> str:
+ """Compact inline label · [text]."""
+ palettes = {
+ "accent": ACCENT,
+ "jade": PULSE,
+ "warn": ACCENT_WARM,
+ "error": ERROR,
+ "mute": INK_MUTE,
+ }
+ c = palettes.get(palette, ACCENT)
+ return color(f"[{text}]", c)
+
+
+def kv(label: str, value: str, *, label_width: int = 16, value_color: str = "ink") -> str:
+ """One left-aligned label / value row.
+
+ Used across status / whoami / devices for the LOCAL / SERVER blocks.
+ """
+ palettes = {
+ "ink": INK, "soft": INK_SOFT, "mute": INK_MUTE, "faint": INK_FAINT,
+ "accent": ACCENT, "ok": PULSE, "warn": ACCENT_WARM, "err": ERROR,
+ }
+ val_color = palettes.get(value_color, INK_SOFT)
+ return f" {color(label.ljust(label_width), INK_FAINT)} {color(value, val_color)}"
+
+
+def success_line(text: str) -> str:
+ """Single-line success marker with gradient + glyph."""
+ return f" {ok(GLYPH_OK)} {gradient_jade(text)}"
+
+
+def warn_line(text: str) -> str:
+ return f" {warn(GLYPH_WARN)} {warn(text)}"
+
+
+def err_line(text: str) -> str:
+ return f" {err(GLYPH_ERR)} {err(text)}"
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/_banner.py b/sibyl-memory-cli/src/sibyl_memory_cli/_banner.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8211d4c00d77902ea5b443186577db8ae3d3577
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/_banner.py
@@ -0,0 +1,114 @@
+"""ASCII banner for sibyl-memory-cli.
+
+Prints the SIBYL wordmark in ANSI Shadow boxchars with a 24-bit truecolor
+vertical gradient flowing from cream/white at the top through warm gold
+to deep ochre at the bottom — aligned with the lab visual identity per
+the operator's brand-discipline rule (creme palette, deep-ochre accent).
+
+Gracefully degrades:
+ - NO_COLOR env var set → plain text fallback
+ - stdout is not a TTY → plain text fallback (or skip entirely)
+ - TERM=dumb → plain text fallback
+
+Truecolor support is detected via $COLORTERM (truecolor / 24bit) — most
+modern terminals (iTerm2, Alacritty, Kitty, wezterm, Windows Terminal,
+modern xterm builds, Ghostty) advertise it. Falls back to 256-color
+gradient when not available.
+"""
+from __future__ import annotations
+
+import os
+import sys
+
+# ANSI Shadow rendering of "SIBYL" — 6 rows, 41 cols. Each row gets its
+# own gradient color (top = pale cream/white, bottom = deep ochre).
+_LINES = (
+ "███████╗██╗██████╗ ██╗ ██╗██╗ ",
+ "██╔════╝██║██╔══██╗╚██╗ ██╔╝██║ ",
+ "███████╗██║██████╔╝ ╚████╔╝ ██║ ",
+ "╚════██║██║██╔══██╗ ╚██╔╝ ██║ ",
+ "███████║██║██████╔╝ ██║ ███████╗",
+ "╚══════╝╚═╝╚═════╝ ╚═╝ ╚══════╝",
+)
+
+# Vertical gradient · cream → gold → deep ochre. One RGB tuple per row.
+# Tuned against the SIBYL palette: --paper #f5f1e6 (top blend),
+# --accent #8a6a2a (mid-bottom), with extra highlight + shadow stops
+# to give the wordmark visible dimension.
+_GRADIENT = (
+ (253, 251, 245), # almost white, slight cream (top highlight)
+ (244, 229, 184), # pale gold (upper)
+ (224, 194, 119), # mid gold (upper-mid)
+ (184, 146, 73), # rich ochre gold (mid)
+ (138, 106, 42), # deep ochre · brand --accent (lower)
+ (106, 79, 31), # deepest (bottom shadow)
+)
+
+_TAGLINE = "memory you can hold in your hand"
+_ATTRIBUTION = "a Sibyl Labs LLC Product. Agentic Infrastructure and Memory Products"
+
+
+def _supports_truecolor() -> bool:
+ """Detect 24-bit color support. Conservative — fall back gracefully."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("TERM", "").lower() == "dumb":
+ return False
+ if not sys.stdout.isatty():
+ return False
+ colorterm = os.environ.get("COLORTERM", "").lower()
+ if "truecolor" in colorterm or "24bit" in colorterm:
+ return True
+ # Many modern terminals don't set COLORTERM but do support truecolor.
+ # Recognize the well-behaved emitters.
+ term_program = os.environ.get("TERM_PROGRAM", "").lower()
+ if term_program in {"iterm.app", "wezterm", "ghostty", "vscode", "tabby"}:
+ return True
+ term = os.environ.get("TERM", "").lower()
+ if any(k in term for k in ("256color", "kitty", "alacritty", "xterm-direct")):
+ return True
+ return False
+
+
+def _rgb(r: int, g: int, b: int) -> str:
+ return f"\033[38;2;{r};{g};{b}m"
+
+
+_RESET = "\033[0m"
+
+
+def render_banner(*, force_color: bool | None = None) -> str:
+ """Return the banner as a string ready to print.
+
+ Args:
+ force_color: Override auto-detection. None = auto, True = force
+ truecolor, False = force plain text. Useful for testing.
+ """
+ use_truecolor = force_color if force_color is not None else _supports_truecolor()
+
+ if not use_truecolor:
+ # Plain text — still visually clean, just no color.
+ body = "\n".join(" " + line for line in _LINES)
+ tagline = f"\n {_TAGLINE}"
+ attribution = f"\n {_ATTRIBUTION}\n"
+ return body + tagline + attribution
+
+ # Colored — apply per-row gradient.
+ colored_lines = []
+ for line, (r, g, b) in zip(_LINES, _GRADIENT):
+ colored_lines.append(f" {_rgb(r, g, b)}{line}{_RESET}")
+
+ body = "\n".join(colored_lines)
+ # Tagline in the deepest gold — present, but not competing with the wordmark.
+ r, g, b = _GRADIENT[-1]
+ tagline = f"\n {_rgb(r, g, b)}{_TAGLINE}{_RESET}"
+ # Attribution dimmer still — a half-step below the tagline so the hierarchy
+ # reads SIBYL > tagline > attribution at a glance. ANSI dim (\033[2m) gives
+ # ~55% perceived opacity across the supported terminals.
+ attribution = f"\n \033[2m{_rgb(r, g, b)}{_ATTRIBUTION}{_RESET}\n"
+ return body + tagline + attribution
+
+
+def print_banner(*, force_color: bool | None = None) -> None:
+ """Print the banner. Safe to call unconditionally; honors NO_COLOR + TTY checks."""
+ print(render_banner(force_color=force_color))
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/_entry.py b/sibyl-memory-cli/src/sibyl_memory_cli/_entry.py
new file mode 100644
index 0000000000000000000000000000000000000000..8af55fdd3b88151e027d1484d1665b4170fadabd
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/_entry.py
@@ -0,0 +1,26 @@
+"""The `sibyl` console script (0.5.0).
+
+`sibyl hook ` is what Claude Code runs at every session start, prompt,
+turn end, compaction and session end, under a 5 s timeout. It goes straight to
+``hooks.main_hook`` (standard library only until a hook actually needs the
+client) instead of importing the whole CLI first. Every other command is the
+unchanged ``cli.main``.
+"""
+from __future__ import annotations
+
+import sys
+
+_HOOK_EVENTS = ("session-start", "prompt", "stop", "pre-compact", "session-end")
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = sys.argv[1:] if argv is None else list(argv)
+ if len(args) == 2 and args[0] == "hook" and args[1] in _HOOK_EVENTS:
+ from .hooks import main_hook
+ return main_hook(args[1])
+ from .cli import main as cli_main
+ return cli_main(argv)
+
+
+if __name__ == "__main__": # pragma: no cover
+ sys.exit(main())
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/_handoff.py b/sibyl-memory-cli/src/sibyl_memory_cli/_handoff.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ccdc5f4646e8f0f89239b054c2f761b0a4acd14
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/_handoff.py
@@ -0,0 +1,75 @@
+"""Agent handoff block (spec agent-handoff-messages 2026-10-03, section 1).
+
+Every stop of a ``sibyl`` command ends with this block, printed to stdout in
+both interactive and non-interactive runs, after the status line:
+
+ later: zero or more; optional follow-ups
+ ask your human: zero or one; only when a person must act
+ next: exactly one; always the last line
+
+A wait (the process is still running and watching) prints, once, when the
+watching starts:
+
+ ask your human:
+ waiting: (up to )
+
+Plain text at column 0: lowercase key, one colon, one space, no glyph, no
+colour, no indentation, even on a TTY. ``next`` is a shell command, ``done``,
+``retry`` or ``retry in minutes``. Placeholders (````,
+````, ````, ````, ````) appear only when the
+``ask your human:`` line names them.
+
+With ``--json`` the block is never printed; ``json_handoff`` adds the same two
+values to the document as ``next`` and ``human_action``.
+"""
+from __future__ import annotations
+
+from typing import Any, Iterable
+
+DONE = "done"
+RETRY = "retry"
+
+
+def retry_in(minutes: Any) -> str:
+ return f"retry in {minutes} minutes"
+
+
+def block(next: str, *, human: str | None = None, later: Iterable[str] = ()) -> str:
+ lines = [f"later: {c}" for c in later if c]
+ if human:
+ lines.append(f"ask your human: {human}")
+ lines.append(f"next: {next}")
+ return "\n".join(lines)
+
+
+def handoff(next: str, *, human: str | None = None, later: Iterable[str] = ()) -> None:
+ """Print the handoff block (the last thing a stopping command prints)."""
+ print(block(next, human=human, later=later), flush=True)
+
+
+def waiting(what: str, seconds: Any, *, human: str | None = None) -> None:
+ """Print the wait lines once, when the watching starts."""
+ try:
+ secs = max(0, int(seconds))
+ except (TypeError, ValueError):
+ secs = 0
+ if human:
+ print(f"ask your human: {human}", flush=True)
+ print(f"waiting: {what} (up to {secs // 60}:{secs % 60:02d})", flush=True)
+
+
+def json_handoff(payload: dict, next: str, human: str | None = None) -> dict:
+ """Add the two handoff keys to a ``--json`` document."""
+ payload["next"] = next
+ payload["human_action"] = human
+ return payload
+
+
+def from_exception(e: BaseException, *, default: str = "sibyl status") -> tuple[str, str | None]:
+ """(next, human) carried by a client exception (rows C1 to C17), or the
+ default when the exception predates the convention."""
+ nxt = getattr(e, "next", None)
+ if not isinstance(nxt, str) or not nxt:
+ return default, None
+ human = getattr(e, "human_action", None)
+ return nxt, human if isinstance(human, str) and human else None
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/_timefmt.py b/sibyl-memory-cli/src/sibyl_memory_cli/_timefmt.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e6257c7d28830cb94ed01d7c33b969c7c632381
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/_timefmt.py
@@ -0,0 +1,61 @@
+"""Times shown to people: always with a zone.
+
+Every clock time the CLI prints is UTC and says so: ``2026-10-09 19:08 UTC``.
+A bare ``2026-10-09 19:08:12`` read as local time by one person and as server
+time by another; the zone removes the guess. Stdlib only.
+"""
+from __future__ import annotations
+
+import calendar
+import re
+import time
+from typing import Any
+
+_ISO_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?"
+ r"(Z|[+-]\d{2}:?\d{2})?$")
+
+
+def _epoch_of(value: Any) -> float | None:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, (int, float)):
+ return float(value)
+ if not isinstance(value, str) or len(value) > 40:
+ return None
+ m = _ISO_RE.match(value.strip())
+ if not m:
+ return None
+ try:
+ y, mo, d, hh, mi = (int(m.group(i)) for i in range(1, 6))
+ epoch = calendar.timegm((y, mo, d, hh, mi, int(m.group(6) or 0), 0, 0, 0))
+ except (ValueError, OverflowError):
+ return None
+ off = m.group(7)
+ if off and off != "Z":
+ sign = -1 if off[0] == "-" else 1
+ digits = off[1:].replace(":", "")
+ epoch -= sign * (int(digits[:2]) * 3600 + int(digits[2:]) * 60)
+ return float(epoch)
+
+
+def utc_minute(value: Any) -> str | None:
+ """Epoch seconds or an ISO-8601 string (no offset = UTC) ->
+ ``'2026-10-09 19:08 UTC'``; None when ``value`` is neither."""
+ epoch = _epoch_of(value)
+ if epoch is None:
+ return None
+ try:
+ return time.strftime("%Y-%m-%d %H:%M", time.gmtime(epoch)) + " UTC"
+ except (ValueError, OverflowError, OSError):
+ return None
+
+
+def utc_hm(value: Any) -> str | None:
+ """Epoch seconds -> ``'19:08 UTC'`` (a time of day, for today's rows)."""
+ epoch = _epoch_of(value)
+ if epoch is None:
+ return None
+ try:
+ return time.strftime("%H:%M", time.gmtime(epoch)) + " UTC"
+ except (ValueError, OverflowError, OSError):
+ return None
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/cli.py b/sibyl-memory-cli/src/sibyl_memory_cli/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..676217c8622fe69521a8c4c2f6442c16d95055b9
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/cli.py
@@ -0,0 +1,3759 @@
+"""`sibyl` command-line interface.
+
+A wrapper around HTTP calls to https://api.sibyllabs.org/api/plugin/* (plus
+pypi.org for `sibyl update`) and the local Sibyl Memory store.
+
+Design pillars:
+ - HTTP is stdlib urllib. The package depends on sibyl-memory-client,
+ sibyl-memory-hermes and pyyaml; some client imports stay lazy (the
+ `sibyl hook` fast path, and `sibyl update` / `sibyl setup`, which must
+ still run on a half-upgraded install).
+ - Credentials are written atomically at mode 0600: a mkstemp temp file
+ (created O_CREAT|O_EXCL) is fchmod'ed to 0600 before any byte is written,
+ fsynced, then renamed over the target.
+ - The URL handed to the browser is an opaque session identifier, never the
+ long-lived bearer (audit SEC-1).
+ - session_token is never printed in full: display a short slice only.
+ - Polling has explicit timeouts; no infinite loops.
+ - Exit codes are per command; see each `cmd_*` docstring.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import platform as _platform
+import re
+import secrets
+import ssl
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import uuid
+import webbrowser
+from pathlib import Path
+from typing import Any
+
+
+from ._timefmt import utc_minute as _utc_minute # times carry a zone
+
+
+def _client_version() -> str:
+ """Return the installed package version from metadata, never hardcoded."""
+ try:
+ from importlib.metadata import PackageNotFoundError, version as _v
+ try:
+ return _v("sibyl-memory-cli")
+ except PackageNotFoundError:
+ return "0.0.0+source"
+ except Exception:
+ return "0.0.0+source"
+
+# ---- Defaults ----------------------------------------------------------
+
+API_BASE = os.environ.get("SIBYL_API_BASE", "https://api.sibyllabs.org")
+# Dedicated short-URL auth subdomain (2026-05-20). Trust + phishing resistance:
+# the URL the user sees in their terminal + browser is purpose-specific and
+# short enough to read at a glance. Legacy URL `sibyllabs.org/plugin/activate
+# ?session=` still resolves so older CLI installs continue to work.
+ACTIVATE_BASE = os.environ.get("SIBYL_ACTIVATE_BASE", "https://auth.sibyllabs.org")
+UPGRADE_BASE = os.environ.get("SIBYL_UPGRADE_BASE", "https://sibyllabs.org/plugin/upgrade")
+# The account page (0.5.0). Every URL the CLI prints or opens on this origin is
+# checked against it first, so a server string can never steer the browser
+# somewhere else. Never carries a token.
+ACCOUNT_BASE = os.environ.get("SIBYL_ACCOUNT_BASE", "https://account.sibyllabs.org").rstrip("/")
+# The account origin as people read it in copy (no scheme), and its security page.
+ACCOUNT_HOST = ACCOUNT_BASE.split("://", 1)[-1]
+ACCOUNT_SECURITY_PAGE = f"{ACCOUNT_HOST}/security"
+# Where a card purchase lands; the checkout code for `sibyl claim` is shown there.
+CLAIM_PAGE = "sibyllabs.org/pro/welcome"
+
+DEFAULT_CRED_PATH = Path("~/.sibyl-memory/credentials.json").expanduser()
+DEFAULT_DB_PATH = Path("~/.sibyl-memory/memory.db").expanduser()
+DEFAULT_TIER_CACHE_PATH = Path("~/.sibyl-memory/tier_cache.json").expanduser()
+
+POLL_INTERVAL_SEC = 3
+# v0.3.5 fix: the CLI no longer carries its own activation deadline. The
+# server's /session-init response includes pairing_ttl_seconds — the CLI
+# polls until that timestamp, deferring to the server as the single source
+# of truth. The constants below are fallbacks only, used when session-init
+# fails to return a value (network error, schema drift). Drift between CLI
+# and server is now impossible by construction; the prior 10min/15min
+# silent-success gap can't recur because there is no CLI-side number to
+# diverge from the server's.
+INIT_TIMEOUT_FALLBACK_SEC = 30 * 60 # used only if session-init returns no TTL
+UPGRADE_TIMEOUT_SEC = 30 * 60 # upgrade flow uses local constant — no server handshake to defer to
+
+# ---- Color / output ----------------------------------------------------
+
+from . import _aesthetic as a
+from . import _account_gate as _gate
+from . import _handoff as _h
+
+# The credentials path of the running command (root --credentials). The
+# X-Sibyl-Entitlement header reads the entitlement.json beside it (0.5.0,
+# spec account-gated 5.6). Set in main(); defaults to the standard location.
+_ENT_CRED_PATH: Path = DEFAULT_CRED_PATH
+# Set by read_credentials when credentials.json is corrupt (row I19): the
+# command's handoff then ends `next: sibyl init --force`.
+_CREDS_CORRUPT = False
+
+
+def _init_next() -> str:
+ """`sibyl init`, or `sibyl init --force` when credentials.json is corrupt."""
+ return "sibyl init --force" if _CREDS_CORRUPT else "sibyl init"
+
+
+# Agent handoff sentences (spec agent-handoff-messages 2026-10-03, section 3).
+WINDOWS_HUMAN = ("install Sibyl Memory inside WSL2 and run sibyl init there; native Windows "
+ "is not supported")
+EMAIL_ADDRESS_HUMAN = "an email address for the account (receipts, security notices, purchases)"
+OFFLINE_HUMAN = "connect this computer to the internet"
+
+
+def _code_human(masked: Any, mins: Any = None) -> str:
+ valid = f" (valid {mins} minutes)" if mins else ""
+ return f"check {masked or 'your inbox'} for a six digit code from Sibyl Labs{valid} and tell me the code"
+
+
+def _verify_human(masked: Any) -> str:
+ return f"the six digit code we will email to {masked or 'the address on file'} in the next step"
+
+
+def _email_web_human() -> str:
+ """Row E11: the browser step, when the api does not take email
+ confirmation from the terminal (``features.cli_email_verify`` not true)."""
+ return (f"add and confirm your email at {ACCOUNT_BASE} (sign in with the email or wallet "
+ "used here)")
+
+_NO_COLOR = bool(os.environ.get("NO_COLOR")) or not sys.stdout.isatty()
+
+
+def c(code: str, s: str) -> str:
+ if _NO_COLOR:
+ return s
+ return f"\033[{code}m{s}\033[0m"
+
+
+def dim(s: str) -> str: return c("2", s)
+def bold(s: str) -> str: return c("1", s)
+def green(s: str) -> str: return c("32", s)
+def yellow(s: str) -> str: return c("33", s)
+def red(s: str) -> str: return c("31", s)
+def cyan(s: str) -> str: return c("36", s)
+
+
+def _detect_os_family() -> str | None:
+ p = sys.platform
+ if p == "darwin": return "macos"
+ if p.startswith("linux"): return "linux"
+ if p.startswith("win"): return "windows"
+ return None
+
+
+# ---- platform support policy (2026-09-04) ------------------------------
+#
+# Sibyl Memory runs on Linux, macOS (Apple Silicon and Intel), and Windows
+# through WSL2. Native Windows is not supported. WSL2 is Linux to Python and
+# to us, so it needs no special case beyond the label.
+#
+# "block" refuses `sibyl init` and `sibyl setup` on native Windows. Every
+# other command keeps working on machines that already activated there, so an
+# existing install never loses `status`, `upgrade`, `claim`, `devices`,
+# `logout`, `health`, `memory` or `update`.
+NATIVE_WINDOWS_POLICY = "block"
+NATIVE_WINDOWS_ESCAPE_ENV = "SIBYL_ALLOW_NATIVE_WINDOWS"
+WSL_DOCS_URL = "https://docs.sibyllabs.org/memory/install#windows"
+
+
+def _platform_info() -> tuple[str, str, bool]:
+ """(os_family, human label, supported). WSL2 is Linux to Python and to us.
+
+ The os_family element is deliberately the same vocabulary
+ `_detect_os_family()` returns (`linux|macos|windows`), because telemetry
+ consumers key on it. `unknown` is the one value that function reports as
+ None instead.
+ """
+ p = sys.platform
+ arch = _platform.machine() or "unknown"
+ if p == "darwin":
+ ver = _platform.mac_ver()[0] or ""
+ return "macos", f"macOS {ver} ({arch})".replace(" ", " "), True
+ if p.startswith("linux"):
+ rel = _platform.release().lower()
+ wsl = "microsoft" in rel or bool(os.environ.get("WSL_DISTRO_NAME"))
+ return "linux", ("Linux, WSL2" if wsl else "Linux") + f" ({arch})", True
+ if p.startswith("win"):
+ return "windows", f"Windows {_platform.release()} native ({arch})", False
+ return "unknown", p, False
+
+
+def _is_wsl() -> bool:
+ if not sys.platform.startswith("linux"):
+ return False
+ return "microsoft" in _platform.release().lower() or bool(os.environ.get("WSL_DISTRO_NAME"))
+
+
+def _native_windows_override() -> bool:
+ """True when the user has explicitly opted into the unsupported path."""
+ v = (os.environ.get(NATIVE_WINDOWS_ESCAPE_ENV) or "").strip().lower()
+ return v not in ("", "0", "false", "no", "off")
+
+
+def print_platform_line(*, gate: bool = False) -> int:
+ """Print the platform line. Returns 0 to continue, 1 to refuse.
+
+ `gate=True` is passed by `sibyl init` and `sibyl setup` only. Those are the
+ two commands that stand up a NEW install, and they are the only two the
+ native-Windows block applies to.
+ """
+ family, label, supported = _platform_info()
+ if supported:
+ print(dim(f" platform {label} \u00b7 supported"))
+ return 0
+
+ blocked = (
+ gate
+ and family == "windows"
+ and NATIVE_WINDOWS_POLICY == "block"
+ and not _native_windows_override()
+ )
+ paint = red if blocked else yellow
+ print(paint(f" platform {label} \u00b7 not supported"))
+
+ if family != "windows":
+ print(yellow(" Sibyl Memory is built and tested on Linux and macOS. This platform is"))
+ print(yellow(" neither, so nothing here is tested or fixed. Continuing anyway."))
+ return 0
+
+ if blocked:
+ print(red(" Sibyl Memory is not supported on native Windows. Install it inside WSL2 and"))
+ print(red(f" run this command again there: {WSL_DOCS_URL}"))
+ print(red(" Already activated here? status, upgrade, claim, devices and logout keep working."))
+ print(red(f" To continue unsupported anyway, set {NATIVE_WINDOWS_ESCAPE_ENV}=1."))
+ return 1
+
+ print(yellow(" Sibyl Memory is not supported on native Windows. Run it inside WSL2:"))
+ print(yellow(f" {WSL_DOCS_URL}"))
+ print(yellow(" Continuing anyway. Nothing on this platform is tested or fixed."))
+ return 0
+
+
+def short(token: str | None) -> str:
+ if not token:
+ return "—"
+ if len(token) <= 12:
+ return token
+ return f"{token[:8]}…{token[-4:]}"
+
+
+def _fmt_cap_bytes(cap: Any) -> str:
+ """Render a server-supplied cap_bytes value defensively.
+
+ CLI-16: `cap_bytes` is None for unlimited, otherwise an int. A non-int,
+ non-None value (e.g. a string from a buggy/old server) would raise on the
+ `:,` format spec. Coerce to int when possible; show the raw value rather
+ than crash when it can't be coerced."""
+ if cap is None:
+ return "unlimited"
+ try:
+ return f"{int(cap):,}"
+ except (TypeError, ValueError):
+ return str(cap)
+
+
+# ---- HTTP --------------------------------------------------------------
+
+class HttpError(Exception):
+ def __init__(self, status: int, body: Any, url: str, headers: dict | None = None) -> None:
+ super().__init__(f"HTTP {status} for {url}: {body}")
+ self.status = status
+ self.body = body
+ self.url = url
+ # Response headers (0.5.0, for Retry-After). Empty for network errors.
+ self.headers = headers or {}
+
+ @property
+ def code(self) -> str | None:
+ """The server's machine-readable `code`, when the body carries one."""
+ if isinstance(self.body, dict) and isinstance(self.body.get("code"), str):
+ return self.body["code"]
+ return None
+
+ @property
+ def message(self) -> str | None:
+ """The server's human `error` string, when the body carries one."""
+ if isinstance(self.body, dict) and isinstance(self.body.get("error"), str):
+ return self.body["error"]
+ return None
+
+
+def _claim_signout_line(e: "HttpError | None") -> str | None:
+ """F-1 (contract C1): the line for the api's 401 ``signed_out_on_claim``
+ (this computer was signed out when the email was confirmed on the account
+ page), or None for any other answer."""
+ if e is None or e.status != 401 or e.code != _gate.SIGNED_OUT_ON_CLAIM:
+ return None
+ return _gate.signed_out_on_claim_line(e.body.get("signed_out_at") if isinstance(e.body, dict) else None)
+
+
+def _https_context() -> ssl.SSLContext:
+ """TLS context for every CLI network call (api.sibyllabs.org, pypi.org).
+
+ Prefers the shared certifi-backed trust context from sibyl-memory-client,
+ the fix for macOS framework-build Pythons that ship an empty OpenSSL trust
+ store (the `session-init failed (0)` / `Bind failed` / `server error: 0`
+ class of report). Degrades to the stdlib default context when the client
+ package is absent, mirroring the `_ver_lt` packaging fallback: the CLI
+ stays runnable stdlib-only, just without the Darwin trust fix. Verification
+ is fully on in both branches; nothing here ever weakens it.
+ """
+ try:
+ from sibyl_memory_client._trust import https_context
+ except ImportError:
+ return ssl.create_default_context()
+ return https_context()
+
+
+try:
+ from sibyl_memory_client._entitlement import _bearer_allowed as _client_bearer_allowed
+except ImportError: # pragma: no cover - a client without the gate
+ _BEARER_HOST = "sibyllabs.org"
+ _LOCAL_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"})
+
+ def _client_bearer_allowed(url: str) -> bool:
+ """Same rule as sibyl_memory_client._entitlement._bearer_allowed."""
+ try:
+ parsed = urllib.parse.urlparse(url)
+ except ValueError:
+ return False
+ host = (parsed.hostname or "").lower()
+ scheme = (parsed.scheme or "").lower()
+ if host in _LOCAL_HOSTS and scheme in ("http", "https"):
+ return True
+ return scheme == "https" and (host == _BEARER_HOST or host.endswith("." + _BEARER_HOST))
+
+
+def _bearer_allowed(url: str) -> bool:
+ """The client's host rule behind the CLI's own refusals (follow-up D3): a
+ backslash, whitespace, a control character or userinfo in the URL is
+ refused first, so cli 0.7.0 is safe with client 0.10.0, whose rule alone
+ accepts ``https://evil.com\\@sibyllabs.org/x``."""
+ return _gate.bearer_url_safe(url) and _client_bearer_allowed(url)
+
+
+UNTRUSTED_BASE_CODE = _gate.UNTRUSTED_BASE_CODE
+_UNTRUSTED_NOTED: set[str] = set()
+_CREDENTIAL_HEADERS = ("authorization", "x-sibyl-entitlement")
+_CREDENTIAL_BODY_KEYS = ("session_token", "bearer_token")
+
+
+def _carries_credential(headers: dict | None, body: dict | None) -> bool:
+ if any(k.lower() in _CREDENTIAL_HEADERS for k in (headers or {})):
+ return True
+ return isinstance(body, dict) and any(body.get(k) for k in _CREDENTIAL_BODY_KEYS)
+
+
+def _untrusted_base_message(base: str, name: str = "SIBYL_API_BASE") -> str:
+ try:
+ p = urllib.parse.urlparse(base)
+ shown = f"{p.scheme}://{p.hostname}" if p.scheme and p.hostname else "an unusable value"
+ except ValueError:
+ shown = "an unusable value"
+ return (f"{name} ({shown}) is not an https *.sibyllabs.org address or a loopback address "
+ "for local development, so the session token was not sent. Unset it or point "
+ "it at the Sibyl api.")
+
+
+def _note_untrusted_base(base: str, name: str = "SIBYL_API_BASE") -> None:
+ """Print the untrusted-base explanation to stderr at most once per process
+ and variable (follow-up D1: `sibyl upgrade` printed it twice)."""
+ if name in _UNTRUSTED_NOTED:
+ return
+ _UNTRUSTED_NOTED.add(name)
+ print(_untrusted_base_message(base, name), file=sys.stderr)
+
+
+def _is_untrusted(e: "HttpError | None") -> bool:
+ """True for the refusal http_request raises instead of sending the
+ sign-in to a host outside the bearer rule (never a network fault)."""
+ return e is not None and e.status == 0 and e.code == UNTRUSTED_BASE_CODE
+
+
+def http_request( # noqa: D401
+ method: str,
+ path: str,
+ *,
+ body: dict | None = None,
+ timeout: float = 15.0,
+ headers: dict | None = None,
+) -> dict:
+ """Single source of truth for HTTP calls. Returns parsed JSON or raises HttpError.
+
+ Panel fix 6 (2026-11-14): a request that carries the session bearer (an
+ Authorization or X-Sibyl-Entitlement header, or a session_token or
+ bearer_token in the body) is sent only to https *.sibyllabs.org or a
+ loopback host, the same gate the client library applies. Otherwise it is
+ not sent at all and HttpError(0, code untrusted_api_base) is raised."""
+ url = f"{API_BASE}{path}"
+ if _carries_credential(headers, body) and not _bearer_allowed(url):
+ msg = _untrusted_base_message(API_BASE)
+ _note_untrusted_base(API_BASE)
+ raise HttpError(0, {"error": msg, "code": UNTRUSTED_BASE_CODE}, url)
+ data = None
+ full_headers = {"Accept": "application/json", "User-Agent": f"sibyl-memory-cli/{_client_version()}"}
+ if body is not None:
+ data = json.dumps(body).encode("utf-8")
+ full_headers["Content-Type"] = "application/json"
+ if headers:
+ full_headers.update(headers)
+ req = urllib.request.Request(url, data=data, method=method, headers=full_headers)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout, context=_https_context()) as resp:
+ return json.loads(resp.read().decode("utf-8"))
+ except urllib.error.HTTPError as e:
+ try:
+ err_body = json.loads(e.read().decode("utf-8"))
+ except Exception:
+ err_body = {"error": "unparseable response body"}
+ try:
+ hdrs = {k: v for k, v in (e.headers.items() if e.headers else [])}
+ except Exception:
+ hdrs = {}
+ raise HttpError(e.code, err_body, url, hdrs) from None
+ except urllib.error.URLError as e:
+ raise HttpError(0, {"error": str(e.reason)}, url) from None
+
+
+# ---- Credentials I/O ---------------------------------------------------
+
+# CLI-15: credentials.json is built from an explicit allowlist of known
+# fields, never the raw server blob. Contract T: tenant_id is persisted so
+# mcp/hermes/langgraph resolve the same tenant.
+CRED_FIELDS = ("account_id", "tenant_id", "tier", "wallet", "email", "issued_at",
+ "bearer_token", "expires_at")
+
+# Rule (release-blocker F1): a field the server's credential signature commits
+# to never changes under an old signature. Server-issued credentials replace
+# the file (email confirm); a local tier/wallet hint (upgrade, claim) drops the
+# signature and signed_at first (hardening L2), and the server stays the tier
+# authority.
+
+
+def _allowlisted_credentials(raw: dict) -> dict:
+ """The persisted subset of a server-issued credentials blob (CLI-15)."""
+ return {k: raw[k] for k in CRED_FIELDS if k in raw}
+
+
+def _credentials_from_server(raw: Any, current: dict) -> dict | None:
+ """Credentials to write after a server re-issued them for THIS account
+ (POST /email-verify/confirm, release-blocker F1): the allowlisted server
+ fields, plus this computer's own session_token / bearer_token / expires_at
+ (the server does not send the bearer back). None when `raw` is not a
+ credentials object for the same account."""
+ if not isinstance(raw, dict) or not raw.get("account_id") or raw.get("account_id") != current.get("account_id"):
+ return None
+ new = _allowlisted_credentials(raw)
+ for k in ("session_token", "bearer_token", "expires_at"):
+ if k not in new and current.get(k):
+ new[k] = current[k]
+ return new
+
+
+def _unsign_for_local_edit(creds: dict) -> dict:
+ """Prepare a local edit of a signed field (the tier / wallet hint after an
+ upgrade or a claim, hardening L2): drop `signature` and `signed_at`, which
+ are not in CRED_FIELDS and which `sibyl init` never persists. An unsigned
+ file makes the adapters send no credentials claim, so the edit cannot read
+ as tampering, and the file never keeps a stale tier next to a newer
+ server tier. Mutates and returns `creds`."""
+ creds.pop("signature", None)
+ creds.pop("signed_at", None)
+ return creds
+
+
+def write_credentials_atomic(creds: dict, path: Path = DEFAULT_CRED_PATH) -> Path:
+ """Write credentials.json atomically at mode 0600.
+
+ v0.1.2 hardening (audit SEC-2): no world-readable window. The temp file
+ is created O_CREAT|O_EXCL by mkstemp and fchmod'ed to 0600 before any
+ byte is written (see CLI-2 below). Previously used write_text() followed
+ by os.chmod(), leaving a world-readable window between syscalls every
+ credential save.
+ """
+ path = path.expanduser()
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ # mkdir's mode is ignored when the dir already exists (bug, dor_alpha 2026-06-01):
+ # a pre-existing 0755 ~/.sibyl-memory left credentials world-readable. Tighten
+ # explicitly to cover the pre-existing-directory case.
+ try:
+ os.chmod(path.parent, 0o700)
+ except OSError:
+ pass
+ data = json.dumps(creds, indent=2).encode("utf-8")
+ # v0.3.17 hardening (audit CLI-2): unique per-process temp via
+ # tempfile.mkstemp instead of the fixed `.tmp` + unlink dance.
+ # The old approach unlinked a leftover temp and then re-created it with
+ # O_EXCL — a TOCTOU window where two concurrent writers (or an attacker
+ # who recreated the path between unlink and open) could collide. mkstemp
+ # picks a name no other process holds and opens it O_CREAT|O_EXCL itself,
+ # so no unlink is needed. We still enforce mode 0600 (fchmod, since mkstemp
+ # honors the process umask) and fsync before the atomic replace.
+ import tempfile
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=path.name + ".", suffix=".tmp")
+ try:
+ os.fchmod(fd, 0o600)
+ os.write(fd, data)
+ os.fsync(fd)
+ except BaseException:
+ os.close(fd)
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ raise
+ else:
+ os.close(fd)
+ os.replace(tmp, str(path))
+ return path
+
+
+def read_credentials(path: Path = DEFAULT_CRED_PATH) -> dict | None:
+ """Read credentials.json.
+
+ v0.1.2 hardening (audit SEC-11): refuses to follow symlinks.
+ Returns None if the file is a symlink or doesn't exist."""
+ path = path.expanduser()
+ if not path.exists():
+ return None
+ if path.is_symlink():
+ return None
+ # v0.3.17 hardening (audit CLI-1 / submitter D1): a corrupt or unreadable
+ # credentials.json must surface a clean one-liner, not a raw traceback.
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (ValueError, OSError):
+ global _CREDS_CORRUPT
+ _CREDS_CORRUPT = True
+ print(red("credentials.json is corrupt or unreadable. Run `sibyl init --force` to re-activate."))
+ return None
+
+
+def _tier_display(value: Any) -> str:
+ """Display word for a tier label: Free / Pro / Elite (tier convention,
+ 2026-10-05). Legacy labels show as the tier they alias (stake -> Pro);
+ an unrecognised label shows as Free. Falls back to the raw label when the
+ client (which owns the one tier module) is not importable."""
+ try:
+ from sibyl_memory_client.tiers import display
+ except Exception: # pragma: no cover - client absent or pre-0.9.0
+ return str(value or "free").capitalize()
+ return display(value or "free")
+
+
+def invalidate_tier_cache(path: Path = DEFAULT_TIER_CACHE_PATH) -> None:
+ """Drop the local tier cache so the next write refreshes against the server."""
+ path = path.expanduser()
+ if path.exists():
+ path.unlink()
+
+
+def is_sqlite_db(path: Path) -> bool:
+ """Lightweight check that `path` is a real SQLite database.
+
+ v0.3.17 (audit CLI-3 / submitter D3): `sibyl status --db ` used to
+ report a non-SQLite file as if it were a normal DB. We check the 16-byte
+ SQLite header magic, then confirm the file opens and answers a trivial
+ PRAGMA. A 0-byte file is a valid (empty) SQLite database, so it passes.
+ Returns False on any read/parse error rather than raising."""
+ import sqlite3
+
+ try:
+ if not path.exists() or not path.is_file():
+ return False
+ size = path.stat().st_size
+ if size == 0:
+ return True # empty file is a valid, freshly-created SQLite DB
+ with open(path, "rb") as fh:
+ header = fh.read(16)
+ if header != b"SQLite format 3\x00":
+ return False
+ con = sqlite3.connect(str(path))
+ try:
+ con.execute("PRAGMA schema_version")
+ finally:
+ con.close()
+ return True
+ except (OSError, sqlite3.Error):
+ return False
+
+
+# ---- account plumbing (0.5.0) ------------------------------------------
+#
+# Shared by init / status / email / claim / upgrade / dashboard. Everything
+# here degrades: an OLD api returns no `features` and no `account`, and the
+# callers then print exactly what 0.4.1 printed.
+
+def _account_url(path: str = "") -> str:
+ return f"{ACCOUNT_BASE}/{path.lstrip('/')}" if path else ACCOUNT_BASE
+
+
+def _bearer_headers(creds: dict, *, entitlement: bool = True) -> dict:
+ """Bearer auth for a session-authenticated call, plus the device's
+ entitlement as X-Sibyl-Entitlement (spec 5.6) when entitlement.json holds a
+ token that verifies, is bound to this computer and is inside exp + og.
+ With no usable token, ONE blocking /entitlement refresh first (the same
+ ensure-fresh path as the security calls), so a device back from offline
+ or finishing setup does not hit the cutoff's 403. A token the api would
+ refuse is never sent; with none the api accepts the call until
+ min_client_version is set."""
+ token = creds.get("bearer_token") or creds.get("session_token")
+ if not token:
+ return {}
+ headers = {"Authorization": f"Bearer {token}"}
+ if entitlement:
+ ent = _gate.ensure_fresh_token(_ENT_CRED_PATH)
+ if ent:
+ headers[_gate.HEADER] = ent
+ return headers
+
+
+def _security_request(method: str, path: str, creds: dict, *, body: dict | None = None,
+ timeout: float = 10.0) -> Any:
+ """A session call for device management and logout (spec 5.6, api O-5).
+
+ A device offline past exp + og holds an expired token, and these are the
+ calls a person makes to recover or to sign out, so: with no usable token,
+ try one /entitlement refresh first; send whatever usable token exists; on
+ a 403 entitlement_invalid retry ONCE without the header (the api accepts an
+ absent token until the cutoff). Never blocks logout or revoke on the gate."""
+ token = creds.get("bearer_token") or creds.get("session_token")
+ auth = {"Authorization": f"Bearer {token}"} if token else {}
+ ent = _gate.ensure_fresh_token(_ENT_CRED_PATH) if token else None
+ headers = dict(auth)
+ if ent:
+ headers[_gate.HEADER] = ent
+ try:
+ return http_request(method, path, body=body, headers=headers, timeout=timeout)
+ except HttpError as e:
+ if ent and e.status == 403 and e.code == "entitlement_invalid":
+ return http_request(method, path, body=body, headers=auth, timeout=timeout)
+ raise
+
+
+def _fetch_access_ex(creds: dict) -> tuple[dict | None, HttpError | None]:
+ """POST /api/plugin/access with the bearer. (body, None) or (None, error)."""
+ token = creds.get("bearer_token") or creds.get("session_token")
+ try:
+ resp = http_request(
+ "POST",
+ "/api/plugin/access",
+ body={"account_id": creds.get("account_id"), "session_token": token},
+ headers=_bearer_headers(creds),
+ timeout=10.0,
+ )
+ except HttpError as e:
+ return None, e
+ return (resp if isinstance(resp, dict) else {}), None
+
+
+def _fetch_access(creds: dict) -> dict | None:
+ """The /access body, or None on any HttpError (callers degrade)."""
+ return _fetch_access_ex(creds)[0]
+
+
+def _features_of(body: Any) -> dict:
+ f = body.get("features") if isinstance(body, dict) else None
+ return f if isinstance(f, dict) else {}
+
+
+def _account_of(body: Any) -> dict:
+ acc = body.get("account") if isinstance(body, dict) else None
+ return acc if isinstance(acc, dict) else {}
+
+
+def _is_interactive() -> bool:
+ try:
+ tty = sys.stdin.isatty() and sys.stdout.isatty()
+ except (AttributeError, ValueError):
+ return False
+ return bool(tty) and not os.environ.get("SIBYL_NONINTERACTIVE")
+
+
+def _on_account_origin(url: Any) -> bool:
+ """True only for the account page origin itself or a path under it.
+
+ A plain startswith() would also accept https://account.sibyllabs.org.evil.example,
+ so the origin must be followed by nothing, `/`, or `?`.
+ """
+ if not isinstance(url, str):
+ return False
+ return url == ACCOUNT_BASE or url.startswith(ACCOUNT_BASE + "/") or url.startswith(ACCOUNT_BASE + "?")
+
+
+_APPROVE_PREFIX_PATH = "/activate?r="
+
+
+def _approve_url_ok(url: Any) -> bool:
+ """Print an approval link only when it is ours and carries the ?r= handle.
+
+ The handle is sha256 of the session id (64 lowercase hex). A legacy
+ `?s=` link is refused: the session id becomes the bearer.
+ """
+ if not isinstance(url, str) or not url.startswith(ACCOUNT_BASE + _APPROVE_PREFIX_PATH):
+ return False
+ return re.fullmatch(r"[0-9a-f]{64}", url.split("?r=", 1)[1]) is not None
+
+
+def _session_ref(session_id: str) -> str:
+ """Same value as the server's db.sessionRef(): sha256 hex of the lowercase uuid."""
+ return hashlib.sha256(session_id.strip().lower().encode("utf-8")).hexdigest()
+
+
+def _retry_minutes(e: HttpError) -> str:
+ raw = None
+ for k, v in (e.headers or {}).items():
+ if str(k).lower() == "retry-after":
+ raw = v
+ break
+ if raw is None and isinstance(e.body, dict):
+ raw = e.body.get("retry_after_seconds")
+ try:
+ secs = int(float(raw))
+ except (TypeError, ValueError):
+ return "a few"
+ return str(max(1, -(-secs // 60)))
+
+
+def _email_error_message(e: HttpError) -> str:
+ """One plain line for an email-verify failure (spec 4.3 error map)."""
+ code = e.code
+ msg = e.message
+ gate_line = _gate.gate_http_line(e.status, code, cred_path=_ENT_CRED_PATH, body=e.body)
+ if gate_line:
+ return gate_line
+ if code == "not_open":
+ return (f"email confirmation from the terminal is not open yet. add your email at "
+ f"{ACCOUNT_BASE} (sign in with the email or wallet you used here).")
+ if code == "wrong_code":
+ left = e.body.get("attempts_remaining") if isinstance(e.body, dict) else None
+ left_s = str(left) if isinstance(left, int) and not isinstance(left, bool) else "a few"
+ return f"that code is not right ({left_s} attempts left)."
+ if code in ("already_verified", "email_taken", "mail_unavailable", "expired",
+ "identity_frozen", "email_required_in_body") and msg:
+ return msg
+ if code == "expired":
+ return "that code expired. run sibyl email verify for a new one."
+ if e.status == 401:
+ return "session expired. re-run sibyl init."
+ if e.status == 403 and isinstance(e.body, dict) and e.body.get("reason") == "tamper_flag_active":
+ return "this account is under review. email sibyl@sibyllabs.org."
+ if e.status == 404:
+ # An api from before 0.5.0 has no email-verify endpoints.
+ return (f"email confirmation is not available on this server yet. add your email at "
+ f"{ACCOUNT_BASE} instead.")
+ if e.status == 429:
+ return f"too many requests. try again in {_retry_minutes(e)} minutes."
+ if e.status == 0:
+ return "could not reach the server."
+ if code and msg:
+ return msg
+ return f"server error: {e.status}"
+
+
+def _email_rc(e: HttpError) -> int:
+ """Exit code for an email-verify failure: 2 server side, 1 otherwise."""
+ if _is_untrusted(e):
+ return 1
+ return 2 if (e.status == 0 or e.status >= 500 or e.status == 404) else 1
+
+
+def _retry_in(e: HttpError) -> str:
+ mins = _retry_minutes(e)
+ return _h.retry_in(mins if mins.isdigit() else 5)
+
+
+def _email_error_handoff(e: HttpError, masked: Any = None) -> tuple:
+ """(next, human) for an email-verify failure: rows E11 to E23, the same
+ branch order as ``_email_error_message``."""
+ code = e.code
+ gate = _gate.gate_http_handoff(e.status, code, cred_path=_ENT_CRED_PATH, body=e.body)
+ if gate is not None:
+ return gate
+ not_open = ("sibyl email", _email_web_human())
+ if code == "not_open":
+ return not_open
+ if code == "wrong_code":
+ left = e.body.get("attempts_remaining") if isinstance(e.body, dict) else None
+ left_s = str(left) if isinstance(left, int) and not isinstance(left, bool) else "a few"
+ return ("sibyl email confirm ", f"re-read the six digit code ({left_s} attempts left)")
+ if code == "already_verified":
+ return ("sibyl status", None)
+ if code == "email_taken":
+ return ("sibyl email add ", "that address belongs to another account; give a "
+ f"different address, or sign in at {ACCOUNT_BASE} with it")
+ if code == "mail_unavailable":
+ return (_h.retry_in(5), None)
+ if code == "expired":
+ return ("sibyl email verify", f"a new code will be sent to {masked or 'the address on file'}")
+ if code == "identity_frozen":
+ return ("done", "this account's identity is frozen; email sibyl@sibyllabs.org")
+ if code == "email_required_in_body":
+ return ("sibyl email add ", EMAIL_ADDRESS_HUMAN)
+ if e.status == 401:
+ return ("sibyl init", None)
+ if e.status == 403 and isinstance(e.body, dict) and e.body.get("reason") == "tamper_flag_active":
+ return _gate.code_handoff("under_review")
+ if e.status == 404:
+ return not_open
+ if e.status == 429:
+ return (_retry_in(e), None)
+ if e.status == 0:
+ return (_h.RETRY, OFFLINE_HUMAN)
+ return (_h.RETRY, None)
+
+
+def _harness_wired() -> bool:
+ """True when an agent harness on this computer already has Sibyl wired
+ (file checks only, never a subprocess). Picks `sibyl status` over
+ `sibyl setup` as the next step after an email is confirmed (row E24)."""
+ try:
+ from .setup import CodexWirer, HermesWirer
+ for w in (HermesWirer(), CodexWirer()):
+ if w.current_state().get("wired_with_sibyl"):
+ return True
+ except Exception:
+ pass
+ home = Path.home()
+ for p in (home / ".claude.json", home / ".claude" / "settings.json"):
+ try:
+ if p.is_file() and '"sibyl-memory"' in p.read_text(encoding="utf-8"):
+ return True
+ except OSError:
+ pass
+ return False
+
+
+def _after_confirm_next() -> str:
+ return "sibyl status" if _harness_wired() else "sibyl setup"
+
+
+def _email_request(creds: dict, address: str | None) -> dict:
+ """POST /api/plugin/email-verify/request. Raises HttpError."""
+ body: dict = {"account_id": creds.get("account_id")}
+ if address:
+ body["email"] = address
+ return http_request(
+ "POST",
+ "/api/plugin/email-verify/request",
+ body=body,
+ headers=_bearer_headers(creds),
+ timeout=15.0,
+ )
+
+
+def _normalize_code(code: str | None) -> str | None:
+ c = "".join(ch for ch in (code or "") if not ch.isspace() and ch != "-")
+ return c if re.fullmatch(r"\d{6}", c) else None
+
+
+def _email_confirm_once_h(creds: dict, code: str, cred_path: Path, *,
+ then: str | None = None) -> tuple:
+ """One confirm call. (exit code, server error code or None, handoff)."""
+ norm = _normalize_code(code)
+ if norm is None:
+ print(a.warn_line("a code is six digits, from the email we sent."))
+ return 1, "bad_format", ("sibyl email confirm ",
+ "the six digit code from the email (digits only)")
+ try:
+ resp = http_request(
+ "POST",
+ "/api/plugin/email-verify/confirm",
+ body={"code": norm},
+ headers=_bearer_headers(creds),
+ timeout=15.0,
+ )
+ except HttpError as e:
+ print(a.warn_line(_email_error_message(e)))
+ return _email_rc(e), (e.code or str(e.status)), _email_error_handoff(e, _mask_email(creds.get("email")))
+ resp = resp if isinstance(resp, dict) else {}
+ handoff = (then or _after_confirm_next(), None)
+ # Release-blocker F1: email is a SIGNED field. Write the credentials the
+ # server re-signed (through the CLI-15 allowlist); an api that sends none
+ # leaves the file exactly as it is (never edit a signed field locally).
+ fresh = _credentials_from_server(resp.get("credentials"), creds)
+ if fresh is not None:
+ try:
+ write_credentials_atomic(fresh, cred_path)
+ creds.clear()
+ creds.update(fresh)
+ except OSError:
+ print(a.warn_line("confirmed on the server, but credentials.json could not be updated."))
+ handoff = ("sibyl init --force", None)
+ # 0.5.0 (spec 3.4, 5.2): the confirm answer carries a re-issued entitlement
+ # (its `acct` must not lag a week). None sent = the old file stays.
+ if resp.get("entitlement") is not None:
+ _gate.write_entitlement_atomic(resp.get("entitlement"), cred_path)
+ try:
+ invalidate_tier_cache() # a pending purchase may have attached
+ except OSError:
+ pass
+ print(a.success_line("Email confirmed. Your account is complete."))
+ attached = resp.get("claims_attached")
+ if isinstance(attached, int) and not isinstance(attached, bool) and attached > 0:
+ print(a.dim(f" {attached} purchase(s) attached"))
+ revoked = resp.get("sessions_revoked")
+ if isinstance(revoked, int) and not isinstance(revoked, bool) and revoked > 0:
+ print(a.dim(f" {revoked} other computer(s) signed out"))
+ return 0, None, handoff
+
+
+def _email_confirm_prompt_h(creds: dict, cred_path: Path, *, masked: Any = None,
+ mins: Any = None, then: str | None = None) -> tuple:
+ """Ask for the emailed code. Three tries on a wrong code; Enter skips.
+ (exit code, (next, human))."""
+ waiting_code = ("sibyl email confirm ", _code_human(masked, mins))
+ for _ in range(3):
+ try:
+ answer = input(" code from the email: ").strip()
+ except EOFError:
+ answer = ""
+ if not answer:
+ print(a.dim(" skipped. when the email arrives: sibyl email confirm "))
+ return 1, waiting_code
+ rc, err, h = _email_confirm_once_h(creds, answer, cred_path, then=then)
+ if rc == 0:
+ return 0, h
+ if err not in ("wrong_code", "bad_format"):
+ return rc, h
+ print(a.dim(" run sibyl email verify for a new code."))
+ return 1, ("sibyl email verify", "the code was wrong three times; a new one will be sent")
+
+
+def _email_request_and_prompt_h(creds: dict, address: str | None, cred_path: Path,
+ *, interactive: bool, then: str | None = None) -> tuple:
+ """Request a code, report where it went, then prompt (TTY) or explain the
+ next step. (exit code, (next, human))."""
+ try:
+ resp = _email_request(creds, address)
+ except HttpError as e:
+ print(a.warn_line(_email_error_message(e)))
+ return _email_rc(e), _email_error_handoff(e, _mask_email(address or creds.get("email")))
+ resp = resp if isinstance(resp, dict) else {}
+ masked = resp.get("to_masked") if isinstance(resp.get("to_masked"), str) else _mask_email(address or creds.get("email"))
+ secs = resp.get("expires_in_seconds")
+ n_mins = max(1, int(secs) // 60) if isinstance(secs, (int, float)) and not isinstance(secs, bool) and secs > 0 else None
+ mins = f" it expires in {n_mins} minutes." if n_mins else ""
+ print(a.dim(f" code sent to {masked}.{mins}"))
+ if interactive:
+ return _email_confirm_prompt_h(creds, cred_path, masked=masked, mins=n_mins, then=then)
+ print(a.dim(" then run: sibyl email confirm "))
+ return 0, ("sibyl email confirm ", _code_human(masked, n_mins))
+
+
+def _looks_like_email(s: str) -> bool:
+ return re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", s or "") is not None
+
+
+# ---- `sibyl init` ------------------------------------------------------
+
+def _gen_pairing_code() -> str:
+ """6-digit cryptographic pairing code. Uniform across 000000-999999."""
+ return f"{secrets.randbelow(1_000_000):06d}"
+
+
+def _hash_pairing_code(code: str, session: str) -> str:
+ return hashlib.sha256(f"{code}:{session}".encode("utf-8")).hexdigest()
+
+
+# F-1a (contract C2): an email typed in the browser at `sibyl init`
+# (pairing code + address) proves terminal and browser, never the mailbox. The
+# first sign-in on the account page with that address is the mailbox proof, and
+# it signs out every computer set up before it, this one included. Said on every
+# path that leaves the email unconfirmed.
+CLAIM_SIGNOUT_WARNING = ("until you confirm your email here, signing in on the account page signs "
+ "this computer out. confirm later with: sibyl email verify")
+
+
+def _usdc_bind_offered(init_resp: Any) -> bool:
+ """True when session-init minted a USDC-send bind for this session."""
+ if not isinstance(init_resp, dict):
+ return False
+ amt = init_resp.get("bind_amount_micros")
+ bus = init_resp.get("bind_bus_wallet")
+ return (isinstance(amt, int) and not isinstance(amt, bool) and amt > 0
+ and isinstance(bus, str) and bool(bus.strip()))
+
+
+def _init_email_step(creds: dict, cred_path: Path, features: dict, account: dict,
+ *, no_email: bool) -> tuple:
+ """After `Activated.`: nag for a missing / unconfirmed email and, on a TTY,
+ offer to fix it now. Never fails init; every error prints and moves on.
+
+ Silent against an old api (no `account` in /check and no `cli_email_verify`
+ feature), so 0.5.0 on a 0.4-era server prints what 0.4.1 printed.
+
+ Returns the init handoff (rows I11 to I15): (next, human, later).
+
+ F7 (onboarding friction 2026-10-08): the installer runs `sibyl setup`
+ before `sibyl init`, so an agent is usually wired already; then the step
+ after activation is `sibyl status`, and `sibyl setup` is not queued.
+ """
+ after = _after_confirm_next()
+ later_setup = ("sibyl setup",) if after == "sibyl setup" else ()
+ done = (after, None, ())
+ server_knows = bool(account) or ("cli_email_verify" in features)
+ if not server_knows or account.get("email_verified") is True:
+ return done
+ required = account.get("email_required") is True
+ if features.get("cli_email_verify") is not True:
+ # The api does not take confirmation from the terminal (row E11):
+ # `sibyl email add` would only fail with not_open, so hand the
+ # browser step to the person instead of asking for an address.
+ print(a.warn_line("confirm your email to finish your account" if creds.get("email")
+ else "add an email to finish your account"))
+ print(a.dim(f" add and confirm it at {ACCOUNT_BASE}. local memory works either way."))
+ print(a.dim(f" {CLAIM_SIGNOUT_WARNING}"))
+ print()
+ return (after, _email_web_human(), ("sibyl email",))
+ can_prompt = _is_interactive() and not no_email
+ if not creds.get("email"):
+ add = (("sibyl email add ", EMAIL_ADDRESS_HUMAN, later_setup) if required
+ else (after, EMAIL_ADDRESS_HUMAN, ("sibyl email add ",)))
+ print(a.warn_line("add an email to finish your account"))
+ print(a.dim(" receipts, security notices and purchases need one. local memory works either way."))
+ print(a.dim(" sibyl email add you@example.com"))
+ print()
+ if not can_prompt:
+ return add
+ try:
+ answer = input(" add an email now? (address, or Enter to skip): ").strip()
+ except EOFError:
+ answer = ""
+ if not answer:
+ print()
+ return add
+ if not _looks_like_email(answer):
+ print(a.warn_line("that does not look like an email address. later: sibyl email add "))
+ print()
+ return add
+ rc, h = _email_request_and_prompt_h(creds, answer, cred_path, interactive=True, then=after)
+ print()
+ return done if rc == 0 else (h[0], h[1], later_setup)
+ if account.get("email_verified") is False:
+ masked = _mask_email(creds.get("email"))
+ verify = (("sibyl email verify", _verify_human(masked), later_setup) if required
+ else (after, None, ("sibyl email verify",)))
+ print(a.dim(" confirm your email to finish your account: sibyl email verify"))
+ if can_prompt:
+ # F-1a (C2): no "confirm it now?" question; the code goes out
+ # and the only prompt is for the code (Enter still skips).
+ rc, h = _email_request_and_prompt_h(creds, None, cred_path, interactive=True,
+ then=after)
+ if rc != 0:
+ print(a.dim(f" {CLAIM_SIGNOUT_WARNING}"))
+ print()
+ return done if rc == 0 else (h[0], h[1], later_setup)
+ print(a.dim(f" {CLAIM_SIGNOUT_WARNING}"))
+ print()
+ return verify
+ return done
+
+
+# ---- computer limit (R1, plan 4.2 / 4.4) --------------------------------
+# The api counts active sign-ins (bearer rows) per account. At the limit it
+# does not bind a new computer: /check answers bound:false with a `limit`
+# object, and bind / email-bind answer 409 with the same object as the body:
+# {code: "device_limit", limit: , tier: ,
+# devices: [{label, os_family, last_seen_at}], manage_url, upgrade_url}
+# (labels only, never tokens). Re-activating a computer that already holds
+# credentials sends replace: {session_token} on session-init, so its old
+# sign-in is revoked in the same transaction and no slot is used. An optional
+# integer `pro_limit` in the object is the paid plans' limit, named in the Free
+# upgrade line only when the api sends it (never a CLI constant there).
+
+# Plan 4.4's `sibyl status` / `sibyl devices` row ("1 of 1 (Free) · Pro: up to 10").
+PRO_DEVICE_LIMIT_HINT = 10
+_LABEL_MAX = 60
+
+
+def _clean_label(v: Any) -> str:
+ t = "".join(ch for ch in str(v or "") if ch.isprintable())
+ t = " ".join(t.split())[:_LABEL_MAX]
+ return t or "(unlabeled)"
+
+
+def _device_limit_of(obj: Any) -> dict | None:
+ """The computer-limit object of a /check body (``limit``) or of a 409 body
+ (the object itself), shape-checked; None when it is not one."""
+ if not isinstance(obj, dict):
+ return None
+ lim = obj if obj.get("code") == "device_limit" else obj.get("limit")
+ if not isinstance(lim, dict) or lim.get("code") != "device_limit":
+ return None
+ devices = []
+ raw = lim.get("devices")
+ for d in (raw if isinstance(raw, list) else [])[:50]:
+ if not isinstance(d, dict):
+ continue
+ seen = d.get("last_seen_at")
+ devices.append({"label": _clean_label(d.get("label")),
+ "os_family": _clean_label(d.get("os_family")) if d.get("os_family") else "",
+ "last_seen_at": _utc_minute(seen) or ""})
+ n = lim.get("limit")
+ limit = n if isinstance(n, int) and not isinstance(n, bool) and n >= 0 else None
+ # Optional: the paid plans' limit, for the Free upgrade line. Plan 4.2's
+ # object does not carry it; without it the line names no number.
+ p = lim.get("pro_limit")
+ pro_limit = p if isinstance(p, int) and not isinstance(p, bool) and p > 0 else None
+ tier = lim.get("tier") if isinstance(lim.get("tier"), str) else None
+ manage = lim.get("manage_url") if _on_account_origin(lim.get("manage_url")) else _account_url("security")
+ up = lim.get("upgrade_url")
+ if not (isinstance(up, str) and (_on_account_origin(up) or up.startswith("https://sibyllabs.org/"))):
+ up = UPGRADE_BASE
+ return {"limit": limit, "tier": tier, "devices": devices, "manage_url": manage, "upgrade_url": up,
+ "pro_limit": pro_limit}
+
+
+def _handle_device_limit(lim: dict, *, interactive: bool, window: Any = None) -> str:
+ """Print the computers holding the slots and what to do. Returns "wait"
+ (the person chose to sign one out on the account page; keep polling) or
+ "stop". Nothing is revoked from this terminal: a new computer holds no
+ credentials for the others; the Security page does it after sign-in."""
+ n = len(lim["devices"])
+ free = (lim["tier"] or "free") == "free"
+ plan = ("Free is one computer" if free and lim["limit"] == 1
+ else f"its plan allows {lim['limit']}" if lim["limit"] is not None else "its plan's limit is reached")
+ print(f"\r{' ' * 80}\r", end="")
+ print()
+ print(a.warn_line(f"This account already has {n or lim['limit'] or 'its'} computer"
+ f"{'' if n == 1 else 's'} signed in; {plan}."))
+ for d in lim["devices"]:
+ meta = " · ".join(x for x in (d["os_family"], f"last seen {d['last_seen_at']}" if d["last_seen_at"] else "")
+ if x)
+ print(a.kv(d["label"], meta or "—"))
+ print()
+ if interactive:
+ who = lim["devices"][0]["label"] if n == 1 else "one of them"
+ print(a.dim(" This terminal cannot sign another computer out; that is done on the account page."))
+ try:
+ ans = input(f"Open the account page to sign {who} out? [y/N]: ").strip().lower()
+ except EOFError:
+ ans = ""
+ if ans in ("y", "yes"):
+ print(a.dim(f" Opening {lim['manage_url']}. Next: choose Sign out next to {who} there, then"))
+ print(a.dim(" finish the sign-in on the activation page in your browser. This terminal keeps waiting."))
+ _h.waiting("for the bind", window if window is not None else INIT_TIMEOUT_FALLBACK_SEC,
+ human=f"on the account page choose Sign out next to {who}, then finish the "
+ "sign-in in the activation tab")
+ try:
+ webbrowser.open(lim["manage_url"], new=2)
+ except Exception:
+ pass
+ return "wait"
+ print(a.dim(f" This computer is not signed in. To use it, sign one of those out at {lim['manage_url']}"))
+ print(a.dim(" (or run `sibyl devices revoke ` on a signed-in computer), then run `sibyl init` again."))
+ if free:
+ up_to = f" (up to {lim['pro_limit']})" if lim.get("pro_limit") else ""
+ print(a.dim(f" Pro works on every computer you use{up_to}: {lim['upgrade_url']}"))
+ print(a.dim(" Nothing was deleted; the computers already signed in keep working."))
+ or_pro = " (or get Pro)" if free else ""
+ _h.handoff("sibyl init", later=("sibyl upgrade",) if free else (),
+ human=f"your account is at its computer limit; sign one out at {lim['manage_url']}"
+ f"{or_pro}, then tell me")
+ return "stop"
+
+
+def cmd_init(args: argparse.Namespace) -> int:
+ """Activation flow. Generate session UUID + pairing code, register with
+ server, open activation page in browser, poll /check until bound.
+
+ The pairing code is printed in the terminal. If the user picks the
+ email path in the browser, they type both their email and this code.
+ Afterwards it offers to add or confirm the account email (the server
+ sends that verification code by email; --no-email skips it)."""
+ # Brand moment — gold/white gradient SIBYL wordmark.
+ # Honors NO_COLOR + TTY detection automatically; safe to always call.
+ from ._banner import print_banner
+ print_banner()
+
+ # Platform line first, so it shows on --force re-activation too.
+ if print_platform_line(gate=True) != 0:
+ _h.handoff("done", human=WINDOWS_HUMAN)
+ return 1
+
+ cred_path = Path(args.credentials).expanduser()
+ if getattr(args, "replace", False):
+ args.force = True
+ if cred_path.exists() and not args.force:
+ existing = read_credentials(cred_path) or {}
+ print(a.section_header("already activated", subtitle="use --force to re-activate"))
+ print()
+ print(a.kv("Account", existing.get("account_id") or "—"))
+ print(a.kv("Tier", _tier_display(_gate.peek_tier(cred_path, existing.get("tier"))).upper(),
+ value_color="accent"))
+ print(a.kv("Credentials", str(cred_path)))
+ print()
+ if _CREDS_CORRUPT:
+ _h.handoff("sibyl init --force")
+ else:
+ _h.handoff("sibyl status", later=("sibyl init --force",))
+ return 0
+
+ # SEC-1 mitigation (v0.1.2): the URL parameter is an opaque pairing
+ # session identifier, NOT the long-lived bearer used by /access and
+ # /check-write. The CLI generates it locally and the server treats
+ # it as the activation rendezvous key only. The persistent bearer
+ # is issued by the server in the /check response (`bearer_token`
+ # field) after activation completes. Servers running pre-SEC-1
+ # firmware that echo the URL identifier as the bearer still work —
+ # we use whichever the server returns in the bound credentials.
+ session_id = str(uuid.uuid4())
+ pairing_code = _gen_pairing_code()
+ code_hash = _hash_pairing_code(pairing_code, session_id)
+ # Path-based URL on the dedicated auth subdomain (2026-05-20).
+ # auth.sibyllabs.org/ reads cleaner in the terminal than the old
+ # query-string form and aligns the wallet popup's "X wants you to sign in"
+ # header with the browser URL bar.
+ if ACTIVATE_BASE.rstrip("/").endswith(".sibyllabs.org") or ACTIVATE_BASE.rstrip("/").endswith("/auth"):
+ activate_url = f"{ACTIVATE_BASE.rstrip('/')}/{session_id}"
+ else:
+ # Legacy fallback: anyone with SIBYL_ACTIVATE_BASE pointing at the old
+ # /plugin/activate path keeps the query-string shape.
+ activate_url = f"{ACTIVATE_BASE}?session={session_id}"
+
+ # Pre-register the session + pairing code hash with the server.
+ # The code itself never leaves the user's machine until they type it
+ # into the browser.
+ #
+ # v0.3.5: capture pairing_ttl_seconds from the response and use it as
+ # the activation deadline. Server is the single source of truth — if
+ # the server-side TTL ever changes, the CLI adopts the new value
+ # automatically without a re-publish. INIT_TIMEOUT_FALLBACK_SEC only
+ # applies when the call fails entirely (network error) or the response
+ # is missing the field (schema drift).
+ pairing_ttl_seconds = None
+ # 0.5.0: the server advertises what it supports. An old api sends no
+ # `features`, and then nothing below prints or asks anything new.
+ features: dict = {}
+ init_body: dict = {
+ "session": session_id,
+ "pairing_code_hash": code_hash,
+ "env": {
+ "os_family": _detect_os_family(),
+ "os_version": _platform.release(),
+ "arch": _platform.machine(),
+ "wsl": _is_wsl(),
+ "install_method": "cli",
+ "client_version": _client_version(),
+ },
+ }
+ # R1 (plan 4.2): re-activation never costs a computer slot. The sign-in
+ # this computer already holds is named so the api revokes it in the same
+ # transaction as the new bind (an api without the limit ignores the key).
+ prior = read_credentials(cred_path) if cred_path.exists() else None
+ prior_token = (prior or {}).get("session_token")
+ if isinstance(prior_token, str) and prior_token:
+ init_body["replace"] = {"session_token": prior_token}
+ interactive = _is_interactive()
+ # the USDC-from-a-mobile-wallet path is offered only when the
+ # api minted this session's USDC-send amount (session-init answers
+ # bind_amount_micros + bind_bus_wallet; both null while USDC sign-in is off,
+ # and with no answer at all there is no amount to send).
+ usdc_on = False
+ try:
+ init_resp = http_request("POST", "/api/plugin/session-init", body=init_body, timeout=10.0)
+ if isinstance(init_resp, dict):
+ v = init_resp.get("pairing_ttl_seconds")
+ if isinstance(v, (int, float)) and v > 0:
+ pairing_ttl_seconds = int(v)
+ features = _features_of(init_resp)
+ usdc_on = _usdc_bind_offered(init_resp)
+ except HttpError as e:
+ lim = _device_limit_of(e.body) if e.status == 409 else None
+ if lim is not None:
+ if _handle_device_limit(lim, interactive=interactive,
+ window=pairing_ttl_seconds or INIT_TIMEOUT_FALLBACK_SEC) == "stop":
+ return 2
+ else:
+ # Non-fatal: SIWE path doesn't need the pairing code. If session-init
+ # fails the user can still complete SIWE. Surface the warning.
+ print(yellow(f"Warning: session-init failed ({e.status}). Wallet path still works; email path may not."))
+
+ activation_window_sec = pairing_ttl_seconds if pairing_ttl_seconds else INIT_TIMEOUT_FALLBACK_SEC
+
+ print()
+ print(a.section_header("activation", subtitle=("three paths" if usdc_on else "two paths")
+ + " · pick whichever fits your device"))
+ print()
+ print(a.kv("Session", short(session_id)))
+ formatted_code = pairing_code[:3] + " " + pairing_code[3:]
+ print(a.kv("Code", a.gradient_gold(formatted_code), value_color="accent")
+ + " " + a.dim("(use this in the email panel)"))
+ if features.get("device_approval") is True:
+ # The ?r= handle is sha256(session id): it names this request without
+ # carrying the session id, which becomes the bearer on approval.
+ # P1 (web-first spec 9.4): the account may exist only on the website.
+ print(a.dim(f" already have a Sibyl Memory account (website or another computer)? approve "
+ f"this one at {_account_url('activate')}?r={_session_ref(session_id)} instead "
+ f"(sign in there, then type this code)"))
+ print(a.kv("Opening", activate_url))
+ print()
+ print(a.dim(" desktop wallet · email + code · or send USDC from any mobile wallet" if usdc_on
+ else " desktop wallet · or email + code"))
+ print(a.dim(" this terminal will pick up automatically when you bind."))
+ print()
+ if features.get("device_approval") is True:
+ # F12 (onboarding friction 2026-10-08): the likeliest path first, so an
+ # agent relays one decision instead of four equal options.
+ paths = ("that code, a desktop wallet, or USDC from a mobile wallet" if usdc_on
+ else "that code or a desktop wallet")
+ bind_human = (f"if you already have a Sibyl Memory account, approve this computer at "
+ f"{_account_url('activate')}?r={_session_ref(session_id)} with the code "
+ f"{formatted_code}; otherwise open {activate_url} and sign in with email plus "
+ f"{paths}; I pick it up here")
+ else:
+ paths = (f"with a desktop wallet, with email plus the code {formatted_code}, or by sending "
+ f"USDC from a mobile wallet" if usdc_on
+ else f"with a desktop wallet or with email plus the code {formatted_code}")
+ bind_human = f"open {activate_url} and sign in {paths}; I pick it up here"
+ _h.waiting(f"for the bind at {urllib.parse.urlparse(activate_url).netloc or 'the activation page'}",
+ activation_window_sec, human=bind_human)
+
+ try:
+ webbrowser.open(activate_url, new=2)
+ except Exception:
+ pass
+
+ # Poll /api/plugin/check
+ deadline = time.time() + activation_window_sec
+ last_status = ""
+ spinner = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
+ spin_i = 0
+ approve_url_printed = False
+ limit_shown = False
+
+ while time.time() < deadline:
+ lim = None
+ try:
+ resp = http_request("GET", f"/api/plugin/check?session={urllib.parse.quote(session_id)}", timeout=10.0)
+ except HttpError as e:
+ if e.status in (404, 503, 0):
+ # Session not yet created server-side, or transient — keep polling
+ resp = {"bound": False}
+ elif e.status == 409 and _device_limit_of(e.body) is not None:
+ resp, lim = {"bound": False}, _device_limit_of(e.body)
+ else:
+ print(red(f"\nUnexpected error: {e.body}"))
+ _h.handoff("sibyl init --force")
+ return 2
+
+ # R1 (plan 4.2): at the computer limit the api does not bind; /check
+ # says why (bound:false + `limit`). Shown once; an old api never sends it.
+ if lim is None and isinstance(resp, dict) and not resp.get("bound"):
+ lim = _device_limit_of(resp)
+ if lim is not None and not limit_shown:
+ limit_shown = True
+ if _handle_device_limit(lim, interactive=interactive,
+ window=int(deadline - time.time())) == "stop":
+ return 2
+
+ if resp.get("bound") and resp.get("credentials"):
+ raw_creds = resp["credentials"]
+ # CLI-15: never trust the server payload shape blindly. A non-dict
+ # `credentials` (string, list, null) would otherwise crash on .get
+ # or persist garbage. Treat it as "not yet bound" and keep polling.
+ if not isinstance(raw_creds, dict):
+ print(f"\r{' ' * 80}\r", end="")
+ print(red("\nServer returned malformed credentials. Re-run `sibyl init --force`."))
+ _h.handoff("sibyl init --force")
+ return 2
+ # SEC-1: prefer the server-issued bearer_token (post-fix) over
+ # echoing the URL pairing-session id. Servers running pre-SEC-1
+ # firmware echo `session_token` back as the bearer — we use
+ # whichever the server returns. The CLI's session_id (URL
+ # identifier) is the rendezvous key, not the persistent bearer.
+ bearer = raw_creds.get("bearer_token") or raw_creds.get("session_token")
+ if not bearer:
+ # Fallback: pre-SEC-1 server flow where neither field is
+ # echoed back — inject the pairing session id so subsequent
+ # /access and /check-write calls have something to send.
+ bearer = session_id
+ # Sanity check on echoed session_token (pre-SEC-1 flow only)
+ if raw_creds.get("session_token") and raw_creds["session_token"] != session_id \
+ and not raw_creds.get("bearer_token"):
+ print(red("\nSession token mismatch — refusing to write credentials."))
+ _h.handoff("sibyl init --force")
+ return 2
+ # CLI-15: build the persisted dict from an explicit allowlist of
+ # known fields, not the raw server blob. This keeps unexpected /
+ # hostile server-supplied keys out of credentials.json.
+ # Contract T (tenant resolution, Real #1): persist the server-issued
+ # tenant_id so mcp/hermes/langgraph all resolve the SAME tenant from
+ # this credentials.json. Without it the CLI dropped tenant_id on
+ # activation and every surface silently fell back to DEFAULT_TENANT.
+ creds = _allowlisted_credentials(raw_creds)
+ creds["session_token"] = bearer
+ path = write_credentials_atomic(creds, cred_path)
+ # 0.5.0 account gate (spec 3.4, 5.2): /check bound:true carries
+ # `entitlement` NEXT TO `credentials`. A token bound to a previous
+ # sign-in is useless, so it goes first; an api that sends none
+ # leaves no file and the client bootstraps on first use.
+ _gate.remove_entitlement(cred_path)
+ ent_written = None
+ if resp.get("entitlement") is not None:
+ ent_written = _gate.write_entitlement_atomic(resp.get("entitlement"), cred_path)
+ # 0.5.0: account state rides NEXT TO the signed credentials (never
+ # inside them). Old apis send none.
+ account = _account_of(resp)
+ print(f"\r{' ' * 80}\r", end="") # clear spinner line
+ print()
+ print(a.success_line("Activated."))
+ print()
+ print(a.kv("Account", creds.get("account_id") or "—"))
+ print(a.kv("Tier", _tier_display(_gate.peek_tier(path, creds.get("tier"))).upper(),
+ value_color="accent"))
+ print(a.kv("Wallet", creds.get("wallet") or "—"))
+ print(a.kv("Email", creds.get("email") or "—"))
+ print(a.kv("Credentials", str(path)))
+ rows_left = False
+ if ent_written is not None:
+ print(a.kv("Access", "active", value_color="ok"))
+ rows_left = _adopt_after_sign_in(Path(args.db).expanduser(), cred_path)
+ _install_skills_quietly()
+ print()
+ nxt, human, later = _init_email_step(creds, path, features, account,
+ no_email=bool(getattr(args, "no_email", False)))
+ # Wiring is `sibyl setup` (installer, then setup, then init): no
+ # hand-edited config and no separate pip step. Already wired: the
+ # handoff says `sibyl status` and nothing is printed here.
+ if not _harness_wired():
+ print(a.dim(" wire it into your agent: sibyl setup (wires Claude Code, Codex and Hermes)"))
+ print()
+ _h.handoff(nxt, human=human,
+ later=(("sibyl memory adopt",) if rows_left else ()) + tuple(later))
+ return 0
+
+ # 0.5.0: web device approval. The email already has an owner, so the
+ # owner approves this computer at the account page.
+ approval = resp.get("approval") if isinstance(resp, dict) else None
+ waiting_approval = (isinstance(approval, dict) and approval.get("required") is True
+ and not approval.get("approved") and not approval.get("declined"))
+ if isinstance(approval, dict) and approval.get("declined") is True:
+ print(f"\r{' ' * 80}\r", end="")
+ print(a.err_line("This computer was not approved (Not me was chosen)."))
+ print(a.dim(" Re-run `sibyl init --force` if that was a mistake."))
+ _h.handoff("done", human="this computer was not approved on the account page; if that "
+ "was a mistake, say so and I will start again")
+ return 2
+ if waiting_approval and not approve_url_printed:
+ url = approval.get("approve_url")
+ # Only our own origin with the ?r= handle, never a server string
+ # pointing anywhere else and never a ?s= link.
+ if _approve_url_ok(url):
+ print(f"\r{' ' * 80}\r", end="")
+ print(a.dim(f" approve this computer at {url}"))
+ _h.waiting(f"for approval at {ACCOUNT_HOST}", int(deadline - time.time()),
+ human=f"on a computer already signed in, open {url}, sign in, and type "
+ f"the code {formatted_code} to approve this one")
+ approve_url_printed = True
+
+ # Spinner tick
+ spin_i = (spin_i + 1) % len(spinner)
+ remaining = int(deadline - time.time())
+ spin_glyph = a.color(spinner[spin_i], a.PULSE)
+ label = f"waiting for approval at {ACCOUNT_HOST}" if waiting_approval else "watching the network for your bind"
+ status = f"\r {spin_glyph} {a.dim(label)} … {a.dim(f'{remaining // 60}:{remaining % 60:02d} left')}"
+ if status != last_status:
+ sys.stdout.write(status)
+ sys.stdout.flush()
+ last_status = status
+ time.sleep(POLL_INTERVAL_SEC)
+
+ print()
+ print(a.err_line("Activation timed out."))
+ print(a.dim(" Re-run `sibyl init --force` to try again."))
+ print()
+ print(a.dim(" If your browser already showed 'Activation successful',"))
+ print(a.dim(" your bind landed server-side but didn't reach this terminal."))
+ print(a.dim(" Running `sibyl init --force` again will start a fresh handshake;"))
+ print(a.dim(" bind through the same browser to write credentials locally."))
+ _h.handoff("sibyl init --force", human="did the browser show Activation successful? either way "
+ "the next command starts a fresh handshake")
+ return 1
+
+
+# ---- `sibyl upgrade` ---------------------------------------------------
+
+def _legacy_upgrade_url(session_token: str) -> str | None:
+ """The pre-2026-05-25 upgrade link. Only for an api with no upgrade-nonce
+ endpoint (404). It carries the bearer in the URL, which is why every other
+ path avoids it."""
+ if not _bearer_allowed(UPGRADE_BASE):
+ # Panel fix 6: the bearer never goes into a link on another host.
+ _note_untrusted_base(UPGRADE_BASE, "SIBYL_UPGRADE_BASE")
+ global _UPGRADE_GATE_HANDOFF
+ _UPGRADE_GATE_HANDOFF = ("done", _gate.UNTRUSTED_UPGRADE_HUMAN)
+ return None
+ return f"{UPGRADE_BASE}?session={session_token}"
+
+
+SESSION_EXPIRED = "session-expired"
+# The gate handoff of a refused upgrade-nonce call (a 403 gate line), if any.
+_UPGRADE_GATE_HANDOFF: tuple | None = None
+PURCHASE_HUMAN = ("Pro is a purchase, so it is your call: buy it on the account page (card, or USDC) "
+ "or stake $SIBYL; I watch for the plan change here")
+
+
+def _upgrade_exchange_url(creds: dict, account_id: str) -> str | None:
+ """POST /api/plugin/upgrade-nonce and return its exchange_url.
+
+ 404 (an api from before the nonce existed) falls back to the legacy link.
+ Any other failure returns None; the caller prints and exits 2.
+ """
+ token = creds.get("bearer_token") or creds.get("session_token")
+ try:
+ resp = http_request(
+ "POST",
+ "/api/plugin/upgrade-nonce",
+ body={"account_id": account_id, "session_token": token},
+ headers=_bearer_headers(creds),
+ timeout=10.0,
+ )
+ except HttpError as e:
+ # A route-level 404 (no such endpoint). "account not found" is a real
+ # answer from a current api, and the legacy page would fail the same way.
+ if e.status == 404 and e.message != "account not found":
+ return _legacy_upgrade_url(token)
+ gate_line = _gate.gate_http_line(e.status, e.code, cred_path=_ENT_CRED_PATH, body=e.body)
+ if gate_line:
+ print(a.warn_line(gate_line))
+ global _UPGRADE_GATE_HANDOFF
+ _UPGRADE_GATE_HANDOFF = _gate.gate_http_handoff(e.status, e.code, cred_path=_ENT_CRED_PATH, body=e.body)
+ return None
+ if e.status == 401:
+ return SESSION_EXPIRED
+ return None
+ url = resp.get("exchange_url") if isinstance(resp, dict) else None
+ if not isinstance(url, str) or not url.startswith("https://"):
+ return None
+ return url
+
+
+def cmd_upgrade(args: argparse.Namespace) -> int:
+ """Upgrade flow. Read existing creds → open upgrade page → poll /access until tier flips."""
+ creds = read_credentials(Path(args.credentials).expanduser())
+ if not creds:
+ print(a.err_line("Not activated."))
+ print(a.dim(" Run `sibyl init` first."))
+ _h.handoff(_init_next(), later=("sibyl upgrade",))
+ return 1
+
+ account_id = creds.get("account_id")
+ session_token = creds.get("session_token")
+ # Shown-tier fix: the tier of the current pass (the saved tier only without one).
+ current_tier = str(_gate.peek_tier(Path(args.credentials).expanduser(), creds.get("tier"))
+ or "free").lower()
+
+ if not account_id or not session_token:
+ print(a.err_line("credentials.json is missing account_id or session_token."))
+ print(a.dim(" Re-run `sibyl init`."))
+ _h.handoff("sibyl init --force")
+ return 1
+
+ # 0.5.0: the bearer never rides a URL. Either the account billing page
+ # (sign in there; no token) or the one-time upgrade-nonce exchange.
+ access, access_err = _fetch_access_ex(creds)
+ if _is_untrusted(access_err):
+ print(a.err_line(_gate.UNTRUSTED_BASE_LINE))
+ nxt, human = _gate.untrusted_base_handoff()
+ _h.handoff(nxt, human=human)
+ return 1
+ if access_err is not None and access_err.status == 401:
+ # Release-blocker F7: say what fixes it, never "try again".
+ claim_line = _claim_signout_line(access_err)
+ print(a.err_line(claim_line or "session expired. re-run sibyl init."))
+ _h.handoff(_gate.SIGNED_OUT_ON_CLAIM_NEXT if claim_line else "sibyl init")
+ return 1
+ features = _features_of(access)
+ account = _account_of(access)
+ dash = features.get("web_dashboard_url")
+
+ print()
+ print(a.section_header("upgrade", subtitle="lift the 5 MB free-tier cap"))
+ print()
+ print(a.kv("Account", account_id or "—"))
+ print(a.kv("Current tier", _tier_display(current_tier).upper(), value_color="accent"))
+
+ # Release-blocker F7: warn whenever the purchase rails would refuse (nag
+ # with the purchase gate on, or enforce past grace), not only on enforced.
+ purchase_human = PURCHASE_HUMAN
+ if account.get("purchase_blocked") is True or (account.get("email_required") is True and account.get("enforced") is True):
+ print(a.warn_line("a confirmed email is required before buying: sibyl email add you@example.com"))
+ purchase_human += ("; the account needs a confirmed email before buying; if the page refuses, "
+ "stop and I will run sibyl email add")
+
+ if features.get("web_checkout") is True and _on_account_origin(dash):
+ upgrade_url = f"{dash.rstrip('/')}/billing"
+ print(a.kv("Opening", upgrade_url))
+ print()
+ print(a.dim(" buy Pro on the account page (sign in first; card, or USDC from the plugin page)."))
+ print(a.dim(" this terminal keeps watching for the tier change."))
+ print()
+ else:
+ global _UPGRADE_GATE_HANDOFF
+ _UPGRADE_GATE_HANDOFF = None
+ upgrade_url = _upgrade_exchange_url(creds, account_id)
+ if upgrade_url == SESSION_EXPIRED:
+ print(a.err_line("session expired. re-run sibyl init."))
+ _h.handoff("sibyl init")
+ return 1
+ if upgrade_url is None:
+ gate_h = _UPGRADE_GATE_HANDOFF
+ if gate_h is not None and gate_h[0] == "done":
+ # D1: an untrusted SIBYL_UPGRADE_BASE; nothing to retry.
+ print(a.err_line("could not start the upgrade: the sign-in was not sent."))
+ _h.handoff(gate_h[0], human=gate_h[1])
+ return 1
+ print(a.err_line("could not start the upgrade. try again."))
+ if gate_h is not None:
+ _h.handoff(gate_h[0], human=gate_h[1], later=("sibyl upgrade",))
+ else:
+ _h.handoff(_h.RETRY)
+ return 2
+ # Never print the opened URL: the exchange code is single-use but still
+ # a credential for 15 minutes, and the legacy fallback holds the bearer.
+ print(a.kv("Opening", UPGRADE_BASE))
+ print()
+ print(a.dim(" two paths in the browser:"))
+ print(a.dim(" 1. Pro in USDC: $12 for one month or $108 for one year (a fixed period)"))
+ print(a.dim(" 2. stake 100,000 $SIBYL on Base: Pro while it stays staked (holding does not count)"))
+ print(a.dim(" by card: $12/month or $108/year plus applicable tax at sibyllabs.org/checkout, then sibyl claim "))
+ print()
+
+ try:
+ webbrowser.open(upgrade_url, new=2)
+ except Exception:
+ pass
+
+ _h.waiting("for the plan change", UPGRADE_TIMEOUT_SEC, human=purchase_human)
+
+ # Poll /api/plugin/access until tier changes
+ deadline = time.time() + UPGRADE_TIMEOUT_SEC
+ last_status = ""
+ spinner = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
+ spin_i = 0
+
+ while time.time() < deadline:
+ try:
+ resp = http_request(
+ "POST",
+ "/api/plugin/access",
+ body={"account_id": account_id, "session_token": session_token},
+ timeout=10.0,
+ )
+ except HttpError as e:
+ if e.status == 401:
+ claim_line = _claim_signout_line(e)
+ print(red("\n" + claim_line) if claim_line else red("\nSession expired. Re-run `sibyl init`."))
+ _h.handoff(_gate.SIGNED_OUT_ON_CLAIM_NEXT if claim_line else "sibyl init")
+ return 1
+ # Transient — keep polling
+ resp = {}
+
+ new_tier = (resp.get("tier") or current_tier).lower()
+ source = resp.get("source")
+
+ if new_tier != current_tier and source in ("subscription", "staker"):
+ # Tier changed. Refresh the local hint. Signed fields never change
+ # under an old signature (release-blocker F1): the signature and
+ # signed_at are dropped with the edit (hardening L2).
+ _unsign_for_local_edit(creds)
+ creds["tier"] = new_tier
+ if resp.get("staker") and resp["staker"].get("wallet"):
+ creds["wallet"] = resp["staker"]["wallet"]
+ write_credentials_atomic(creds, Path(args.credentials).expanduser())
+ invalidate_tier_cache()
+
+ print(f"\r{' ' * 80}\r", end="")
+ print()
+ print(a.success_line(f"Upgraded to {new_tier.upper()} via {source}."))
+ print()
+ print(a.kv("Source", source))
+ if resp.get("expires_at"):
+ print(a.kv("Expires", _utc_minute(resp["expires_at"]) or str(resp["expires_at"])))
+ if resp.get("cap_bytes") is None:
+ print(a.kv("Storage cap", "unlimited", value_color="ok"))
+ else:
+ print(a.kv("Storage cap", f"{_fmt_cap_bytes(resp.get('cap_bytes'))} bytes"))
+ if resp.get("staker"):
+ s = resp["staker"]
+ print(a.kv("Wallet", s.get("wallet", "—")))
+ print(a.kv("$SIBYL held", str(s.get("total_sibyl", "—"))))
+ print()
+ print(a.dim(" local tier cache cleared. your next write will sync the new tier."))
+ _h.handoff("sibyl refresh")
+ return 0
+
+ spin_i = (spin_i + 1) % len(spinner)
+ remaining = int(deadline - time.time())
+ spin_glyph = a.color(spinner[spin_i], a.PULSE)
+ tier_glyph = a.color(current_tier.upper(), a.ACCENT)
+ status = f"\r {spin_glyph} {a.dim('waiting for browser upgrade')} · current: {tier_glyph} {a.dim(f'{remaining // 60}:{remaining % 60:02d} left')}"
+ if status != last_status:
+ sys.stdout.write(status)
+ sys.stdout.flush()
+ last_status = status
+ time.sleep(POLL_INTERVAL_SEC)
+
+ print()
+ print(a.err_line("Upgrade timed out. Tier unchanged."))
+ print(a.dim(" Re-run `sibyl upgrade` to retry."))
+ _h.handoff("sibyl refresh", later=("sibyl claim ",),
+ human="did the payment complete? if you paid by card, give me the cs_ code from the "
+ "welcome page")
+ return 1
+
+
+# ---- `sibyl status` ----------------------------------------------------
+
+def _discover_stores(primary_db: Path) -> list[dict[str, Any]]:
+ """Enumerate every memory.db an agent on this machine might resolve.
+
+ Beta reports (2026-06-11) showed split-brain storage: the SDK / CLI /
+ MCP default (``~/.sibyl-memory/memory.db``), the Hermes adapter
+ (``$HERMES_HOME/sibyl/memory.db``), per-profile DBs
+ (``$HERMES_HOME/sibyl/profiles//memory.db``), and an MCP
+ ``SIBYL_MEMORY_DB`` override can each hold a disjoint set of memories, so a
+ user switching entry points sees memory "vanish". This surfaces all of
+ them in one place. Read-only: it never creates or moves anything (path
+ unification is a separate, migration-gated change).
+
+ Returns one dict per DISTINCT existing store, resolved + deduped:
+ ``{"label", "path", "size"}``.
+ """
+ candidates: list[tuple[str, Path]] = [("default (SDK/CLI/MCP)", primary_db)]
+
+ hermes_home_env = os.environ.get("HERMES_HOME")
+ hermes_home = Path(hermes_home_env).expanduser() if hermes_home_env else (Path.home() / ".hermes")
+ candidates.append(("hermes adapter", hermes_home / "sibyl" / "memory.db"))
+ profiles_dir = hermes_home / "sibyl" / "profiles"
+ if profiles_dir.is_dir():
+ # #15 hygiene: iterdir() raises PermissionError on a restricted
+ # profiles directory (e.g. a 0700 dir owned by another user). Skip the
+ # whole profiles sweep gracefully rather than crashing `sibyl status`.
+ try:
+ profiles = sorted(profiles_dir.iterdir())
+ except (PermissionError, OSError):
+ profiles = []
+ for prof in profiles:
+ db = prof / "memory.db"
+ if db.exists():
+ candidates.append((f"hermes profile · {prof.name}", db))
+
+ mcp_override = os.environ.get("SIBYL_MEMORY_DB")
+ if mcp_override:
+ candidates.append(("MCP SIBYL_MEMORY_DB", Path(mcp_override).expanduser()))
+
+ seen: set[str] = set()
+ stores: list[dict[str, Any]] = []
+ for label, path in candidates:
+ try:
+ resolved = str(path.resolve())
+ except OSError:
+ resolved = str(path)
+ if resolved in seen or not path.exists():
+ continue
+ seen.add(resolved)
+ try:
+ size = path.stat().st_size
+ except OSError:
+ size = 0
+ stores.append({"label": label, "path": str(path), "size": size})
+ return stores
+
+
+def _print_account_rows(resp: Any, creds: dict) -> None:
+ """Email / Account / Dashboard rows (0.5.0). Nothing when the api sends no
+ `account` / `features`, so status on an old api is unchanged."""
+ account = _account_of(resp)
+ if account:
+ verified = account.get("email_verified")
+ label = account.get("email_masked") if isinstance(account.get("email_masked"), str) else None
+ if label is None and creds.get("email"):
+ label = _mask_email(creds.get("email"))
+ if verified is True:
+ print(a.kv("Email", f"confirmed \u00b7 {label}" if label else "confirmed", value_color="ok"))
+ elif label:
+ print(a.kv("Email", "not confirmed \u00b7 run sibyl email verify", value_color="warn"))
+ else:
+ print(a.kv("Email", "none \u00b7 run sibyl email add you@example.com", value_color="warn"))
+ if account.get("email_required") is True:
+ grace = account.get("grace_until")
+ value = f"incomplete \u00b7 email required by {grace[:10]}" if isinstance(grace, str) and grace else "incomplete"
+ if account.get("enforced") is True:
+ value += " \u00b7 purchases need a confirmed email (local memory unaffected)"
+ print(a.kv("Account", value, value_color="warn"))
+ dash = _features_of(resp).get("web_dashboard_url")
+ if _on_account_origin(dash):
+ print(a.kv("Dashboard", dash))
+
+
+def _print_version_row() -> None:
+ """Version row (2026-10-08): the first `sibyl status` row, in both branches, so a report
+ pasted from status always carries the build."""
+ client = _installed_version("sibyl-memory-client") or "not installed"
+ print(a.eyebrow("plugin"))
+ print(a.kv("Version", f"cli {_client_version()} \u00b7 client {client}"))
+
+
+def cmd_status(args: argparse.Namespace) -> int:
+ """Show local + server-side state. Runs one access check-in when online,
+ which may renew entitlement.json and the saved tier; nothing else changes.
+
+ LIGHT treatment: utilitarian dashboard. No banner, no section header,
+ no chrome. Eyebrow labels + kv rows + ↓ status drift surfaces. Same
+ convention as `git status`, `ls -la`, `btop` panel bodies."""
+ cred_path = Path(args.credentials).expanduser()
+ creds = read_credentials(cred_path)
+
+ print()
+
+ if not creds:
+ _print_version_row()
+ print(a.warn_line("Not activated."))
+ print(a.dim(" Run `sibyl init`."))
+ print(a.dim(" agents cannot use memory until you do. your local data is kept."))
+ pre = _default_tenant_hint(Path(args.db).expanduser(), None)
+ _h.handoff(_init_next(), later=("sibyl memory adopt",) if pre else ())
+ return 0
+
+ # 0.5.0 account gate (spec 3.4): one refresh attempt when online (the
+ # refresh IS the status check), then the state from the entitlement.
+ # Shown-tier fix (2026-10-08): taken BEFORE the local rows, so the Tier row shows
+ # the current verified pass (the refresh also rewrites the saved tier),
+ # falling back to the saved tier only without a valid pass.
+ ent_info = _gate.status_info(cred_path, refresh=True)
+ creds = read_credentials(cred_path) or creds
+ tier_shown = _gate.display_tier(ent_info, creds.get("tier"))
+
+ _print_version_row()
+
+ # Local view
+ print(a.eyebrow("local"))
+ print(a.kv("Credentials", str(cred_path)))
+ print(a.kv("Account", creds.get("account_id") or "—"))
+ print(a.kv("Tier", _tier_display(tier_shown), value_color="accent"))
+ print(a.kv("Wallet", creds.get("wallet") or "—"))
+ print(a.kv("Email", creds.get("email") or "—"))
+ print(a.kv("Issued", _utc_minute(creds.get("issued_at")) or creds.get("issued_at") or "—"))
+ _family, plat_label, plat_ok = _platform_info()
+ print(a.kv("Platform", plat_label if plat_ok else f"{plat_label} \u00b7 unsupported",
+ value_color="ink" if plat_ok else "warn"))
+
+ db_path = Path(args.db).expanduser()
+ if db_path.exists():
+ # CLI-3 / D3: a path that exists but is not a SQLite DB is labeled
+ # explicitly instead of being reported as a normal memory store.
+ if not is_sqlite_db(db_path):
+ # Not a DB: report the raw file size, since the logical SQLite
+ # measure does not apply to an arbitrary file.
+ size = db_path.stat().st_size
+ print(a.kv("DB path", str(db_path)))
+ print(a.kv("DB size", f"{size:,} bytes (not a SQLite database)", value_color="err"))
+ else:
+ # B001 (audit #13): report the same WAL-inclusive logical footprint
+ # the cap gate enforces (sibyl_memory_client.storage.db_size_bytes),
+ # not the raw memory.db st_size. The raw file under-reports during a
+ # write burst (committed pages still in memory.db-wal), so the
+ # displayed size/percentage would otherwise disagree with the gate.
+ from sibyl_memory_client.storage import db_size_bytes
+ from sibyl_memory_client._capcheck import FREE_TIER_CAP_BYTES
+ from sibyl_memory_client.tiers import is_paid
+
+ size = db_size_bytes(db_path)
+ # Panel fix 2026-09-04: the divisor was a hardcoded pre-2026-08-06
+ # 2 MiB; the free cap is FREE_TIER_CAP_BYTES (5 MiB). And a paid
+ # tier has no cap, so no percentage is shown for it.
+ tier_now = tier_shown or "free"
+ if is_paid(tier_now):
+ size_label = f"{size:,} bytes ({size / (1024 * 1024):.2f} MB · uncapped)"
+ size_color = "soft"
+ else:
+ pct = size / FREE_TIER_CAP_BYTES * 100
+ size_label = f"{size:,} bytes ({size / (1024 * 1024):.2f} MB · {pct:.1f}% of free cap)"
+ size_color = "warn" if pct > 80 else "soft"
+ print(a.kv("DB path", str(db_path)))
+ print(a.kv("DB size", size_label, value_color=size_color))
+ else:
+ print(a.kv("DB path", f"{db_path} (not created)"))
+ pre_rows = _default_tenant_hint(db_path, creds)
+
+ print()
+ print(a.eyebrow("access"))
+ if ent_info is None:
+ print(a.kv("Access", "unknown · sibyl-memory-client is not installed", value_color="warn"))
+ nxt, human = "pip install -U sibyl-memory-client", None
+ else:
+ nxt, human = _gate.access_handoff(ent_info)
+ row = _gate.access_row(ent_info)
+ color = ("ok" if ent_info.get("state") == "fresh"
+ else "warn" if ent_info.get("state") in ("stale", "bootstrap") else "err")
+ print(a.kv("Access", row, value_color=color))
+ plan = _gate.plan_row(ent_info)
+ if plan:
+ print(a.kv("Plan", plan, value_color="warn" if " \u00b7 ends " in plan else "ink"))
+ comp = _computers_label(cred_path)
+ if comp:
+ print(a.kv("Computers", comp,
+ value_color="warn" if "over the limit" in comp else "ink"))
+
+ # All resolvable stores on this machine (split-brain visibility floor,
+ # beta report 2026-06-11). Read-only: lists what exists, moves
+ # nothing. A divergence warning fires when more than one store holds data,
+ # because that is exactly when an agent "loses" memory by switching the
+ # entry point it reads from.
+ stores = _discover_stores(db_path)
+ split_n = 0
+ if len(stores) > 1:
+ print()
+ print(a.eyebrow("memory stores"))
+ for s in stores:
+ mb = s["size"] / (1024 * 1024)
+ print(a.kv(s["label"], f"{s['path']} ({s['size']:,} bytes · {mb:.2f} MB)"))
+ with_data = [s for s in stores if s["size"] > 0]
+ if len(with_data) > 1:
+ split_n = len(with_data)
+ print()
+ print(a.warn_line("Multiple memory stores hold data on this machine."))
+ print(a.dim(" Memory is NOT shared across these paths. An agent reads only the store"))
+ print(a.dim(" for its entry point (SDK/CLI vs Hermes vs profile vs MCP), so memory can"))
+ print(a.dim(" look 'missing' when you switch. Point every entry point at one path via"))
+ print(a.dim(" --db / SIBYL_MEMORY_DB, or back up and consolidate before relying on recall."))
+
+ tier_cache = Path(args.tier_cache).expanduser()
+ if tier_cache.exists():
+ # CLI-4: a corrupt tier_cache.json must not crash `sibyl status` —
+ # same crash class as D1, separate call site. Degrade to empty dict.
+ try:
+ cache = json.loads(tier_cache.read_text(encoding="utf-8"))
+ except (ValueError, OSError):
+ cache = {}
+ if not isinstance(cache, dict):
+ cache = {}
+ # checked_at is written by _capcheck.py as epoch seconds (float), but
+ # older caches / future formats may carry an ISO string. Render both;
+ # never index a float (TypeError on every `sibyl status` run with a
+ # populated tier cache; Discord report 2026-06-10).
+ checked = cache.get("checked_at")
+ checked = _utc_minute(checked) or (str(checked)[:19] if checked else "?")
+ cached_tier = cache.get("tier", "?")
+ if (_gate.has_valid_pass(ent_info)
+ and _tier_display(cached_tier) != _tier_display(tier_shown)):
+ # Shown-tier fix: one tier per screen; the pass decides, the cache is old.
+ print(a.kv("Tier cache", f"superseded by the access pass (checked {checked})"))
+ else:
+ print(a.kv("Tier cache", f"{cached_tier} (checked {checked})"))
+ else:
+ print(a.kv("Tier cache", "—"))
+
+ # Server view (only if account_id + session_token are present)
+ drift = False
+ server_err: int | str | None = None
+ if creds.get("account_id") and creds.get("session_token"):
+ print()
+ print(a.eyebrow("server"))
+ try:
+ resp = http_request(
+ "POST",
+ "/api/plugin/access",
+ body={"account_id": creds["account_id"], "session_token": creds["session_token"]},
+ timeout=10.0,
+ )
+ print(a.kv("Tier", _tier_display(resp.get("tier")), value_color="accent"))
+ print(a.kv("Source", resp.get("source") or "—"))
+ print(a.kv("Cap bytes", _fmt_cap_bytes(resp.get("cap_bytes"))))
+ if resp.get("expires_at"):
+ print(a.kv("Expires", _utc_minute(resp["expires_at"]) or str(resp["expires_at"])))
+ if resp.get("staker"):
+ s = resp["staker"]
+ print(a.kv("$SIBYL held", str(s.get("total_sibyl", "—"))))
+ print(a.kv("Threshold", str(s.get("threshold_sibyl", "—"))))
+ print(a.kv("Qualified", "yes" if s.get("qualified") else "no",
+ value_color="ok" if s.get("qualified") else "soft"))
+ _print_account_rows(resp, creds)
+ # Detect server/local drift
+ # Compared as display words, so a legacy local label (stake) and
+ # the server's canonical one (pro) are not reported as drift.
+ srv_tier = _tier_display(resp.get("tier"))
+ loc_tier = _tier_display(tier_shown)
+ if srv_tier != loc_tier:
+ print()
+ print(a.warn_line(f"Local tier ({loc_tier}) differs from server tier ({srv_tier})."))
+ print(a.dim(" Run `sibyl refresh` to pick up the server plan, or `sibyl init --force` to re-activate."))
+ drift = True
+ except HttpError as e:
+ server_err = e.status
+ claim_line = _claim_signout_line(e)
+ if claim_line:
+ print(a.kv("Tier", "signed out", value_color="err"))
+ print(a.dim(f" {claim_line}"))
+ elif _is_untrusted(e):
+ server_err = UNTRUSTED_BASE_CODE
+ print(a.kv("Tier", "not checked", value_color="err"))
+ print(a.dim(f" {_gate.UNTRUSTED_BASE_LINE}"))
+ else:
+ print(a.kv("Tier", f"server error: {e.status}", value_color="err"))
+ if e.status == 0 and server_err != UNTRUSTED_BASE_CODE and ent_info \
+ and isinstance(ent_info.get("acct"), dict):
+ # Offline: the last known account state, from the entitlement.
+ when = ent_info.get("received_at")
+ as_of = _utc_minute(when) or "?"
+ print(a.dim(f" as of {as_of} (last check-in):"))
+ _print_account_rows({"account": ent_info["acct"]}, creds)
+
+ # Save and debloat (spec plugin-save-debloat 4.3): local only, no network.
+ from . import lifecycle_cli as _lc
+ _lc.status_rows(args, creds)
+
+ print()
+ # Agent handoff (rows S3 to S12): the access state first; a healthy state
+ # gives way to an unreachable server, then tier drift, then split stores.
+ if server_err == UNTRUSTED_BASE_CODE or (ent_info or {}).get("refresh_code") == UNTRUSTED_BASE_CODE:
+ # D1: the access state above was not checked with the server because
+ # the sign-in was not sent; the only fix is the environment.
+ nxt, human = _gate.untrusted_base_handoff()
+ elif nxt == "done":
+ if server_err is not None:
+ nxt, human = "sibyl refresh", (OFFLINE_HUMAN if server_err == 0 else None)
+ elif drift:
+ nxt = "sibyl refresh"
+ elif split_n:
+ human = (f"memory is split across {split_n} stores (listed above); choose which path "
+ "every agent should use")
+ _h.handoff(nxt, human=human, later=("sibyl memory adopt",) if pre_rows else ())
+ return 0
+
+
+def _adopt_after_sign_in(db_path: Path, cred_path: Path) -> bool:
+ """First sign-in on this computer: memory written before sign-in
+ (DEFAULT_TENANT) moves into the account, in one local transaction (client
+ _adopt, the same rule the agents apply on their first operation). Never
+ fails `sibyl init`; a store that has held another account is left for
+ `sibyl memory adopt`, which asks first. Returns True when rows were left
+ for that command (row I14: `later: sibyl memory adopt`)."""
+ try:
+ res = _gate.adopt_pre_signin(db_path, cred_path, trigger="auto")
+ except Exception:
+ return False
+ if res is None:
+ return False
+ if res.status == "moved":
+ print(a.kv("Local memory", f"{res.moved} rows from before sign-in moved into your account",
+ value_color="ok"))
+ if res.renamed:
+ print(a.dim(f" {len(res.renamed)} kept under a new name ending in (before sign-in): "
+ "your account already had that key"))
+ elif res.status == "skipped" and res.reason == "other_account":
+ print(a.warn_line("This computer's memory store also holds another account's memory."))
+ print(a.dim(" Rows written before sign-in were not moved. " + _gate.ADOPT_HINT
+ + " (it asks first)."))
+ return True
+ return False
+
+
+def _install_skills_quietly() -> None:
+ """Save/debloat build (spec 3.2): the save and debloat procedures land in
+ ~/.sibyl-memory/skills/ the moment an account exists (never overwriting a
+ person's edit). One line; never fails `sibyl init`."""
+ try:
+ from sibyl_memory_client import skills as _sk
+ rep = _sk.install(Path.home())
+ except Exception:
+ return
+ state = "ready" if rep.ok else "see sibyl skills status"
+ print(a.kv("Save + debloat", f"procedures v{rep.version} {state} · wire them with sibyl setup"))
+ for m in rep.messages:
+ print(a.dim(" " + m))
+
+
+def _default_tenant_hint(db_path: Path, creds: dict | None) -> int:
+ """Spec 3.5: a one-line hint when the default store holds entities written
+ under DEFAULT_TENANT before an account existed (a COUNT only, no content,
+ read-only sqlite, no gate, no network). Returns the count (row S12)."""
+ try:
+ from sibyl_memory_client import DEFAULT_TENANT
+ except Exception:
+ return 0
+ active = (creds or {}).get("tenant_id") or (creds or {}).get("account_id")
+ if active == DEFAULT_TENANT or not db_path.exists() or not is_sqlite_db(db_path):
+ return 0
+ import sqlite3
+ try:
+ con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
+ try:
+ n = con.execute("SELECT COUNT(*) FROM entities WHERE tenant_id = ?",
+ (DEFAULT_TENANT,)).fetchone()[0]
+ finally:
+ con.close()
+ except sqlite3.Error:
+ return 0
+ if n:
+ print(a.dim(f" {n} entities from before sign-in are kept under the default tenant; "
+ f"agents signed in to your account do not see them yet."))
+ if active:
+ print(a.dim(" " + _gate.ADOPT_HINT + "."))
+ return int(n or 0)
+
+
+# ---- `sibyl dashboard` -------------------------------------------------
+
+def cmd_dashboard(args: argparse.Namespace) -> int:
+ """Open the account page the server advertises (features.web_dashboard_url).
+
+ No token rides the URL, ever: you sign in on the page with your confirmed
+ email or your wallet. 0.4.x opened SIBYL_DASHBOARD_BASE with the bearer in
+ the query string, which the account page never read; that path is gone.
+ When the server advertises no account page (or cannot be reached), this
+ falls through to `sibyl status` as before.
+ """
+ creds = read_credentials(Path(args.credentials).expanduser())
+ access = _fetch_access(creds) if creds and creds.get("account_id") and \
+ (creds.get("bearer_token") or creds.get("session_token")) else None
+ url = _features_of(access).get("web_dashboard_url")
+ if _on_account_origin(url):
+ account = _account_of(access)
+ print()
+ print(a.kv("Opening", url))
+ print(a.dim(" sign in with your confirmed email (or your wallet)."))
+ dash_human = "sign in on the account page with your confirmed email or wallet"
+ if account.get("email_verified") is False:
+ print(a.dim(" your account has no confirmed email yet: sign in with your wallet and add one there,"))
+ print(a.dim(" or run sibyl email add."))
+ dash_human += "; add an email there or tell me one"
+ print()
+ try:
+ webbrowser.open(url, new=2)
+ except Exception:
+ pass
+ _h.handoff("done", human=dash_human)
+ return 0
+ if access is not None:
+ print()
+ print(a.dim(" the account page is not open yet."))
+ return cmd_status(args)
+
+
+# ---- `sibyl whoami` ----------------------------------------------------
+
+def _mask_email(e: str | None) -> str:
+ if not e or "@" not in e:
+ return "—"
+ user, _, domain = e.partition("@")
+ if "." not in domain:
+ return f"{user[0]}***@{domain[0]}***"
+ name, _, tld = domain.rpartition(".")
+ return f"{user[0]}***@{name[0]}***.{tld}"
+
+
+def _mask_wallet(w: str | None) -> str:
+ if not w or not w.startswith("0x") or len(w) < 12:
+ return w or "—"
+ return f"{w[:6]}…{w[-4:]}"
+
+
+def cmd_whoami(args: argparse.Namespace) -> int:
+ """One-line account summary. Shows account_id + tier + linked email/wallet + this device.
+
+ LIGHT treatment: 4-line glance. No banner, no section header. Same shape
+ as `whoami` on unix, `gh auth status`, `aws sts get-caller-identity`."""
+ creds = read_credentials(Path(args.credentials).expanduser())
+ if not creds:
+ print(a.warn_line("Not activated."))
+ print(a.dim(" Run `sibyl init`."))
+ _h.handoff(_init_next())
+ return 1
+
+ full = bool(getattr(args, "full", False))
+ acct = creds.get("account_id") or ""
+ tier = _tier_display(_gate.peek_tier(Path(args.credentials).expanduser(),
+ creds.get("tier"))).upper()
+ email = creds.get("email") if full else _mask_email(creds.get("email"))
+ wallet = creds.get("wallet") if full else _mask_wallet(creds.get("wallet"))
+
+ print()
+ print(f" {a.color('account', a.INK_FAINT)} {a.bold(acct or '—')} {a.dim(a.GLYPH_DOT)} {a.gradient_gold(tier)}")
+ print(f" {a.color('wallet ', a.INK_FAINT)} {a.color(wallet or '—', a.INK)}")
+ print(f" {a.color('email ', a.INK_FAINT)} {a.color(email or '—', a.INK)}")
+ _family, plat_label, plat_ok = _platform_info()
+ device_line = f"sibyl-memory-cli/{_client_version()} {plat_label}"
+ if not plat_ok:
+ device_line += " \u00b7 unsupported"
+ print(f" {a.color('device ', a.INK_FAINT)} {a.dim(device_line)}")
+ print()
+ _h.handoff("done")
+ return 0
+
+
+# ---- `sibyl claim` -----------------------------------------------------
+
+def _looks_like_checkout_code(cs: str) -> bool:
+ """Mirror of the server's CS_ID_RE without importing re: cs_ prefix,
+ optional test_/live_ marker, then 10..240 alphanumerics."""
+ if not cs.startswith("cs_"):
+ return False
+ rest = cs[3:]
+ for marker in ("test_", "live_"):
+ if rest.startswith(marker):
+ rest = rest[len(marker):]
+ break
+ return 10 <= len(rest) <= 240 and rest.isalnum()
+
+
+def cmd_claim(args: argparse.Namespace) -> int:
+ """Link a card purchase (Stripe checkout) to this account.
+
+ Buy-before-install: the page after checkout shows the buyer their
+ checkout code (cs_...). This redeems it onto the account activated on
+ this machine — email or wallet activation both work. The bearer rides
+ along as session_token so the server verifies the caller controls the
+ destination account, not just the receipt.
+ """
+ cs = (getattr(args, "checkout_code", "") or "").strip()
+ if not _looks_like_checkout_code(cs):
+ print(a.warn_line("That does not look like a checkout code."))
+ print(a.dim(" It starts with cs_ and appears on the page you landed on after paying"))
+ print(a.dim(f" ({CLAIM_PAGE}). Copy the whole code."))
+ _h.handoff("sibyl claim ", human="the whole cs_ code from the page after paying "
+ f"({CLAIM_PAGE})")
+ return 1
+
+ creds = read_credentials(Path(args.credentials).expanduser())
+ if not creds or not creds.get("account_id"):
+ print(a.warn_line("Not activated."))
+ print(a.dim(" Run `sibyl init` first, then `sibyl claim` again."))
+ _h.handoff(_init_next(), later=(f"sibyl claim {cs}",))
+ return 1
+ account_id = creds["account_id"]
+
+ body: dict = {"cs": cs, "account_id": account_id}
+ token = creds.get("bearer_token") or creds.get("session_token")
+ if token:
+ body["session_token"] = token
+
+ try:
+ resp = http_request("POST", "/api/plugin/stripe-claim", body=body,
+ headers=_bearer_headers(creds))
+ except HttpError as e:
+ msg = e.body.get("error") if isinstance(e.body, dict) else None
+ print(a.warn_line(f"Claim failed ({'sign-in not sent' if _is_untrusted(e) else e.status or 'network'})."))
+ gate_line = _gate.gate_http_line(e.status, e.code, cred_path=_ENT_CRED_PATH, body=e.body)
+ if gate_line:
+ print(a.dim(f" {gate_line}"))
+ gnext, ghuman = _gate.gate_http_handoff(e.status, e.code, cred_path=_ENT_CRED_PATH, body=e.body)
+ _h.handoff(gnext, human=ghuman, later=(f"sibyl claim {cs}",))
+ return 1
+ if msg:
+ print(a.dim(f" {msg}"))
+ again = (f"sibyl claim {cs}",)
+ if e.code in ("unclaimed_account", "email_required"):
+ if creds.get("email"):
+ claim_h = ("sibyl email verify", _verify_human(_mask_email(creds.get("email"))))
+ else:
+ claim_h = ("sibyl email add ", "the email address you used to buy")
+ elif e.status == 403:
+ claim_h = (_init_next(), None)
+ elif e.status == 0:
+ claim_h = (_h.RETRY, OFFLINE_HUMAN)
+ again = ()
+ else:
+ claim_h = ("sibyl claim ", f"the purchase could not be linked ({msg or e.status}); "
+ "check the code on the welcome page")
+ again = ()
+ # 0.5.0: branch on the server's machine code, not the status alone.
+ if e.code == "unclaimed_account":
+ if creds.get("email"):
+ print(a.dim(" fastest path: sibyl email verify (confirms the email you used here and keeps"))
+ print(a.dim(f" this computer signed in), then sibyl claim {cs} again."))
+ else:
+ # Release-blocker F7: no email on file, so there is nothing to verify.
+ print(a.dim(" fastest path: sibyl email add you@example.com (confirms an email from this"))
+ print(a.dim(f" computer and keeps it signed in), then sibyl claim {cs} again."))
+ elif e.code == "email_required":
+ print(a.dim(f" then run sibyl claim {cs} again."))
+ elif e.status == 403:
+ print(a.dim(" This session does not match the account. Run `sibyl init`, then retry."))
+ elif e.status == 0:
+ print(a.dim(" Could not reach the server. Check your connection and retry."))
+ _h.handoff(claim_h[0], human=claim_h[1], later=again)
+ return 1
+
+ tier = _tier_display(resp.get("tier") or "pro").upper()
+ print()
+ print(a.success_line(f"Purchase linked. Tier: {tier}"))
+ if resp.get("expires_at"):
+ print(a.kv("Covers through", _utc_minute(resp["expires_at"]) or str(resp["expires_at"])))
+ print(a.dim(" Run the next command and agents pick it up on their next call."))
+ print()
+ _h.handoff("sibyl refresh")
+
+ # Sync local state so the very next write sees the new tier. Signed fields
+ # never change under an old signature (release-blocker F1): the signature
+ # and signed_at are dropped with the edit (hardening L2). The server is the
+ # tier authority either way.
+ try:
+ _unsign_for_local_edit(creds)
+ creds["tier"] = resp.get("tier") or "pro"
+ write_credentials_atomic(creds, Path(args.credentials).expanduser())
+ except Exception:
+ pass # server is the source of truth; local hint refreshes on next access check
+ try:
+ invalidate_tier_cache()
+ except Exception:
+ pass
+ return 0
+
+
+# ---- `sibyl email` -----------------------------------------------------
+
+def cmd_email(args: argparse.Namespace) -> int:
+ """Show, add or confirm the account's email (0.5.0).
+
+ sibyl email state: confirmed / not confirmed / none
+ sibyl email add send a code to a new address, then confirm it
+ sibyl email verify send a code to the address on file, then confirm it
+ sibyl email confirm confirm a code sent earlier
+
+ Confirming from this computer keeps it signed in and signs out every other
+ computer on the account that was set up before (someone who paired your
+ address first loses theirs; you keep yours).
+ """
+ cred_path = Path(args.credentials).expanduser()
+ creds = read_credentials(cred_path)
+ sub = getattr(args, "email_cmd", None)
+
+ if not creds or not creds.get("account_id") or not (creds.get("bearer_token") or creds.get("session_token")):
+ print()
+ print(a.warn_line("Not activated."))
+ print(a.dim(" Run `sibyl init`."))
+ print()
+ asked = " ".join(x for x in ("sibyl email", sub, (getattr(args, "address", "") or "").strip()
+ if sub == "add" else (getattr(args, "code", "") or "").strip()
+ if sub == "confirm" else "") if x) if sub else ""
+ _h.handoff(_init_next() if not creds or _CREDS_CORRUPT else "sibyl init --force",
+ later=(asked,) if asked else ())
+ return 0 if sub is None else 1
+
+ print()
+ if sub is None:
+ access, err = _fetch_access_ex(creds)
+ if access is None:
+ if err is not None and err.status == 401:
+ claim_line = _claim_signout_line(err)
+ print(a.warn_line(claim_line or "session expired. re-run sibyl init."))
+ print()
+ _h.handoff(_gate.SIGNED_OUT_ON_CLAIM_NEXT if claim_line else "sibyl init")
+ return 1
+ if _is_untrusted(err):
+ print(a.warn_line(_gate.UNTRUSTED_BASE_LINE))
+ print()
+ nxt, human = _gate.untrusted_base_handoff()
+ _h.handoff(nxt, human=human)
+ return 1
+ offline = err is None or err.status == 0
+ print(a.warn_line("could not reach the server." if offline
+ else f"server error: {err.status}"))
+ print()
+ _h.handoff(_h.RETRY, human=OFFLINE_HUMAN if offline else None)
+ return 2
+ account = _account_of(access)
+ if not account:
+ print(a.dim(" this server does not report email state yet."))
+ print()
+ _h.handoff("done")
+ return 0
+ masked = account.get("email_masked") if isinstance(account.get("email_masked"), str) else None
+ if masked is None and creds.get("email"):
+ masked = _mask_email(creds.get("email"))
+ web_only = _features_of(access).get("cli_email_verify") is not True
+ if account.get("email_verified") is True:
+ print(a.kv("Email", f"confirmed {masked or ''}".rstrip(), value_color="ok"))
+ state_h = ("done", None)
+ elif web_only:
+ # Row E11: the terminal cannot add or confirm on this api, so
+ # `sibyl email add` / `verify` would loop on not_open.
+ print(a.kv("Email", f"not confirmed {masked}" if masked else "none", value_color="warn"))
+ print(a.dim(f" add and confirm it at {ACCOUNT_BASE}"))
+ state_h = ("done", _email_web_human())
+ elif masked:
+ print(a.kv("Email", f"not confirmed {masked}", value_color="warn"))
+ print(a.dim(" run sibyl email verify"))
+ state_h = ("sibyl email verify", _verify_human(masked))
+ else:
+ print(a.kv("Email", "none", value_color="warn"))
+ print(a.dim(" run sibyl email add "))
+ state_h = ("sibyl email add ", "an email address for the account")
+ print()
+ _h.handoff(state_h[0], human=state_h[1])
+ return 0
+
+ interactive = _is_interactive()
+ if sub == "add":
+ address = (getattr(args, "address", "") or "").strip()
+ if not _looks_like_email(address):
+ print(a.warn_line("that does not look like an email address."))
+ print(a.dim(" usage: sibyl email add you@example.com"))
+ print()
+ _h.handoff("sibyl email add ",
+ human="a valid email address (the one given was not one)")
+ return 1
+ rc, hand = _email_request_and_prompt_h(creds, address, cred_path, interactive=interactive)
+ elif sub == "verify":
+ rc, hand = _email_request_and_prompt_h(creds, None, cred_path, interactive=interactive)
+ elif sub == "confirm":
+ rc, _err, hand = _email_confirm_once_h(creds, getattr(args, "code", "") or "", cred_path)
+ else:
+ print(a.warn_line("usage: sibyl email [add | verify | confirm ]"))
+ rc, hand = 1, ("sibyl email", None)
+ print()
+ _h.handoff(hand[0], human=hand[1])
+ return rc
+
+
+# ---- `sibyl devices` ---------------------------------------------------
+
+def _devices_error_line(e: HttpError) -> str:
+ """Readable devices/revoke failure. The tamper 403 gets its own copy
+ instead of a raw body dump."""
+ if e.status == 403 and isinstance(e.body, dict) and e.body.get("reason") == "tamper_flag_active":
+ return "this account is under review. email sibyl@sibyllabs.org."
+ gate_line = _gate.gate_http_line(e.status, e.code, cred_path=_ENT_CRED_PATH, body=e.body)
+ if gate_line:
+ return gate_line
+ if e.status == 0:
+ return "could not reach the server."
+ return f"server error: {e.status} {e.message or e.body}"
+
+
+def _devices_error_handoff(e: HttpError) -> tuple:
+ """(next, human) for a devices / revoke failure (row V4), same branch
+ order as ``_devices_error_line``."""
+ if e.status == 403 and isinstance(e.body, dict) and e.body.get("reason") == "tamper_flag_active":
+ return _gate.code_handoff("under_review")
+ gate = _gate.gate_http_handoff(e.status, e.code, cred_path=_ENT_CRED_PATH, body=e.body)
+ if gate is not None:
+ return gate
+ if e.status == 0:
+ return (_h.RETRY, OFFLINE_HUMAN)
+ return (_h.RETRY, None)
+
+
+def cmd_devices(args: argparse.Namespace) -> int:
+ """List active bearer tokens (devices) for the account. Optional: revoke by index."""
+ creds = read_credentials(Path(args.credentials).expanduser())
+ if not creds:
+ print(a.err_line("Not activated."))
+ print(a.dim(" Run `sibyl init`."))
+ _h.handoff(_init_next())
+ return 1
+ account_id = creds.get("account_id")
+ session_token = creds.get("session_token")
+ if not account_id or not session_token:
+ print(a.err_line("credentials.json missing account_id or session_token."))
+ print(a.dim(" Run `sibyl init`."))
+ _h.handoff("sibyl init --force")
+ return 1
+
+ sub = getattr(args, "sub", None)
+
+ # `sibyl devices revoke ` path
+ if sub == "revoke":
+ idx = getattr(args, "index", None)
+ if idx is None:
+ print(red("usage: sibyl devices revoke "))
+ _h.handoff("sibyl devices")
+ return 1
+ # CLI-5: reject negative indexes. Python's negative indexing means
+ # `revoke -1` would silently target the LAST device — a footgun that
+ # could revoke the wrong (or your own) device. Require an explicit
+ # non-negative index from `sibyl devices` output.
+ if idx < 0:
+ print(red(f"invalid index {idx}. Use a non-negative index from `sibyl devices`."))
+ _h.handoff("sibyl devices")
+ return 1
+ # List first to map index → bearer_id
+ try:
+ resp = _security_request(
+ "GET", f"/api/plugin/devices?account_id={urllib.parse.quote(account_id)}", creds)
+ except HttpError as e:
+ print(red(_devices_error_line(e)))
+ dn, dh = _devices_error_handoff(e)
+ _h.handoff(dn, human=dh)
+ return 2
+ devices = resp.get("devices", [])
+ try:
+ target = devices[idx]
+ except (IndexError, TypeError):
+ print(red(f"no device at index {idx}. Run `sibyl devices` to see indexes."))
+ _h.handoff("sibyl devices")
+ return 1
+ if not isinstance(target, dict):
+ print(red(f"malformed device record at index {idx}. Run `sibyl devices`."))
+ _h.handoff("sibyl devices")
+ return 2
+ if target.get("is_this_device"):
+ print(red("refusing to revoke your own device — that would lock you out. Run `sibyl logout` instead, then `sibyl init` on a fresh activation."))
+ _h.handoff("sibyl logout", human="that is this computer; signing it out is sibyl logout, "
+ "which removes local credentials; confirm")
+ return 1
+ # CLI-5: bail cleanly if the server payload lacks bearer_id instead of
+ # raising KeyError on hostile/malformed data.
+ bearer_id = target.get("bearer_id")
+ if not bearer_id:
+ print(red(f"device at index {idx} has no bearer_id. Run `sibyl devices` to refresh."))
+ _h.handoff("sibyl devices")
+ return 2
+ try:
+ revoke_resp = _security_request(
+ "POST", "/api/plugin/devices", creds, body={"bearer_id": bearer_id})
+ except HttpError as e:
+ print(red(f"revoke failed: {_devices_error_line(e)}"))
+ dn, dh = _devices_error_handoff(e)
+ _h.handoff(dn, human=dh)
+ return 2
+ name = target.get('device_label') or bearer_id
+ if isinstance(revoke_resp, dict) and revoke_resp.get("already_revoked") is True:
+ print(a.dim(f" {name}: already revoked"))
+ _h.handoff("sibyl devices")
+ return 0
+ print(green(f"✓ Revoked device {name}"))
+ _h.handoff("sibyl devices")
+ return 0 if isinstance(revoke_resp, dict) and revoke_resp.get("revoked") else 1
+
+ # Default: list devices
+ try:
+ resp = _security_request(
+ "GET", f"/api/plugin/devices?account_id={urllib.parse.quote(account_id)}", creds)
+ except HttpError as e:
+ if _claim_signout_line(e):
+ print(a.err_line(_claim_signout_line(e)))
+ _h.handoff(_gate.SIGNED_OUT_ON_CLAIM_NEXT)
+ elif e.status == 401:
+ print(a.err_line("Session expired."))
+ print(a.dim(" Re-run `sibyl init`."))
+ _h.handoff("sibyl init")
+ else:
+ print(a.err_line(_devices_error_line(e)))
+ dn, dh = _devices_error_handoff(e)
+ _h.handoff(dn, human=dh)
+ return 1 if _is_untrusted(e) else 2
+
+ devices = resp.get("devices", [])
+ # LIGHT treatment: table-like dashboard. Eyebrow line with count + the rows. No banner.
+ print()
+ limit_note = _computers_label(Path(args.credentials).expanduser(), resp)
+ print(f" {a.eyebrow('devices')} {a.dim(f'· {len(devices)} active')}"
+ + (f" {a.dim('· ' + limit_note)}" if limit_note else ""))
+ print()
+ if not devices:
+ print(a.dim(" no active devices"))
+ print()
+ _h.handoff("sibyl init")
+ return 0
+
+ for i, d in enumerate(devices):
+ is_this = d.get("is_this_device")
+ marker = a.ok("▶") if is_this else " "
+ label = d.get("device_label") or "(unlabeled)"
+ installed = d.get("install_method") or "—"
+ last_seen = _utc_minute(d.get("last_seen_at")) or "unknown"
+ idx_chip = a.chip(str(i), palette="jade" if is_this else "mute")
+ label_color = a.gradient_gold(label) if is_this else a.color(label, a.INK)
+ meta = f"{a.dim(installed)} {a.dim(a.GLYPH_DOT)} {a.dim('last seen ' + last_seen)}"
+ note = a.color("(this device)", a.PULSE) if is_this else a.dim(f"revoke: sibyl devices revoke {i}")
+ print(f" {marker} {idx_chip} {label_color} {meta} {note}")
+ print()
+ comp = _computers_info(Path(args.credentials).expanduser(), resp)
+ if comp is not None and comp["over"]:
+ from sibyl_memory_client.tiers import is_paid
+ _h.handoff("sibyl devices revoke ",
+ later=() if is_paid(comp["tier"]) else ("sibyl upgrade",),
+ human="which computer to sign out (the index is the number in the row), or get Pro")
+ else:
+ _h.handoff("done")
+ return 0
+
+
+def _computers_info(cred_path: Path, devices_resp: Any = None) -> dict | None:
+ """``{n, limit, over, tier}`` for this account: ``acct.devices`` of the
+ verified entitlement (plan 4.2; read locally, no network), with the tier
+ from the same token. A /devices response's own ``limit`` (an int), when
+ an api sends one, fills a missing limit. None when unknown."""
+ try:
+ info = _gate.status_info(cred_path, refresh=False) or {}
+ except Exception:
+ info = {}
+ from sibyl_memory_client.exceptions import device_limit_info
+ d = device_limit_info(info.get("acct"))
+ if d is None:
+ return None
+ if d["limit"] is None and isinstance(devices_resp, dict):
+ lim = devices_resp.get("limit")
+ if isinstance(lim, int) and not isinstance(lim, bool) and lim >= 0:
+ d["limit"] = lim
+ d["tier"] = info.get("tier")
+ return d
+
+
+def _computers_label(cred_path: Path, devices_resp: Any = None) -> str | None:
+ """`1 of 1 (Free) · Pro: up to 10` (plan 4.4), or None when the api has not
+ sent the computer count yet."""
+ d = _computers_info(cred_path, devices_resp)
+ if d is None:
+ return None
+ from sibyl_memory_client.tiers import is_paid
+ paid = is_paid(d["tier"])
+ if d["limit"] is None:
+ text = f"{d['n']} signed in"
+ else:
+ text = f"{d['n']} of {d['limit']} ({_tier_display(d['tier'])})"
+ if not paid:
+ text += f" · Pro: up to {PRO_DEVICE_LIMIT_HINT}"
+ if d["over"]:
+ text += " · over the limit: new memories save only on the computer that signed in most recently"
+ return text
+
+
+# ---- `sibyl logout` ----------------------------------------------------
+
+# Real #4 (audit): the same offline caveat wherever a logout revoke can't be
+# confirmed — mirrors the `sibyl devices revoke` remediation path.
+_LOGOUT_REVOKE_CAVEAT = (
+ "remote session may still be active; run `sibyl devices revoke` from another device"
+)
+
+
+def _logout_revoke_status(creds: dict) -> tuple[str, str | None]:
+ """Best-effort revoke THIS device's server bearer before local logout.
+
+ Real #4 (audit): `sibyl logout` used to unlink local credentials only, so
+ the bearer (which has no server-side expiry) stayed valid forever after
+ logout. This revokes it first, reusing the EXACT endpoint + auth shape of
+ `sibyl devices revoke` (no new endpoint invented):
+
+ GET /api/plugin/devices?account_id=... (Authorization: Bearer )
+ POST /api/plugin/devices {"bearer_id": ...} (same Bearer auth)
+
+ credentials.json stores only the bearer TOKEN, not its server-side
+ bearer_id, so we list devices to find THIS one (``is_this_device``) and
+ revoke it by id, identical to the interactive revoke flow.
+
+ Returns ("revoked" | "nothing" | "unconfirmed", caveat or None): the
+ caveat is None on a confirmed revoke (or when there is nothing to revoke).
+ 0.5.0: lets logout say "signed out on the server too." only when the
+ server confirmed. Network failure is swallowed but reported (never
+ crashes logout).
+ """
+ account_id = creds.get("account_id")
+ session_token = creds.get("session_token")
+ if not account_id or not session_token:
+ # Pre-activation / malformed creds: nothing server-side to revoke.
+ return "nothing", None
+ try:
+ resp = _security_request(
+ "GET", f"/api/plugin/devices?account_id={urllib.parse.quote(account_id)}", creds)
+ devices = resp.get("devices", []) if isinstance(resp, dict) else []
+ this = next(
+ (d for d in devices if isinstance(d, dict) and d.get("is_this_device")),
+ None,
+ )
+ bearer_id = this.get("bearer_id") if this else None
+ if not bearer_id:
+ # Couldn't identify this device's server record — can't confirm.
+ return "unconfirmed", _LOGOUT_REVOKE_CAVEAT
+ revoke_resp = _security_request(
+ "POST", "/api/plugin/devices", creds, body={"bearer_id": bearer_id})
+ if isinstance(revoke_resp, dict) and revoke_resp.get("revoked"):
+ return "revoked", None
+ return "unconfirmed", _LOGOUT_REVOKE_CAVEAT
+ except Exception:
+ # Best-effort: swallow ANY network/HTTP failure, but report it so the
+ # user knows the remote bearer may still be live.
+ return "unconfirmed", _LOGOUT_REVOKE_CAVEAT
+
+
+def cmd_logout(args: argparse.Namespace) -> int:
+ """Delete credentials.json + tier_cache.json. memory.db stays — that's your data."""
+ cred_path = Path(args.credentials).expanduser()
+ tier_cache = Path(args.tier_cache).expanduser()
+
+ # Real #4: revoke THIS device's server bearer BEFORE unlinking local creds
+ # (once credentials.json is gone we no longer have the token to authorize
+ # the revoke). Best-effort; a failure only produces a printed caveat.
+ revoke_caveat = None
+ revoke_state = "nothing"
+ creds = read_credentials(cred_path)
+ if creds:
+ revoke_state, revoke_caveat = _logout_revoke_status(creds)
+
+ deleted = []
+ if cred_path.exists():
+ cred_path.unlink()
+ deleted.append(str(cred_path))
+ # 0.5.0: the entitlement goes with the credentials (spec 3.4).
+ deleted.extend(_gate.remove_entitlement(cred_path))
+ if tier_cache.exists():
+ tier_cache.unlink()
+ deleted.append(str(tier_cache))
+
+ # LIGHT treatment: quick confirmation. No banner, no section header.
+ print()
+ if not deleted:
+ print(a.warn_line("Nothing to remove."))
+ print(a.dim(" Already logged out."))
+ else:
+ print(a.success_line("Logged out."))
+ for path in deleted:
+ print(f" {a.dim('removed')} {a.color(path, a.INK)}")
+ print()
+ print(a.dim(" memory.db untouched. run `sibyl init` to activate a fresh account."))
+ print(a.dim(" agents cannot use memory until you sign in again. `sibyl memory` still reads it."))
+ if revoke_state == "revoked":
+ print(a.dim(" signed out on the server too."))
+ if revoke_caveat:
+ print(a.warn_line(revoke_caveat))
+ print()
+ # Rows O1 to O3: the person asked to sign out, so the agent stops here;
+ # signing in again stays available as a later step, never the next one.
+ _h.handoff("done", human=("this computer's sign-in may still be active on the server; on "
+ "another signed-in computer run sibyl devices and revoke it, or "
+ f"sign it out at {ACCOUNT_SECURITY_PAGE}")
+ if revoke_caveat else None, later=("sibyl init",))
+ return 0
+
+
+# ---- `sibyl health` ----------------------------------------------------
+
+def cmd_health(args: argparse.Namespace) -> int:
+ """SibylMemoryProvider.health() — minimal self-check."""
+ try:
+ from sibyl_memory_hermes import SibylMemoryProvider
+ except ImportError:
+ print(a.err_line("sibyl-memory-hermes not installed."))
+ print(a.dim(" pip install sibyl-memory-hermes"))
+ _h.handoff("pip install sibyl-memory-hermes")
+ return 1
+
+ # LIGHT treatment: verdict + details. No banner, no section header.
+ # Pattern: `pg_isready` / `redis-cli ping` / `gh auth status`.
+ print()
+ # CLI-6: expanduser the db path (a leading ~ was passed through literally),
+ # and wrap provider construction + health() so a bad DB / provider error
+ # prints a clean line instead of a traceback.
+ db_path = Path(args.db).expanduser()
+ try:
+ provider = SibylMemoryProvider(db_path=str(db_path))
+ h = provider.health()
+ except Exception as e:
+ print(a.err_line(f"Health check failed: {type(e).__name__}: {e}"))
+ print()
+ _h.handoff("sibyl status")
+ return 1
+ if not isinstance(h, dict):
+ print(a.err_line("Health check returned an unexpected result."))
+ print()
+ _h.handoff("sibyl status")
+ return 1
+ ok_state = bool(h.get("ok"))
+ if ok_state:
+ print(a.success_line("All green."))
+ else:
+ print(a.err_line("Health check reports issues."))
+ print()
+ for k, v in h.items():
+ if k == "ok":
+ continue
+ val = str(v)
+ print(a.kv(k, val, value_color="ok" if v is True else ("soft" if v else "warn")))
+ # 0.5.0 account gate (spec 3.4): the local state and the pinned kids. A
+ # report, not a check: it never changes the exit code.
+ info = _gate.status_info(Path(args.credentials).expanduser(), refresh=False)
+ if info is not None:
+ state = info.get("state") or "?"
+ if info.get("code") and state == "locked":
+ state = f"locked ({info['code']})"
+ print(a.kv("entitlement", state, value_color="ok" if state == "fresh" else "warn"))
+ print(a.kv("pinned kids", ", ".join(_gate.pinned_kids()) or "none"))
+ print()
+ if info is not None:
+ hn, hh = _gate.access_handoff(info)
+ else:
+ hn, hh = "pip install -U sibyl-memory-client", None
+ if hn == "done" and not ok_state:
+ hn = "sibyl status"
+ _h.handoff(hn, human=hh)
+ return 0 if ok_state else 1
+
+
+def cmd_doctor(args: argparse.Namespace) -> int:
+ from .doctor import run_doctor
+ return run_doctor(args)
+
+
+# ---- `sibyl update` ----------------------------------------------------
+
+# Every Sibyl package `sibyl update` knows about. The installer
+# (sibyllabs.org/install) installs `sibyl-memory-cli[mcp]`, so the MCP server
+# (what Claude Code talks to) is present on every standard install; langgraph
+# is installed only by people who use it. `sibyl update` checks and upgrades
+# the ones that are INSTALLED and never installs a missing one. The [mcp]
+# extra only sets a version floor, so upgrading the CLI alone would leave the
+# MCP server behind: it is named in the same pip call instead.
+UPDATE_PACKAGES = (
+ "sibyl-memory-cli",
+ "sibyl-memory-hermes",
+ "sibyl-memory-client",
+ "sibyl-memory-mcp",
+ "sibyl-memory-langgraph",
+)
+
+
+def _installed_version(pkg: str) -> str | None:
+ """Return the locally-installed version of a package, or None if not installed."""
+ try:
+ from importlib.metadata import PackageNotFoundError, version as _v
+ try:
+ return _v(pkg)
+ except PackageNotFoundError:
+ return None
+ except Exception:
+ return None
+
+
+def _pypi_latest(pkg: str, timeout: float = 4.0) -> str | None:
+ """Hit PyPI's JSON endpoint for the latest published version. Best-effort."""
+ url = f"https://pypi.org/pypi/{pkg}/json"
+ try:
+ req = urllib.request.Request(url, headers={"User-Agent": f"sibyl-memory-cli/{_client_version()}"})
+ with urllib.request.urlopen(req, timeout=timeout, context=_https_context()) as r:
+ data = json.loads(r.read().decode("utf-8"))
+ return (data.get("info") or {}).get("version")
+ except Exception:
+ return None
+
+
+def _ver_tuple(v: str) -> tuple:
+ """Lenient version tuple for comparison. Splits on '.', tolerates non-numeric tails."""
+ out = []
+ for part in (v or "").split("."):
+ digits = ""
+ for ch in part:
+ if ch.isdigit():
+ digits += ch
+ else:
+ break
+ out.append(int(digits) if digits else 0)
+ return tuple(out)
+
+
+def _ver_lt(installed: str, latest: str) -> bool:
+ """True if `installed` is strictly older than `latest`.
+
+ CLI-13: prefer packaging.version.parse for PEP 440 correctness (rc/dev/post
+ tags handled, 1.2 == 1.2.0). If packaging is unavailable (stdlib-only
+ environments), fall back to a length-normalized numeric-tuple compare so
+ 1.2 vs 1.2.0 no longer mis-orders (the old raw-tuple compare made (1,2) <
+ (1,2,0), reporting a spurious update)."""
+ try:
+ from packaging.version import InvalidVersion, parse as _parse
+ try:
+ return _parse(installed) < _parse(latest)
+ except InvalidVersion:
+ pass # fall through to tuple compare on unparseable input
+ except ImportError:
+ pass
+ a_t, b_t = _ver_tuple(installed), _ver_tuple(latest)
+ width = max(len(a_t), len(b_t))
+ a_t = a_t + (0,) * (width - len(a_t))
+ b_t = b_t + (0,) * (width - len(b_t))
+ return a_t < b_t
+
+
+def _detect_install_method() -> str:
+ """Best-guess of how the CLI was installed — pipx / venv / system-pip / pep668-blocked."""
+ exe = sys.executable
+ if "/pipx/" in exe or "/.local/pipx/" in exe:
+ return "pipx"
+ if exe and ("venv" in exe.lower() or "virtualenv" in exe.lower() or os.environ.get("VIRTUAL_ENV")):
+ return "venv"
+ # Look for PEP 668 marker file
+ for parent in Path(exe).resolve().parents:
+ marker = parent / "lib" / "EXTERNALLY-MANAGED"
+ if marker.exists():
+ return "pep668"
+ marker2 = parent / "EXTERNALLY-MANAGED"
+ if marker2.exists():
+ return "pep668"
+ if str(parent) in ("/", "/home", "/usr"):
+ break
+ return "system"
+
+
+PEP668_HUMAN = ("this Python is externally managed; choose a venv or allow "
+ "--break-system-packages")
+
+
+def _update_handoff(rows: list, any_outdated: bool) -> tuple:
+ """(next, human) for `sibyl update` (rows Z1, Z2, Z5)."""
+ if not any_outdated:
+ if any(r["latest"] is None for r in rows):
+ return (_h.RETRY, None)
+ return ("done", None)
+ method = _detect_install_method()
+ if method == "pipx":
+ return ("pipx upgrade " + " ".join(r["pkg"] for r in rows if r["outdated"]), None)
+ if method == "pep668":
+ return ("sibyl update --apply", PEP668_HUMAN)
+ return ("sibyl update --apply", None)
+
+
+def cmd_update(args: argparse.Namespace) -> int:
+ """Check installed package versions against PyPI, optionally apply upgrade."""
+ rows = []
+ any_outdated = False
+ for pkg in UPDATE_PACKAGES:
+ installed = _installed_version(pkg)
+ if installed is None:
+ # Not installed: not shown, not checked, never installed by --apply.
+ continue
+ latest = _pypi_latest(pkg)
+ outdated = False
+ if installed and latest:
+ outdated = _ver_lt(installed, latest)
+ rows.append({"pkg": pkg, "installed": installed, "latest": latest, "outdated": outdated})
+ if outdated:
+ any_outdated = True
+
+ if args.json:
+ doc = {"packages": rows, "any_outdated": any_outdated}
+ un, uh = _update_handoff(rows, any_outdated)
+ print(json.dumps(_h.json_handoff(doc, un, uh), indent=2))
+ return 0 if not any_outdated else 2
+
+ # ASCII output — keep it small and readable, follow `sibyl status` style.
+ print()
+ if any_outdated:
+ print(a.err_line("Updates available."))
+ else:
+ # Distinguish "all current" from "could not reach PyPI"
+ any_unreachable = any(r["latest"] is None for r in rows)
+ if any_unreachable:
+ print(a.dim("Could not reach PyPI for one or more packages — showing what we know."))
+ else:
+ print(a.success_line("All packages current."))
+ print()
+
+ name_w = max((len(r["pkg"]) for r in rows), default=0)
+ for r in rows:
+ installed = r["installed"]
+ latest = r["latest"] or "(unreachable)"
+ if r["outdated"]:
+ line = f" {yellow(r['pkg'].ljust(name_w))} {installed} → {green(latest)}"
+ else:
+ line = f" {r['pkg'].ljust(name_w)} {a.dim(installed)}"
+ print(line)
+ print()
+
+ if not any_outdated:
+ un, uh = _update_handoff(rows, any_outdated)
+ _h.handoff(un, human=uh)
+ return 0
+
+ pip_cmd_pkgs = " ".join(r["pkg"] for r in rows if r["outdated"])
+ method = _detect_install_method()
+
+ if args.apply:
+ # Best-effort in-process pip invocation
+ import subprocess
+ pip_args = [sys.executable, "-m", "pip", "install", "-U", *pip_cmd_pkgs.split()]
+ if method == "pep668":
+ pip_args.append("--break-system-packages")
+ if method == "pipx":
+ # pipx is a separate tool; we can't drive it via `pip install`.
+ print(a.err_line("Detected pipx install. Run instead:"))
+ print(f" pipx upgrade {' '.join(r['pkg'] for r in rows if r['outdated'])}")
+ _h.handoff(f"pipx upgrade {' '.join(r['pkg'] for r in rows if r['outdated'])}")
+ return 2
+ print(a.dim("Running: ") + " ".join(pip_args))
+ try:
+ rc = subprocess.call(pip_args)
+ except FileNotFoundError:
+ print(a.err_line("pip not found at " + sys.executable + " -m pip"))
+ _h.handoff("done", human=f"pip is missing for {sys.executable}; install pip or point me "
+ "at the right Python")
+ return 2
+ if rc == 0:
+ print()
+ print(a.success_line("Upgrade complete. Re-run `sibyl update` to confirm."))
+ # Save/debloat build (spec 3.2): refresh the installed procedures
+ # from the NEW package (a fresh interpreter, so the upgraded code
+ # and text are the ones used). Never overwrites a person's edit.
+ try:
+ subprocess.call([sys.executable, "-c",
+ "from sibyl_memory_cli.cli import main; main(['skills', 'install'])"])
+ except Exception:
+ pass
+ _h.handoff("sibyl update", human="restart any running agent so it loads the new version")
+ else:
+ # A failed pip run (permissions, PEP 668, a resolver conflict,
+ # offline) fails the same way again, so a person reads pip's
+ # output instead of the agent re-running it.
+ _h.handoff("done", human=f"pip exited {rc} upgrading the packages (output above); "
+ "tell me what it said")
+ return rc
+
+ # Default: print the command, do not execute
+ print(a.dim("To upgrade, run:"))
+ if method == "pipx":
+ print(f" pipx upgrade {pip_cmd_pkgs}")
+ elif method == "pep668":
+ print(f" pip install --break-system-packages -U {pip_cmd_pkgs}")
+ print()
+ print(a.dim(" (Your Python flags itself as externally-managed under PEP 668.)"))
+ print(a.dim(" (Cleanest: install inside a venv. See https://beta.sibyllabs.org for the recommended path.)"))
+ else:
+ print(f" pip install -U {pip_cmd_pkgs}")
+ print()
+ print(a.dim("Or let sibyl run it:") + " sibyl update --apply")
+ print()
+ un, uh = _update_handoff(rows, any_outdated)
+ _h.handoff(un, human=uh)
+ return 2 # exit 2 signals "outdated" without being a hard error
+
+
+# ---- Guided migration (sibyl migrate) ----------------------------------
+
+def _migrate_io():
+ """Interactive IO for the guided flow: prints narration live and reads real
+ stdin for pauses/confirms. Subclasses the testable GuidedIO seam in migrate.py
+ (whose .say() only buffers, for non-interactive tests)."""
+ from .migrate import GuidedIO
+
+ class _PrintingIO(GuidedIO):
+ def say(self, s: str = "") -> None:
+ super().say(s)
+ print(s)
+
+ return _PrintingIO()
+
+
+def cmd_migrate(args: argparse.Namespace) -> int:
+ """`sibyl migrate` — guided onboarding. Backs up existing memory/agent files
+ FIRST, wires Sibyl into every detected harness, hands the semantic extraction
+ to the user's own agent (it holds the memory tools; Sibyl Labs never sees the
+ files), verifies what landed, then optionally trims the originals — only on an
+ explicit confirm and only because a verified backup exists."""
+ from . import migrate as M
+
+ home = Path.home()
+ cwd = Path.cwd()
+ db_path = Path(args.db).expanduser()
+ backup_parent = Path(args.backup_dir).expanduser() if getattr(args, "backup_dir", None) else home
+
+ print()
+ print(bold("Sibyl Memory — guided migration"))
+ print(dim("Back up existing memory, populate Sibyl Memory, optionally slim the originals."))
+ print()
+ print(yellow("Your files are copied to a timestamped backup FIRST and are never modified"))
+ print(yellow("except by an explicit, confirmed trim at the very end. You run the extraction"))
+ print(yellow("in your own agent — Sibyl Labs never sees your files or memory."))
+ print(dim("No warranty: keep your backup. Sibyl Labs is not responsible for data loss."))
+ print()
+
+ # 0.5.0: the extraction runs in the person's own agent, whose memory tools
+ # need an account. Reading and backing up need none.
+ signed_in = _gate.has_account_access(
+ Path(getattr(args, "credentials", None) or DEFAULT_CRED_PATH).expanduser())
+ if not signed_in:
+ print(dim(_gate.NO_ACCOUNT_MEMORY_LINE))
+ print(dim("Run `sibyl init` before the extraction step so your agent can write memory."))
+ print()
+
+ files = M.scan_memory_files(home, cwd)
+ if not files:
+ print(yellow("No memory/agent files found in your home or current project."))
+ print(dim("Looked for CLAUDE.md, AGENTS.md, .codex/config.toml, .hermes/*, and similar."))
+ print(dim("If your files live elsewhere, run this from that project directory."))
+ _h.handoff("sibyl setup", human="where your CLAUDE.md, AGENTS.md or Hermes files live, if anywhere")
+ return 0
+
+ print(dim("Will back up (originals untouched):"))
+ for f in files:
+ kind = "dir " if f.is_dir else "file"
+ print(f" {kind} {f.rel} {dim(f'({f.size} bytes)')}")
+ print()
+ print(dim("After Sibyl is wired, if your agent was already open, restart it (or"))
+ print(dim("reconnect the sibyl-memory MCP) before running the extraction prompt."))
+ print()
+
+ if not args.yes:
+ try:
+ ans = input("Proceed? [Y/n]: ").strip().lower()
+ except EOFError:
+ ans = ""
+ print("no terminal: proceeding (pass --yes to say so)")
+ if ans.startswith("n"):
+ print(dim("Aborted. Nothing was changed."))
+ _h.handoff("done")
+ return 0
+ print()
+
+ io = _migrate_io()
+ report = M.run_guided_setup(
+ home=home, cwd=cwd, db_path=db_path, backup_parent=backup_parent,
+ io=io, debloat=not args.no_debloat, force=getattr(args, "force", False),
+ )
+
+ ph = report.get("phases", {})
+ print()
+ print(bold("Summary"))
+ bk = ph.get("backup", {})
+ if bk:
+ print(f" {green('backup')} {bk.get('files', 0)} files")
+ print(f" {dim('location')} {bk.get('dir', '')}")
+ wire = ph.get("wire", {})
+ if wire:
+ wired = ", ".join(f"{n} ({s})" for n, s in wire.items())
+ print(f" {green('wired')} {wired}")
+ v = ph.get("verify", {})
+ if v:
+ cats = ", ".join(f"{k}:{n}" for k, n in (v.get("by_category") or {}).items())
+ print(f" {green('extracted')} {v.get('new_total', 0)} new entries" + (f" {dim(cats)}" if cats else ""))
+ trims = ph.get("debloat")
+ if isinstance(trims, dict): # older report shape
+ trims = [dict(trims, file=trims.get("file", "CLAUDE.md"))]
+ for rec in trims or []:
+ if not rec.get("written"):
+ continue
+ saved = max(0, rec.get("before", 0) - rec.get("after", 0))
+ print(f" {green('trimmed')} {rec.get('file', '?')} {dim(f'(-{saved} bytes; full copy in backup)')}")
+
+ later = list(report.get("later") or [])
+ if not signed_in:
+ later.insert(0, "sibyl init")
+ if not report.get("ok"):
+ print()
+ print(yellow("Migration did not complete. Your originals and backup are intact."))
+ fail = report.get("handoff") or {"next": "sibyl status", "human": None}
+ _h.handoff(fail["next"], human=fail.get("human"), later=later)
+ return 1
+ print()
+ if (v or {}).get("new_total", 0) == 0:
+ # Finding 5.3.3 (handoff spec 2026-10-03): with nothing extracted yet
+ # (a run without a terminal verifies at once) "Done." was misleading.
+ print(green("Backed up and wired. Extraction has not run yet."))
+ else:
+ print(green("Done. Your memory now lives in Sibyl and is recalled on demand."))
+ if bk:
+ print(dim(f"Backup retained at {bk.get('dir','')} — delete it once you've confirmed everything."))
+ agents = [n for n, st in (wire or {}).items() if st in ("wired", "already")]
+ names = {"claude-code": "Claude Code", "codex": "Codex", "hermes": "Hermes"}
+ who = " / ".join(names.get(n, n) for n in agents) or "your agent"
+ human = (f"restart {who} if it was open while wiring; the backup at {bk.get('dir', '')} can be "
+ "deleted once you have checked")
+ if not signed_in:
+ human = "this computer is not signed in yet, so run sibyl init first (listed above); " + human
+ _h.handoff("sibyl status", human=human, later=later)
+ return 0
+
+
+# ---- Dispatch ----------------------------------------------------------
+
+# `sibyl --version` order and short names. The CLI is always
+# shown; the others only when installed.
+VERSION_PACKAGES = (
+ ("cli", "sibyl-memory-cli"),
+ ("client", "sibyl-memory-client"),
+ ("mcp", "sibyl-memory-mcp"),
+ ("hermes", "sibyl-memory-hermes"),
+ ("langgraph", "sibyl-memory-langgraph"),
+)
+
+
+def version_line() -> str:
+ parts = []
+ for short_name, pkg in VERSION_PACKAGES:
+ v = _client_version() if pkg == "sibyl-memory-cli" else _installed_version(pkg)
+ if v:
+ parts.append(f"{short_name} {v}")
+ return "sibyl " + " \u00b7 ".join(parts)
+
+
+class _VersionAction(argparse.Action):
+ def __init__(self, option_strings, dest=argparse.SUPPRESS, default=argparse.SUPPRESS,
+ help="show the version of every installed Sibyl package and exit"):
+ super().__init__(option_strings=option_strings, dest=dest, default=default, nargs=0,
+ help=help)
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ print(version_line())
+ parser.exit()
+
+
+def build_parser() -> argparse.ArgumentParser:
+ p = argparse.ArgumentParser(
+ prog="sibyl",
+ description="Command-line interface for the Sibyl Memory Plugin.",
+ )
+ # Version row (2026-10-08): `sibyl --version` exits 0 before the required-subcommand check
+ # and touches no file. One line naming every installed Sibyl package,
+ # `sibyl cli 0.5.0 · client 0.9.0 · mcp 0.3.0` (read when the flag is used).
+ p.add_argument("--version", action=_VersionAction)
+ p.add_argument("--credentials", default=str(DEFAULT_CRED_PATH),
+ help="Path to credentials.json (default: ~/.sibyl-memory/credentials.json)")
+ p.add_argument("--db", default=str(DEFAULT_DB_PATH),
+ help="Path to memory.db (default: ~/.sibyl-memory/memory.db)")
+ p.add_argument("--tier-cache", default=str(DEFAULT_TIER_CACHE_PATH),
+ help="Path to tier_cache.json (default: ~/.sibyl-memory/tier_cache.json)")
+
+ sub = p.add_subparsers(dest="cmd", required=True)
+
+ p_init = sub.add_parser("init", help="Activate the plugin in your browser")
+ p_init.add_argument("--force", action="store_true", help="Re-activate even if credentials.json exists")
+ p_init.add_argument("--no-email", action="store_true", help="Skip the email prompt after activation")
+ p_init.add_argument("--replace", action="store_true",
+ help=("Re-activate this computer in place of its earlier sign-in (implies --force; "
+ "done automatically whenever credentials exist), and when the account is at "
+ "its computer limit, offer to sign another computer out"))
+ p_init.set_defaults(func=cmd_init)
+
+ p_up = sub.add_parser("upgrade", help="Open the upgrade flow (account billing page, or stake / subscribe)")
+ p_up.set_defaults(func=cmd_upgrade)
+
+ p_claim = sub.add_parser("claim", help=f"Link a card purchase to this account (code from {CLAIM_PAGE})")
+ p_claim.add_argument("checkout_code", help="The cs_... checkout code shown after paying")
+ p_claim.set_defaults(func=cmd_claim)
+
+ p_em = sub.add_parser("email", help="Show, add or confirm your account email (receipts, security notices)")
+ em_sub = p_em.add_subparsers(dest="email_cmd")
+ p_ema = em_sub.add_parser("add", help="Send a confirmation code to a new address")
+ p_ema.add_argument("address", help="The email address to add")
+ p_ema.set_defaults(func=cmd_email)
+ p_emv = em_sub.add_parser("verify", help="Send a confirmation code to the address on file")
+ p_emv.set_defaults(func=cmd_email)
+ p_emc = em_sub.add_parser("confirm", help="Confirm the six-digit code from the email")
+ p_emc.add_argument("code", help="The six-digit code")
+ p_emc.set_defaults(func=cmd_email)
+ p_em.set_defaults(func=cmd_email)
+
+ p_st = sub.add_parser("status", help="Show local + server tier / DB stats")
+ p_st.set_defaults(func=cmd_status)
+
+ p_who = sub.add_parser("whoami", help="One-line account summary (masked by default)")
+ p_who.add_argument("--full", action="store_true", help="Show full email + wallet (no masking)")
+ p_who.set_defaults(func=cmd_whoami)
+
+ p_dev = sub.add_parser("devices", help="List devices (active bearer tokens) for the account")
+ dev_sub = p_dev.add_subparsers(dest="sub")
+ p_rev = dev_sub.add_parser("revoke", help="Revoke a device by index (run `sibyl devices` for indexes)")
+ p_rev.add_argument("index", type=int, help="Index from `sibyl devices` output")
+ p_dev.set_defaults(func=cmd_devices)
+ p_rev.set_defaults(func=cmd_devices)
+
+ p_dash = sub.add_parser("dashboard", help="Open the account page (no token in the URL; falls back to status while it is not open)")
+ p_dash.set_defaults(func=cmd_dashboard)
+
+ p_lo = sub.add_parser("logout", help="Remove local credentials (memory.db stays)")
+ p_lo.set_defaults(func=cmd_logout)
+
+ p_h = sub.add_parser("health", help="Run the provider self-check")
+ p_h.set_defaults(func=cmd_health)
+
+ from .setup import cmd_setup, SETUP_TARGETS, ALL_WIRERS, SETUP_ALIASES
+ p_doc = sub.add_parser(
+ "doctor",
+ help="End-to-end check: start the MCP server, list tools, save a marked test memory, "
+ "recall it, delete it; checks each agent's wiring (--fix repairs stale paths)",
+ )
+ p_doc.add_argument("--json", action="store_true", help="Machine-readable output")
+ p_doc.add_argument("--fix", action="store_true",
+ help="Repair stale or broken harness wiring without asking (never adds a missing one)")
+ p_doc.add_argument("--harness", action="append", default=None,
+ choices=list(ALL_WIRERS) + list(SETUP_ALIASES) + ["grokbot"],
+ help="Limit harness checks and repairs to this harness; repeatable "
+ "(grokbot checks the Cursor file, where setup grokbot wires it)")
+ p_doc.add_argument("--no-harness", action="store_true",
+ help="Skip harness checks: server round trip only")
+ p_doc.set_defaults(func=cmd_doctor)
+
+ p_mem = sub.add_parser("memory", help="Inspect your memory store (list / search / recall / neighbors), or adopt memory from before sign-in")
+ mem_sub = p_mem.add_subparsers(dest="mem_cmd")
+ p_ml = mem_sub.add_parser("list", help="List entities (optionally filtered by category)")
+ p_ml.add_argument("category", nargs="?", default=None, help="Optional category to filter by")
+ p_ml.add_argument("--limit", type=int, default=50, help="Max rows (default 50)")
+ p_ml.set_defaults(func=cmd_memory)
+ p_ms = mem_sub.add_parser("search", help="Full-text search across entities + state + reference + journal")
+ p_ms.add_argument("query", help="Search query (matches stored text, not meaning)")
+ p_ms.add_argument("--limit", type=int, default=20, help="Max hits (default 20)")
+ p_ms.set_defaults(func=cmd_memory)
+ p_mr = mem_sub.add_parser("recall", help="Recall one entity by category + name")
+ p_mr.add_argument("category", help="Entity category")
+ p_mr.add_argument("name", help="Entity name")
+ p_mr.set_defaults(func=cmd_memory)
+ p_mn = mem_sub.add_parser(
+ "neighbors",
+ help="List the edges of one node (entity, reference document or state document)")
+ p_mn_node = p_mn.add_mutually_exclusive_group(required=True)
+ p_mn_node.add_argument("--entity", nargs=2, metavar=("CATEGORY", "NAME"),
+ help="An entity node")
+ p_mn_node.add_argument("--reference", metavar="KEY", help="A reference document node")
+ p_mn_node.add_argument("--state", metavar="KEY", help="A state document node")
+ p_mn.add_argument("--relation", action="append", default=None,
+ help="Only this relation (repeatable)")
+ p_mn.add_argument("--direction", choices=("out", "in", "both"), default="both")
+ p_mn.add_argument("--tier", choices=("entity", "reference", "state"), default=None,
+ help="Only edges whose other node is in this tier")
+ p_mn.add_argument("--limit", type=int, default=50, help="Max edges (default 50, max 200)")
+ p_mn.add_argument("--cursor", default=None, help="next_cursor from a previous page")
+ p_mn.set_defaults(func=cmd_memory)
+ p_ma = mem_sub.add_parser(
+ "adopt",
+ help="Move memory written on this computer before sign-in into your account "
+ "(local, one transaction, nothing deleted)")
+ p_ma.add_argument("--yes", action="store_true",
+ help="Do not ask when this store also holds another account's memory")
+ p_ma.set_defaults(func=cmd_memory)
+ p_mem.set_defaults(func=cmd_memory)
+
+ p_update = sub.add_parser(
+ "update",
+ help="Check for newer sibyl-memory-* releases on PyPI (use --apply to upgrade)",
+ )
+ p_update.add_argument("--apply", action="store_true", help="Run pip install -U for the outdated packages")
+ p_update.add_argument("--json", action="store_true", help="Machine-readable output")
+ p_update.set_defaults(func=cmd_update)
+
+ # v0.1.4: one-command auto-detect-and-wire setup for any agent stack
+ # (cmd_setup and SETUP_TARGETS are imported above, before p_doc)
+ p_setup = sub.add_parser(
+ "setup",
+ help="Auto-detect Hermes / Claude Code / Codex / Cursor / DeepSeek Harness and wire SIBYL as the memory provider",
+ )
+ p_setup.add_argument(
+ "target", nargs="?", choices=list(SETUP_TARGETS),
+ help="Wire just this framework (default: detect all). deepseek = DeepSeek Harness "
+ "(dsh is an alias). grokbot = Cursor wiring + confirmation",
+ )
+ p_setup.add_argument(
+ "--yes", "-y", action="store_true",
+ help="Skip prompts, accept defaults (still respects destructive-default-NO unless --force)",
+ )
+ p_setup.add_argument(
+ "--force", action="store_true",
+ help="Overwrite existing non-SIBYL memory provider configs",
+ )
+ p_setup.add_argument(
+ "--dry-run", action="store_true",
+ help="Print what would change without writing",
+ )
+ p_setup.add_argument(
+ "--hermes-home", default=None,
+ help="Override HERMES_HOME autodetection",
+ )
+ p_setup.add_argument(
+ "--claude-settings", default=None,
+ help="Path to Claude Code's settings.json (default: ~/.claude/settings.json)",
+ )
+ p_setup.add_argument(
+ "--codex-config", default=None,
+ help="Override ~/.codex/config.toml autodetection",
+ )
+ p_setup.add_argument(
+ "--cursor-config", default=None,
+ help="Override ~/.cursor/mcp.json autodetection",
+ )
+ p_setup.add_argument(
+ "--dsh-home", default=None,
+ help="DeepSeek Harness home (default: $DSH_HOME, else ~/.dsh)",
+ )
+ p_setup.add_argument(
+ "--dsh-profile", default=None,
+ help="Write to one DeepSeek Harness profile's patch file instead of the home patch "
+ "that covers every profile",
+ )
+ p_setup.add_argument(
+ "--print-config", action="store_true",
+ help="Print the absolute sibyl-memory-mcp path and a copy-paste mcpServers JSON block, then exit",
+ )
+ p_setup.set_defaults(func=cmd_setup)
+
+ p_migrate = sub.add_parser(
+ "migrate",
+ help="Guided: back up existing memory/agent files, wire Sibyl, populate Sibyl Memory, optionally slim the originals",
+ )
+ p_migrate.add_argument(
+ "--backup-dir", default=None,
+ help="Where to write the timestamped backup (default: your home directory)",
+ )
+ p_migrate.add_argument(
+ "--no-debloat", action="store_true",
+ help="Skip the optional trim step (back up + wire + extract + verify only)",
+ )
+ p_migrate.add_argument(
+ "--yes", "-y", action="store_true",
+ help="Skip the initial confirm (the trim step still always asks separately)",
+ )
+ p_migrate.add_argument(
+ "--force", action="store_true",
+ help="Overwrite an existing non-sibyl memory provider when wiring a harness "
+ "(without this, migrate stops at that harness and tells you to re-run with --force)",
+ )
+ p_migrate.set_defaults(func=cmd_migrate)
+
+ # Save and debloat (spec plugin-save-debloat 2026-09-27).
+ from . import lifecycle_cli as _lc
+ p_save = sub.add_parser(
+ "save",
+ help="Save to Sibyl Memory: one fact now, a session capsule (Pro), or how to run the save procedure")
+ p_save.add_argument("--fact", default=None, help="Write one fact (category 'fact')")
+ p_save.add_argument("--capsule", action="store_true",
+ help="Write a session capsule now (Pro; counts only, no content)")
+ p_save.add_argument("--preview", action="store_true", help="Say what would be written; write nothing")
+ p_save.add_argument("--status", action="store_true", help="Last save, writes since, decisions queued")
+ p_save.set_defaults(func=_lc.cmd_save)
+
+ p_deb = sub.add_parser(
+ "debloat",
+ help="Measure the instruction files your agent loads every start; plan, apply, or undo a context trim")
+ p_deb.add_argument("action", nargs="?", choices=["plan", "apply", "auto", "manual", "undo"],
+ help="plan | apply [] | auto | manual | undo []")
+ p_deb.add_argument("file", nargs="?", default=None, help="An instruction file (as `sibyl debloat` names it)")
+ p_deb.add_argument("--fyi", action="store_true", help="One line")
+ p_deb.add_argument("--json", action="store_true", help="Machine-readable record")
+ p_deb.add_argument("--root", default=None, help="Project directory (default: the current directory)")
+ p_deb.add_argument("--config", default=None, help="A .debloat.json to use instead of /.debloat.json")
+ p_deb.add_argument("--include", action="append", default=[], help="Also measure this file (repeatable)")
+ p_deb.add_argument("--yes", "-y", action="store_true", help="Answer yes to the confirmation")
+ p_deb.set_defaults(func=_lc.cmd_debloat)
+
+ p_sk = sub.add_parser("skills", help="The save and debloat procedures installed for your agents")
+ sk_sub = p_sk.add_subparsers(dest="skills_cmd")
+ p_ski = sk_sub.add_parser("install", help="Install or refresh them (never overwrites your edits)")
+ p_ski.add_argument("--force", action="store_true", help="Replace files you edited too")
+ p_ski.set_defaults(func=_lc.cmd_skills)
+ p_sks = sk_sub.add_parser("status", help="Version, checksums, shims and hooks")
+ p_sks.set_defaults(func=_lc.cmd_skills)
+ p_skr = sk_sub.add_parser("reset", help="Replace one file with the shipped version")
+ p_skr.add_argument("name", help="SAVE.md or DEBLOAT.md")
+ p_skr.add_argument("--yes", "-y", action="store_true")
+ p_skr.set_defaults(func=_lc.cmd_skills)
+ p_sku = sk_sub.add_parser(
+ "uninstall",
+ help=("Remove what this plugin installed: the procedures, shims, Claude Code hooks and the "
+ "Codex block (edited files are kept). Run it BEFORE pip uninstall: the hooks in "
+ "~/.claude/settings.json point at this package's sibyl command"),
+ description=("Removes the save/debloat procedures, the harness shims, the five Claude Code "
+ "hooks in ~/.claude/settings.json and the block in Codex's AGENTS.md. Files you "
+ "edited are kept. Run this before `pip uninstall sibyl-memory-cli`: the hooks "
+ "call this package's `sibyl` command (they exit quietly if it is gone, but "
+ "they stay in your settings until removed)."))
+ p_sku.add_argument("--yes", "-y", action="store_true")
+ p_sku.set_defaults(func=_lc.cmd_skills)
+ p_skp = sk_sub.add_parser(
+ "proposals",
+ help="Pro: skills Sibyl proposes from your sessions (list, show, accept, reject, mute, unmute)",
+ description=("Skill proposals are mined locally on Pro, from your journal and from the tool "
+ "sequences and entity rewrites in ~/.sibyl-memory/signals.json (sibyl skills "
+ "signals). Nothing is created "
+ "without an accept: `accept ` writes a SKILL.md for Claude Code, Codex and Hermes "
+ "(the folders present on this computer, or --to ) and a reference copy in memory; "
+ "`reject ` keeps it from coming back for 30 days (twice rejected: muted until "
+ "`unmute `); `mute ` stops a kind of proposal."))
+ p_skp.add_argument("proposal_action", nargs="?", default="list",
+ choices=["list", "show", "accept", "reject", "mute", "unmute"])
+ p_skp.add_argument("target", nargs="?", help="proposal id (or its first 6+ characters), kind or slug")
+ p_skp.add_argument("--to", help="accept: write //SKILL.md instead of the harness folders")
+ p_skp.add_argument("--note", help="accept / reject: a note kept with the decision")
+ p_skp.add_argument("--days", type=int, help="mute: how many days (default 30)")
+ p_skp.set_defaults(func=_lc.cmd_skills)
+ p_sksg = sk_sub.add_parser(
+ "signals",
+ help="Pro: the local record skill proposals learn from (status, clear, off, on)",
+ description=("On Pro, Sibyl keeps a small local record (~/.sibyl-memory/signals.json) of which "
+ "tools your agent calls in which order and which entities are rewritten, so it can "
+ "propose a skill for a sequence you repeat. Tool and MCP server names are kept; argument names and "
+ "entity names only as hashes; never a value. Nothing leaves this computer. `clear` "
+ "deletes the file, `off` stops recording, `on` starts it again from now."))
+ p_sksg.add_argument("signals_action", nargs="?", default="status",
+ choices=["status", "clear", "off", "on"])
+ p_sksg.set_defaults(func=_lc.cmd_skills)
+ p_sk.set_defaults(func=_lc.cmd_skills)
+
+ p_as = sub.add_parser("autosave", help=("Pro automatic save: status, on, off, or every of "
+ "active work (30 to 240; default 60)"))
+ p_as.add_argument("action", nargs="?", choices=["status", "on", "off", "every"], default="status")
+ p_as.add_argument("minutes", nargs="?", type=int)
+ p_as.set_defaults(func=_lc.cmd_autosave)
+
+ p_ref = sub.add_parser("refresh", help=("Check your account now (picks up an upgrade or a plan change "
+ "at once) and refresh the procedures, shims and hooks"))
+ p_ref.set_defaults(func=_lc.cmd_refresh)
+
+ p_rem = sub.add_parser("reminders", help="Save and debloat reminders: on, off, or quiet (Pro reports)")
+ p_rem.add_argument("state", nargs="?", choices=["on", "off", "quiet", "status"], default="status")
+ p_rem.set_defaults(func=_lc.cmd_reminders)
+
+ p_hook = sub.add_parser("hook", help="Claude Code hook entry point (installed by sibyl setup; not for manual use)")
+ p_hook.add_argument("event", choices=["session-start", "prompt", "stop", "pre-compact", "session-end"])
+ p_hook.set_defaults(func=_lc.cmd_hook)
+
+ return p
+
+
+def cmd_memory(args: argparse.Namespace) -> int:
+ """Read-only inspection of the local memory store (PKG-4, beta reports).
+
+ sibyl memory list [category] list entities
+ sibyl memory search full-text search across tiers
+ sibyl memory recall recall one entity by category + name
+
+ Opens the resolved DB read-only via the SDK; never writes. Respects --db so
+ you can inspect any split-brain store that `sibyl status` surfaces.
+ """
+ from sibyl_memory_client import DEFAULT_TENANT, MemoryClient
+ # THE canonical cause vocabulary (stage 3, 2026-08-31). Imported from the
+ # client, never re-declared here — the CLI prints causes, it does not own
+ # them.
+ from sibyl_memory_client.verdicts import refine_zero
+
+ db_path = Path(args.db).expanduser()
+ print()
+ if not db_path.exists():
+ print(a.warn_line(f"No memory store at {db_path}."))
+ print(a.dim(" Run `sibyl status` to see every store on this machine."))
+ _h.handoff("sibyl status")
+ return 1
+ if getattr(args, "mem_cmd", None) == "adopt":
+ return _cmd_memory_adopt(args, db_path)
+ # F1 (Polish-language eval 2026-08-12): resolve the ACTIVATED tenant exactly like
+ # the MCP server does (Contract T ladder: tenant_id -> account_id ->
+ # DEFAULT_TENANT), so `sibyl memory list/search/recall` reads the same tenant
+ # the MCP writes. Without this the CLI always read DEFAULT_TENANT and an
+ # activated account saw "(no entities)" for a perfectly healthy store. `--credentials`
+ # is a root parser arg so args.credentials is present on the real path; a
+ # direct cmd_memory(Namespace(...)) call (CLI-7 unit tests) may omit it, so we
+ # fall back to the parser default resolved at call time.
+ cred_arg = getattr(args, "credentials", None) or str(DEFAULT_CRED_PATH)
+ creds = read_credentials(Path(cred_arg).expanduser()) or {}
+ tenant_id = creds.get("tenant_id") or creds.get("account_id") or DEFAULT_TENANT
+ # 0.5.0 ESCAPE HATCH (spec 3.4, D2): the person's own data is never held
+ # hostage to the account. This read-only command builds the client with a
+ # NullEntitlementGate ON PURPOSE (constructor-injected; no env var, no
+ # config) and passes no account ids, so it never calls the network. Agents
+ # (MCP, hermes, langgraph) stay gated.
+ from sibyl_memory_client.testing import NullEntitlementGate
+ client = MemoryClient.local(path=db_path, tenant_id=tenant_id,
+ entitlement_gate=NullEntitlementGate())
+ signin_later: tuple = ()
+ if not _gate.has_account_access(Path(cred_arg).expanduser()):
+ print(a.dim(_gate.NO_ACCOUNT_MEMORY_LINE))
+ signin_later = ("sibyl init",)
+ op = getattr(args, "mem_cmd", None)
+ if op == "list":
+ rows = client.list_entities(category=args.category, limit=args.limit)
+ if not rows:
+ print(a.dim("(no entities)"))
+ _h.handoff("done", later=signin_later)
+ return 0
+ print(a.eyebrow(f"entities ({len(rows)})"))
+ for r in rows:
+ # CLI-7: tolerate SDK rows missing category/name keys.
+ cat = r.get("category", "?")
+ name = r.get("name", "?")
+ print(a.kv(f"{cat}/{name}", r.get("status") or "-"))
+ _h.handoff("done", later=signin_later)
+ return 0
+ if op == "search":
+ # THE VERDICT CONTRACT (stage 3, 2026-08-31). This used to print
+ # "(no matches)" and stop — the terminal-shaped version of the defect
+ # this stage closes: a zero that cannot explain itself. The SDK now
+ # returns a cause on every call, and `refine_zero` pays one COUNT on the
+ # zero path so a brand-new user is told their store is EMPTY rather than
+ # left to conclude their query was wrong.
+ hits = refine_zero(client, client.search(args.query, limit=args.limit))
+ if not hits:
+ print(a.dim(f"(no matches for {args.query!r})"))
+ verdict = getattr(hits, "verdict", None)
+ if verdict is not None:
+ # Plain language, generated from the enum and never from stored
+ # text, so it is always safe to print to a terminal.
+ print(a.warn_line(verdict.explain()))
+ print(a.dim(f"cause: {verdict.code.value}"))
+ _h.handoff("done", later=signin_later)
+ return 0
+ print(a.eyebrow(f"matches ({len(hits)})"))
+ for h in hits:
+ snip = (h.get("snippet") or "").replace("\n", " ")[:100]
+ print(a.kv(f"[{h.get('tier') or '-'}] {h.get('key') or '-'}", snip))
+ _h.handoff("done", later=signin_later)
+ return 0
+ if op == "recall":
+ try:
+ ent = client.get_entity(args.category, args.name)
+ except Exception as e:
+ print(a.warn_line(str(e)))
+ _h.handoff("sibyl memory list", later=signin_later)
+ return 1
+ # CLI-7: tolerate SDK rows missing category/name keys.
+ print(a.eyebrow(f"{ent.get('category', args.category)}/{ent.get('name', args.name)}"))
+ print(a.kv("status", ent.get("status") or "-"))
+ print(a.kv("updated", _utc_minute(ent.get("updated_at")) or ent.get("updated_at") or "-"))
+ body = ent.get("body")
+ print(body if isinstance(body, str) else json.dumps(body, indent=2, ensure_ascii=False))
+ _h.handoff("done", later=signin_later)
+ return 0
+ if op == "neighbors":
+ return _cmd_memory_neighbors(args, client, signin_later)
+ print(a.warn_line("Usage: sibyl memory {list|search|recall|neighbors|adopt} ..."))
+ _h.handoff("sibyl memory list", later=signin_later)
+ return 1
+
+
+def _cmd_memory_neighbors(args: argparse.Namespace, client: Any, signin_later: tuple) -> int:
+ """`sibyl memory neighbors`: the edges of one node (v6 relations), read-only."""
+ if getattr(args, "entity", None):
+ node = {"tier": "entity", "category": args.entity[0], "key": args.entity[1]}
+ elif getattr(args, "reference", None):
+ node = {"tier": "reference", "key": args.reference}
+ else:
+ node = {"tier": "state", "key": args.state}
+ try:
+ res = client.neighbors(node, relation=args.relation, direction=args.direction,
+ tier=args.tier, limit=args.limit, cursor=args.cursor)
+ except Exception as e:
+ print(a.warn_line(str(e)))
+ _h.handoff("sibyl memory list", later=signin_later)
+ return 1
+ deg = res.get("degree") or {}
+ label = (f"{node['category']}/{node['key']}" if node["tier"] == "entity"
+ else f"{node['tier']} {node['key']}")
+ print(a.eyebrow(f"{label} out {deg.get('out', 0)} in {deg.get('in', 0)}"))
+ if not res.get("edges"):
+ print(a.dim("(no edges)"))
+ for e in res.get("edges") or []:
+ n = e.get("node") or {}
+ other = (f"{n.get('category')}/{n.get('key')}" if n.get("tier") == "entity"
+ else f"{n.get('tier')} {n.get('key')}")
+ arrow = "->" if e.get("direction") == "out" else "<-"
+ state = "" if n.get("exists") else (" (archived)" if n.get("archived") else " (missing)")
+ print(a.kv(f"{arrow} {e.get('relation')}", other + state))
+ if res.get("next_cursor"):
+ print(a.dim(f" more: --cursor {res['next_cursor']}"))
+ _h.handoff("done", later=signin_later)
+ return 0
+
+
+def _cmd_memory_adopt(args: argparse.Namespace, db_path: Path) -> int:
+ """`sibyl memory adopt`: move this store's rows written before sign-in
+ (DEFAULT_TENANT) into the signed-in account. Local only: one SQLite
+ transaction, nothing deleted, conflicting keys kept under a new name, an
+ audit row in the store. Needs a verified sign-in (sibyl init). When the
+ store has held another account it asks first (or --yes)."""
+ from sibyl_memory_client import EntitlementError
+ from sibyl_memory_client._adopt import AdoptionRefused
+
+ cred_path = Path(getattr(args, "credentials", None) or DEFAULT_CRED_PATH).expanduser()
+
+ def _run(confirm: bool):
+ return _gate.adopt_pre_signin(db_path, cred_path, trigger="command",
+ confirm_other_accounts=confirm)
+ try:
+ try:
+ res = _run(bool(getattr(args, "yes", False)))
+ except AdoptionRefused as e:
+ if e.reason != "other_account":
+ raise
+ print(a.warn_line("This store also holds another account's memory."))
+ print(a.dim(" The rows written before sign-in may not be yours. Moving them makes"))
+ print(a.dim(" them part of the account signed in now. Nothing is deleted either way."))
+ if not sys.stdin.isatty():
+ print(a.dim(" Not a terminal: re-run with --yes to move them."))
+ _h.handoff("sibyl memory adopt --yes",
+ human="this store also holds another account's memory; confirm the pre "
+ "sign-in rows are yours before I move them (nothing is deleted either way)")
+ return 1
+ answer = input(" Move them into this account? [y/N] ").strip().lower()
+ if answer not in ("y", "yes"):
+ print(a.dim(" Nothing moved."))
+ _h.handoff("done")
+ return 1
+ res = _run(True)
+ except EntitlementError as e:
+ print(a.warn_line(str(e).splitlines()[0]))
+ print(a.dim(" Sign in first: sibyl init. Nothing moved."))
+ en, eh = _h.from_exception(e, default="sibyl init")
+ _h.handoff(en, human=eh, later=("sibyl memory adopt",))
+ return 1
+ except AdoptionRefused as e:
+ print(a.warn_line(str(e)))
+ print(a.dim(" Nothing moved."))
+ _h.handoff("sibyl status")
+ return 1
+ held = list(getattr(res, "held_links", None) or []) if res is not None else []
+ if res is None or res.status == "nothing_to_move":
+ if held:
+ print(a.dim(f"Nothing moved: {len(held)} links from before sign-in are held back."))
+ _print_held_links(held)
+ else:
+ print(a.dim("Nothing to move: no memory from before sign-in in this store."))
+ _h.handoff("done")
+ return 0
+ print(a.success_line(f"Moved {res.moved} rows from before sign-in into your account."))
+ for table, n in sorted(res.counts.items()):
+ print(a.kv(table, str(n)))
+ if res.renamed:
+ print(a.dim(f" {len(res.renamed)} kept under a new name ending in (before sign-in): "
+ "your account already had that key."))
+ dropped = getattr(res, "dropped_links", None) or []
+ if dropped:
+ print(a.dim(f" {len(dropped)} links were already in your account and were not copied twice."))
+ if held:
+ _print_held_links(held)
+ _h.handoff("done")
+ return 0
+
+
+def _print_held_links(held: list) -> None:
+ """Edges adoption could not place: their endpoint name exists in the
+ account twice (the account's own and a "(before sign-in)" copy) and no
+ record says which one they belong to. They stay where they are."""
+ print(a.dim(f" {len(held)} links not moved: each points at a name your account holds both "
+ "as itself and as \"(before sign-in)\", and nothing records which one it meant."))
+ for h in held[:5]:
+ f, t = h.get("from") or {}, h.get("to") or {}
+ print(a.dim(f" {f.get('key')} --{h.get('relation')}--> {t.get('key')}"))
+ print(a.dim(" Forget (archive) the copy they should not attach to, then run sibyl memory adopt again."))
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ global _ENT_CRED_PATH
+ try:
+ _ENT_CRED_PATH = Path(getattr(args, "credentials", None) or DEFAULT_CRED_PATH).expanduser()
+ except (TypeError, ValueError):
+ _ENT_CRED_PATH = DEFAULT_CRED_PATH
+ global _CREDS_CORRUPT
+ _CREDS_CORRUPT = False
+ try:
+ return args.func(args)
+ except KeyboardInterrupt:
+ print(red("\nInterrupted."))
+ return 130
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/doctor.py b/sibyl-memory-cli/src/sibyl_memory_cli/doctor.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5b87ab5152fc5cb6fa0b69480bc4da95e3f8b20
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/doctor.py
@@ -0,0 +1,682 @@
+"""`sibyl doctor`: end-to-end check of the MCP path an agent actually uses.
+
+Starts the real ``sibyl-memory-mcp`` stdio server, lists its tools, saves a
+clearly MARKED test memory, recalls it, deletes it, then verifies nothing is
+left behind. Reports pass/fail per step.
+
+Deletion note: the server's ``memory_forget`` tool ARCHIVES (the body is kept in
+``archived_entities``). A doctor run must leave no data, so after exercising
+``memory_forget`` the exact test row (a unique uuid name) is purged from both
+``entities`` and ``archived_entities`` with a narrowly scoped DELETE, and the
+purge is verified with row counts. Nothing but that one name is ever touched.
+
+The MCP client here is a minimal newline-delimited JSON-RPC speaker over the
+child's pipes (no dependency on the ``mcp`` package).
+
+Harness checks (cli 0.7.0, spec dsh-doctor v2 section 5): after the server
+round trip, each detected harness's sibyl-memory wiring is probed and
+reported (ok, missing, stale, broken, foreign, duplicate, unreadable,
+disabled, overridden, unverifiable). Read-only by default. ``--fix`` repairs
+stale and broken entries without asking; at a terminal each repair is asked,
+default No. A missing entry is a warning and is never added (the
+``sibyl setup `` command is named instead). Doctor never installs
+packages and only ever starts a command whose name starts with
+sibyl-memory-mcp. Timestamped ``.bak`` files older versions left beside
+harness configs are listed, never touched.
+"""
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import os
+import queue
+import re
+import shutil
+import sqlite3
+import subprocess
+import sys
+import threading
+import time
+import uuid
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+from . import _aesthetic as a
+
+TEST_CATEGORY = "_sibyl_doctor"
+REQUIRED_TOOLS = ("memory_remember", "memory_recall", "memory_forget")
+STEP_TIMEOUT = 25.0
+
+
+@dataclass
+class Step:
+ name: str
+ ok: bool
+ detail: str = ""
+ skipped: bool = False
+
+
+class McpStdioClient:
+ """Just enough MCP over stdio: initialize, tools/list, tools/call."""
+
+ def __init__(self, cmd: list, env: dict):
+ self.proc = subprocess.Popen(
+ cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
+ self._q: "queue.Queue[dict]" = queue.Queue()
+ self._next = 1
+ self._err = b""
+ threading.Thread(target=self._read, daemon=True).start()
+ threading.Thread(target=self._drain_err, daemon=True).start()
+
+ def _drain_err(self) -> None:
+ try:
+ for chunk in iter(lambda: self.proc.stderr.read(1024), b""):
+ self._err = (self._err + chunk)[-2000:]
+ except Exception:
+ pass
+
+ def _read(self) -> None:
+ try:
+ for line in self.proc.stdout:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ msg = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(msg, dict):
+ self._q.put(msg)
+ except Exception:
+ pass
+
+ def _send(self, obj: dict) -> None:
+ self.proc.stdin.write((json.dumps(obj) + "\n").encode())
+ self.proc.stdin.flush()
+
+ def request(self, method: str, params: Optional[dict] = None, timeout: float = STEP_TIMEOUT) -> dict:
+ rid = self._next
+ self._next += 1
+ self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}})
+ deadline = time.monotonic() + timeout
+ while True:
+ left = deadline - time.monotonic()
+ if left <= 0:
+ raise TimeoutError(f"{method} timed out after {timeout:.0f}s")
+ try:
+ msg = self._q.get(timeout=left)
+ except queue.Empty:
+ continue
+ if msg.get("id") == rid and ("result" in msg or "error" in msg):
+ if "error" in msg:
+ raise RuntimeError(f"{method}: {msg['error']}")
+ return msg["result"]
+ if self.proc.poll() is not None and self._q.empty():
+ raise RuntimeError(f"server exited (code {self.proc.returncode}): "
+ f"{self._err.decode(errors='replace')[:200]}")
+
+ def initialize(self) -> dict:
+ res = self.request("initialize", {
+ "protocolVersion": "2024-11-05", "capabilities": {},
+ "clientInfo": {"name": "sibyl-doctor", "version": "1"}})
+ self._send({"jsonrpc": "2.0", "method": "notifications/initialized"})
+ return res
+
+ def call(self, tool: str, arguments: dict) -> tuple:
+ """Returns (is_error, payload dict)."""
+ res = self.request("tools/call", {"name": tool, "arguments": arguments})
+ payload: Any = res.get("structuredContent")
+ if not isinstance(payload, dict):
+ payload = {}
+ for part in res.get("content") or []:
+ if isinstance(part, dict) and part.get("type") == "text":
+ try:
+ loaded = json.loads(part.get("text", ""))
+ if isinstance(loaded, dict):
+ payload = loaded
+ break
+ except ValueError:
+ payload = {"message": str(part.get("text", ""))[:300]}
+ return bool(res.get("isError")), payload
+
+ def close(self) -> None:
+ try:
+ self.proc.stdin.close()
+ except Exception:
+ pass
+ try:
+ self.proc.terminate()
+ self.proc.wait(timeout=3)
+ except Exception:
+ try:
+ self.proc.kill()
+ except Exception:
+ pass
+
+
+def purge_test_rows(db_path: Path, name: str) -> int:
+ """Delete the doctor's test rows (exact category + unique name) from
+ entities and archived_entities. Returns how many rows remain (0 = clean)."""
+ if not db_path.exists():
+ return 0
+ conn = sqlite3.connect(str(db_path), timeout=10)
+ try:
+ for table in ("entities", "archived_entities"):
+ try:
+ conn.execute(f"DELETE FROM {table} WHERE category = ? AND name = ?",
+ (TEST_CATEGORY, name))
+ except sqlite3.Error:
+ pass
+ conn.commit()
+ left = 0
+ for table in ("entities", "archived_entities"):
+ try:
+ left += conn.execute(
+ f"SELECT COUNT(*) FROM {table} WHERE category = ? AND name = ?",
+ (TEST_CATEGORY, name)).fetchone()[0]
+ except sqlite3.Error:
+ pass
+ return left
+ finally:
+ conn.close()
+
+
+def run_checks(*, server_cmd: list, db_path: Path, cred_path: Path,
+ purge: Callable[[Path, str], int] = purge_test_rows) -> list:
+ steps: list = []
+ env = dict(os.environ)
+ env["SIBYL_MEMORY_DB"] = str(db_path)
+ env["SIBYL_CREDENTIALS"] = str(cred_path)
+ name = f"doctor-test-{uuid.uuid4().hex[:12]}"
+ marker = f"SIBYL-DOCTOR-TEST-{uuid.uuid4().hex}"
+ body = {"marker": marker, "note": "sibyl doctor test memory. Safe to delete; removed automatically."}
+
+ try:
+ client = McpStdioClient(server_cmd, env)
+ except Exception as e:
+ steps.append(Step("start server", False, f"{type(e).__name__}: {e}"))
+ return steps
+
+ saved = False
+ try:
+ try:
+ info = client.initialize()
+ sv = (info.get("serverInfo") or {})
+ steps.append(Step("start server", True,
+ f"{sv.get('name', 'mcp server')} {sv.get('version', '')}".strip()))
+ except Exception as e:
+ steps.append(Step("start server", False, str(e)))
+ return steps
+
+ try:
+ tools = [t.get("name") for t in client.request("tools/list").get("tools", [])]
+ missing = [t for t in REQUIRED_TOOLS if t not in tools]
+ if missing:
+ steps.append(Step("list tools", False, "missing: " + ", ".join(missing)))
+ return steps
+ steps.append(Step("list tools", True, f"{len(tools)} tools"))
+ except Exception as e:
+ steps.append(Step("list tools", False, str(e)))
+ return steps
+
+ try:
+ is_err, res = client.call("memory_remember",
+ {"category": TEST_CATEGORY, "name": name, "body": body})
+ if is_err or not res.get("ok", False):
+ raw = json.dumps(res)[:300] if res else "tool error"
+ code = res.get("code") if isinstance(res, dict) else None
+ if code == "ACCOUNT_REQUIRED" or "ACCOUNT_REQUIRED" in raw:
+ steps.append(Step("save test memory", False,
+ "sign-in required: run `sibyl init` in a terminal, then re-run `sibyl doctor`"))
+ else:
+ steps.append(Step("save test memory", False, raw))
+ for n in ("recall test memory", "delete test memory"):
+ steps.append(Step(n, False, "skipped (save failed)", skipped=True))
+ return steps
+ saved = True
+ steps.append(Step("save test memory", True, f"{TEST_CATEGORY}/{name}"))
+ except Exception as e:
+ steps.append(Step("save test memory", False, str(e)))
+ return steps
+
+ try:
+ is_err, res = client.call("memory_recall", {"category": TEST_CATEGORY, "name": name})
+ text = json.dumps(res)
+ if is_err or marker not in text:
+ steps.append(Step("recall test memory", False, "saved memory did not come back"))
+ else:
+ steps.append(Step("recall test memory", True, "marker round-tripped"))
+ except Exception as e:
+ steps.append(Step("recall test memory", False, str(e)))
+
+ try:
+ is_err, res = client.call("memory_forget",
+ {"category": TEST_CATEGORY, "name": name,
+ "reason": "sibyl doctor cleanup"})
+ if is_err:
+ steps.append(Step("delete test memory", False, json.dumps(res)[:300]))
+ else:
+ steps.append(Step("delete test memory", True, "forgotten via memory_forget"))
+ except Exception as e:
+ steps.append(Step("delete test memory", False, str(e)))
+ finally:
+ client.close()
+ if saved:
+ # Runs even when a step above failed: the doctor never leaves data.
+ try:
+ left = purge(db_path, name)
+ if left:
+ steps.append(Step("verify nothing left behind", False,
+ f"{left} test row(s) remain for {TEST_CATEGORY}/{name}"))
+ else:
+ steps.append(Step("verify nothing left behind", True, "0 test rows remain"))
+ except Exception as e:
+ steps.append(Step("verify nothing left behind", False,
+ f"{type(e).__name__}: {e}"))
+ return steps
+
+
+def _server_cmd() -> Optional[list]:
+ from .setup import resolve_mcp_binary # same lookup as setup (cli 0.6.1)
+ w = resolve_mcp_binary()
+ return [w] if w else None
+
+
+# ----------------------------------------------------------------------
+# Harness checks (spec dsh-doctor v2, 5.2 to 5.7)
+# ----------------------------------------------------------------------
+
+@dataclass
+class HarnessCheck:
+ name: str # wirer.name
+ display_name: str
+ location: str # "" or "home" / "profile:" for DeepSeek Harness
+ status: str # ok | missing | stale | broken | foreign | duplicate | unreadable
+ # | disabled | overridden | unverifiable
+ level: str # pass | warn | fail
+ command: Optional[str]
+ config_path: str
+ detail: str
+ fixable: bool
+ hint: str = "" # e.g. "sibyl setup cursor" for missing
+ fixed: bool = False
+ fix_message: str = ""
+ # Panel fix 8: text to paste by hand, kept with its newlines (valid YAML
+ # or TOML as printed); printed under the FAIL line.
+ fix_block: str = ""
+
+
+_WARN_STATUSES = ("foreign", "duplicate", "unreadable", "disabled", "overridden", "unverifiable")
+
+
+def _loc_suffix(location: str) -> str:
+ if location.startswith("profile:"):
+ return ", profile " + location.split(":", 1)[1]
+ return ""
+
+
+def _abs_command(cmd: str) -> Optional[str]:
+ if os.path.isabs(cmd):
+ return cmd
+ w = shutil.which(cmd)
+ return os.path.abspath(w) if w else None
+
+
+def check_harness(wirer: Any, probe: dict, *, verified: dict) -> HarnessCheck:
+ """Turn one probe into a check. ``verified`` caches _verify_mcp_starts
+ results per absolute path (the round-trip server path is pre-seeded)."""
+ from . import setup as S
+ entry = probe.get("entry")
+ cmd = probe.get("command")
+ cfg = str(probe.get("config_path") or "")
+ loc = probe.get("location") or ""
+ pdetail = probe.get("detail") or ""
+
+ def mk(status: str, level: str, detail: str, fixable: bool = False, hint: str = "") -> HarnessCheck:
+ return HarnessCheck(wirer.name, wirer.display_name, loc, status, level, cmd, cfg,
+ detail, fixable, hint)
+
+ if entry in _WARN_STATUSES:
+ # Name the config file once (sandbox M4): a detail that already lists
+ # it, such as the duplicate one, is not followed by it again.
+ if not pdetail:
+ c = mk(entry, "warn", f"{entry}: see {cfg}")
+ elif cfg and cfg in pdetail:
+ c = mk(entry, "warn", f"{entry}: {pdetail}")
+ else:
+ c = mk(entry, "warn", f"{entry}: {pdetail}; {cfg}")
+ elif entry == "absent":
+ hint = f"sibyl setup {wirer.name}"
+ c = mk("missing", "warn", f"missing: no sibyl-memory entry; to add it run: {hint}",
+ hint=hint)
+ elif entry == "present" and probe.get("broken"):
+ c = mk("broken", "fail", f"broken: {pdetail or 'the entry does not work'}; {cfg}",
+ fixable=bool(probe.get("fixable", True)))
+ elif entry == "present" and cmd is None:
+ c = mk("ok", "pass", pdetail or "wired")
+ elif entry == "present" and not S._command_resolves(cmd, strict=True):
+ why = "does not exist" if os.path.isabs(cmd) else "is not on PATH"
+ c = mk("stale", "fail", f"stale: {cmd} {why}; {cfg}", fixable=True)
+ elif entry == "present":
+ path = _abs_command(cmd) or cmd
+ if not S._is_our_command(path):
+ # Doctor only ever starts a command named sibyl-memory-mcp*.
+ c = mk("foreign", "warn", f"foreign: the entry runs another command; {cfg}")
+ c.command = None # never a foreign command string in the output
+ else:
+ if path not in verified:
+ verified[path] = bool(S._verify_mcp_starts(path)[0])
+ if not verified[path]:
+ mine = S.resolve_mcp_binary()
+ alt = bool(mine and os.path.abspath(mine) != os.path.abspath(path))
+ if alt and mine not in verified:
+ verified[mine] = bool(S._verify_mcp_starts(mine)[0])
+ c = mk("broken", "fail", f"broken: {cmd} does not start; {cfg}",
+ fixable=bool(alt and verified.get(mine)))
+ else:
+ notes = []
+ mine = S.resolve_mcp_binary()
+ if mine and os.path.abspath(mine) != os.path.abspath(path):
+ notes.append("uses a different install than this CLI")
+ if not os.path.isabs(cmd):
+ notes.append("relies on PATH")
+ c = mk("ok", "pass", "; ".join([f"wired; {cmd}"] + notes))
+ else:
+ c = mk("unreadable", "warn", f"unreadable: unknown probe result; {cfg}")
+ # Nothing to fix by hand: customized entries, and no installed server to
+ # point at (Hermes broken excepted: its repair installs the plugin).
+ if c.fixable and probe.get("customized"):
+ c.fixable = False
+ c.detail += f" ({pdetail})" if pdetail else (
+ " (entry has custom env or args; update the path by hand)")
+ if c.fixable and S.resolve_mcp_binary() is None and not (
+ wirer.name == "hermes" and c.status == "broken"):
+ c.fixable = False
+ if c.status in ("stale", "broken") and not c.fixable and wirer.name == "claude-code" \
+ and probe.get("customized"):
+ binpath = S.mcp_command_path()
+ c.detail = (f"{c.status}: entry has custom env or args; update the path by hand: "
+ f"claude mcp remove -s user sibyl-memory, then claude mcp add --scope user "
+ f"sibyl-memory -- {binpath} with your settings")
+ return c
+
+
+def find_legacy_backups() -> list:
+ """Timestamped .bak files that sibyl versions before 0.7.0 wrote beside
+ harness configs. Listed only: never opened, moved or deleted."""
+ from . import setup as S
+ out = []
+ for name, cls in S.ALL_WIRERS.items():
+ if name == "deepseek":
+ continue # it never wrote one
+ try:
+ w = cls()
+ except Exception:
+ continue
+ cfg = getattr(w, "settings_path", None) if name == "claude-code" else getattr(w, "config_path", None)
+ if cfg is None:
+ continue
+ cfg = Path(cfg)
+ pat = re.compile(r"^" + re.escape(cfg.name) + r"\.\d{8}T\d{6}Z\.bak$")
+ try:
+ for f in cfg.parent.iterdir():
+ if pat.match(f.name):
+ out.append(str(f.absolute()))
+ except OSError:
+ continue
+ return sorted(set(out))
+
+
+# `doctor --harness` names that check another harness's file: Grok Bot is
+# wired into the Cursor file (sibyl setup grokbot), so its check is Cursor's.
+DOCTOR_ALIASES: dict = {"grokbot": "cursor"}
+
+
+def run_harness_checks(only: list, verified: dict) -> list:
+ """[(wirer, probe, check)] for each detected harness (default paths;
+ Grok Bot is the Cursor file, so it is not checked twice)."""
+ from . import setup as S
+ rows = []
+ for name, cls in S.ALL_WIRERS.items():
+ if only and name not in only:
+ continue
+ try:
+ w = cls()
+ present = w.is_present()
+ except Exception:
+ continue
+ if not present:
+ if only:
+ rows.append((w, None, HarnessCheck(name, w.display_name, "", "ok", "pass", None,
+ str(getattr(w, "config_path", "") or ""),
+ "not detected", False)))
+ continue
+ try:
+ probes = w.doctor_probe()
+ except Exception as e: # doctor_probe never raises; belt and braces
+ probes = [{"entry": "unreadable", "command": None, "location": "",
+ "config_path": str(getattr(w, "config_path", "")), "detail": type(e).__name__}]
+ for pr in probes:
+ rows.append((w, pr, check_harness(w, pr, verified=verified)))
+ return rows
+
+
+def repair_check(wirer: Any, probe: dict, check: HarnessCheck, verified: dict) -> tuple:
+ """Repair one check. Every repair runs with stdout captured (the Hermes
+ plugin installer prints a banner; under --json that would break the
+ document). Returns (new check, outcome or None)."""
+ buf = io.StringIO()
+ try:
+ with contextlib.redirect_stdout(buf):
+ out = wirer.repair_mcp(probe)
+ except Exception as e:
+ check.fixed = False
+ check.fix_message = f"repair failed ({type(e).__name__})"
+ return check, None
+ try:
+ with contextlib.redirect_stdout(buf):
+ probes = wirer.doctor_probe()
+ except Exception:
+ probes = []
+ same = [p for p in probes if (p.get("location") or "") == (probe.get("location") or "")]
+ newp = same[0] if same else (probes[0] if probes else probe)
+ new = check_harness(wirer, newp, verified=verified)
+ new.fixed = new.status == "ok"
+ if not new.fixed:
+ # A repair that did not take fails the run whatever the entry is now
+ # (a failed Claude Code re-add leaves it unregistered: "missing").
+ new.level = "fail"
+ new.fixable = False
+ text = str(out.message or "")
+ block = getattr(out, "manual_block", None)
+ if block and text.endswith(block):
+ # Panel fix 8: the paste-by-hand block keeps its line breaks; only the
+ # lead sentence is folded onto the FAIL line.
+ text = text[:-len(block)]
+ new.fix_block = block
+ msg = " ".join(text.split())
+ if out.backup_path:
+ msg += f"; backup at {out.backup_path}"
+ new.fix_message = msg
+ return new, out
+
+
+def _prompt_for(wirer: Any, check: HarnessCheck) -> str:
+ from . import setup as S
+ newp = S.mcp_command_path()
+ if wirer.name == "hermes":
+ return (f"Repair Hermes? (installs the Sibyl plugin into {wirer.plugin_dir}; "
+ "config.yaml is not changed)")
+ if wirer.name == "claude-code":
+ return ("Repair Claude Code? (removes the sibyl-memory registration and adds it again "
+ f"with {newp})")
+ return (f"Repair {check.display_name}{_loc_suffix(check.location)}? "
+ f"(points it at {newp}; a backup is kept)")
+
+
+def _doctor_handoff(steps: list, server_cmd: Optional[list], checks: list, repairs: list) -> tuple:
+ """(next, human, later) by the rules of spec 5.5, first match wins.
+ ``repairs``: [(check after repair, outcome or None)]."""
+ from . import setup as S
+ later = tuple(dict.fromkeys(c.hint for c in checks if c.status == "missing" and c.hint))
+ if not all(s.ok for s in steps):
+ if any("sign-in required" in (s.detail or "") for s in steps):
+ return "sibyl init", None, later
+ if server_cmd is None:
+ nxt, human, _l = S._binary_missing_handoff("doctor")
+ return nxt, human, later + (("sibyl doctor",) if nxt != "done" else ())
+ return "done", "run sibyl-memory-mcp in a terminal and tell me the first error line", later
+ for c, out in repairs:
+ if not c.fixed:
+ if out is not None and out.handoff:
+ nxt, human, more = out.handoff
+ return nxt, human, later + tuple(more or ())
+ why = " ".join((c.fix_message or c.detail or "an error").split())[:200]
+ return "done", f"{c.display_name} wiring could not be repaired ({why})", later
+ if any(c.fixable and c.level == "fail" for c in checks):
+ return "sibyl doctor --fix", None, later
+ for c in checks:
+ if c.level == "fail":
+ return "done", f"{c.config_path} needs fixing by hand ({c.detail})", later
+ fixed = [c for c, _o in repairs if c.fixed]
+ if fixed:
+ asks = list(dict.fromkeys(S._RESTART_HUMAN.get(c.name, f"restart {c.display_name}")
+ for c in fixed))
+ return "done", "; ".join(asks), later
+ return "done", None, later
+
+
+def _check_line(c: HarnessCheck) -> str:
+ who = f"{c.display_name}{_loc_suffix(c.location)}"
+ if c.fixed:
+ return a.success_line(f"FIXED {who} ({c.fix_message})")
+ if c.level == "pass":
+ return a.success_line(f"PASS {who} ({c.detail})")
+ if c.level == "warn":
+ return a.warn_line(f"WARN {who} ({c.detail})")
+ line = f"FAIL {who} ({c.detail})"
+ if c.fix_message:
+ line += f" not fixed: {c.fix_message}"
+ if c.fix_block:
+ # Column 0, unstyled, so it can be pasted as it is.
+ return a.err_line(line) + "\n" + c.fix_block
+ return a.err_line(line)
+
+
+def _print_harness_report(checks: list, legacy: list) -> None:
+ print()
+ print("Harnesses")
+ if not checks:
+ print(a.dim(" none detected (sibyl setup wires one)"))
+ for c in checks:
+ print(_check_line(c))
+ if legacy:
+ print(a.dim(f" INFO {len(legacy)} backup file{'s' if len(legacy) != 1 else ''} from "
+ "older sibyl versions sit beside harness configs (not removed):"))
+ for p in legacy:
+ print(a.dim(f" {p}"))
+
+
+def run_doctor(args: Any) -> int:
+ from . import _handoff as _h
+ from . import setup as S
+ db_path = Path(getattr(args, "db", None) or "~/.sibyl-memory/memory.db").expanduser()
+ cred_path = Path(getattr(args, "credentials", None) or "~/.sibyl-memory/credentials.json").expanduser()
+ as_json = bool(getattr(args, "json", False))
+ fix = bool(getattr(args, "fix", False))
+ only = [DOCTOR_ALIASES.get(n, S.SETUP_ALIASES.get(n, n))
+ for n in (getattr(args, "harness", None) or [])]
+ no_harness = bool(getattr(args, "no_harness", False))
+ cmd = _server_cmd()
+ if cmd is None:
+ steps = [Step("start server", False, "sibyl-memory-mcp not found. Run: pip install sibyl-memory-mcp")]
+ else:
+ steps = run_checks(server_cmd=cmd, db_path=db_path, cred_path=cred_path)
+ server_ok = all(s.ok for s in steps)
+
+ verified: dict = {}
+ if cmd is not None and any(s.name == "start server" and s.ok for s in steps):
+ verified[os.path.abspath(cmd[0])] = True
+ rows: list = []
+ legacy: list = []
+ if not no_harness:
+ rows = run_harness_checks(only, verified)
+ legacy = find_legacy_backups()
+
+ def checks() -> list:
+ return [c for _w, _p, c in rows]
+
+ wants = [i for i, (_w, p, c) in enumerate(rows) if c.fixable and p is not None]
+ prompted = False
+ repairs: list = []
+ if wants and fix:
+ to_fix = wants
+ elif wants and not as_json and sys.stdin.isatty() and sys.stdout.isatty():
+ prompted = True
+ _print_steps(steps)
+ _print_harness_report(checks(), legacy)
+ print()
+ to_fix = [i for i in wants
+ if S._interactive_prompt(_prompt_for(rows[i][0], rows[i][2]), default="N") == "y"]
+ else:
+ to_fix = []
+ attempted, fixed_ids = [], []
+ for i in to_fix:
+ w, p, c = rows[i]
+ new, out = repair_check(w, p, c, verified)
+ rows[i] = (w, p, new)
+ repairs.append((new, out))
+ ident = w.name + (f":{c.location}" if c.location else "")
+ attempted.append(ident)
+ if new.fixed:
+ fixed_ids.append(ident)
+
+ all_checks = checks()
+ harness_fail = any(c.level == "fail" and not c.fixed for c in all_checks)
+ ok = server_ok and not harness_fail
+ nxt, human, later = _doctor_handoff(steps, cmd, all_checks, repairs)
+
+ if as_json:
+ payload = {
+ "ok": ok,
+ "server_ok": server_ok,
+ "steps": [s.__dict__ for s in steps],
+ "harnesses": [asdict(c) for c in all_checks],
+ "fix": {"requested": fix, "attempted": attempted, "fixed": fixed_ids},
+ "legacy_backups": {"count": len(legacy), "paths": legacy},
+ }
+ _h.json_handoff(payload, nxt, human)
+ payload["later"] = list(later)
+ print(json.dumps(payload, indent=2))
+ return 0 if ok else 1
+
+ if prompted:
+ if repairs:
+ print()
+ for c, _o in repairs:
+ print(_check_line(c))
+ else:
+ _print_steps(steps)
+ if not no_harness:
+ _print_harness_report(all_checks, legacy)
+ print()
+ warned = any(c.level == "warn" for c in all_checks)
+ if not ok:
+ print(a.err_line("Doctor: some steps failed."))
+ elif warned:
+ print(a.warn_line("Doctor: passed with warnings."))
+ else:
+ print(a.success_line("Doctor: all steps passed."))
+ print()
+ _h.handoff(nxt, human=human, later=later)
+ return 0 if ok else 1
+
+
+def _print_steps(steps: list) -> None:
+ print()
+ for s in steps:
+ mark = "PASS" if s.ok else ("SKIP" if s.skipped else "FAIL")
+ line = f"{mark} {s.name}" + (f" ({s.detail})" if s.detail else "")
+ print(a.success_line(line) if s.ok else a.err_line(line))
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/hooks.py b/sibyl-memory-cli/src/sibyl_memory_cli/hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e49bb2b26d9a00d952247bd44ae7d17e284c154
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/hooks.py
@@ -0,0 +1,502 @@
+"""`sibyl hook `: the Claude Code hooks (spec plugin-save-debloat 5.2).
+
+Installed by `sibyl setup` into ~/.claude/settings.json; not for manual use.
+Each call reads the hook JSON from stdin (bounded), always exits 0, prints at
+most one JSON object on stdout, and logs one short line (event and outcome,
+never content) to ~/.sibyl-memory/lifecycle.log. A failure never blocks a
+session: it degrades to printing nothing.
+
+Output contract, verified against Claude Code 2.1.283's hook schemas (the
+binary's zod definitions; see the release notes):
+
+* SessionStart / UserPromptSubmit add context with
+ ``{"hookSpecificOutput": {"hookEventName": "", "additionalContext": ""}}``;
+* Stop continues the session with ``{"decision": "block", "reason": ""}``
+ (``decision`` is ``"approve" | "block"``); the re-entry carries
+ ``stop_hook_active: true`` and gets nothing.
+
+Free tier: reminders only (the debloat FYI and the unsaved-last-session line
+at start, the save-due line on a prompt). Pro (a verified fresh/stale
+entitlement whose tier is paid, never a file hint): the start runs the debloat
+plan under the person's policy and reports one line, and names up to three
+relevant skill proposals (read-only, at most once a day); Stop asks the model
+to run the save procedure headless by ACTIVE time (R1, plan 2.2): once early
+(the first turn end after 5 memory writes, or after a compaction of THIS
+session; the write count is the account's, plan D6.5), then after
+every interval of active work (default 60 minutes; `sibyl autosave`), never
+more than 8 times a session or 12 a day, and only when there is something to
+save (Stop fires at every turn end, not only at the end of a session). Active
+time: every SessionStart, UserPromptSubmit, Stop and PreCompact adds the time
+since the previous event, capped at 5 minutes, except the model's own turn
+(from a prompt to its Stop), capped at 30 minutes. A scripted `claude -p` run is
+never continued (no transcript, or fewer than two prompts in the session).
+Each continuation carries its sequence number ("save 2 of this session"), so
+the transcript guard applies per request; a request is recorded (per-session
+and per-day caps, the interval) only when it is actually emitted. PreCompact
+and SessionEnd write the session capsule.
+
+Skill signals (R2, Pro): Stop also reads the transcript INCREMENTALLY from the
+session's stored byte offset (at most 4 MiB per Stop) and records each
+tool_use block's name and the hashed, sorted key names of its input in
+~/.sibyl-memory/signals.json; values and text are never kept. The learner
+never runs in a hook: the next MCP server start turns the record into
+proposals.
+
+Time bound (Claude Code kills a hook at its timeout, 5 s): nothing in a hook
+touches the network. The Pro client's entitlement gate never refreshes, its
+usage heartbeat is off (the exit flush would wait on the network), and a
+memory write (a trim's history, a capsule) happens only when the cap gate can
+decide it locally (a fresh tier cache) and within ``WRITE_BUDGET_SECONDS`` of
+the hook's start; otherwise the start only plans and the write waits for a
+later start or the MCP server. Measured: see the release notes.
+
+Fast path: this module imports only the standard library. A hook first reads
+the payload, the credentials and the UNVERIFIED tier claim in
+entitlement.json; when that claim is not a paid tier the device cannot be Pro
+(the verified tier is that same claim), so Stop returns at once and
+PreCompact / SessionEnd record their counters without verifying the token or
+opening the memory database. A claim that says paid is always verified.
+"""
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+import time
+from pathlib import Path
+from typing import Any
+
+MAX_STDIN_BYTES = 1024 * 1024
+MAX_TRANSCRIPT_SCAN = 64 * 1024 * 1024
+STOP_REASON_BASE = ("Sibyl Memory Pro auto-save: read ~/.sibyl-memory/skills/SAVE.md and run it in "
+ "headless mode now (ask nothing, skip skill extraction, queue decisions)")
+# A scripted run (`claude -p`) has one prompt: never continue a session with
+# fewer prompts than this.
+MIN_PROMPTS_FOR_STOP = 2
+
+
+def stop_reason(seq: int) -> str:
+ """The Stop continuation for the ``seq``-th automatic save of a session."""
+ return f"{STOP_REASON_BASE} (save {int(seq)} of this session). Then stop."
+
+
+STOP_REASON = stop_reason(1)
+EVENTS = {"session-start": "SessionStart", "prompt": "UserPromptSubmit", "stop": "Stop",
+ "pre-compact": "PreCompact", "session-end": "SessionEnd"}
+# A memory write starts only this long after the hook started (the harness
+# kills the hook at 5 s; the write itself is local and takes milliseconds).
+WRITE_BUDGET_SECONDS = 2.5
+# Mirrors sibyl_memory_client.tiers.PAID_TIERS (kept literal so the fast path
+# imports nothing); test_f11_paid_tier_literal_matches_the_client asserts
+# equality; edit both. Canonical paid tiers pro + elite, then the legacy aliases.
+PAID_TIERS = frozenset({"pro", "elite", "sync", "team", "lifetime", "stake", "enterprise"})
+ENTITLEMENT_FILENAME = "entitlement.json"
+
+
+def _paths(home: Path | None) -> tuple[Path, Path, Path]:
+ home = home or Path.home()
+ cred = Path(os.environ.get("SIBYL_CREDENTIALS") or (home / ".sibyl-memory" / "credentials.json"))
+ db = Path(os.environ.get("SIBYL_MEMORY_DB") or (home / ".sibyl-memory" / "memory.db"))
+ return home, cred.expanduser(), db.expanduser()
+
+
+def _read_creds(path: Path) -> dict[str, Any]:
+ try:
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > 64 * 1024:
+ return {}
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ return raw if isinstance(raw, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def _transcript_has(path: Any, needle: str) -> bool:
+ """True when the session transcript already carries ``needle`` (our
+ continuation reason with its sequence number): a second guard beside
+ lifecycle.json, so each numbered request is made at most once even if that
+ file was rewritten."""
+ if not isinstance(path, str) or not path:
+ return False
+ p = Path(path)
+ try:
+ if p.is_symlink() or not p.is_file():
+ return False
+ b = needle.encode("utf-8")
+ seen = 0
+ tail = b""
+ with open(p, "rb") as fh:
+ while seen < MAX_TRANSCRIPT_SCAN:
+ chunk = fh.read(1024 * 1024)
+ if not chunk:
+ return False
+ seen += len(chunk)
+ if b in tail + chunk:
+ return True
+ tail = chunk[-len(b):]
+ except OSError:
+ return False
+ return False
+
+
+def _context(event_name: str, lines: list[str]) -> str:
+ if not lines:
+ return ""
+ return json.dumps({"hookSpecificOutput": {"hookEventName": event_name,
+ "additionalContext": "\n".join(lines)}})
+
+
+def claim_label(cred: Path) -> str | None:
+ """The UNVERIFIED tier label of the entitlement next to ``cred``, stripped
+ and lowercased; None when there is no readable SE1 token or no string
+ label. Standard library only (no signature check, no client import)."""
+ try:
+ p = Path(cred).parent / ENTITLEMENT_FILENAME
+ if p.is_symlink() or not p.is_file() or p.stat().st_size > 64 * 1024:
+ return None
+ token = json.loads(p.read_text(encoding="utf-8")).get("token")
+ if not isinstance(token, str):
+ return None
+ parts = token.split(".")
+ if len(parts) != 3 or parts[0] != "SE1":
+ return None
+ seg = parts[1] + "=" * (-len(parts[1]) % 4)
+ claim = json.loads(base64.urlsafe_b64decode(seg.encode("ascii")))
+ if not isinstance(claim, dict) or not isinstance(claim.get("tier"), str):
+ return None
+ return claim["tier"].strip().lower()
+ except (OSError, ValueError, UnicodeError, AttributeError):
+ return None
+
+
+def claims_paid(cred: Path) -> bool:
+ """The UNVERIFIED tier claim of the entitlement next to ``cred`` is a paid
+ tier. Standard library only (no signature check, no client import). False
+ means the device cannot be Pro: the verified tier is this same claim. True
+ means nothing until the gate has verified the token."""
+ return claim_label(cred) in PAID_TIERS
+
+
+def _pro_client(db: Path, cred: Path, creds: dict[str, Any], tenant: str):
+ """The gated client a Pro hook writes through, bounded for a hook: its
+ entitlement gate never refreshes (no network, no thread) and its usage
+ heartbeat is off (its exit flush would wait on the network)."""
+ from sibyl_memory_client import MemoryClient
+ from sibyl_memory_client._entitlement import EntitlementGate
+ from sibyl_memory_client._heartbeat import _NullHeartbeat
+ db.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ client = MemoryClient.local(str(db), tenant_id=tenant, account_id=creds.get("account_id"),
+ session_token=creds.get("session_token"),
+ tier=creds.get("tier", "free"), credentials_path=cred,
+ entitlement_gate=EntitlementGate(cred, allow_refresh=False))
+ client._heartbeat = _NullHeartbeat()
+ return client
+
+
+def _local_write_ok(client: Any, delta: int = 0) -> bool:
+ gate = getattr(client, "_cap_gate", None)
+ try:
+ return bool(gate is not None and gate.decides_locally(delta))
+ except Exception:
+ return False
+
+
+def _payload(stdin_text: str) -> dict[str, Any] | None:
+ try:
+ payload = json.loads(stdin_text) if stdin_text.strip() else None
+ except ValueError:
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+def run_hook(event: str, stdin_text: str, *, home: Path | None = None, now: float | None = None,
+ started: float | None = None) -> str:
+ """The hook's stdout ('' for nothing). Never raises. ``started`` is the
+ ``time.monotonic()`` of the process start (the write budget counts from
+ it; default: now)."""
+ t0 = time.monotonic() if started is None else started
+ home, cred, db = _paths(home)
+ paid_claim = True
+ try:
+ paid_claim = claims_paid(cred)
+ if event == "stop":
+ payload = _payload(stdin_text)
+ if payload is not None:
+ if payload.get("stop_hook_active") is True:
+ return "" # the re-entry after our own continuation: never loop
+ if not paid_claim:
+ return "" # free: Stop does nothing (no import, no verify, no DB)
+ except Exception:
+ paid_claim = True # unsure: take the verified path
+ try:
+ return _run(event, stdin_text, home, cred, db, time.time() if now is None else now,
+ t0, paid_claim)
+ except Exception as e:
+ try:
+ from sibyl_memory_client.lifecycle import state as ST
+ ST.log(f"hook {event}: error {type(e).__name__}", home)
+ except Exception:
+ pass
+ return ""
+
+
+def main_hook(event: str) -> int:
+ """`sibyl hook ` as a process: bounded stdin, one write to stdout,
+ exit 0 always."""
+ t0 = time.monotonic()
+ try:
+ raw = sys.stdin.buffer.read(MAX_STDIN_BYTES + 1) if not sys.stdin.isatty() else b""
+ text = raw[:MAX_STDIN_BYTES].decode("utf-8", "replace")
+ except Exception:
+ text = ""
+ out = run_hook(event, text, started=t0)
+ if out:
+ try:
+ sys.stdout.write(out + "\n")
+ sys.stdout.flush()
+ except Exception:
+ pass
+ return 0
+
+
+def _run(event: str, stdin_text: str, home: Path, cred: Path, db: Path, now: float,
+ t0: float, paid_claim: bool) -> str:
+ from sibyl_memory_client.lifecycle import capsule as C
+ from sibyl_memory_client.lifecycle import reminders as R
+ from sibyl_memory_client.lifecycle import state as ST
+
+ if event not in EVENTS:
+ ST.log(f"hook {event}: unknown event", home)
+ return ""
+ payload = _payload(stdin_text)
+ if payload is None:
+ ST.log(f"hook {event}: malformed input", home)
+ return ""
+ creds = _read_creds(cred)
+ tenant = (creds.get("tenant_id") or creds.get("account_id") or "")
+ if not isinstance(tenant, str) or not tenant:
+ ST.log(f"hook {event}: no account", home)
+ return ""
+ if event == "stop" and payload.get("stop_hook_active") is True:
+ return "" # the re-entry after our own continuation: never loop
+ if paid_claim:
+ from sibyl_memory_client.lifecycle.entitled import automation_allowed_for_credentials
+ pro, why = automation_allowed_for_credentials(cred)
+ if why == "tier_unknown":
+ # The signed label is not one this version knows: treated as Free.
+ # Logged so a support ticket can be diagnosed without the token.
+ ST.log(f"hook {event}: tier_unknown (access label not recognised, treated as free)", home)
+ else:
+ pro, why = False, "free"
+ label = claim_label(cred)
+ if label and label != "free":
+ # Not free and not a paid label this version knows (claims_paid
+ # said no): treated as Free; the reason goes to lifecycle.log.
+ why = "tier_unknown"
+ ST.log(f"hook {event}: tier_unknown (access label not recognised, treated as free)", home)
+ sk = ST.session_key(payload.get("session_id"))
+ cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) else os.getcwd()
+ store = ST.LifecycleState(home)
+ # The save marker lives in memory.db. A free PreCompact / SessionEnd does
+ # not need it (the next start or prompt folds it in), so it opens nothing.
+ need_marker = pro or event in ("session-start", "prompt")
+ marker = ST.read_save_marker(db, tenant) if need_marker else None
+
+ def _budget_left() -> bool:
+ return time.monotonic() - t0 < WRITE_BUDGET_SECONDS
+
+ def _session(st: dict[str, Any]) -> dict[str, Any]:
+ s = ST.ensure_session(st, sk, tenant_id=tenant, harness="claude-code", now=now)
+ if marker is not None and s.get("started_at") is not None and marker >= s["started_at"]:
+ s["saved"] = True
+ return s
+
+ if event == "session-start":
+ tier_class = "paid" if pro else ("free" if why == "free" else None)
+
+ def _start(st: dict[str, Any]) -> list[str]:
+ ST.observe_marker(st, tenant, marker)
+ s = _session(st)
+ ST.add_active(s, now, kind="start")
+ out = []
+ line = R.tier_change_line(st, tenant, tier_class)
+ if line:
+ out.append(line)
+ line = R.unsaved_session_line(st, tenant, now, exclude_session=sk)
+ if line:
+ out.append(line)
+ return out
+ lines = store.update(_start)
+ if pro:
+ try:
+ from sibyl_memory_client.lifecycle.runner import run_automatic
+ client = _pro_client(db, cred, creds, tenant)
+ local = _local_write_ok(client, 64 * 1024)
+ rep = run_automatic(client, home=home, cwd=Path(cwd), harness="claude-code", now=now,
+ allow_apply=local, deadline=t0 + WRITE_BUDGET_SECONDS)
+ if rep.line and R.reports_enabled(store.load()):
+ lines.append(rep.line)
+ ST.log(f"hook session-start: pro run {rep.reason}"
+ f"{'' if local else ' (plan only: no fresh tier cache)'}", home)
+ except Exception as e:
+ ST.log(f"hook session-start: pro run failed {type(e).__name__}", home)
+ pending = ST.read_pending_count(db, tenant)
+ pl = R.pending_line(pending)
+ if pl and R.enabled(store.load()):
+ lines.append(pl)
+ # R1 (plan 3.2): relevant skill proposals, named, read-only.
+ from sibyl_memory_client.lifecycle import proposals as PR
+ st0 = store.load()
+ s0 = st0.get("sessions", {}).get(sk) or {}
+ anchor = PR.last_session_start(st0, tenant, exclude=sk, before=s0.get("started_at") or now)
+ names, total = PR.read_relevant(db, tenant, now, anchor=anchor,
+ muted=PR.muted_kinds(st0, now))
+ if total:
+ sl = store.update(lambda st: PR.skill_prompt(st, tenant, sk, now, names, total))
+ if sl:
+ lines.append(sl)
+ else:
+ from sibyl_memory_client.lifecycle.runner import measure_for_reminder
+ rec = measure_for_reminder(home, Path(cwd))
+ if rec is not None:
+ line = store.update(lambda st: R.debloat_reminder(st, tenant, now, rec, pro=False))
+ if line:
+ lines.append(line)
+ ST.log(f"hook session-start: {len(lines)} line(s), {'pro' if pro else why}", home)
+ return _context("SessionStart", lines)
+
+ if event == "prompt":
+ def _prompt(st: dict[str, Any]) -> str | None:
+ ST.observe_marker(st, tenant, marker)
+ s = _session(st)
+ ST.add_active(s, now, kind="prompt")
+ s["prompts"] = int(s.get("prompts") or 0) + 1
+ if pro:
+ return None # Pro: the prompt only counts active time
+ return R.save_reminder(st, tenant, now, pro=False, sk=sk)
+ line = store.update(_prompt)
+ return _context("UserPromptSubmit", [line] if line else [])
+
+ if event == "pre-compact":
+ def _pre(st: dict[str, Any]) -> dict[str, Any]:
+ ST.observe_marker(st, tenant, marker)
+ s = _session(st)
+ in_turn = s.get("last_event_kind") in ("prompt", "compact")
+ ST.add_active(s, now, kind="compact",
+ cap=ST.TURN_CAP_SECONDS if in_turn else ST.IDLE_CAP_SECONDS)
+ s["compactions"] = int(s.get("compactions") or 0) + 1
+ # This session's compaction (another session's never makes this
+ # one due); cleared by the next save.
+ s["compaction_seen"] = True
+ t = ST.tenant(st, tenant)
+ return dict(s, writes=max(0, int(t.get("writes_total") or 0) - int(s.get("writes_at_start") or 0)))
+ s = store.update(_pre)
+ if pro:
+ cap = C.build_capsule(harness="claude-code", session_id=payload.get("session_id"),
+ started_at=s.get("started_at"), ended_at=None, turns=None,
+ memory_writes=s.get("writes", 0), saved_by_skill=bool(s.get("saved")),
+ cwd=cwd)
+ ev, why_not = _write_capsule(C, db, cred, creds, tenant, cap, _budget_left)
+ if ev:
+ store.update(lambda st: _session(st).update(capsule_written=True, capsule_at=now))
+ ST.log(f"hook pre-compact: capsule {'written' if ev else 'not written' + why_not}", home)
+ return ""
+
+ if event == "stop":
+ if not pro:
+ return ""
+ # R2 (spec plugin-paid-tier-r2 1.2): skill signals from the Claude Code
+ # workflow. The transcript is read from this session's stored offset,
+ # at most 4 MiB per Stop; only each tool_use block's name and the
+ # hashed sorted key names of its input are kept (signals.json), the
+ # parsed text is dropped. Local only; never the learner here.
+ try:
+ from sibyl_memory_client.lifecycle import signals as SG
+ srep = SG.record_transcript(home, sk, payload.get("transcript_path"), tenant_id=tenant, now=now)
+ if srep.get("events"):
+ ST.log(f"hook stop: signals {srep['events']} tool events", home)
+ except Exception as e:
+ ST.log(f"hook stop: signals skipped {type(e).__name__}", home)
+ scripted = not (isinstance(payload.get("transcript_path"), str) and payload["transcript_path"])
+
+ def _stop(st: dict[str, Any]) -> tuple[int, str] | None:
+ # Decides only; the request is recorded (caps, interval) once it is
+ # actually emitted, after the transcript guard below.
+ ST.observe_marker(st, tenant, marker)
+ s = _session(st)
+ # The model worked from the prompt to this turn end: that gap is
+ # active (bounded); a gap after a turn end is the person's pause.
+ in_turn = s.get("last_event_kind") in ("prompt", "compact")
+ ST.add_active(s, now, kind="stop",
+ cap=ST.TURN_CAP_SECONDS if in_turn else ST.IDLE_CAP_SECONDS)
+ if scripted or int(s.get("prompts") or 0) < MIN_PROMPTS_FOR_STOP:
+ return None # a `claude -p` run: never continued
+ why_due = R.autosave_due(st, tenant, sk, now)
+ if why_due is None:
+ return None
+ return ST.next_nudge_seq(s), why_due
+ got = store.update(_stop)
+ if not got:
+ ST.log("hook stop: pass", home)
+ return ""
+ seq, why_due = got
+ reason = stop_reason(seq)
+ if _transcript_has(payload.get("transcript_path"), reason):
+ # This numbered request is already in the transcript (the state
+ # lost it): not asked again and not counted; the next one is
+ # numbered past it.
+ store.update(lambda st: ST.note_seq_seen(st, tenant, sk, seq, now=now,
+ harness="claude-code"))
+ ST.log(f"hook stop: pass (request {seq} already in the transcript)", home)
+ return ""
+
+ def _record(st: dict[str, Any]) -> int | None:
+ s = _session(st)
+ if ST.next_nudge_seq(s) != seq or R.autosave_due(st, tenant, sk, now) is None:
+ return None # another hook recorded a request, or a save landed, meanwhile
+ return ST.record_nudge(st, tenant, sk, now, harness="claude-code")
+ if store.update(_record) != seq:
+ ST.log("hook stop: pass (recorded elsewhere)", home)
+ return ""
+ ST.log(f"hook stop: continue {seq} ({why_due})", home)
+ return json.dumps({"decision": "block", "reason": reason})
+
+ # session-end
+ def _end(st: dict[str, Any]) -> dict[str, Any]:
+ ST.observe_marker(st, tenant, marker)
+ s = _session(st)
+ t = ST.tenant(st, tenant)
+ s["ended_at"] = now
+ s["writes"] = max(0, int(t.get("writes_total") or 0) - int(s.get("writes_at_start") or 0))
+ last_save = t.get("last_save_at")
+ need = (not s.get("capsule_at")) or (last_save is not None and s["capsule_at"] <= last_save)
+ return dict(s, need_capsule=need)
+ s = store.update(_end)
+ if pro and s.get("need_capsule"):
+ cap = C.build_capsule(harness="claude-code", session_id=payload.get("session_id"),
+ started_at=s.get("started_at"), ended_at=now, turns=None,
+ memory_writes=s.get("writes", 0), saved_by_skill=bool(s.get("saved")),
+ cwd=cwd)
+ ev, why_not = _write_capsule(C, db, cred, creds, tenant, cap, _budget_left)
+ if ev:
+ store.update(lambda st: _session(st).update(capsule_written=True, capsule_at=now))
+ ST.log(f"hook session-end: capsule {'written' if ev else 'not written' + why_not}", home)
+ else:
+ ST.log("hook session-end: recorded", home)
+ return ""
+
+
+def _write_capsule(C: Any, db: Path, cred: Path, creds: dict[str, Any], tenant: str,
+ cap: dict[str, Any], budget_left: Any) -> tuple[Any, str]:
+ """(event id or None, why not). Writes only when the cap gate decides
+ locally and the hook is inside its write budget."""
+ if not budget_left():
+ return None, " (out of time)"
+ client = _pro_client(db, cred, creds, tenant)
+ if not _local_write_ok(client, 4096):
+ return None, " (no fresh tier cache; a later hook or the MCP server writes it)"
+ return C.write_capsule(client, cap), ""
+
+
+__all__ = ["EVENTS", "MIN_PROMPTS_FOR_STOP", "PAID_TIERS", "STOP_REASON", "STOP_REASON_BASE",
+ "WRITE_BUDGET_SECONDS", "claim_label", "claims_paid", "main_hook", "run_hook", "stop_reason"]
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/lifecycle_cli.py b/sibyl-memory-cli/src/sibyl_memory_cli/lifecycle_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..aedb30ec566cab44d8f514932d5770c76ac29b6c
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/lifecycle_cli.py
@@ -0,0 +1,1233 @@
+"""`sibyl save`, `sibyl debloat`, `sibyl skills`, `sibyl reminders`, `sibyl hook`
+and the `lifecycle` rows of `sibyl status` (spec plugin-save-debloat 4.3, 6.3,
+7.1). The procedures themselves live in sibyl-memory-client (``skills``,
+``lifecycle``); this module is the terminal surface.
+
+Naming (spec 0.1): the plugin's step is "the debloat step" / "context trim";
+"automatic debloat on Pro". Nothing here prints a token or file content (a
+plan shows section headings and token counts only).
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import shlex
+import sys
+import time
+from pathlib import Path
+from typing import Any
+
+from . import _aesthetic as a
+from . import _handoff as _h
+
+
+# ----------------------------------------------------------------------
+# helpers
+# ----------------------------------------------------------------------
+
+def _home() -> Path:
+ return Path.home()
+
+
+def _cred(args: argparse.Namespace) -> Path:
+ from .cli import DEFAULT_CRED_PATH
+ return Path(getattr(args, "credentials", None) or DEFAULT_CRED_PATH).expanduser()
+
+
+def _db(args: argparse.Namespace) -> Path:
+ from .cli import DEFAULT_DB_PATH
+ return Path(getattr(args, "db", None) or DEFAULT_DB_PATH).expanduser()
+
+
+def _creds(args: argparse.Namespace) -> dict[str, Any]:
+ from .cli import read_credentials
+ return read_credentials(_cred(args)) or {}
+
+
+def _tenant(creds: dict[str, Any]) -> str | None:
+ return (creds.get("tenant_id") or creds.get("account_id") or None)
+
+
+def _client(args: argparse.Namespace):
+ """The gated client an agent would use (the account gate applies)."""
+ from sibyl_memory_client import DEFAULT_TENANT, MemoryClient
+ creds = _creds(args)
+ db = _db(args)
+ db.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ client = MemoryClient.local(str(db), tenant_id=_tenant(creds) or DEFAULT_TENANT,
+ account_id=creds.get("account_id"),
+ session_token=creds.get("session_token"),
+ tier=creds.get("tier", "free"), credentials_path=_cred(args))
+ client.enable_lifecycle_counting(_home()) # `sibyl save --fact` counts like an agent write
+ return client
+
+
+def _pro(args: argparse.Namespace) -> tuple[bool, str]:
+ from sibyl_memory_client.lifecycle.entitled import automation_allowed_for_credentials
+ return automation_allowed_for_credentials(_cred(args))
+
+
+# The question `_ask` could not put because there is no terminal (row G1):
+# the caller's handoff relays it and names the same command with --yes.
+_NI_QUESTION: str | None = None
+
+
+def _ask(question: str, *, yes: bool) -> bool:
+ global _NI_QUESTION
+ _NI_QUESTION = None
+ if yes:
+ return True
+ if not sys.stdin.isatty():
+ print(a.dim(" Not a terminal: re-run with --yes to confirm."))
+ _NI_QUESTION = question
+ return False
+ try:
+ return input(f"{question} [y/N]: ").strip().lower() in ("y", "yes")
+ except EOFError:
+ _NI_QUESTION = question
+ return False
+
+
+def _declined(command: str) -> None:
+ """Handoff after `_ask` said no: the same command with --yes and the
+ question relayed when there was no terminal (G1), else done (G2)."""
+ if _NI_QUESTION:
+ _h.handoff(f"{command} --yes", human=_NI_QUESTION)
+ else:
+ _h.handoff("done")
+
+
+def _entitlement_handoff(e: BaseException, *, later: tuple = ()) -> None:
+ nxt, human = _h.from_exception(e, default="sibyl init")
+ _h.handoff(nxt, human=human, later=later)
+
+
+def _fmt_ts(ts: Any) -> str:
+ if not isinstance(ts, (int, float)) or isinstance(ts, bool):
+ return "never"
+ from ._timefmt import utc_minute
+ return utc_minute(ts) or "never"
+
+
+def _slug(text: str) -> str:
+ s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:60].strip("-")
+ return s or ("fact-" + hashlib.sha256(text.encode("utf-8")).hexdigest()[:8])
+
+
+# ----------------------------------------------------------------------
+# sibyl save
+# ----------------------------------------------------------------------
+
+THREE_WAYS = (
+ "Saving a session is a distillation, so your agent does it with the save procedure:",
+ " Claude Code /sibyl-save (installed by sibyl setup)",
+ " any MCP host the `save` prompt on the sibyl-memory server (/mcp__sibyl-memory__save)",
+ " Codex, Hermes ask the agent to follow ~/.sibyl-memory/skills/SAVE.md",
+ "From a terminal: sibyl save --fact \"\" writes one fact; sibyl save --status shows the last save.",
+ "On Pro, your agent is asked to save by itself: once early (after 5 memory writes or a compaction), "
+ "then about every hour of active work (sibyl autosave sets the interval or turns it off).",
+)
+
+
+def cmd_save(args: argparse.Namespace) -> int:
+ from sibyl_memory_client.lifecycle import state as ST
+ print()
+ if getattr(args, "status", False):
+ creds = _creds(args)
+ tid = _tenant(creds)
+ st = ST.LifecycleState(_home()).load()
+ t = st.get("tenants", {}).get(tid or "", {}) if tid else {}
+ marker = ST.read_save_marker(_db(args), tid) if tid else None
+ last = max([x for x in (marker, t.get("last_save_at")) if isinstance(x, (int, float))], default=None)
+ print(a.eyebrow("save"))
+ print(a.kv("last save", _fmt_ts(last)))
+ print(a.kv("writes since", str(int(t.get("writes_since_save") or 0))))
+ pend = ST.read_pending_count(_db(args), tid) if tid else 0
+ print(a.kv("to decide", f"{pend} item(s) queued by a headless save" if pend else "nothing queued"))
+ _h.handoff("done")
+ return 0
+ fact = getattr(args, "fact", None)
+ if fact is not None:
+ text = fact.strip()
+ if not text:
+ print(a.warn_line("Nothing to save: the fact is empty."))
+ _h.handoff('sibyl save --fact ""', human="the fact to save")
+ return 1
+ slug = _slug(text)
+ if getattr(args, "preview", False):
+ print(a.dim(f"would write fact/{slug} (nothing written)"))
+ _h.handoff("done")
+ return 0
+ from sibyl_memory_client import EntitlementError
+ from sibyl_memory_client.exceptions import CapExceededError
+ try:
+ c = _client(args)
+ c.set_entity("fact", slug, {"value": text,
+ "saved_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())})
+ except CapExceededError as e:
+ # Finding 5.3.2 (handoff spec 2026-10-03): the free cap used to
+ # escape as a traceback. Its first line, then the handoff.
+ print(a.warn_line(str(e).splitlines()[0] if str(e) else "The free 5 MB memory cap is full."))
+ print(a.dim(" Nothing was written."))
+ _h.handoff("done", later=("sibyl upgrade",))
+ return 1
+ except EntitlementError as e:
+ print(a.warn_line(str(e).splitlines()[0]))
+ print(a.dim(" Sign in first: sibyl init. Nothing was written."))
+ _entitlement_handoff(e, later=(f"sibyl save --fact {shlex.quote(text)}",))
+ return 1
+ print(a.success_line(f"Saved fact/{slug}."))
+ print(a.dim(f" recall it with: sibyl memory recall fact {slug}"))
+ _h.handoff("done")
+ return 0
+ if getattr(args, "capsule", False):
+ ok, _why = _pro(args)
+ if not ok:
+ print(a.dim("Automatic save is on Pro. Nothing was written."))
+ print(a.dim(" On the free plan run the save procedure yourself (sibyl save shows how)."))
+ _h.handoff("sibyl save", later=("sibyl upgrade",))
+ return 0
+ if getattr(args, "preview", False):
+ print(a.dim("would write one session capsule (counts only) (nothing written)"))
+ _h.handoff("done")
+ return 0
+ from sibyl_memory_client.lifecycle import capsule as C
+ cap = C.build_capsule(harness="cli", session_id=f"cli-{time.time()}", started_at=None,
+ ended_at=time.time(), turns=None, memory_writes=0,
+ saved_by_skill=False, cwd=Path.cwd())
+ ev = C.write_capsule(_client(args), cap)
+ print(a.success_line("Session capsule written.") if ev else a.warn_line("Capsule not written."))
+ _h.handoff("done" if ev else "sibyl status")
+ return 0 if ev else 1
+ for ln in THREE_WAYS:
+ print(ln if not ln.startswith(" ") else a.dim(ln))
+ if getattr(args, "preview", False):
+ print(a.dim("(preview: nothing was written)"))
+ _h.handoff("done")
+ return 0
+
+
+# ----------------------------------------------------------------------
+# sibyl debloat
+# ----------------------------------------------------------------------
+
+def _root(args: argparse.Namespace) -> Path:
+ """The project root, as its real path (``--root`` given through a symlink
+ names the same files, the same authorisations and the same backups as
+ the real folder)."""
+ return Path(os.path.realpath(str(Path(getattr(args, "root", None) or Path.cwd()).expanduser())))
+
+
+def _measure(args: argparse.Namespace) -> dict[str, Any]:
+ from sibyl_memory_client.lifecycle import measure as M
+ from sibyl_memory_client.lifecycle import policy as P
+ pol = P.load(_home())
+ root = _root(args)
+ return M.measure(root, home=_home(), config_path=getattr(args, "config", None),
+ includes=getattr(args, "include", None) or [], surface=pol.get("surface"),
+ thresholds=pol.get("thresholds"), per_file_soft=pol.get("perFileSoft"),
+ write_journal=True)
+
+
+def _candidates(args: argparse.Namespace):
+ from sibyl_memory_client.lifecycle import apply as A
+ from sibyl_memory_client.lifecycle import policy as P
+ pol = P.load(_home())
+ root = _root(args)
+ cands, rec = A.candidates(_home(), root, pol)
+ return cands, rec, pol, root
+
+
+def _plans(args: argparse.Namespace) -> list[dict[str, Any]]:
+ from sibyl_memory_client.lifecycle import apply as A
+ cands, _rec, pol, _root = _candidates(args)
+ out = []
+ for c in cands:
+ if not c.trimmable:
+ out.append({"file": c.label, "trimmable": False, "reason": c.why_not})
+ continue
+ pl, reason = A.plan(c, pol)
+ d = {"file": c.label, "trimmable": True, "reason": reason}
+ if pl is not None:
+ d.update({"safe": pl.safe, "sections": pl.sections, "tok_before": pl.tok_before,
+ "tok_history": pl.tok_history, "tok_after": pl.tok_after})
+ out.append(d)
+ return out
+
+
+def _legacy_notice() -> None:
+ """Once: an earlier build stored automatic trims by file NAME; those
+ entries are dropped (never guessed at) and the person is told."""
+ try:
+ from sibyl_memory_client.lifecycle import policy as P
+ line = P.take_legacy_notice(_home())
+ except Exception:
+ line = None
+ if line:
+ print(a.warn_line(line))
+
+
+def cmd_debloat(args: argparse.Namespace) -> int:
+ action = getattr(args, "action", None)
+ if action is not None or not (getattr(args, "json", False) or getattr(args, "fyi", False)):
+ _legacy_notice()
+ try:
+ if action is None:
+ return _debloat_measure(args)
+ if action == "plan":
+ return _debloat_plan(args)
+ if action == "apply":
+ return _debloat_apply(args)
+ if action in ("auto", "manual"):
+ return _debloat_auto(args, action == "auto")
+ if action == "undo":
+ return _debloat_undo(args)
+ except KeyboardInterrupt:
+ raise
+ except Exception as e: # the measurement always exits 0; actions report
+ print(a.warn_line(f"debloat: {type(e).__name__}: {e}"))
+ if not (action is None and getattr(args, "fyi", False)) and not getattr(args, "json", False):
+ _h.handoff("done" if action is None else "sibyl debloat plan")
+ return 0 if action is None else 1
+ return 0
+
+
+def _debloat_measure(args: argparse.Namespace) -> int:
+ from sibyl_memory_client.lifecycle import measure as M
+ from sibyl_memory_client.lifecycle import policy as P
+ rec = _measure(args)
+ if rec.get("config_error"):
+ print(rec["config_error"] + " (defaults used)", file=sys.stderr)
+ heavy_next = "sibyl debloat plan" if any(f.get("heavy") for f in rec.get("files") or []) else "done"
+ if getattr(args, "json", False):
+ out = M.public_record(rec)
+ if P.policy_path(_home()).exists():
+ out["plan"] = _plans(args)
+ print(json.dumps(_h.json_handoff(out, heavy_next, None), indent=2))
+ return 0
+ if getattr(args, "fyi", False):
+ # The one-line FYI is a startup-line format (like --json, one shape):
+ # no handoff block.
+ if not rec["files"]:
+ print("context: no always-load files found")
+ else:
+ print(M.fyi(rec))
+ return 0
+ print(M.report(rec))
+ _h.handoff(heavy_next)
+ return 0
+
+
+def _debloat_plan(args: argparse.Namespace) -> int:
+ plans = _plans(args)
+ print()
+ if not plans:
+ print(a.dim("No instruction files found for this project or your home."))
+ _h.handoff("done")
+ return 0
+ print(a.eyebrow("context trim plan (nothing is changed)"))
+ for p in plans:
+ if not p.get("trimmable"):
+ print(a.kv(p["file"], f"not trimmed: {p['reason']}"))
+ elif p.get("safe"):
+ secs = ", ".join(p["sections"][:5]) + (" ..." if len(p["sections"]) > 5 else "")
+ print(a.kv(p["file"], f"{p['tok_before']} -> {p['tok_after']} tok; would move "
+ f"{len(p['sections'])} section(s): {secs}"))
+ else:
+ print(a.kv(p["file"], p.get("reason") or "nothing to move"))
+ print()
+ print(a.dim("Apply one with: sibyl debloat apply (asks first; a verified backup is made)"))
+ if any(p.get("trimmable") and p.get("safe") for p in plans):
+ _h.handoff("sibyl debloat apply ",
+ human="which file to trim (it asks before writing; a verified backup is made)")
+ else:
+ _h.handoff("done")
+ return 0
+
+
+def _debloat_apply(args: argparse.Namespace) -> int:
+ from sibyl_memory_client.lifecycle import apply as A
+ from sibyl_memory_client.lifecycle import policy as P
+ from sibyl_memory_client.lifecycle import state as ST
+ cands, _rec, pol, root = _candidates(args)
+ want = getattr(args, "file", None)
+ surface = {c.label for c in cands}
+ chosen = [c for c in cands if c.trimmable and (want is None or want in (c.label, c.key))]
+ print()
+ if want is not None and not chosen:
+ print(a.warn_line(f"{want} is not a trimmable instruction file here."))
+ for c in cands:
+ if want in (c.label, c.key):
+ print(a.dim(f" {c.why_not}"))
+ _h.handoff("sibyl debloat plan")
+ return 1
+ pro, _tier = _pro(args)
+ destination = pol["destination"] if pro else "sibling"
+ client = _client(args) if pro else None # free: no client is constructed for the write
+ results = []
+ ids: dict[str, str] = {}
+ ni_question = None
+ declined = False
+ for c in chosen:
+ pl, reason = A.plan(c, pol)
+ if pl is None or not pl.safe:
+ print(a.kv(c.label, reason or "nothing to move"))
+ continue
+ where = ("Sibyl Memory (a reference document) plus a sibling file" if destination == "memory+sibling"
+ else "Sibyl Memory (a reference document)" if destination == "memory"
+ else f"{A.sibling_path(c.path).name} beside it")
+ q = (f"Move {len(pl.sections)} history section(s) of {c.label} ({pl.tok_history} tok) to "
+ f"{where}? A verified backup is made first")
+ if not _ask(q, yes=bool(getattr(args, "yes", False))):
+ print(a.dim(f" {c.label}: left as is."))
+ ni_question = ni_question or _NI_QUESTION
+ declined = True
+ continue
+ res = A.apply_one(c, home=_home(), cwd=root, destination=destination, client=client,
+ policy=pol, surface_labels=surface)
+ results.append(res)
+ ids[c.label] = P.auth_id(c.path, _home())
+ if res.applied:
+ dest = res.key or res.sibling
+ print(a.success_line(f"{c.label}: {res.tok_before} -> {res.tok_after} tok; history in {dest}."))
+ print(a.dim(f" backup: {res.backup} undo: sibyl debloat undo {shlex.quote(c.label)}"))
+ else:
+ print(a.warn_line(f"{c.label}: {res.reason}"))
+ if results:
+ def _upd(st: dict[str, Any]) -> None:
+ st.setdefault("debloat", {})["last_apply"] = {
+ "ts": time.time(), "results": [{"file": r.file, "id": ids.get(r.file),
+ "applied": r.applied,
+ "reason": r.reason, "key": r.key,
+ "backup": r.backup if r.applied else None}
+ for r in results]}
+ ST.LifecycleState(_home()).update(_upd)
+ if pol.get("journal"):
+ rec = _measure(args)
+ A.journal(_home(), {"ts": time.time(), "total_tok": rec["total_tok"], "weight": rec["weight"],
+ "targets": len(rec["targets"]),
+ "applied": len([r for r in results if r.applied])})
+ elif not chosen:
+ print(a.dim("Nothing to trim."))
+ applied = [r.file for r in results if r.applied]
+ if results and not all(r.applied for r in results):
+ _h.handoff("sibyl debloat plan", later=[f"sibyl debloat undo {shlex.quote(str(f))}" for f in applied])
+ elif ni_question and not applied:
+ _h.handoff("sibyl debloat apply" + (f" {shlex.quote(str(want))}" if want else "") + " --yes",
+ human=ni_question)
+ else:
+ _h.handoff("done", later=[f"sibyl debloat undo {shlex.quote(str(f))}" for f in applied])
+ return 0 if all(r.applied for r in results) else (1 if results else 0)
+
+
+def _debloat_auto(args: argparse.Namespace, on: bool) -> int:
+ from sibyl_memory_client.lifecycle import policy as P
+ want = getattr(args, "file", None)
+ print()
+ if not want:
+ print(a.warn_line(f"Usage: sibyl debloat {'auto' if on else 'manual'} "))
+ _h.handoff("sibyl debloat plan")
+ return 1
+ cands, _rec, pol, root = _candidates(args)
+ match = [c for c in cands if want in (c.label, c.key)]
+ if on:
+ if not match or not match[0].trimmable:
+ print(a.warn_line(f"{want} is not a trimmable instruction file here."))
+ _h.handoff("sibyl debloat plan")
+ return 1
+ c = match[0]
+ fid = P.auth_id(c.path, _home())
+ print(f"Automatic context trim for this file at {fid} means:")
+ print(a.dim(" at every agent start, Sibyl measures it and, when the deterministic splitter finds"))
+ print(a.dim(" accreted history (a sibyl:history region, a History/Changelog heading, dated sections"))
+ print(a.dim(f" older than {pol['history_after_days']} days with no open item), it moves that history"))
+ print(a.dim(" into Sibyl Memory (searchable), keeps a byte-verified backup, rewrites the file last"))
+ print(a.dim(" with a one-line pointer, and tells you in one line. Nothing is ever deleted."))
+ print(a.dim(" Only this file at this path: a file with the same name in another project, or in"))
+ print(a.dim(" your home, is not affected."))
+ print(a.dim(f" Take it back any time: sibyl debloat manual {shlex.quote(c.label)}. Undo a trim: sibyl debloat undo {shlex.quote(c.label)}."))
+ pro, _t = _pro(args)
+ if not pro:
+ print(a.dim(" Automatic trims run on Pro; this choice is kept for when they do."))
+ if not _ask(f"Let Sibyl trim this file at {fid} automatically?",
+ yes=bool(getattr(args, "yes", False))):
+ print(a.dim("Nothing changed."))
+ _declined(f"sibyl debloat auto {shlex.quote(str(want))}")
+ return 1
+ pol = P.set_auto(fid, True, _home())
+ print(a.success_line(f"{fid} is on automatic (mode {pol['mode']})."))
+ _h.handoff("done")
+ return 0
+ if match:
+ fid = P.auth_id(match[0].path, _home())
+ elif P.is_path_id(want):
+ fid = P.auth_id(P.id_path(want, _home()), _home())
+ else:
+ fid = P.auth_id(Path(root) / want, _home())
+ if fid not in P.load(_home())["auto_files"]:
+ print(a.dim(f"{fid} was not on automatic; nothing changed."))
+ _h.handoff("done")
+ return 0
+ pol = P.set_auto(fid, False, _home())
+ print(a.success_line(f"{fid} is back to manual (mode {pol['mode']})."))
+ _h.handoff("done")
+ return 0
+
+
+def _debloat_undo(args: argparse.Namespace) -> int:
+ from sibyl_memory_client.lifecycle import apply as A
+ from sibyl_memory_client.lifecycle import policy as P
+ from sibyl_memory_client.lifecycle import state as ST
+ want = getattr(args, "file", None)
+ cands, _rec, _pol, root = _candidates(args)
+ last = ST.LifecycleState(_home()).load().get("debloat", {}).get("last_apply") or {}
+ done = [r for r in last.get("results", []) if isinstance(r, dict) and r.get("applied")]
+ # The last apply is matched on the FILE it trimmed (its auth_id), never on
+ # the bare label: `AGENTS.md` trimmed in one project is not this project's.
+ if want is None:
+ if not done:
+ print(a.dim("No trim to undo."))
+ _h.handoff("done")
+ return 0
+ rid = done[0].get("id")
+ if not isinstance(rid, str) or not P.is_path_id(rid):
+ print(a.dim(f"The last trim ({done[0].get('file')}) was recorded without its path; "
+ "name the file: sibyl debloat undo "))
+ _h.handoff("sibyl debloat undo ", human="which file to restore (the last trim "
+ "was recorded without its path)")
+ return 1
+ match = [c for c in cands if P.auth_id(c.path, _home()) == rid]
+ if not match:
+ print(a.warn_line(f"The last trim was {rid}, which is not a file of this project or your "
+ "home here; run `sibyl debloat undo ` where it lives."))
+ _h.handoff("done", human=f"the last trim was {rid}; run sibyl debloat undo in that "
+ "project's folder")
+ return 1
+ want = match[0].label
+ else:
+ match = [c for c in cands if want in (c.label, c.key)]
+ path = match[0].path if match else ((_home() / want[2:]) if str(want).startswith("~/") else root / want)
+ fid = P.auth_id(path, _home())
+ # The backup the last apply of THIS file recorded (not merely the newest
+ # one, which an interrupted later attempt could have made identical to
+ # the file as it is now).
+ prefer = next((r.get("backup") for r in done if r.get("id") == fid and r.get("backup")), None)
+ print()
+ which = "the backup its last trim made" if prefer else "its most recent backup"
+ if not _ask(f"Restore {want} from {which}? (the current file is backed up first)",
+ yes=bool(getattr(args, "yes", False))):
+ print(a.dim("Nothing changed."))
+ _declined(f"sibyl debloat undo {shlex.quote(str(want))}")
+ return 1
+ ok, msg, _src = A.undo(path, home=_home(), cwd=root, prefer=prefer)
+ print(a.success_line(f"{want}: {msg}") if ok else a.warn_line(f"{want}: {msg}"))
+ if ok:
+ rec = _measure(args)
+ print(a.dim(f" context now ~{rec['total_tok']} tok ({rec['weight']})"))
+ _h.handoff("done" if ok else "sibyl debloat plan")
+ return 0 if ok else 1
+
+
+# ----------------------------------------------------------------------
+# sibyl skills
+# ----------------------------------------------------------------------
+
+def _present_wirers(args: argparse.Namespace) -> dict[str, Any]:
+ from .setup import ClaudeCodeWirer, CodexWirer, HermesWirer
+ out: dict[str, Any] = {}
+ cc = ClaudeCodeWirer()
+ if cc.settings_path.parent.exists():
+ out["claude-code"] = cc
+ cx = CodexWirer()
+ if cx.config_path.parent.exists():
+ out["codex"] = cx
+ hw = HermesWirer()
+ if hw.hermes_home.exists():
+ out["hermes"] = hw
+ return out
+
+
+def cmd_skills(args: argparse.Namespace) -> int:
+ from sibyl_memory_client import skills as SK
+ from .setup import install_shims
+ op = getattr(args, "skills_cmd", None) or "status"
+ home = _home()
+ print()
+ if op == "proposals":
+ return _proposals(args)
+ if op == "signals":
+ return _signals(args)
+ if op == "install":
+ rep = SK.install(home, force=bool(getattr(args, "force", False)))
+ print(a.eyebrow(f"skills v{rep.version}"))
+ for n, s in rep.results.items():
+ print(a.kv(n, s))
+ for m in rep.messages:
+ print(a.dim(" " + m))
+ for name, w in _present_wirers(args).items():
+ lines = []
+ if name == "codex":
+ lines = w.wire_block() + install_shims(name, w.skill_shim_targets())
+ else:
+ lines = install_shims(name, w.skill_shim_targets())
+ for ln in lines:
+ print(a.dim(f" {name}: {ln}"))
+ _h.handoff("done" if rep.ok else "sibyl skills status")
+ return 0 if rep.ok else 1
+ if op == "reset":
+ name = getattr(args, "name", None)
+ if name not in SK.SKILL_NAMES:
+ print(a.warn_line(f"Usage: sibyl skills reset {{{'|'.join(SK.SKILL_NAMES)}}}"))
+ _h.handoff("sibyl skills status")
+ return 1
+ if not _ask(f"Replace {name} with the shipped version {SK.version()}? Your edits in it are lost "
+ "(copy them first if you want them)", yes=bool(getattr(args, "yes", False))):
+ print(a.dim("Nothing changed."))
+ _declined(f"sibyl skills reset {name}")
+ return 1
+ rep = SK.reset(home, name)
+ print(a.kv(name, rep.results.get(name, "?")))
+ _h.handoff("done" if rep.ok else "sibyl skills status")
+ return 0 if rep.ok else 1
+ if op == "uninstall":
+ if not _ask("Remove the save/debloat files, shims, hooks and the Codex block this plugin "
+ "installed? (edited files are kept)", yes=bool(getattr(args, "yes", False))):
+ print(a.dim("Nothing changed."))
+ _declined("sibyl skills uninstall")
+ return 1
+ for name, w in _present_wirers(args).items():
+ if name == "claude-code":
+ for ln in w.unwire_hooks():
+ print(a.dim(f" {name}: {ln}"))
+ if name == "codex":
+ for ln in w.unwire_block():
+ print(a.dim(f" {name}: {ln}"))
+ for k, v in SK.uninstall(home).items():
+ print(a.kv(Path(k).name if "/" in k else k, v))
+ _h.handoff("done")
+ return 0
+ # status
+ st = SK.status(home)
+ print(a.eyebrow("skills"))
+ if not st["exists"]:
+ print(a.kv("installed", "no · sibyl skills install (or sibyl setup)"))
+ print(a.kv("package", f"v{st['package_version']}"))
+ _h.handoff("sibyl skills install")
+ return 0
+ print(a.kv("version", f"v{st['installed_version'] or '?'} (package v{st['package_version']})"))
+ for n, info in st["files"].items():
+ extra = ""
+ if info.get("upstream_waiting"):
+ extra = f" · new version waiting: {', '.join(info['upstream_waiting'])} (sibyl skills reset {n})"
+ label = {"ok": "ok", "edited": "edited by you", "outdated": "outdated (sibyl skills install)",
+ "missing": "missing", "symlink": "a symlink (refused)", "oversize": "too large (refused)"}
+ print(a.kv(n, label.get(info["state"], info["state"]) + extra))
+ for p, info in st["shims"].items():
+ print(a.kv(info.get("harness") or "shim", f"{p} · {info['state']}"))
+ for name, w in _present_wirers(args).items():
+ if name == "claude-code":
+ hs = w.hooks_state()
+ print(a.kv("claude hooks", f"{hs['present']} of 5 wired" + (f" · settings.json {hs['error']}"
+ if hs["error"] else "")))
+ if name == "codex":
+ print(a.kv("codex block", "present" if w.block_state() else "absent"))
+ # Rows T2: an outdated file is reinstalled; a new version waiting behind
+ # a person's edit is their call.
+ files = st["files"]
+ waiting = [n for n, info in files.items() if info.get("upstream_waiting")]
+ if any(info["state"] in ("outdated", "missing") for info in files.values()):
+ _h.handoff("sibyl skills install")
+ elif waiting:
+ _h.handoff("done", later=[f"sibyl skills reset {n}" for n in waiting],
+ human=f"{', '.join(waiting)} {'was' if len(waiting) == 1 else 'were'} edited by you; "
+ "resetting replaces your edits")
+ else:
+ _h.handoff("done")
+ return 0
+
+
+# ----------------------------------------------------------------------
+# sibyl skills proposals (R1, plan 3.3): Pro, local, explicit accept only
+# ----------------------------------------------------------------------
+
+def _short_id(pid: str) -> str:
+ return str(pid or "")[:8]
+
+
+def _skill_targets(args: argparse.Namespace, name: str) -> dict[str, Path]:
+ """Where an accepted skill goes: ``--to `` only, else every harness
+ folder present on this computer (Claude Code ~/.claude/skills, Codex
+ ~/.codex/skills, Hermes $HERMES_HOME/skills)."""
+ to = getattr(args, "to", None)
+ if to:
+ return {"dir": Path(to).expanduser() / name / "SKILL.md"}
+ out: dict[str, Path] = {}
+ for harness, w in _present_wirers(args).items():
+ if harness == "claude-code":
+ out[harness] = w.settings_path.parent / "skills" / name / "SKILL.md"
+ elif harness == "codex":
+ out[harness] = w.config_path.parent / "skills" / name / "SKILL.md"
+ elif harness == "hermes":
+ out[harness] = w.hermes_home / "skills" / name / "SKILL.md"
+ return out
+
+
+def _find_proposal(learner: Any, ref: str | None) -> Any:
+ """A proposal by full id or a unique prefix of at least 6 characters."""
+ from sibyl_memory_client.exceptions import NotFoundError
+ ref = (ref or "").strip()
+ if not ref:
+ return None
+ try:
+ return learner.get_proposal(ref)
+ except NotFoundError:
+ pass
+ if len(ref) < 6:
+ return None
+ hits = []
+ for status in ("pending", "accepted", "rejected"):
+ hits += [p for p in learner.list_proposals(status=status, limit=500) if p.id.startswith(ref)]
+ return hits[0] if len(hits) == 1 else None
+
+
+def _proposals(args: argparse.Namespace) -> int:
+ from sibyl_memory_client.exceptions import EntitlementError, TierGateError, ValidationError
+ from sibyl_memory_client.lifecycle import proposals as PR
+ from sibyl_memory_client.lifecycle import state as ST
+ action = getattr(args, "proposal_action", None) or "list"
+ target = getattr(args, "target", None)
+ now = time.time()
+ store = ST.LifecycleState(_home())
+ print(a.eyebrow("skill proposals"))
+ if action in ("mute", "unmute"):
+ # Local settings only; they apply on Pro, where proposals exist.
+ if not target:
+ print(a.warn_line(f"Usage: sibyl skills proposals {action} "
+ + (" | " if action == "unmute" else "")))
+ print(a.dim(" kinds: " + ", ".join(PR.KINDS)))
+ _h.handoff("sibyl skills proposals")
+ return 1
+ if action == "mute":
+ if target not in PR.KINDS:
+ print(a.warn_line(f"Unknown kind {target!r}. Kinds: {', '.join(PR.KINDS)}"))
+ _h.handoff("sibyl skills proposals")
+ return 1
+ days = getattr(args, "days", None) or PR.MUTE_DAYS_DEFAULT
+ if not (1 <= int(days) <= 365):
+ print(a.warn_line("--days must be between 1 and 365."))
+ _h.handoff("sibyl skills proposals")
+ return 1
+
+ def _mute(st: dict[str, Any]) -> None:
+ st.setdefault("skills", ST.default_skills()).setdefault("muted_kinds", {})[target] = \
+ now + int(days) * 86400
+ store.update(_mute)
+ print(a.kv("muted", f"{target} for {int(days)} days (nothing of this kind is proposed)"))
+ _h.handoff("done")
+ return 0
+
+ def _unmute(st: dict[str, Any]) -> str:
+ sk = st.setdefault("skills", ST.default_skills())
+ if target in PR.KINDS:
+ sk.setdefault("muted_kinds", {}).pop(target, None)
+ return f"{target}: proposed again"
+ sk.setdefault("unmuted", {})[target[:80]] = now
+ return f"{target[:80]}: may be proposed again (earlier rejections no longer count)"
+ print(a.kv("unmuted", store.update(_unmute)))
+ _h.handoff("done")
+ return 0
+ if not _creds(args):
+ print(a.warn_line("Not activated. Run `sibyl init`."))
+ print(a.dim(" Skill proposals are part of Pro; nothing is proposed without an account."))
+ _h.handoff("sibyl init")
+ return 0
+ client = _client(args)
+ try:
+ learner = client.learner()
+ except TierGateError:
+ print(a.kv("proposals", "on Pro · Sibyl proposes skills from your sessions; you decide"))
+ print(a.dim(" On the free plan, /sibyl-save still offers skills when you run it yourself."))
+ _h.handoff("done", later=("sibyl upgrade",))
+ return 0
+ except EntitlementError as e:
+ print(a.warn_line(str(e).splitlines()[0]))
+ _entitlement_handoff(e)
+ return 1
+ if action == "list":
+ st = store.load()
+ muted = PR.muted_kinds(st, now)
+ rows = learner.list_proposals(status="pending", limit=50)
+ if not rows:
+ print(a.kv("pending", "none"))
+ print(a.dim(" Sibyl proposes a skill when the same work recurs across your sessions."))
+ _h.handoff("done")
+ return 0
+ print(a.kv("pending", f"{len(rows)} · accept or reject: sibyl skills proposals accept|reject "))
+ for p in rows:
+ ts = sorted(t for t in (ST._iso_to_epoch(e.get("ts")) for e in p.evidence
+ if isinstance(e, dict)) if t is not None)
+ seen = (f"{_fmt_ts(ts[0])} .. {_fmt_ts(ts[-1])}" if ts else "?")
+ flag = " · kind muted" if p.pattern_kind in muted else ""
+ print(a.kv(_short_id(p.id), f"{p.proposed_title or p.proposed_slug} · {p.pattern_kind} · "
+ f"confidence {p.confidence:.2f} · {len(p.evidence)} events · "
+ f"{seen}{flag}"))
+ _h.handoff("sibyl skills proposals show ",
+ human="which proposals to accept or reject (ids above; a skill file is written only "
+ "on accept)")
+ return 0
+ p = _find_proposal(learner, target)
+ if p is None:
+ print(a.warn_line(f"No proposal {target!r}. Run `sibyl skills proposals` for the ids."))
+ _h.handoff("sibyl skills proposals")
+ return 1
+ if action == "show":
+ print(a.kv("id", p.id))
+ print(a.kv("title", p.proposed_title or p.proposed_slug))
+ print(a.kv("kind", f"{p.pattern_kind} · confidence {p.confidence:.2f} · {len(p.evidence)} events"))
+ print(a.kv("status", p.status))
+ print()
+ print(p.proposed_body)
+ if p.status == "pending":
+ _h.handoff(f"sibyl skills proposals accept {_short_id(p.id)}",
+ later=(f"sibyl skills proposals reject {_short_id(p.id)}",),
+ human="accept this proposal (writes the skill file) or reject it; your call")
+ else:
+ _h.handoff("done")
+ return 0
+ if action == "reject":
+ if p.status != "pending":
+ print(a.warn_line(f"This proposal is {p.status}; only a pending one can be rejected."))
+ _h.handoff("sibyl skills proposals")
+ return 1
+ try:
+ client.reject_skill_proposal(p.id, note=getattr(args, "note", None))
+ except (ValidationError, EntitlementError) as e:
+ print(a.warn_line(str(e).splitlines()[0]))
+ if isinstance(e, EntitlementError):
+ _entitlement_handoff(e)
+ else:
+ _h.handoff("sibyl skills proposals")
+ return 1
+ print(a.kv("rejected", f"{p.proposed_slug} · not proposed again for {PR.COOL_OFF_DAYS} days; "
+ f"a second rejection mutes it (sibyl skills proposals unmute {p.proposed_slug})"))
+ _h.handoff("done")
+ return 0
+ # accept
+ if p.status == "rejected":
+ print(a.warn_line("This proposal was rejected. It is not proposed again for a while; "
+ f"unmute with sibyl skills proposals unmute {p.proposed_slug}."))
+ _h.handoff("done", later=(f"sibyl skills proposals unmute {p.proposed_slug}",))
+ return 1
+ if p.status == "pending":
+ try:
+ client.accept_skill_proposal(p.id, note=getattr(args, "note", None))
+ except (ValidationError, EntitlementError) as e:
+ print(a.warn_line(str(e).splitlines()[0]))
+ if isinstance(e, EntitlementError):
+ _entitlement_handoff(e)
+ else:
+ _h.handoff("sibyl skills proposals")
+ return 1
+ except Exception as e: # the cap gate (a free cap cannot apply on Pro, but never a traceback)
+ print(a.warn_line(f"Not accepted: {type(e).__name__}. Nothing was written."))
+ nxt, human = _h.from_exception(e, default="sibyl status")
+ _h.handoff(nxt, human=human)
+ return 1
+ print(a.kv("accepted", f"{p.proposed_slug} · reference copy in memory as skill/{p.proposed_slug}"))
+ else:
+ print(a.kv("accepted", f"{p.proposed_slug} (earlier) · writing its skill files again"))
+ from sibyl_memory_client import skills as SK
+ name = SK.skill_name(p.proposed_slug)
+ text = SK.proposal_skill_text(p)
+ problems = SK.validate_skill_text(text, name)
+ if problems:
+ print(a.warn_line("The skill file did not pass validation: " + "; ".join(problems)))
+ _h.handoff("done", human="this proposal's skill file did not pass validation (above); "
+ "reject it or write it by hand")
+ return 1
+ targets = _skill_targets(args, name)
+ rc = 0
+ for harness, path in targets.items():
+ st_ = SK.write_skill(_home(), path, text, harness=harness, slug=p.proposed_slug)
+ label = {"installed": "written", "unchanged": "already there", "updated": "updated",
+ "exists": "a different file is already there (kept; use --to )"}.get(st_, st_)
+ print(a.kv(harness, f"{path} · {label}"))
+ if st_.startswith("refused") or st_ == "exists":
+ rc = 1
+ if not targets:
+ print(a.dim(" No Claude Code, Codex or Hermes folder on this computer: the skill is in memory as "
+ f"skill/{p.proposed_slug}. Write the file with --to ."))
+ if (_home() / ".cursor").exists():
+ print(a.dim(f" Cursor: no skill folder is written; the reference copy is skill/{p.proposed_slug}."))
+ if rc:
+ _h.handoff(f"sibyl skills proposals accept {_short_id(p.id)} --to ",
+ human="a folder to write the skill file to (a different file is already in the "
+ "usual place)")
+ else:
+ _h.handoff("done")
+ return rc
+
+
+# ----------------------------------------------------------------------
+# sibyl skills signals (R2, spec plugin-paid-tier-r2 1.3): Pro, local only
+# ----------------------------------------------------------------------
+
+SIGNALS_PRO_LINE = "Skill signals are on Pro."
+
+
+def _kb(n: Any) -> str:
+ return f"{(n or 0) / 1024:.1f} KB" if isinstance(n, int) else "none"
+
+
+def _signals(args: argparse.Namespace) -> int:
+ """status | clear | off | on. Prints counts, size and dates, never an
+ entry. Off and clear work on any plan; on and the recording itself need a
+ verified paid entitlement."""
+ from sibyl_memory_client.lifecycle import signals as SG
+ action = getattr(args, "signals_action", None) or "status"
+ home = _home()
+ print(a.eyebrow("skill signals"))
+ pro, _why = _pro(args)
+ if action == "clear":
+ removed = SG.clear(home)
+ print(a.kv("cleared", "signals.json deleted" if removed else "nothing was recorded"))
+ print(a.dim(" Nothing recorded before now is kept or proposed."))
+ return 0
+ if action == "off":
+ SG.set_enabled(home, False)
+ print(a.kv("recording", "off · nothing new is recorded (sibyl skills signals on)"))
+ print(a.dim(" What is already recorded stays until it ages out; sibyl skills signals clear deletes it."))
+ return 0
+ if not pro:
+ print(a.kv("signals", SIGNALS_PRO_LINE))
+ if action == "status":
+ st = SG.status(home)
+ if st["exists"]:
+ print(a.dim(f" A file from an earlier Pro period is here ({_kb(st['bytes'])}); "
+ "sibyl skills signals clear deletes it."))
+ return 0
+ if action == "on":
+ SG.set_enabled(home, True)
+ print(a.kv("recording", "on · from now; nothing from while it was off is read back"))
+ return 0
+ st = SG.status(home)
+ print(a.kv("recording", ("on" if st["on"] else "off (sibyl skills signals on)")
+ + " · tool sequences and repeated entity rewrites, on this computer only"))
+ print(a.kv("file", f"~/.sibyl-memory/{SG.SIGNALS_NAME} · {_kb(st['bytes'])}" if st["exists"]
+ else "none yet"))
+ print(a.kv("sequences", str(st["ngrams"])))
+ print(a.kv("entities", f"{st['entity_keys']} ({st['entity_writes']} writes)"))
+ print(a.kv("oldest", _fmt_ts(st["oldest"])))
+ print(a.kv("newest", _fmt_ts(st["newest"])))
+ print(a.dim(" Tool and MCP server names are kept; argument names and entity names only as hashes; never a value."))
+ return 0
+
+
+# ----------------------------------------------------------------------
+# sibyl autosave (R1, plan 2.4)
+# ----------------------------------------------------------------------
+
+def _autosave_summary(st: dict[str, Any], tid: str | None, now: float) -> str:
+ from sibyl_memory_client.lifecycle import state as ST
+ cfg = ST.autosave_settings(st)
+ if not cfg["enabled"]:
+ return "off · sibyl autosave on"
+ parts = [f"every {cfg['interval_seconds'] // 60} min of active work"]
+ t = st.get("tenants", {}).get(tid or "", {}) if tid else {}
+ n = ST.nudges_today(t, now) if t else 0
+ parts.append(f"{n} save{'s' if n != 1 else ''} requested today")
+ last = t.get("last_nudge_at") if t else None
+ if isinstance(last, (int, float)):
+ from ._timefmt import utc_hm
+ parts.append("last " + (utc_hm(last) or "?"))
+ return " · ".join(parts)
+
+
+def cmd_autosave(args: argparse.Namespace) -> int:
+ from sibyl_memory_client.lifecycle import state as ST
+ op = getattr(args, "action", None) or "status"
+ store = ST.LifecycleState(_home())
+ print()
+ if op == "every":
+ minutes = getattr(args, "minutes", None)
+ lo, hi = ST.AUTOSAVE_INTERVAL_MIN // 60, ST.AUTOSAVE_INTERVAL_MAX // 60
+ if minutes is None or not (lo <= int(minutes) <= hi):
+ print(a.warn_line(f"Usage: sibyl autosave every ({lo} to {hi})."))
+ _h.handoff("sibyl autosave")
+ return 1
+
+ def _every(st: dict[str, Any]) -> None:
+ cfg = ST.autosave_settings(st)
+ cfg["interval_seconds"] = int(minutes) * 60
+ cfg["enabled"] = True
+ st["autosave"] = cfg
+ store.update(_every)
+ elif op in ("on", "off"):
+ def _onoff(st: dict[str, Any]) -> None:
+ cfg = ST.autosave_settings(st)
+ cfg["enabled"] = op == "on"
+ st["autosave"] = cfg
+ store.update(_onoff)
+ st = store.load()
+ tid = _tenant(_creds(args))
+ pro, _tier = _pro(args)
+ print(a.eyebrow("automatic save"))
+ print(a.kv("autosave", _autosave_summary(st, tid, time.time())))
+ cfg = ST.autosave_settings(st)
+ print(a.kv("rule", f"once early (after 5 memory writes or a compaction), then every "
+ f"{cfg['interval_seconds'] // 60} min of active work; at most "
+ f"{cfg['max_per_session']} a session and {cfg['max_per_day']} a day"))
+ if not pro:
+ print(a.kv("plan", "automatic save is on Pro · this setting applies the day you upgrade"))
+ if not st.get("reminders", True):
+ print(a.dim(" reminders are off (sibyl reminders on): nothing is requested meanwhile."))
+ print(a.dim(" Each automatic save is one extra model turn that reads and writes memory."))
+ _h.handoff("done", later=() if pro else ("sibyl upgrade",))
+ return 0
+
+
+# ----------------------------------------------------------------------
+# sibyl refresh (R1, plan 5.2): no new endpoint
+# ----------------------------------------------------------------------
+
+def _cap_label(cap: Any) -> str:
+ if cap is None:
+ return "none"
+ if isinstance(cap, int) and not isinstance(cap, bool):
+ return f"{cap / (1024 * 1024):.0f} MB"
+ return "?"
+
+
+def _devices_label(acct: Any) -> str | None:
+ from sibyl_memory_client.exceptions import device_limit_info
+ info = device_limit_info(acct)
+ if info is None:
+ return None
+ lim = info["limit"]
+ return f"{info['n']} of {lim}" if lim is not None else f"{info['n']} (no limit)"
+
+
+def _refresh_diff(before: dict[str, Any], after: dict[str, Any]) -> list[tuple[str, str]]:
+ rows: list[tuple[str, str]] = []
+ bt, at = before.get("tier"), after.get("tier")
+ src = after.get("src")
+ if bt != at:
+ rows.append(("tier", f"{bt or 'none'} -> {at or 'none'}" + (f" ({src})" if isinstance(src, str) and src
+ and src != at else "")))
+ if "cap" in before or "cap" in after:
+ bc, ac = before.get("cap", "?"), after.get("cap", "?")
+ if bc != ac:
+ rows.append(("cap", f"{_cap_label(bc)} -> {_cap_label(ac)}"))
+ bd, ad = _devices_label(before.get("acct")), _devices_label(after.get("acct"))
+ if ad is not None and bd != ad:
+ rows.append(("computers", f"{bd} -> {ad}" if bd else ad))
+ be = (before.get("acct") or {}).get("email_verified")
+ ae = (after.get("acct") or {}).get("email_verified")
+ if ae is True and be is not True:
+ rows.append(("email", "verified"))
+ if before.get("state") != after.get("state"):
+ rows.append(("access", f"{before.get('state') or 'none'} -> {after.get('state') or 'none'}"))
+ return rows
+
+
+def cmd_refresh(args: argparse.Namespace) -> int:
+ """Check the account now (one /entitlement call), refresh the procedures,
+ shims and hooks for this computer, and say what changed. Exits 0 with no
+ account (it says what to do), 2 when the server could not be reached."""
+ from . import _account_gate as G
+ from sibyl_memory_client import skills as SK
+ print()
+ cred = _cred(args)
+ creds = _creds(args)
+ if not creds:
+ print(a.warn_line("Not activated. Run `sibyl init`."))
+ print(a.dim(" sibyl refresh picks up a plan change on a signed-in computer; nothing to refresh yet."))
+ from . import cli as _cli
+ _h.handoff(_cli._init_next())
+ return 0
+ print(a.eyebrow("account"))
+ before = G.status_info(cred, refresh=False) or {}
+ after = G.status_info(cred, refresh=True)
+ rc = 0
+ if after is None:
+ print(a.kv("account", "sibyl-memory-client is not installed", value_color="warn"))
+ _h.handoff("pip install -U sibyl-memory-client")
+ return 2
+ outcome = after.get("refreshed")
+ nxt, human = G.access_handoff(after)
+ if outcome in ("ok", "shared"):
+ diff = _refresh_diff(before, after)
+ for k, v in diff:
+ print(a.kv(k, v, value_color="ok"))
+ if not diff:
+ print(a.kv("checked", f"no change · {after.get('tier') or 'no plan'} · "
+ + G.access_row(after)))
+ else:
+ print(a.kv("access", G.access_row(after)))
+ elif outcome == "denied":
+ print(a.kv("access", G.access_row(after), value_color="err"))
+ rc = 1
+ elif after.get("refresh_code") == G.UNTRUSTED_BASE_CODE:
+ # Follow-up D1: the sign-in was not sent (SIBYL_API_BASE is not a Sibyl
+ # address). Not a network fault: no retry, no "connect".
+ from . import cli as _cli
+ _cli._note_untrusted_base(_cli.API_BASE)
+ print(a.kv("account", G.UNTRUSTED_BASE_LINE, value_color="err"))
+ print(a.kv("access", G.access_row(after)))
+ rc = 1
+ nxt, human = G.untrusted_base_handoff()
+ else:
+ print(a.kv("account", "could not reach the server; this is the last check-in", value_color="warn"))
+ print(a.kv("access", G.access_row(after)))
+ rc = 2
+ nxt, human = _h.RETRY, "connect this computer to the internet once"
+ dev = _devices_label(after.get("acct"))
+ if dev:
+ print(a.kv("computers", dev))
+ print()
+ print(a.eyebrow("this computer"))
+ rep = SK.install(_home())
+ print(a.kv("procedures", f"v{rep.version} " + ", ".join(f"{n} {st_}" for n, st_ in rep.results.items())))
+ for m in rep.messages:
+ print(a.dim(" " + m))
+ from .setup import install_shims
+ for name, w in _present_wirers(args).items():
+ lines = install_shims(name, w.skill_shim_targets())
+ if name == "codex":
+ lines = w.wire_block() + lines
+ if name == "claude-code" and w.hooks_state().get("present"):
+ lines += w.wire_hooks() # refresh only hooks already wired (sibyl setup adds them)
+ for ln in lines:
+ print(a.dim(f" {name}: {ln}"))
+ print(a.dim(" Hooks and shims are the same on every plan: Pro behaviour switches on because this "
+ "computer's entitlement says so."))
+ print(a.dim(" Running agents pick this up on their next call."))
+ status_rows(args, creds)
+ print()
+ _h.handoff(nxt, human=human)
+ return rc
+
+
+# ----------------------------------------------------------------------
+# sibyl reminders
+# ----------------------------------------------------------------------
+
+def cmd_reminders(args: argparse.Namespace) -> int:
+ from sibyl_memory_client.lifecycle import state as ST
+ op = getattr(args, "state", None) or "status"
+ store = ST.LifecycleState(_home())
+ print()
+ if op in ("on", "off", "quiet"):
+ def _set(st: dict[str, Any]) -> None:
+ if op == "on":
+ st["reminders"], st["quiet"] = True, False
+ elif op == "off":
+ st["reminders"] = False
+ else:
+ st["reminders"], st["quiet"] = True, True
+ store.update(_set)
+ st = store.load()
+ val = "off" if not st.get("reminders", True) else ("quiet (Pro reports silenced)" if st.get("quiet") else "on")
+ print(a.kv("reminders", val))
+ _h.handoff("done")
+ return 0
+
+
+# ----------------------------------------------------------------------
+# sibyl hook
+# ----------------------------------------------------------------------
+
+def cmd_hook(args: argparse.Namespace) -> int:
+ # The installed `sibyl` command reaches hooks.main_hook directly (see
+ # _entry.py) without importing this module; this is the same path.
+ from .hooks import main_hook
+ return main_hook(getattr(args, "event", ""))
+
+
+# ----------------------------------------------------------------------
+# sibyl status rows
+# ----------------------------------------------------------------------
+
+def status_rows(args: argparse.Namespace, creds: dict[str, Any] | None) -> None:
+ """The `lifecycle` eyebrow of `sibyl status` (spec 4.3). Never raises."""
+ try:
+ _status_rows(args, creds or {})
+ except Exception:
+ pass
+
+
+def _status_rows(args: argparse.Namespace, creds: dict[str, Any]) -> None:
+ from sibyl_memory_client import skills as SK
+ from sibyl_memory_client.lifecycle import policy as P
+ from sibyl_memory_client.lifecycle import state as ST
+ from sibyl_memory_client.lifecycle.runner import measure_for_reminder
+ tid = _tenant(creds)
+ pro, _tier = _pro(args)
+ _legacy_notice()
+ st = ST.LifecycleState(_home()).load()
+ t = st.get("tenants", {}).get(tid or "", {}) if tid else {}
+ marker = ST.read_save_marker(_db(args), tid) if tid else None
+ last = max([x for x in (marker, t.get("last_save_at")) if isinstance(x, (int, float))], default=None)
+ print()
+ print(a.eyebrow("lifecycle"))
+ save = f"last {_fmt_ts(last)} · {int(t.get('writes_since_save') or 0)} writes since · "
+ save += ("automatic · " + _autosave_summary(st, tid, time.time()) if pro
+ else "manual (automatic on Pro)")
+ print(a.kv("save", save))
+ rec = measure_for_reminder(_home(), Path.cwd())
+ if rec is not None and rec["files"]:
+ heavy = [f["file"] for f in rec["files"] if f["heavy"]]
+ ctx = f"~{rec['total_tok'] / 1000:.1f}k tok always-load ({rec['weight']})"
+ if heavy:
+ ctx += f" · heavy: {', '.join(heavy[:3])}"
+ else:
+ ctx = "no always-load files found here"
+ pol = P.load(_home())
+ if pro:
+ ctx += f" · policy {pol['mode']}"
+ if pol["auto_files"]:
+ ctx += f" ({len(pol['auto_files'])} file{'s' if len(pol['auto_files']) != 1 else ''} auto)"
+ elif pol["auto_files"]:
+ ctx += f" · {len(pol['auto_files'])} file(s) set to auto (runs on Pro)"
+ print(a.kv("context", ctx))
+ sst = SK.status(_home())
+ if sst["exists"]:
+ parts = [f"v{sst['installed_version'] or '?'}"]
+ for n, info in sst["files"].items():
+ parts.append(f"{n} {'edited by you' if info['state'] == 'edited' else info['state']}")
+ harnesses = sorted({i.get('harness') for i in sst['shims'].values() if i.get('state') == 'ok'})
+ if harnesses:
+ parts.append(", ".join(f"{h} wired" for h in harnesses))
+ print(a.kv("skills", " · ".join(parts)))
+ else:
+ print(a.kv("skills", "not installed · sibyl skills install"))
+ if pro and tid:
+ n = _pending_proposals(_db(args), tid)
+ print(a.kv("proposals", f"{n} skill proposal{'s' if n != 1 else ''} pending"
+ + (" · sibyl skills proposals" if n else "")))
+ rem = "off" if not st.get("reminders", True) else ("quiet" if st.get("quiet") else "on")
+ print(a.kv("reminders", rem))
+
+
+def _pending_proposals(db: Path, tid: str) -> int:
+ """How many proposals are pending, read-only (no gate, no network)."""
+ import sqlite3
+ try:
+ if not db.is_file() or db.is_symlink():
+ return 0
+ con = sqlite3.connect(f"file:{db}?mode=ro", uri=True, timeout=1.0)
+ try:
+ row = con.execute("SELECT count(*) FROM skill_proposals WHERE tenant_id = ? AND "
+ "status = 'pending'", (tid,)).fetchone()
+ finally:
+ con.close()
+ return int(row[0]) if row else 0
+ except sqlite3.Error:
+ return 0
+
+
+__all__ = ["cmd_autosave", "cmd_debloat", "cmd_hook", "cmd_refresh", "cmd_reminders", "cmd_save",
+ "cmd_skills", "status_rows"]
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/migrate.py b/sibyl-memory-cli/src/sibyl_memory_cli/migrate.py
new file mode 100644
index 0000000000000000000000000000000000000000..40622426b83db2cbeaba7289a3e5e6c88c221cd4
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/migrate.py
@@ -0,0 +1,742 @@
+"""`sibyl setup` guided onboarding flow (v2): backup -> wire MCP -> extract -> verify -> debloat.
+
+Design (operator-locked 2026-05-31): one dynamic, resumable, guided flow that gets a
+user "set up and optimized" no matter which harness they run. The CLI does the
+DETERMINISTIC work (back up files, detect state, verify the DB, trim files) and
+CONDUCTS; the user's own harness does the semantic EXTRACTION (it has the memory
+tools). Every gap (no plugin, MCP not wired) prints exact per-harness instructions.
+
+This module adds the new phases on top of the existing wirers in setup.py
+(HermesWirer / ClaudeCodeWirer) and adds CodexWirer so all three harnesses are
+first-class. Nothing here touches live files except the explicitly-confirmed
+debloat step, and only after a verified backup exists.
+"""
+from __future__ import annotations
+
+import shlex
+import json
+import os
+import shutil
+import sqlite3
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Callable, Optional
+
+# ----------------------------------------------------------------------
+# 1. Memory/agent file discovery (per harness)
+# ----------------------------------------------------------------------
+# Candidate memory + agent files we back up + (optionally) extract from.
+# Globs are resolved relative to `home`. Directories are copied whole.
+
+HARNESS_FILES: dict[str, list[str]] = {
+ "claude-code": ["CLAUDE.md", ".claude/CLAUDE.md", ".claude/settings.json"],
+ "codex": ["AGENTS.md", ".codex/config.toml", ".codex/AGENTS.md"],
+ "hermes": [".hermes/config.yaml", ".hermes/memory"],
+ "generic": ["AGENTS.md", "MEMORY.md", "memory.md", ".cursorrules", ".cursor/rules"],
+}
+
+
+# Save/debloat build (spec plugin-save-debloat 6.1): one surface definition.
+# CONTEXT_FILES are the instruction files an agent loads on every session
+# (measured by `sibyl debloat`, trimmable by the migrate trim step);
+# CONFIG_FILES are backed up and extracted from, NEVER trimmed. The union is
+# every HARNESS_FILES entry (a test keeps the three from drifting).
+try:
+ from sibyl_memory_client.lifecycle.measure import CONFIG_FILES, CONTEXT_FILES
+except Exception: # pragma: no cover - client without the lifecycle package
+ CONTEXT_FILES = frozenset({"CLAUDE.md", ".claude/CLAUDE.md", "AGENTS.md", ".codex/AGENTS.md",
+ "MEMORY.md", "memory.md", ".cursorrules", ".cursor/rules"})
+ CONFIG_FILES = frozenset({".claude/settings.json", ".codex/config.toml",
+ ".hermes/config.yaml", ".hermes/memory"})
+
+
+@dataclass
+class FoundFile:
+ harness: str
+ path: Path # absolute
+ rel: str # path relative to home (for backup layout)
+ is_dir: bool
+ size: int
+ matched: str = "" # the HARNESS_FILES entry it matched (root-relative name)
+
+
+def _backup_rel(p: Path, home: Path, cwd: Optional[Path]) -> str:
+ """Collision-free backup path for a source file. Files under home keep their
+ home-relative path; files outside home (a project elsewhere) get a `project/`
+ prefix; anything else `external/`. This prevents a home file and a
+ same-named project file from clobbering each other in the backup (data-loss bug)."""
+ try:
+ if p.is_relative_to(home):
+ return str(p.relative_to(home))
+ except (ValueError, OSError):
+ pass
+ if cwd:
+ try:
+ cwd = Path(cwd)
+ if p.is_relative_to(cwd):
+ return "project/" + str(p.relative_to(cwd))
+ except (ValueError, OSError):
+ pass
+ return "external/" + p.name
+
+
+def scan_memory_files(home: Optional[Path] = None, cwd: Optional[Path] = None) -> list[FoundFile]:
+ """Find existing memory/agent files across harnesses. De-dupes by resolved path.
+ Looks in both the user's home and the current project dir (CLAUDE.md lives in projects)."""
+ home = Path(home).expanduser() if home else Path.home()
+ roots = [home]
+ if cwd:
+ roots.append(Path(cwd))
+ seen: set[Path] = set()
+ found: list[FoundFile] = []
+ for harness, rels in HARNESS_FILES.items():
+ for rel in rels:
+ for root in roots:
+ p = (root / rel)
+ if not p.exists():
+ continue
+ try:
+ key = p.resolve()
+ except OSError:
+ key = p
+ if key in seen:
+ continue
+ seen.add(key)
+ is_dir = p.is_dir()
+ size = _tree_size(p) if is_dir else p.stat().st_size
+ found.append(FoundFile(harness, p, _backup_rel(p, home, cwd), is_dir, size, rel))
+ return found
+
+
+def _tree_size(p: Path) -> int:
+ """Sum the byte size of every regular file under ``p``.
+
+ B005 (audit #19): a permission-denied file or a broken symlink raises
+ OSError on ``is_file()``/``stat()``. A single un-statable entry must not
+ abort the whole size estimate, so each entry is guarded independently and
+ the offending one is simply skipped (counted as zero).
+ """
+ total = 0
+ for f in p.rglob("*"):
+ try:
+ if f.is_file():
+ total += f.stat().st_size
+ except OSError:
+ continue
+ return total
+
+
+def _fsync_path(p: Path) -> None:
+ """Best-effort fsync of a file or directory so a crash right after backup
+ can't leave a partially-flushed copy. CLI-9: backups must survive a power
+ loss before we trust them enough to trim the originals."""
+ try:
+ if p.is_dir():
+ flags = getattr(os, "O_DIRECTORY", 0)
+ fd = os.open(str(p), os.O_RDONLY | flags)
+ else:
+ fd = os.open(str(p), os.O_RDONLY)
+ try:
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+ except (OSError, ValueError):
+ # Directory fsync is not portable everywhere; never fail the backup on it.
+ pass
+
+
+# ----------------------------------------------------------------------
+# 2. Backup (deterministic, verified, timestamped) — the safety win
+# ----------------------------------------------------------------------
+
+@dataclass
+class BackupResult:
+ backup_dir: Path
+ files: list[str] = field(default_factory=list)
+ total_bytes: int = 0
+ ok: bool = True
+ error: Optional[str] = None
+
+
+def backup_dir_name(now: Optional[datetime] = None) -> str:
+ now = now or datetime.now(timezone.utc)
+ return "sibyl-migration-backup-" + now.strftime("%Y-%m-%dT%H_%M_%S")
+
+
+def run_backup(files: list[FoundFile], dest_parent: Path, *, now: Optional[datetime] = None) -> BackupResult:
+ """Copy each found file/dir into a fresh timestamped backup folder under dest_parent.
+ Verifies byte counts. Never modifies sources. Aborts (ok=False) on first failure."""
+ dest_parent = Path(dest_parent).expanduser()
+ backup = dest_parent / backup_dir_name(now)
+ res = BackupResult(backup_dir=backup)
+ try:
+ backup.mkdir(parents=True, exist_ok=False)
+ except Exception as e:
+ res.ok = False; res.error = f"could not create backup dir: {e}"
+ return res
+ for f in files:
+ target = backup / f.rel
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if f.is_dir:
+ shutil.copytree(f.path, target, dirs_exist_ok=True)
+ src_sz, dst_sz = _tree_size(f.path), _tree_size(target)
+ # CLI-9: fsync every copied file in the tree so the backup is
+ # durable before we ever trim an original.
+ for cf in target.rglob("*"):
+ if cf.is_file():
+ _fsync_path(cf)
+ else:
+ shutil.copy2(f.path, target)
+ src_sz, dst_sz = f.path.stat().st_size, target.stat().st_size
+ _fsync_path(target) # CLI-9: durable copy before any trim
+ if src_sz != dst_sz:
+ res.ok = False; res.error = f"byte mismatch on {f.rel} ({src_sz} != {dst_sz})"
+ return res
+ res.files.append(f.rel); res.total_bytes += dst_sz
+ except Exception as e:
+ res.ok = False; res.error = f"copy failed on {f.rel}: {type(e).__name__}: {e}"
+ return res
+ # CLI-9: fsync the backup directory itself so its directory entries (the
+ # newly-created files) are persisted, not just the file contents.
+ _fsync_path(backup)
+ return res
+
+
+# ----------------------------------------------------------------------
+# 3. Wirers live in setup.py (canonical). Codex now auto-wires config.toml;
+# Claude Code registers via `claude mcp add --scope user`.
+# ----------------------------------------------------------------------
+
+from .setup import CodexWirer, ClaudeCodeWirer, HermesWirer # noqa: E402 (canonical wirers)
+
+
+# Per-harness wiring instructions for the guided flow (no silent edits across the board;
+# we print and let the user run them, matching the operator's 'walk them through' intent).
+def wire_instructions(harness: str) -> list[str]:
+ if harness == "claude-code":
+ return ["Open a new terminal and run:",
+ " claude mcp add sibyl-memory -- sibyl-memory-mcp",
+ "Restart Claude Code (or /mcp -> reconnect sibyl-memory), then return here."]
+ if harness == "codex":
+ return CodexWirer().instructions()
+ if harness == "hermes":
+ return ["Open a new terminal and run:",
+ " sibyl setup hermes",
+ "It installs the plugin and sets memory.provider: sibyl in your Hermes config.yaml. Restart Hermes."]
+ return ["Register an MCP server named 'sibyl-memory' with command 'sibyl-memory-mcp' in your agent's MCP config, then restart it."]
+
+
+# ----------------------------------------------------------------------
+# 4. Extraction handoff — the harness does the semantic work, from the backup
+# ----------------------------------------------------------------------
+
+def extraction_prompt(harness: str, backup_dir: Path) -> str:
+ """Tailored backup-first prompt the user runs IN their harness. Reads only from
+ the backup; never edits live files. Mirrors the beta-page conventions."""
+ tool = "sibyl_remember" if harness in ("claude-code", "codex") else "your memory tool"
+ return (
+ f"Read ONLY from the backup folder at {backup_dir} (never touch my live files). "
+ "For every piece of accumulated memory in those files (facts and configs, preferences "
+ "and patterns, project context, people and relationship notes), write each one into Sibyl "
+ f"Memory using {tool}:\n"
+ " - facts/configs/env: structured key-value content\n"
+ " - preferences/patterns: tagged as preference\n"
+ " - project context/history: under a project namespace\n"
+ " - people/relationships: with the person's name as context\n"
+ "Do not edit, trim, or delete any live file. When done, tell me how many entries you wrote "
+ "in each category."
+ )
+
+
+# ----------------------------------------------------------------------
+# 5. Verify — count what actually landed in the local Sibyl DB
+# ----------------------------------------------------------------------
+
+# Sentinel returned by db_baseline when the path EXISTS but is not a readable
+# SQLite database (garbage bytes, wrong magic, locked, corrupt). Distinct from
+# 0 (a valid empty DB / no DB yet). CLI-3 migrate half: the orchestrator must
+# ABORT verify + debloat on this, never silently treat it as a 0-row DB and
+# proceed to trim the user's real files against a backup it can't trust.
+DB_UNREADABLE = -1
+
+
+def _is_readable_db(db_path: Path) -> bool:
+ """True if `db_path` is a non-empty file that opens as a real SQLite DB.
+
+ A 0-byte file is treated as a fresh/empty DB by sqlite and counts as
+ readable (no rows yet). Anything that fails the header check or PRAGMA is
+ unreadable."""
+ try:
+ if not db_path.is_file():
+ return False
+ if db_path.stat().st_size == 0:
+ return True
+ with open(db_path, "rb") as fh:
+ if fh.read(16) != b"SQLite format 3\x00":
+ return False
+ con = sqlite3.connect(str(db_path))
+ try:
+ con.execute("PRAGMA schema_version")
+ finally:
+ con.close()
+ return True
+ except (OSError, sqlite3.Error):
+ return False
+
+
+def db_baseline(db_path: Path) -> int:
+ """Total entity count now, to diff against after extraction.
+
+ Returns 0 if no DB exists yet (or an empty DB with no rows), and
+ DB_UNREADABLE (-1) when the path exists but is not a usable SQLite DB —
+ CLI-3: the caller must distinguish "no DB" from "unreadable DB"."""
+ db_path = Path(db_path).expanduser()
+ if not db_path.exists():
+ return 0
+ if not _is_readable_db(db_path):
+ return DB_UNREADABLE
+ # B001 (audit #19): close the connection on the error path too. If the
+ # COUNT raises (e.g. no `entities` table yet), the bare con.close() below
+ # the query would be skipped and the connection would leak.
+ try:
+ con = sqlite3.connect(str(db_path)); con.row_factory = sqlite3.Row
+ try:
+ n = con.execute("SELECT COUNT(*) c FROM entities").fetchone()["c"]
+ finally:
+ con.close()
+ return int(n)
+ except sqlite3.Error:
+ # Readable SQLite file but no `entities` table yet (fresh schema) —
+ # that's 0 baseline, not an unreadable DB.
+ return 0
+
+
+def verify_new_entries(db_path: Path, baseline_total: int) -> dict:
+ """Return {'new_total': N, 'by_category': {...}, 'ok': bool}. ok = new_total > 0.
+
+ CLI-3: if the DB path exists but is unreadable, set ok=False and flag
+ `unreadable` so the orchestrator aborts rather than reporting 0 new
+ entries (which would falsely gate a debloat)."""
+ db_path = Path(db_path).expanduser()
+ out = {"new_total": 0, "by_category": {}, "ok": False}
+ if not db_path.exists():
+ return out
+ if not _is_readable_db(db_path):
+ out["unreadable"] = True
+ out["error"] = "database file exists but is not a readable SQLite database"
+ return out
+ # B001 (audit #19): wrap connect+query in try/finally so the connection is
+ # always closed. The previous bare con.close() ran only after both queries
+ # succeeded — any sqlite3.Error mid-query leaked the open connection.
+ try:
+ con = sqlite3.connect(str(db_path)); con.row_factory = sqlite3.Row
+ try:
+ total = con.execute("SELECT COUNT(*) c FROM entities").fetchone()["c"]
+ cats = con.execute("SELECT category, COUNT(*) c FROM entities GROUP BY category ORDER BY c DESC").fetchall()
+ finally:
+ con.close()
+ out["new_total"] = max(0, int(total) - int(baseline_total))
+ out["by_category"] = {r["category"]: int(r["c"]) for r in cats}
+ out["ok"] = out["new_total"] > 0
+ except sqlite3.Error as e:
+ out["error"] = str(e)
+ return out
+
+
+# ----------------------------------------------------------------------
+# 6. Debloat — confirmed trim of the live file; safe because backup exists
+# ----------------------------------------------------------------------
+
+KEEP_START, KEEP_END = "", ""
+
+
+def heuristic_lean(text: str) -> str:
+ """Conservative lean version when the agent didn't provide one.
+ If the file marks a keep-block, keep exactly that. Otherwise keep everything up to
+ the first H2 section (identity/rules usually live at the top) and append a pointer.
+ The full original is always in the backup, so this is reversible."""
+ if KEEP_START in text and KEEP_END in text:
+ core = text.split(KEEP_START, 1)[1].split(KEEP_END, 1)[0].strip()
+ else:
+ lines, core_lines = text.splitlines(), []
+ seen_h2 = 0
+ for ln in lines:
+ if ln.startswith("## "):
+ seen_h2 += 1
+ if seen_h2 > 1: # keep the first ## section (identity/core), trim the rest
+ break
+ core_lines.append(ln)
+ core = "\n".join(core_lines).strip()
+ # The pointer claims only what is true: the whole file is in the backup,
+ # and the migrate extraction stored entries (not necessarily this text)
+ # in Sibyl Memory.
+ pointer = ("\n\n\n")
+ return core + pointer
+
+
+def verify_backup_of(live_path: Path, backup_dir: Path, *, home: Path, cwd: Optional[Path]) -> bool:
+ """Re-stat the SPECIFIC backup copy of `live_path` and confirm it exists
+ with a matching byte count.
+
+ CLI-9: before trimming an original we must verify the backup file on disk
+ right now — not trust the in-memory `bk.ok` flag from earlier, which can't
+ catch a backup that was deleted/truncated/corrupted in the meantime."""
+ try:
+ rel = _backup_rel(Path(live_path), Path(home), cwd)
+ backup_copy = Path(backup_dir) / rel
+ if not backup_copy.is_file():
+ return False
+ return backup_copy.stat().st_size == Path(live_path).stat().st_size
+ except OSError:
+ return False
+
+
+def debloat_file(live_path: Path, lean_text: str, *, backup_exists: bool, dry_run: bool = False) -> dict:
+ """Atomically replace live_path with lean_text. REFUSES unless backup_exists is True.
+ Returns {before, after, written, error}."""
+ live_path = Path(live_path).expanduser()
+ out = {"before": 0, "after": len(lean_text.encode()), "written": False}
+ if not backup_exists:
+ out["error"] = "refused: no verified backup exists"; return out
+ # CLI-8: refuse to trim through a symlink. os.replace on a symlinked target
+ # would clobber whatever the link points at — potentially a file outside
+ # the intended scope. The debloat is the highest-blast-radius step; it must
+ # only ever rewrite a regular file we backed up.
+ if live_path.is_symlink():
+ out["error"] = "refused: live file is a symlink"; return out
+ if not live_path.exists():
+ out["error"] = "live file not found"; return out
+ out["before"] = live_path.stat().st_size
+ if dry_run:
+ return out
+ # CLI-8: mkstemp (unique per-process) + fsync + atomic os.replace, instead
+ # of a fixed `.sibyl-tmp` name that two runs could collide on.
+ data = lean_text.encode("utf-8")
+ import tempfile
+ fd, tmp = tempfile.mkstemp(dir=str(live_path.parent),
+ prefix=live_path.name + ".", suffix=".sibyl-tmp")
+ try:
+ os.write(fd, data)
+ os.fsync(fd)
+ except BaseException:
+ os.close(fd)
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ raise
+ else:
+ os.close(fd)
+ os.replace(tmp, str(live_path))
+ out["written"] = True
+ return out
+
+
+# ----------------------------------------------------------------------
+# 7. Orchestrator — the guided, resumable flow
+# ----------------------------------------------------------------------
+
+def detect_state(home: Optional[Path] = None, cwd: Optional[Path] = None, db_path: Optional[Path] = None) -> dict:
+ """Snapshot for resumability: what's present, what's wired, how much memory exists."""
+ from .setup import HermesWirer, ClaudeCodeWirer
+ home = Path(home).expanduser() if home else Path.home()
+ db_path = Path(db_path).expanduser() if db_path else (home / ".sibyl-memory" / "memory.db")
+ wirers = {"claude-code": ClaudeCodeWirer(), "codex": CodexWirer(), "hermes": HermesWirer()}
+ return {
+ "files": scan_memory_files(home, cwd),
+ "harnesses": {n: {"present": w.is_present(), **w.current_state()} for n, w in wirers.items()},
+ "db_entries": db_baseline(db_path),
+ "db_path": db_path,
+ }
+
+
+class GuidedIO:
+ """IO seam so the guided flow is testable non-interactively. Pass `scripted`
+ answers (list) to drive confirms/pauses without a TTY."""
+ def __init__(self, scripted=None):
+ self.scripted = list(scripted or [])
+ self.lines: list[str] = []
+ # True when the last confirm/pause hit end of input (no terminal):
+ # the flow then says which default it took (agent handoff, N6 / N9).
+ self.last_eof = False
+
+ def say(self, s: str = "") -> None:
+ self.lines.append(str(s))
+
+ def confirm(self, q: str, *, default: bool = True) -> bool:
+ self.last_eof = False
+ if self.scripted:
+ ans = self.scripted.pop(0)
+ else:
+ try:
+ ans = input(f"{q} [{'Y/n' if default else 'y/N'}]: ").strip()
+ except EOFError:
+ ans = ""
+ self.last_eof = True
+ return default if not ans else ans.strip().lower().startswith("y")
+
+ def pause(self, q: str = "press Enter to continue") -> None:
+ self.last_eof = False
+ if self.scripted:
+ self.scripted.pop(0)
+ return
+ try:
+ input(q)
+ except EOFError:
+ self.last_eof = True
+
+
+def run_guided_setup(*, home=None, cwd=None, db_path=None, backup_parent=None,
+ io: Optional[GuidedIO] = None, wirers: Optional[dict] = None,
+ extract_fn: Optional[Callable[[Path, Path], None]] = None,
+ debloat: bool = True, force: bool = False, now=None) -> dict:
+ """The assembled guided flow: backup -> auto-wire each harness (instructions on
+ failure) -> extraction handoff -> verify -> confirmed debloat. Returns a structured
+ report. `extract_fn(backup_dir, db_path)` performs/simulates extraction; default
+ prints the prompt for the user to run in their own harness. `wirers` is injectable
+ so tests (and isolation) never touch real config."""
+ from .setup import ALL_WIRERS
+ io = io or GuidedIO()
+ home = Path(home).expanduser() if home else Path.home()
+ db_path = Path(db_path).expanduser() if db_path else (home / ".sibyl-memory" / "memory.db")
+ backup_parent = Path(backup_parent).expanduser() if backup_parent else home
+ # Agent handoff (spec 2026-10-03 rows N4 to N10): `handoff` is the block of
+ # a failing phase; `later` collects follow-ups for the final block.
+ report: dict = {"ok": True, "phases": {}, "later": []}
+
+ # 1. scan + backup (deterministic, first, never modifies sources)
+ files = scan_memory_files(home, cwd)
+ report["files"] = [f.rel for f in files]
+ if not files:
+ io.say("No memory/agent files found. Nothing to migrate.")
+ report["ok"] = False
+ report["handoff"] = {"next": "sibyl setup", "human": None}
+ return report
+ bk = run_backup(files, backup_parent, now=now)
+ report["phases"]["backup"] = {"ok": bk.ok, "dir": str(bk.backup_dir), "files": len(bk.files)}
+ if not bk.ok:
+ io.say(f"Backup failed: {bk.error}. Aborting; nothing else touched.")
+ report["ok"] = False
+ report["handoff"] = {
+ "next": "sibyl migrate --backup-dir ",
+ "human": f"the backup folder {backup_parent} could not be written ({bk.error}); pick "
+ "another with --backup-dir"}
+ return report
+ io.say(f"Backed up {len(bk.files)} files -> {bk.backup_dir} (originals untouched)")
+
+ # 2. detect + auto-wire each present harness; fall back to instructions
+ if wirers is None:
+ wirers = {n: cls() for n, cls in ALL_WIRERS.items()}
+ detected = {n: w for n, w in wirers.items() if w.is_present()}
+ wire_report = {}
+ for name, w in detected.items():
+ if w.current_state().get("wired_with_sibyl"):
+ wire_report[name] = "already"
+ continue
+ outcome = w.wire(force=force)
+ wire_report[name] = outcome.status
+ if outcome.status not in ("wired", "already"):
+ io.say(f"{name}: auto-wire incomplete ({outcome.message}). Do this manually:")
+ for ln in wire_instructions(name):
+ io.say(" " + ln)
+ io.say(f"ask your human: run the steps above, restart {getattr(w, 'display_name', name)}, "
+ "then tell me")
+ report["later"].append(f"sibyl setup {name} --force")
+ report["phases"]["wire"] = wire_report
+
+ # 3. extraction (the harness does it; default prints the prompt + pauses)
+ baseline = db_baseline(db_path)
+ # CLI-3: if the DB path exists but is unreadable, do NOT proceed to verify
+ # + debloat. A debloat trims the user's live files; gating it on a DB we
+ # cannot read would be unsafe. Abort cleanly with the originals intact.
+ if baseline == DB_UNREADABLE:
+ io.say("Sibyl memory DB exists but is unreadable (not a valid SQLite database).")
+ io.say("Aborting before verify/trim — your originals and backup are intact.")
+ report["phases"]["verify"] = {"new_total": 0, "by_category": {}, "ok": False, "unreadable": True}
+ report["ok"] = False
+ report["handoff"] = {"next": "sibyl status",
+ "human": f"{db_path} is not a readable SQLite file; move it aside or "
+ "point --db elsewhere"}
+ return report
+ target = next(iter(detected), "claude-code")
+ if extract_fn is not None:
+ extract_fn(bk.backup_dir, db_path)
+ else:
+ io.say("Run this in your agent (it reads the backup, writes to Sibyl):")
+ io.say(extraction_prompt(target, bk.backup_dir))
+ io.pause("After it finishes, press Enter to verify")
+ if io.last_eof:
+ io.say("no terminal to wait on: verify runs now and will count 0; after your agent runs "
+ "the prompt above, check with sibyl memory list and trim with sibyl debloat plan")
+ io.say("ask your human: nothing; I run the extraction prompt above myself in this session")
+
+ # 4. verify
+ v = verify_new_entries(db_path, baseline)
+ report["phases"]["verify"] = v
+ io.say(f"Verified {v['new_total']} new entries in Sibyl Memory.")
+
+ # 5. debloat (confirmed per file; safe because the backup exists).
+ # Save/debloat build (spec 6.2): every instruction file the scan found is a
+ # candidate (CLAUDE.md, AGENTS.md, .cursorrules, ...), not a hardcoded
+ # CLAUDE.md; configuration files are never candidates; .cursor/rules is a
+ # directory (measured by `sibyl debloat`, never trimmed). A project
+ # .debloat.json "surface" narrows the candidates. One question per file,
+ # default No; --yes never answers it.
+ if debloat and v["ok"]:
+ records: list[dict] = []
+ for f, why in trim_candidates(files, home=home, cwd=cwd):
+ if why:
+ io.say(f"{f.matched or f.path.name}: {why}; left as is.")
+ continue
+ label = _trim_label(f, home=home, cwd=cwd)
+ try:
+ text = f.path.read_bytes().decode("utf-8")
+ except (OSError, UnicodeDecodeError):
+ io.say(f"{label}: not UTF-8 text; left as is.")
+ _later_once(report, "sibyl debloat plan")
+ continue
+ lean = lean_text_for(text, f.path.name, bk.backup_dir)
+ if lean is None:
+ io.say(f"{label}: no safe trim found; left as is.")
+ _later_once(report, "sibyl debloat plan")
+ continue
+ if not io.confirm(f"Trim {label} to lean now? Full backup is safe at {bk.backup_dir}",
+ default=False):
+ if io.last_eof:
+ io.say(f"no terminal: {label} not trimmed (default no); later: "
+ f"sibyl debloat apply {shlex.quote(label)} --yes")
+ records.append({"file": label, "written": False, "declined": True,
+ "before": f.path.stat().st_size, "after": 0})
+ _later_once(report, "sibyl debloat plan")
+ continue
+ # CLI-9: re-verify the actual backup copy of THIS file on disk right
+ # now, instead of trusting the earlier in-memory bk.ok.
+ backup_ok_now = bk.ok and verify_backup_of(f.path, bk.backup_dir, home=home, cwd=cwd)
+ if not backup_ok_now:
+ io.say(f"Backup of {label} could not be re-verified; skipping trim. Original untouched.")
+ records.append({"file": label, "written": False, "before": f.path.stat().st_size,
+ "after": 0, "error": "backup re-verification failed"})
+ _later_once(report, "sibyl debloat plan")
+ continue
+ d = debloat_file(f.path, lean, backup_exists=backup_ok_now)
+ records.append({"file": label, "written": d["written"], "before": d["before"],
+ "after": d["after"], **({"error": d["error"]} if d.get("error") else {})})
+ if d["written"]:
+ io.say(f"Trimmed {label}. Backup safe at {bk.backup_dir}")
+ if records:
+ report["phases"]["debloat"] = records
+ return report
+
+
+def _later_once(report: dict, cmd: str) -> None:
+ later = report.setdefault("later", [])
+ if cmd not in later:
+ later.append(cmd)
+
+
+def _trim_label(f: FoundFile, *, home: Path, cwd: Optional[Path]) -> str:
+ """The name a person recognises: project files relative to the project,
+ home files as ~/."""
+ if cwd is not None:
+ try:
+ return str(Path(f.path).relative_to(Path(cwd)))
+ except ValueError:
+ pass
+ try:
+ return "~/" + str(Path(f.path).relative_to(Path(home)))
+ except ValueError:
+ return f.path.name
+
+
+def _within_roots(p: Path, home: Path, cwd: Optional[Path]) -> bool:
+ ap = Path(os.path.normpath(str(p)))
+ for base in [home] + ([Path(cwd)] if cwd is not None else []):
+ bp = Path(os.path.normpath(str(base)))
+ try:
+ if ap == bp or ap.is_relative_to(bp):
+ return True
+ except ValueError:
+ continue
+ return False
+
+
+def _project_surface(cwd: Optional[Path], home: Path) -> Optional[set]:
+ """Resolved absolute paths named by a project .debloat.json "surface", or
+ None when there is none. Entries outside home and the project are ignored."""
+ if cwd is None:
+ return None
+ cfg = Path(cwd) / ".debloat.json"
+ try:
+ if not cfg.is_file() or cfg.is_symlink() or cfg.stat().st_size > 64 * 1024:
+ return None
+ data = json.loads(cfg.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ surface = data.get("surface") if isinstance(data, dict) else None
+ if not isinstance(surface, list):
+ return None
+ out = set()
+ for entry in surface:
+ if not isinstance(entry, str) or not entry:
+ continue
+ p = Path(entry) if Path(entry).is_absolute() else Path(cwd) / entry
+ if _within_roots(p, home, cwd):
+ out.add(os.path.normpath(str(p)))
+ return out
+
+
+def trim_candidates(files: list[FoundFile], *, home: Path, cwd: Optional[Path]
+ ) -> list[tuple[FoundFile, str]]:
+ """(file, reason-it-is-skipped or '') for every scanned file that is an
+ instruction file, in scan order. Config files never appear; a directory
+ (.cursor/rules) appears with its reason; an empty file is skipped."""
+ surface = _project_surface(cwd, Path(home))
+ out: list[tuple[FoundFile, str]] = []
+ for f in files:
+ if f.matched not in CONTEXT_FILES:
+ continue
+ if surface is not None and os.path.normpath(str(f.path)) not in surface:
+ continue
+ if f.is_dir:
+ out.append((f, "a directory (measured by sibyl debloat, never trimmed)"))
+ continue
+ if f.size <= 0:
+ continue
+ if f.path.is_symlink():
+ out.append((f, "a symlink"))
+ continue
+ out.append((f, ""))
+ return out
+
+
+def lean_text_for(text: str, name: str, backup_dir: Path, *, now=None) -> Optional[str]:
+ """The lean version of an instruction file, or None when there is no safe
+ trim. The safe splitter's CURRENT projection when it finds history
+ (spec 6.2), else the first-H2 rule (heuristic_lean). A result that keeps
+ under 10 % or over 90 % of the original is not a safe trim; neither is a
+ file that is not Markdown or plain text."""
+ try:
+ from sibyl_memory_client.lifecycle import splitter as S
+ except Exception: # pragma: no cover
+ S = None
+ kind = S.kind_for(name) if S is not None else ("markdown" if name.endswith(".md") else None)
+ if kind is None:
+ return None
+ lean = None
+ if S is not None:
+ pl = S.split(text, kind=kind, now=now)
+ if pl.safe:
+ eol = "\r\n" if "\r\n" in text else "\n"
+ sep = "" if (pl.current == "" or pl.current.endswith("\n")) else eol
+ lean = (pl.current + sep + "" + eol)
+ if lean is None:
+ lean = heuristic_lean(text)
+ before, after = len(text.encode("utf-8")), len(lean.encode("utf-8"))
+ if before == 0 or after >= before * 0.9 or after <= before * 0.1:
+ return None
+ return lean
diff --git a/sibyl-memory-cli/src/sibyl_memory_cli/setup.py b/sibyl-memory-cli/src/sibyl_memory_cli/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe3c06d999dc64cd57cbcc3c687115e564f37262
--- /dev/null
+++ b/sibyl-memory-cli/src/sibyl_memory_cli/setup.py
@@ -0,0 +1,4215 @@
+"""`sibyl setup`: auto-detect agent frameworks and wire SIBYL as memory provider.
+
+Maximum-efficiency onboarding command. Single-command path for the user:
+
+ pip install sibyl-memory-cli
+ sibyl setup # auto-detects Hermes, Claude Code, Codex, Cursor and DeepSeek Harness, prompts per stack, wires
+
+Wirers:
+ - HermesWirer: install-plugin + edit $HERMES_HOME/config.yaml (memory.provider)
+ - ClaudeCodeWirer: `claude mcp add --scope user sibyl-memory` (the discovery
+ surface); ~/.claude/settings.json holds the hooks and the
+ skills directory sits beside it
+ - CodexWirer: add [mcp_servers.sibyl_memory] to ~/.codex/config.toml
+ - CursorWirer: mcpServers.sibyl-memory in ~/.cursor/mcp.json (GrokBotWirer,
+ explicit target only, is the same wiring)
+ - DeepSeekWirer: one @deepseek-ai/dsh-mcp-client insert row in a DeepSeek
+ Harness patch file ($DSH_HOME or ~/.dsh, cordis.patch.yml),
+ edited as text and verified before every write
+
+Each wirer follows the same protocol:
+ is_present() -> bool (filesystem + PATH detect)
+ current_state() -> dict (configured? wired-with-sibyl? current-value?)
+ wire(force, dry_run, prompt_fn) -> WireOutcome
+
+Destructive operations (overwriting an existing non-SIBYL config) default to NO
+on the prompt. Fresh adds default to YES. --force overrides destructive guards.
+--yes accepts all defaults (still respects the destructive-default-NO unless
+--force is also passed). --dry-run prints intent without writing.
+
+All config edits are atomic: back up to
+~/.sibyl-memory/backups//..bak (0600), write a
+temp file beside the target, rename (the temp file is removed on failure).
+"""
+from __future__ import annotations
+
+import argparse
+import contextlib
+import json
+import os
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Optional, Union
+
+
+def backups_root() -> Path:
+ """Where every wirer's config backups live (cli 0.7.0): under the plugin
+ home, never beside the harness's own config. Computed at call time so an
+ isolated HOME (tests, sandboxes) is honored."""
+ return Path.home() / ".sibyl-memory" / "backups"
+
+
+def _timestamped_backup(path: Path, harness: str = "other", sub: str = "") -> Optional[Path]:
+ """Copy ``path`` to ``~/.sibyl-memory/backups/[/]/`` and
+ return the backup path (or None if the source does not exist).
+
+ B005 (audit #19): every run keeps its own backup. The name is the original
+ file name plus a UTC timestamp, e.g. ``config.yaml.20260630T142530Z.bak``;
+ a second backup in the same second gets ``.2.bak`` (up to ``.99.bak``) and
+ an existing file is never overwritten (O_EXCL). The timestamp is computed
+ BEFORE it is used in the file name.
+
+ cli 0.7.0 (one footprint): backups used to sit beside the harness config.
+ They now go under the plugin home with directories 0700 and files 0600
+ (a config backup can carry secrets), whatever the source's mode was.
+ Raises OSError (``_fsio.RefusedPath`` for a symlinked or non-directory
+ backup folder) when the backup cannot be written; callers then leave the
+ config alone.
+ """
+ if not path.exists():
+ return None
+ from sibyl_memory_client import _fsio
+ plugin_home = Path.home() / ".sibyl-memory"
+ if not plugin_home.exists():
+ plugin_home.mkdir(parents=True, exist_ok=True, mode=0o700)
+ d = _fsio.ensure_private_dir(backups_root())
+ d = _fsio.ensure_private_dir(d / harness)
+ if sub:
+ d = _fsio.ensure_private_dir(d / sub)
+ ts = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
+ data = path.read_bytes()
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
+ for n in range(1, 100):
+ name = f"{path.name}.{ts}.bak" if n == 1 else f"{path.name}.{ts}.{n}.bak"
+ dest = d / name
+ try:
+ fd = os.open(str(dest), flags, 0o600)
+ except FileExistsError:
+ continue
+ try:
+ with os.fdopen(fd, "wb") as fh:
+ fh.write(data)
+ fh.flush()
+ os.fsync(fh.fileno())
+ try:
+ os.fchmod(fh.fileno(), 0o600)
+ except (OSError, AttributeError):
+ pass
+ except BaseException:
+ try:
+ os.unlink(str(dest))
+ except OSError:
+ pass
+ raise
+ return dest
+ raise FileExistsError(f"too many backups of {path.name} in one second under {d}")
+
+
+def _probe(entry: str, config_path: Any, *, command: Optional[str] = None, location: str = "",
+ detail: str = "", **extra: Any) -> dict:
+ """One doctor probe record (spec dsh-doctor v2, section 4). ``detail``
+ never holds file contents: paths, commands and fixed wording only."""
+ d = {"entry": entry, "command": command, "config_path": str(config_path),
+ "location": location, "detail": detail}
+ d.update(extra)
+ return d
+
+
+def _is_our_command(cmd: Any) -> bool:
+ return bool(isinstance(cmd, str) and cmd
+ and Path(cmd.replace("\\", "/")).name.startswith(MCP_BINARY_NAME))
+
+
+def _backup_failed(name: str, config: Path, harness: str, e: BaseException) -> "WireOutcome":
+ """Uniform outcome when a backup cannot be written: the config is left alone."""
+ return WireOutcome(name, "error",
+ f"could not back up {config} to {backups_root() / harness} "
+ f"({type(e).__name__}); {config} was not modified")
+
+
+def _current_umask() -> int:
+ old = os.umask(0o022)
+ os.umask(old)
+ return old
+
+
+def _write_via_tmp(target: Path, tmp: Path, text: str, *, through_symlink: bool = False) -> None:
+ """Write ``text`` to a new temp file beside ``target`` and rename it over
+ ``target``, keeping ``target``'s mode.
+
+ Panel fix 5 (2026-11-14): the temp file is created with
+ O_CREAT | O_EXCL | O_NOFOLLOW under a unique name derived from ``tmp``
+ (never a fixed name another run or a pre-placed symlink can share), its
+ mode is set to the target's mode (0666 & ~umask for a new file) BEFORE any
+ content is written, the data is fsync'ed before the rename and the
+ directory after it, and only this run's own temp file is removed on
+ failure. The text is written as UTF-8 bytes with no newline translation.
+
+ ``through_symlink`` (Cursor, Codex and Hermes, CHECK-FABLE N-2): when
+ ``target`` is a symlink, the file it resolves to is replaced (the temp file
+ sits beside that file) and the link itself is kept, so a config kept in a
+ dotfiles folder stays linked and current. Without it a symlinked target is
+ replaced by a regular file, as before."""
+ import secrets
+ target = Path(target)
+ tmp = Path(tmp)
+ if through_symlink and target.is_symlink():
+ target = Path(os.path.realpath(str(target)))
+ parent = target.parent
+ try:
+ mode = target.stat().st_mode & 0o777
+ except FileNotFoundError:
+ mode = 0o666 & ~_current_umask()
+ data = text.encode("utf-8")
+ flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
+ | getattr(os, "O_CLOEXEC", 0))
+ fd = -1
+ tmp_path: Optional[Path] = None
+ for _ in range(20):
+ cand = parent / f"{tmp.stem}.{secrets.token_hex(6)}{tmp.suffix}"
+ try:
+ fd = os.open(str(cand), flags, 0o600)
+ except FileExistsError:
+ continue
+ tmp_path = cand
+ break
+ if tmp_path is None:
+ raise FileExistsError(f"could not create a temp file beside {target}")
+ try:
+ try:
+ os.fchmod(fd, mode)
+ except (OSError, AttributeError):
+ pass
+ fh = os.fdopen(fd, "wb")
+ fd = -1
+ with fh:
+ fh.write(data)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(str(tmp_path), str(target))
+ tmp_path = None
+ try:
+ dfd = os.open(str(parent), os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
+ except OSError:
+ dfd = -1
+ if dfd >= 0:
+ try:
+ os.fsync(dfd)
+ except OSError:
+ pass
+ finally:
+ os.close(dfd)
+ except BaseException:
+ if fd >= 0:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ if tmp_path is not None:
+ try:
+ os.unlink(str(tmp_path))
+ except OSError:
+ pass
+ raise
+
+
+def _verify_mcp_starts(binary: Optional[str]) -> tuple:
+ """Smoke-test an MCP stdio server binary: spawn it and confirm it does not
+ crash on startup. Returns (ok: bool, message: str).
+
+ B005 (audit #19): this was a method on ClaudeCodeWirer that CodexWirer
+ called via the fragile cross-class dispatch
+ ``ClaudeCodeWirer.verify_mcp_starts(self)``. Pulled out to a standalone
+ helper so both wirers share one implementation cleanly. The only state it
+ needed was the resolved binary path, so it takes that as an argument.
+
+ Catches the common failures: ImportError (missing dep),
+ ModuleNotFoundError, bad credentials file — all of which manifest within
+ the first second as a non-zero exit. A slow-but-alive import is treated as
+ healthy (it is blocking on stdin), not crashed.
+ """
+ if not binary:
+ return False, "MCP binary not found"
+ try:
+ proc = subprocess.Popen(
+ [binary],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ # CLI-12: MCP stdio servers block on stdin; a crash-on-import exits
+ # quickly with a non-zero code. POLL the exit code over a short window
+ # instead of a fixed sleep — a slow import (cold caches, heavy deps)
+ # that is still alive at the deadline is treated as healthy.
+ deadline = time.monotonic() + 3.0
+ rc = None
+ while time.monotonic() < deadline:
+ rc = proc.poll()
+ if rc is not None:
+ break
+ time.sleep(0.1)
+ if rc is not None and rc != 0:
+ # CLI-12: bound the stderr read so a server that floods stderr
+ # before exiting can't make us block on an unbounded read.
+ try:
+ err = (proc.stderr.read(4096) or b"").decode(errors="replace").strip()
+ except Exception:
+ err = ""
+ return False, f"Server crashed on startup (exit {rc}): {err[:200]}"
+ if rc == 0:
+ # Exited cleanly without blocking — unusual for a stdio server but
+ # not a crash.
+ return True, "MCP server verified (exited cleanly)"
+ # Still running (blocking on stdin) — binary works.
+ proc.terminate()
+ try:
+ proc.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+ return True, "MCP server verified (starts cleanly)"
+ except Exception as e:
+ return False, f"Could not start server: {type(e).__name__}: {e}"
+
+
+def _run(cmd: list[str], *, timeout: float = 20.0) -> tuple[int, str, str]:
+ """Run a command, return (rc, stdout, stderr). rc=127 if not found, 124 on timeout.
+ Centralized so tests can monkeypatch one place."""
+ try:
+ p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
+ return p.returncode, (p.stdout or ""), (p.stderr or "")
+ except FileNotFoundError:
+ return 127, "", "command not found"
+ except subprocess.TimeoutExpired:
+ return 124, "", "timed out"
+ except Exception as e: # never let a wirer crash the whole flow
+ return 1, "", f"{type(e).__name__}: {e}"
+
+
+def _install_pkg_or_instruct(package: str) -> Optional[str]:
+ """Attempt to install `package` into the current interpreter, respecting PEP 668.
+
+ CLI-11: in an externally-managed (PEP 668) or pipx-managed environment we do
+ NOT silently `pip install` (that mutates a system/managed env and surprises
+ the user). We return an instruction string instead. For a plain venv/system
+ install we run pip with output captured and return the captured stderr/stdout
+ on failure so the caller can surface it. Returns None on success, otherwise a
+ human-readable error/instruction string."""
+ try:
+ from .cli import _detect_install_method
+ method = _detect_install_method()
+ except Exception:
+ method = "system"
+
+ if method == "pep668":
+ return (
+ f"'{package}' is missing and this Python is externally-managed (PEP 668). "
+ f"Install it yourself, ideally in a venv:\n"
+ f" pip install {package}\n"
+ f" or, if you understand the risk:\n"
+ f" pip install --break-system-packages {package}"
+ )
+ if method == "pipx":
+ return (
+ f"'{package}' is missing and the CLI is running under pipx. "
+ f"Inject it into the pipx venv:\n"
+ f" pipx inject sibyl-memory-cli {package}"
+ )
+ rc, out, err = _run([sys.executable, "-m", "pip", "install", package], timeout=120.0)
+ if rc == 0:
+ return None
+ detail = (err or out or "").strip()
+ return f"pip install {package} failed (exit {rc}): {detail[:400]}" if detail \
+ else f"pip install {package} failed (exit {rc})."
+
+# Color helpers re-imported from cli module via late binding to avoid circular dep.
+# When called via `sibyl setup` they resolve through the cli module's tty detection.
+def _color_fns():
+ from .cli import bold, cyan, dim, green, red, yellow
+ return bold, cyan, dim, green, red, yellow
+
+
+# ----------------------------------------------------------------------
+# WireOutcome
+# ----------------------------------------------------------------------
+
+@dataclass
+class WireOutcome:
+ """Result of a wirer.wire() call. Composable across multiple wirers."""
+ name: str
+ status: str # 'wired' / 'already' / 'skipped' / 'dry-run' / 'error'
+ message: str
+ backup_path: Optional[Path] = None
+ # Save/debloat build: one line per skill file, shim, hook or instruction
+ # block the wirer wrote (or would write, on --dry-run).
+ lifecycle: list = field(default_factory=list)
+ # Agent handoff (spec 2026-10-03 rows X8 to X11): (next, human, later) for
+ # an error outcome; `overwrite_of` names what an existing entry is when the
+ # wirer stopped short of replacing it (X6).
+ handoff: Optional[tuple] = None
+ overwrite_of: Optional[str] = None
+ # Panel fix 8: text the person pastes by hand (valid YAML or TOML as
+ # printed). It is also the tail of ``message``; doctor prints it on its
+ # own lines instead of folding it into one.
+ manual_block: Optional[str] = None
+
+
+PEP668_HUMAN = ("this Python is externally managed (PEP 668); choose a venv or allow "
+ "--break-system-packages")
+
+
+def _binary_missing_handoff(name: str) -> tuple:
+ """Row X9: the MCP binary is missing; how to get it depends on the install."""
+ try:
+ from .cli import _detect_install_method
+ method = _detect_install_method()
+ except Exception:
+ method = "system"
+ if method == "pep668":
+ return ("done", PEP668_HUMAN, ())
+ if method == "pipx":
+ return ("pipx inject sibyl-memory-cli sibyl-memory-mcp", None, (f"sibyl setup {name}",))
+ return ("pip install sibyl-memory-mcp", None, (f"sibyl setup {name}",))
+
+
+# ----------------------------------------------------------------------
+# Save / debloat wiring (spec plugin-save-debloat 3.5). Shared by the three
+# wirers: the canonical procedure files in ~/.sibyl-memory/skills/, one thin
+# shim per harness, the Claude Code hooks, the Codex AGENTS.md block.
+# ----------------------------------------------------------------------
+
+HOOK_EVENTS: tuple = (
+ ("SessionStart", "session-start"),
+ ("UserPromptSubmit", "prompt"),
+ ("Stop", "stop"),
+ ("PreCompact", "pre-compact"),
+ ("SessionEnd", "session-end"),
+)
+# 5 s kept after measuring (release notes): the slowest hook, a Pro
+# SessionStart that trims a file, takes about 0.3 s end to end and never waits
+# on the network; a longer timeout would only lengthen a stall.
+HOOK_TIMEOUT_SECONDS = 5
+_HOOK_ARGS = "|".join(a for _e, a in HOOK_EVENTS)
+# Our entries are recognised by their command: `/sibyl hook `
+# (quoted or not), optionally inside the guard hook_command writes
+# (`[ -x ] && exec hook ; exit 0`). No extra key is added
+# to the hook object, so nothing the settings schema does not know ever lands
+# in a person's settings.json.
+_OUR_HOOK_RE = re.compile(r"(?:^|[/\\'\"\s])sibyl(?:\.exe)?['\"]?\s+hook\s+(" + _HOOK_ARGS
+ + r")\s*(?:;\s*exit\s+0\s*)?$")
+
+CODEX_BLOCK_BEGIN = ""
+CODEX_BLOCK_END = ""
+CODEX_BLOCK_BODY = (
+ "## Sibyl Memory\n"
+ "Sibyl Memory is wired (MCP server `sibyl_memory`). To save a session, read "
+ "`~/.sibyl-memory/skills/SAVE.md` and follow it (triggers: save, save session, sync "
+ "memory). To measure or trim always-loaded context files, read "
+ "`~/.sibyl-memory/skills/DEBLOAT.md`. Both are also MCP prompts on the `sibyl_memory` "
+ "server (`save`, `debloat`). When a Sibyl Memory tool result carries a `notice` asking you "
+ "to save, run the save procedure in headless mode, then continue the task."
+)
+
+
+def _skills_mod():
+ try:
+ from sibyl_memory_client import skills
+ return skills
+ except Exception: # pragma: no cover - client without the skills module
+ return None
+
+
+def sibyl_binary() -> str:
+ """Absolute path of the `sibyl` command for hook entries (a hook runs from
+ Claude Code's own PATH, which may not include a venv's bin: the lesson
+ from the MCP registration)."""
+ w = shutil.which("sibyl")
+ if w:
+ return os.path.abspath(w)
+ cand = Path(sys.executable).parent / "sibyl"
+ if cand.exists():
+ return str(cand)
+ return "sibyl"
+
+
+def hook_command(binary: str, event_arg: str) -> str:
+ """The settings.json command for one hook. Claude Code runs a command
+ hook through the shell (bash; the 2.1.283 schema: "Shell command to
+ execute"), so an absolute path is wrapped in a guard: when the package was
+ uninstalled without `sibyl skills uninstall`, the hook exits 0 silently
+ instead of failing at every session start, prompt and turn end. The path
+ is written twice rather than through a variable (no `$` in the command)."""
+ q = shlex.quote(binary)
+ if os.name != "nt" and os.path.isabs(binary):
+ return f"[ -x {q} ] && exec {q} hook {event_arg}; exit 0"
+ return f"{q} hook {event_arg}"
+
+
+def is_our_hook(h: Any) -> bool:
+ return (isinstance(h, dict) and h.get("type") == "command"
+ and isinstance(h.get("command"), str) and bool(_OUR_HOOK_RE.search(h["command"])))
+
+
+def merge_hooks(cfg: dict, binary: str) -> dict:
+ """Return ``cfg`` with our five hook entries (replacing any previous ones
+ of ours) and every other hook, matcher group and key left as it was.
+ Raises ValueError when ``hooks`` exists but is not the documented shape
+ (never clobbered)."""
+ out = dict(cfg)
+ hooks = out.get("hooks", {})
+ if not isinstance(hooks, dict):
+ raise ValueError("settings.json 'hooks' is not an object; left unchanged")
+ hooks = dict(hooks)
+ for event, arg in HOOK_EVENTS:
+ groups = hooks.get(event, [])
+ if not isinstance(groups, list):
+ raise ValueError(f"settings.json hooks.{event} is not a list; left unchanged")
+ kept = []
+ for g in groups:
+ if isinstance(g, dict) and isinstance(g.get("hooks"), list):
+ rest = [h for h in g["hooks"] if not is_our_hook(h)]
+ if len(rest) == len(g["hooks"]):
+ kept.append(g)
+ elif rest:
+ kept.append({**g, "hooks": rest})
+ else:
+ kept.append(g)
+ kept.append({"hooks": [{"type": "command", "command": hook_command(binary, arg),
+ "timeout": HOOK_TIMEOUT_SECONDS}]})
+ hooks[event] = kept
+ out["hooks"] = hooks
+ return out
+
+
+def remove_hooks(cfg: dict) -> dict:
+ out = dict(cfg)
+ hooks = out.get("hooks")
+ if not isinstance(hooks, dict):
+ return out
+ hooks = dict(hooks)
+ for event, _arg in HOOK_EVENTS:
+ groups = hooks.get(event)
+ if not isinstance(groups, list):
+ continue
+ kept = []
+ for g in groups:
+ if isinstance(g, dict) and isinstance(g.get("hooks"), list):
+ rest = [h for h in g["hooks"] if not is_our_hook(h)]
+ if rest:
+ kept.append({**g, "hooks": rest} if len(rest) != len(g["hooks"]) else g)
+ else:
+ kept.append(g)
+ if kept:
+ hooks[event] = kept
+ else:
+ hooks.pop(event, None)
+ out["hooks"] = hooks
+ if not hooks:
+ out.pop("hooks")
+ return out
+
+
+def count_our_hooks(cfg: Any) -> int:
+ if not isinstance(cfg, dict) or not isinstance(cfg.get("hooks"), dict):
+ return 0
+ n = 0
+ for groups in cfg["hooks"].values():
+ if isinstance(groups, list):
+ for g in groups:
+ if isinstance(g, dict) and isinstance(g.get("hooks"), list):
+ n += sum(1 for h in g["hooks"] if is_our_hook(h))
+ return n
+
+
+def install_canonical_skills(*, dry_run: bool = False, force: bool = False) -> list:
+ """~/.sibyl-memory/skills/{SAVE,DEBLOAT}.md (never overwriting an edit)."""
+ sk = _skills_mod()
+ if sk is None:
+ return ["skills: sibyl-memory-client has no skills module; update it"]
+ d = sk.skills_dir(Path.home())
+ if dry_run:
+ return _dry_run_skills(sk, d, force=force)
+ rep = sk.install(Path.home(), force=force)
+ lines = [f"skills v{rep.version}: " + ", ".join(f"{n} {s}" for n, s in rep.results.items())]
+ lines.extend(rep.messages)
+ return lines
+
+
+# `sibyl setup --dry-run` compares with what is installed
+# and says "already in" for skills, shims, hooks and the Codex block that are
+# already there, as it does for the MCP server. Reads only; never writes.
+
+def _dry_run_skills(sk, d: Path, *, force: bool = False) -> list:
+ status = getattr(sk, "status", None)
+ try:
+ files = status(Path.home()).get("files", {}) if callable(status) else {}
+ except Exception:
+ files = {}
+ names = tuple(getattr(sk, "SKILL_NAMES", ("SAVE.md", "DEBLOAT.md")))
+ states = {n: (files.get(n) or {}).get("state") for n in names}
+ if names and all(st == "ok" for st in states.values()):
+ return [f"skills v{sk.version()}: {', '.join(names)} already in {d}"]
+ lines = []
+ for n in names:
+ st = states.get(n)
+ if st == "ok":
+ lines.append(f"skills: {n} already in {d}")
+ elif st == "outdated":
+ lines.append(f"would update {d}/{n} (v{sk.version()})")
+ elif st == "edited":
+ lines.append(f"would replace your edited {d}/{n}" if force
+ else f"would keep {d}/{n} (edited by you; the new version goes beside it)")
+ elif st in ("symlink", "oversize"):
+ lines.append(f"would leave {d}/{n} alone ({st})")
+ else:
+ lines.append(f"would install {d}/{n} (v{sk.version()})")
+ return lines
+
+
+def _dry_run_shim(sk, name: str, harness: str, path, *, force: bool = False) -> str:
+ p = Path(path)
+ try:
+ want = sk.shim_text(name, harness).encode("utf-8")
+ except Exception:
+ return f"would write shim {p}"
+ if p.is_symlink():
+ return f"would leave shim {p} alone (symlink)"
+ if not p.exists():
+ return f"would write shim {p}"
+ try:
+ cur = p.read_bytes() if p.is_file() and p.stat().st_size <= 262144 else None
+ except OSError:
+ cur = None
+ if cur == want:
+ return f"shim {p}: already in"
+ recorded = None
+ status = getattr(sk, "status", None)
+ try:
+ recorded = (status(Path.home()).get("shims", {}).get(str(p)) or {}).get("state") if callable(status) else None
+ except Exception:
+ recorded = None
+ if recorded == "ok" or force:
+ return f"would update shim {p}"
+ return f"would keep shim {p} (edited by you)"
+
+
+def install_shims(harness: str, targets: dict, *, dry_run: bool = False, force: bool = False) -> list:
+ """``targets``: {skill name: shim path}."""
+ sk = _skills_mod()
+ if sk is None:
+ return []
+ lines = []
+ for name, path in targets.items():
+ if dry_run:
+ lines.append(_dry_run_shim(sk, name, harness, path, force=force))
+ continue
+ st = sk.install_shim(Path.home(), path, sk.shim_text(name, harness), harness=harness,
+ skill=name, force=force)
+ lines.append(f"shim {path}: {st}")
+ if st == "user_modified":
+ lines.append(f" {path} was edited by you and was kept (sibyl skills status).")
+ return lines
+
+
+def _atomic_text(path: Path, text: str) -> None:
+ if path.is_symlink():
+ raise ValueError(f"{path} is a symlink; not followed")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix="." + path.name + ".", suffix=".sibyl-tmp")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ fh.write(text)
+ fh.flush()
+ os.fsync(fh.fileno())
+ try:
+ os.chmod(tmp, (path.stat().st_mode & 0o777) if path.exists() else 0o644)
+ except OSError:
+ pass
+ os.replace(tmp, str(path))
+ except BaseException:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ raise
+
+
+def codex_block() -> str:
+ return f"{CODEX_BLOCK_BEGIN}\n{CODEX_BLOCK_BODY}\n{CODEX_BLOCK_END}\n"
+
+
+def upsert_block(existing: str, block: str) -> str:
+ """Insert ``block`` once, or replace it in place between the markers;
+ the text around it is untouched."""
+ b = existing.find(CODEX_BLOCK_BEGIN)
+ if b != -1:
+ e = existing.find(CODEX_BLOCK_END, b)
+ if e != -1:
+ e_end = e + len(CODEX_BLOCK_END)
+ if existing[e_end:e_end + 1] == "\n":
+ e_end += 1
+ return existing[:b] + block + existing[e_end:]
+ if not existing:
+ return block
+ sep = "" if existing.endswith("\n\n") else ("\n" if existing.endswith("\n") else "\n\n")
+ return existing + sep + block
+
+
+def remove_block(existing: str) -> str:
+ b = existing.find(CODEX_BLOCK_BEGIN)
+ if b == -1:
+ return existing
+ e = existing.find(CODEX_BLOCK_END, b)
+ if e == -1:
+ return existing
+ e_end = e + len(CODEX_BLOCK_END)
+ if existing[e_end:e_end + 1] == "\n":
+ e_end += 1
+ head = existing[:b]
+ if head.endswith("\n\n"):
+ head = head[:-1]
+ out = head + existing[e_end:]
+ return out
+
+
+# ----------------------------------------------------------------------
+# Lazy YAML import. Hermes wirer needs it; Claude-only users do not.
+# ----------------------------------------------------------------------
+
+def _import_yaml():
+ try:
+ import yaml
+ return yaml
+ except ImportError:
+ return None
+
+
+# ----------------------------------------------------------------------
+# Tolerant YAML reader for DeepSeek Harness patch files (spec dsh-doctor v2,
+# 3.2). Read-only: used to locate nodes and to prove that edited text parses
+# to exactly the intended result. Nothing is ever re-serialized.
+#
+# PyYAML is not js-yaml: it accepts !!timestamp, !!binary, merge keys, YAML
+# 1.1 booleans and duplicate mapping keys, which js-yaml JSON_SCHEMA (what
+# DeepSeek Harness uses) rejects or reads differently. That is harmless here
+# because existing bytes are never changed outside the one span we replace and
+# our own text is fixed, but a file PyYAML accepts can still be invalid for
+# DeepSeek Harness.
+# ----------------------------------------------------------------------
+
+DSH_JS_TAG = "tag:yaml.org,2002:js"
+
+
+class _JsExpr(str):
+ """A `!!js` scalar from a DeepSeek Harness patch file. Kept as text, never
+ evaluated. It is a str subclass, so == cannot tell it from a plain string;
+ callers that need to know check type(x) is _JsExpr."""
+
+
+_DSH_LOADER: Any = None
+
+
+def _dsh_loader_cls():
+ """A SafeLoader subclass that accepts the one custom tag DeepSeek Harness
+ uses (`!!js`). Built lazily so PyYAML stays a lazy import; the global
+ SafeLoader is not mutated."""
+ global _DSH_LOADER
+ if _DSH_LOADER is None:
+ yaml = _import_yaml()
+ if yaml is None:
+ raise ImportError("PyYAML is not installed")
+
+ class _DshLoader(yaml.SafeLoader):
+ pass
+
+ _DshLoader.add_constructor(DSH_JS_TAG, lambda l, n: _JsExpr(l.construct_scalar(n)))
+ _DSH_LOADER = _DshLoader
+ return _DSH_LOADER
+
+
+def _dsh_yaml_load(text: str):
+ """Parse one YAML document (raises on anything PyYAML rejects, including a
+ second document)."""
+ yaml = _import_yaml()
+ return yaml.load(text, Loader=_dsh_loader_cls())
+
+
+def _dsh_yaml_compose(text: str):
+ """The node tree with marks (character offsets into ``text``), or None."""
+ yaml = _import_yaml()
+ return yaml.compose(text, Loader=_dsh_loader_cls())
+
+
+def _yaml_error_brief(e: BaseException) -> str:
+ """The only way a YAML error reaches a message, a detail field or a log:
+ the exception type and the line and column, never str(e), e.problem or
+ e.context (those can carry text from the file, a secret included)."""
+ name = type(e).__name__
+ mark = getattr(e, "problem_mark", None)
+ line = getattr(mark, "line", None)
+ col = getattr(mark, "column", None)
+ if isinstance(line, int) and isinstance(col, int):
+ return f"{name} at line {line + 1}, column {col + 1}"
+ return name
+
+
+# ----------------------------------------------------------------------
+# HermesWirer
+# ----------------------------------------------------------------------
+
+class _HermesConfigNotMapping(ValueError):
+ """Raised by HermesWirer._write_config_with_sibyl itself; its text holds a
+ path and a type name only, so it may be shown."""
+
+
+class _HandoffHold:
+ """stdout for the Hermes installer: everything passes through as written
+ except the handoff lines (next:, later:, ask your human:), which are held
+ while they are the last lines seen and then printed or dropped by
+ ``release``. Colors and tty checks still see the real stream."""
+
+ _PREFIXES = ("next:", "later:", "ask your human:")
+
+ def __init__(self, real) -> None:
+ self._real = real
+ self._partial = ""
+ self._held: list = []
+
+ def write(self, data: str) -> int:
+ text = self._partial + data
+ lines = text.split("\n")
+ self._partial = lines.pop()
+ for ln in lines:
+ if ln.startswith(self._PREFIXES):
+ self._held.append(ln + "\n")
+ else:
+ self._emit_held()
+ self._real.write(ln + "\n")
+ return len(data)
+
+ def _emit_held(self) -> None:
+ for h in self._held:
+ self._real.write(h)
+ self._held = []
+
+ def release(self, keep: bool) -> None:
+ if keep:
+ self._emit_held()
+ if self._partial:
+ self._real.write(self._partial)
+ elif self._partial and not self._partial.startswith(self._PREFIXES):
+ self._real.write(self._partial)
+ self._held, self._partial = [], ""
+ self.flush()
+
+ def flush(self) -> None:
+ try:
+ self._real.flush()
+ except Exception:
+ pass
+
+ def __getattr__(self, name):
+ return getattr(self._real, name)
+
+
+class _HermesManualEdit(ValueError):
+ """Raised by HermesWirer._write_config_with_sibyl when the text edit
+ cannot be made or proven (panel fix 1); config.yaml is not modified."""
+
+
+class _HermesPluginRefused(RuntimeError):
+ """sibyl_memory_hermes.install_plugin.install() returned a refusal code
+ (panel fix 4): 2 folder not empty, 3 symlink, 4 not a Sibyl install."""
+
+ def __init__(self, rc: int, dest: Path):
+ super().__init__(f"install-plugin refused (code {rc})")
+ self.rc = rc
+ self.dest = dest
+
+
+_HERMES_NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,40}$")
+HERMES_MANUAL_LINES = ("memory:", " provider: sibyl")
+
+
+def _hermes_provider_text(text: str) -> Optional[str]:
+ """config.yaml text with memory.provider set to sibyl, edited as text
+ (panel fix 1), or None when the edit cannot be made or proven. Nothing is
+ re-serialized: with the node marks from yaml.compose, an existing
+ memory.provider scalar is replaced in place, a block `memory:` mapping
+ without provider gets one line, a scalar or empty `memory` value becomes
+ `{provider: sibyl}`, and a file with no `memory` key gets two lines
+ appended. The file's line ending is kept. The proof: yaml.safe_load of the
+ new text equals the old data with only memory.provider changed."""
+ import copy
+ yaml = _import_yaml()
+ if yaml is None:
+ return None
+ nl = "\r\n" if "\r\n" in text else "\n"
+ old = yaml.safe_load(text)
+ if old is None:
+ old = {}
+ if not isinstance(old, dict):
+ return None
+ want = copy.deepcopy(old)
+ if isinstance(want.get("memory"), dict):
+ want["memory"]["provider"] = "sibyl"
+ else:
+ want["memory"] = {"provider": "sibyl"}
+ root = yaml.compose(text)
+ append = f"memory:{nl} provider: sibyl{nl}"
+
+ def _appended() -> str:
+ sep = "" if (text == "" or text.endswith("\n")) else nl
+ return text + sep + append
+
+ new: Optional[str] = None
+ if root is None:
+ new = _appended()
+ elif (type(root).__name__ == "MappingNode" and not root.flow_style
+ and root.start_mark.column == 0):
+ pairs = [(k, v) for k, v in root.value
+ if type(k).__name__ == "ScalarNode" and k.value == "memory"]
+ if len(pairs) > 1:
+ return None
+ if not pairs:
+ new = _appended()
+ else:
+ k, v = pairs[0]
+ a, b = v.start_mark.index, v.end_mark.index
+ if a < k.end_mark.index:
+ return None # an alias to a node defined earlier
+ kind = type(v).__name__
+ if kind == "MappingNode" and not v.flow_style and v.value:
+ prov = [(pk, pv) for pk, pv in v.value
+ if type(pk).__name__ == "ScalarNode" and pk.value == "provider"]
+ if len(prov) > 1:
+ return None
+ if prov:
+ pk, pv = prov[0]
+ pa, pb = pv.start_mark.index, pv.end_mark.index
+ if (type(pv).__name__ != "ScalarNode" or pv.style not in (None, "'", '"')
+ or pa < pk.end_mark.index or pa == pb):
+ return None
+ new = text[:pa] + "sibyl" + text[pb:]
+ else:
+ fk = v.value[0][0]
+ idx, col = fk.start_mark.index, fk.start_mark.column
+ ls = idx - col
+ if ls < 0 or text[ls:idx].strip(" ") != "":
+ return None
+ new = text[:ls] + " " * col + "provider: sibyl" + nl + text[ls:]
+ elif kind == "MappingNode" and v.flow_style and not v.value:
+ new = text[:a] + "{provider: sibyl}" + text[b:]
+ elif kind == "ScalarNode" and v.style in (None, "'", '"'):
+ if a == b:
+ new = text[:a] + " {provider: sibyl}" + text[b:]
+ else:
+ new = text[:a] + "{provider: sibyl}" + text[b:]
+ else:
+ return None
+ else:
+ return None
+ try:
+ got = yaml.safe_load(new)
+ except Exception:
+ return None
+ if got != want:
+ return None
+ return new
+
+
+class HermesWirer:
+ name = "hermes"
+ display_name = "Hermes"
+ initial = "h"
+ BACKUP_LABEL = "hermes"
+
+ def __init__(self, *, hermes_home: Optional[Union[str, Path]] = None):
+ self.hermes_home = (
+ Path(hermes_home).expanduser() if hermes_home
+ else self._auto_hermes_home()
+ )
+ self.config_path = self.hermes_home / "config.yaml"
+ self.plugin_dir = self.hermes_home / "plugins" / "sibyl"
+
+ @staticmethod
+ def _auto_hermes_home() -> Path:
+ env = os.environ.get("HERMES_HOME")
+ if env:
+ return Path(env).expanduser()
+ return Path.home() / ".hermes"
+
+ def is_present(self) -> bool:
+ # Present if HERMES_HOME exists OR `hermes` binary on PATH
+ if self.hermes_home.exists():
+ return True
+ if shutil.which("hermes"):
+ return True
+ return False
+
+ def current_state(self) -> dict:
+ config_exists = self.config_path.exists()
+ plugin_installed = (self.plugin_dir / "__init__.py").exists()
+ memory_provider: Optional[str] = None
+ if config_exists:
+ yaml = _import_yaml()
+ if yaml is not None:
+ try:
+ raw = self.config_path.read_text(encoding="utf-8")
+ cfg = yaml.safe_load(raw) or {}
+ if isinstance(cfg, dict):
+ mem = cfg.get("memory")
+ if isinstance(mem, dict):
+ memory_provider = mem.get("provider")
+ elif mem is not None:
+ # Panel fix 1: `memory: honcho` or `memory: true` is
+ # an existing setting, so the overwrite gate runs.
+ label = str(mem) if (isinstance(mem, (str, int, float, bool))
+ and _HERMES_NAME_RE.match(str(mem))) \
+ else "a non-mapping value"
+ memory_provider = f"memory: {label}"
+ except Exception:
+ pass
+ return {
+ "hermes_home": str(self.hermes_home),
+ "config_path": str(self.config_path),
+ "config_exists": config_exists,
+ "plugin_installed": plugin_installed,
+ "memory_provider": memory_provider,
+ "wired_with_sibyl": memory_provider == "sibyl",
+ }
+
+ def skill_shim_targets(self) -> dict:
+ """hermes-agent 0.19.0 documents ~/.hermes/skills/ (hermes_constants.
+ get_skills_dir() = $HERMES_HOME/skills; SKILL.md with name +
+ description frontmatter, discovered recursively)."""
+ sk = _skills_mod()
+ names = sk.SHIM_NAMES if sk is not None else {}
+ return {n: self.hermes_home / "skills" / s / "SKILL.md" for n, s in names.items()}
+
+ def wire_lifecycle(self, *, force: bool = False, dry_run: bool = False) -> list:
+ lines = install_canonical_skills(dry_run=dry_run)
+ lines += install_shims("hermes", self.skill_shim_targets(), dry_run=dry_run, force=force)
+ return lines
+
+ def wire(self, *, force: bool = False, dry_run: bool = False,
+ prompt_fn: Optional[Callable[..., str]] = None) -> WireOutcome:
+ out = self._wire_provider(force=force, dry_run=dry_run, prompt_fn=prompt_fn)
+ if out.status in ("wired", "already", "dry-run"):
+ try:
+ out.lifecycle = self.wire_lifecycle(force=force, dry_run=dry_run)
+ except Exception as e: # never fail the provider wiring on the extras
+ out.lifecycle = [f"skills not installed: {type(e).__name__}: {e}"]
+ return out
+
+ def _wire_provider(self, *, force: bool = False, dry_run: bool = False,
+ prompt_fn: Optional[Callable[..., str]] = None) -> WireOutcome:
+ state = self.current_state()
+ yaml = _import_yaml()
+ if yaml is None:
+ return WireOutcome(
+ self.name, "error",
+ "PyYAML not installed. Run `pip install pyyaml` and retry.",
+ handoff=("pip install pyyaml", None, ("sibyl setup hermes",)),
+ )
+
+ # 0. A config.yaml that cannot be read stops here, before any install,
+ # backup or write (CHECK-FABLE B-1). Only the error type and its
+ # line and column are reported: never the file text, which can hold
+ # credentials (spec 3.2).
+ if self.config_path.exists():
+ try:
+ yaml.safe_load(self.config_path.read_text(encoding="utf-8"))
+ except Exception as e:
+ brief = _yaml_error_brief(e)
+ kind = "is not valid YAML" if isinstance(e, getattr(yaml, "YAMLError", ())) \
+ else "could not be read"
+ return WireOutcome(
+ self.name, "error",
+ f"{self.config_path} {kind} ({brief}). Fix the file or move it aside "
+ "and re-run; it was not modified.",
+ )
+
+ # 1. Already wired? no-op (no install needed; nothing to overwrite).
+ if state["wired_with_sibyl"] and state["plugin_installed"]:
+ return WireOutcome(
+ self.name, "already",
+ f"Hermes already has SIBYL as memory provider in {self.config_path}",
+ )
+
+ # 2. Existing non-SIBYL provider? confirm or refuse FIRST.
+ # CLI-10: the overwrite-confirm gate must run before any side effect
+ # (plugin install / config write) so a declined overwrite writes
+ # nothing — previously the plugin was installed before this gate.
+ if state["memory_provider"] and state["memory_provider"] != "sibyl" and not force:
+ if prompt_fn is None:
+ return WireOutcome(
+ self.name, "skipped",
+ f"Existing memory.provider '{state['memory_provider']}'. Use --force to overwrite.",
+ overwrite_of=f"memory provider {state['memory_provider']}",
+ )
+ ans = prompt_fn(
+ f"Hermes currently uses '{state['memory_provider']}' as memory provider. Overwrite with SIBYL?",
+ default="N",
+ )
+ if ans != "y":
+ return WireOutcome(self.name, "skipped", "Memory provider overwrite declined.",
+ overwrite_of=f"memory provider {state['memory_provider']}")
+
+ # 2b. Follow-up D5: prove the config.yaml edit is possible before any
+ # install or backup, so a file setup cannot edit ends with nothing
+ # installed, no backup and the two lines to set by hand.
+ try:
+ self._planned_config_text(yaml)
+ except _HermesConfigNotMapping as e:
+ return WireOutcome(self.name, "error", f"config write failed: {e}")
+ except _HermesManualEdit:
+ return self._manual_edit_outcome()
+ except Exception as e:
+ # Never str(e): a YAML or decode error can quote the file (spec 3.2).
+ return WireOutcome(self.name, "error", f"config write failed: {_yaml_error_brief(e)}")
+
+ # 3. Dry-run report — never installs or writes.
+ if dry_run:
+ actions = []
+ if not state["plugin_installed"]:
+ actions.append(f"install plugin at {self.plugin_dir}")
+ actions.append(f"set memory.provider=sibyl in {self.config_path}")
+ return WireOutcome(self.name, "dry-run", "Would: " + "; ".join(actions))
+
+ # 4. Install plugin if missing — only now that the gate has passed.
+ # Panel fix 4: a refusal code or a plugin folder still without
+ # __init__.py stops here, before config.yaml is touched.
+ if not state["plugin_installed"]:
+ try:
+ self._install_plugin()
+ except _HermesPluginRefused as e:
+ return self._refused_outcome(e, "memory.provider was not changed")
+ except Exception as e:
+ return WireOutcome(
+ self.name, "error",
+ f"install-plugin failed: {type(e).__name__}: {e}",
+ )
+ if not (self.plugin_dir / "__init__.py").exists():
+ return WireOutcome(self.name, "error",
+ f"install-plugin did not install the plugin at {self.plugin_dir}; "
+ "memory.provider was not changed")
+
+ # 5. Real write. Backup, then atomic rename.
+ try:
+ backup = self._backup_config()
+ except (OSError, ValueError) as e:
+ return _backup_failed(self.name, self.config_path, self.BACKUP_LABEL, e)
+ try:
+ self._write_config_with_sibyl(yaml)
+ except _HermesConfigNotMapping as e:
+ return WireOutcome(self.name, "error", f"config write failed: {e}",
+ backup_path=backup)
+ except _HermesManualEdit:
+ return self._manual_edit_outcome(backup)
+ except Exception as e:
+ # Never str(e): a YAML or decode error can quote the file (spec 3.2).
+ return WireOutcome(
+ self.name, "error",
+ f"config write failed: {_yaml_error_brief(e)}",
+ backup_path=backup,
+ )
+ return WireOutcome(
+ self.name, "wired",
+ f"Wired memory.provider=sibyl in {self.config_path}",
+ backup_path=backup,
+ )
+
+ def _manual_edit_outcome(self, backup: Optional[Path] = None) -> WireOutcome:
+ return WireOutcome(self.name, "error",
+ f"could not change {self.config_path} safely; it was not modified. "
+ "Set this in it by hand:\n" + "\n".join(HERMES_MANUAL_LINES),
+ backup_path=backup, manual_block="\n".join(HERMES_MANUAL_LINES), handoff=(
+ "done", f"set memory.provider to sibyl in {self.config_path} by hand "
+ "(the two printed lines); setup could not edit it safely", ()))
+
+ # -- doctor (spec dsh-doctor v2, 4.2) -------------------------------------
+ def doctor_probe(self) -> list:
+ try:
+ cfg: Any = None
+ if self.config_path.exists():
+ yaml = _import_yaml()
+ if yaml is None:
+ return [_probe("unreadable", self.config_path,
+ detail="PyYAML is not installed, so config.yaml cannot be read")]
+ try:
+ cfg = yaml.safe_load(self.config_path.read_text(encoding="utf-8"))
+ except Exception as e:
+ return [_probe("unreadable", self.config_path, detail=_yaml_error_brief(e))]
+ mem = cfg.get("memory") if isinstance(cfg, dict) else None
+ if mem is not None and not isinstance(mem, dict):
+ # Follow-up D5: `memory: honcho` is another setting, the same
+ # case setup's overwrite gate stops at, not an absent one.
+ name = str(mem) if (isinstance(mem, (str, int, float, bool))
+ and _HERMES_NAME_RE.match(str(mem))) else "a non-mapping value"
+ return [_probe("foreign", self.config_path,
+ detail=f"memory is {name}, not memory.provider sibyl")]
+ provider = mem.get("provider") if isinstance(mem, dict) else None
+ if not provider:
+ return [_probe("absent", self.config_path)]
+ if provider != "sibyl":
+ name = str(provider) if re.match(r"^[A-Za-z0-9_.-]{1,40}$", str(provider)) else "another provider"
+ return [_probe("foreign", self.config_path,
+ detail=f"memory.provider is {name}, not sibyl")]
+ if (self.plugin_dir / "__init__.py").exists():
+ return [_probe("present", self.config_path,
+ detail="memory.provider is sibyl; plugin installed")]
+ return [_probe("present", self.config_path, broken=True, detail="plugin not installed")]
+ except Exception as e:
+ return [_probe("unreadable", self.config_path, detail=type(e).__name__)]
+
+ def repair_mcp(self, probe: dict) -> WireOutcome:
+ """Broken only: install the plugin and nothing else. config.yaml is not
+ opened for writing and stays byte-identical, so no backup is taken."""
+ try:
+ self._install_plugin()
+ except _HermesPluginRefused as e:
+ return self._refused_outcome(e, "nothing was installed")
+ except Exception as e:
+ return WireOutcome(self.name, "error",
+ f"install-plugin failed: {type(e).__name__}: {e}")
+ if not (self.plugin_dir / "__init__.py").exists():
+ return WireOutcome(self.name, "error",
+ f"install-plugin did not install the plugin at {self.plugin_dir}")
+ return WireOutcome(self.name, "wired",
+ f"Installed the Sibyl plugin for Hermes at {self.plugin_dir}")
+
+ def _install_plugin(self) -> None:
+ """Run the Hermes plugin installer. Panel fix 4: install() signals a
+ refusal by return code, not by raising; a non-zero code raises
+ _HermesPluginRefused here."""
+ from sibyl_memory_hermes.install_plugin import install
+ out = _HandoffHold(sys.stdout)
+ try:
+ with contextlib.redirect_stdout(out):
+ rc = install(hermes_home=Path(self.hermes_home), force=False, dry_run=False)
+ except BaseException:
+ out.release(True)
+ raise
+ refused = isinstance(rc, int) and not isinstance(rc, bool) and rc != 0
+ # Minor (follow-up): on a refusal the installer's own handoff (next:
+ # install-plugin --force) is dropped, so only setup's handoff prints.
+ out.release(not refused)
+ if refused:
+ raise _HermesPluginRefused(rc, self.plugin_dir)
+
+ def _refused_outcome(self, e: "_HermesPluginRefused", tail: str) -> WireOutcome:
+ """Error outcome for an installer refusal, with what the person decides.
+ The replacing command sits inside the question, never as next:."""
+ dest = e.dest
+ home = "" if Path(self.hermes_home) == self._auto_hermes_home() \
+ else f" --hermes-home {shlex.quote(str(self.hermes_home))}"
+ setup = "sibyl setup hermes" + home
+ if e.rc == 2:
+ why = f"{dest} already has files"
+ human = (f"{dest} already has files that may be an older Sibyl plugin; if they can "
+ f"be replaced, run: sibyl-memory-hermes install-plugin --force{home}, then "
+ f"{setup}")
+ elif e.rc == 3:
+ why = f"{dest} is a symlink"
+ human = f"{dest} is a symlink; remove it, then run {setup}"
+ else:
+ why = f"{dest} holds files that are not a Sibyl install"
+ human = f"{dest} holds files that are not a Sibyl install; move them aside, then run {setup}"
+ return WireOutcome(self.name, "error",
+ f"install-plugin refused (code {e.rc}): {why}; {tail}",
+ handoff=("done", human, ()))
+
+ def _backup_config(self) -> Optional[Path]:
+ # B005 (audit #19): timestamped backup so repeated runs don't clobber it.
+ return _timestamped_backup(self.config_path, self.BACKUP_LABEL)
+
+ def _write_config_with_sibyl(self, yaml) -> None:
+ """Set memory.provider: sibyl as a text edit (panel fix 1): comments,
+ anchors, key order, quoting and non-ASCII text stay as written, and a
+ symlinked config.yaml is written through (the link is kept, as for
+ Cursor and Codex). Raises _HermesManualEdit when the edit cannot be
+ proven; the file is never re-serialized."""
+ raw, new = self._planned_config_text(yaml)
+ if new == raw:
+ return
+ self.config_path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = self.config_path.with_suffix(".yaml.tmp")
+ _write_via_tmp(self.config_path, tmp, new, through_symlink=True)
+
+ def _planned_config_text(self, yaml) -> tuple:
+ """(current text, edited text) of config.yaml, nothing written.
+ Raises _HermesConfigNotMapping or _HermesManualEdit when setup cannot
+ make the edit (checked before any install or backup, follow-up D5)."""
+ raw = ""
+ if self.config_path.exists():
+ with open(self.config_path, encoding="utf-8", newline="") as fh:
+ raw = fh.read()
+ loaded = yaml.safe_load(raw)
+ if loaded is not None and not isinstance(loaded, dict):
+ # Fail fast: a non-mapping top level means the config is not
+ # something we can merge into. Silently reinitializing would
+ # destroy the user's existing Hermes settings.
+ raise _HermesConfigNotMapping(
+ f"{self.config_path} top level is not a YAML mapping "
+ f"(got {type(loaded).__name__}). Fix the file or move it "
+ "aside and re-run; it was not modified."
+ )
+ new = _hermes_provider_text(raw)
+ if new is None:
+ raise _HermesManualEdit(str(self.config_path))
+ return raw, new
+
+
+# ----------------------------------------------------------------------
+# ClaudeCodeWirer
+# ----------------------------------------------------------------------
+
+class ClaudeCodeWirer:
+ name = "claude-code"
+ display_name = "Claude Code"
+ initial = "c"
+
+ SIBYL_MCP_BLOCK = {"command": "sibyl-memory-mcp"}
+ MCP_BINARY = "sibyl-memory-mcp"
+ MCP_PACKAGE = "sibyl-memory-mcp"
+ MCP_NAME = "sibyl-memory" # the server name as Claude Code knows it
+
+ def __init__(self, *, settings_path: Optional[Union[str, Path]] = None):
+ self.settings_path = (
+ Path(settings_path).expanduser() if settings_path
+ else Path.home() / ".claude" / "settings.json"
+ )
+
+ def is_present(self) -> bool:
+ if self.settings_path.exists():
+ return True
+ if shutil.which("claude"):
+ return True
+ return False
+
+ def _mcp_binary_found(self) -> bool:
+ return resolve_mcp_binary() is not None
+
+ @staticmethod
+ def _claude_cli() -> Optional[str]:
+ """Path to the `claude` binary, or None. The CLI is the reliable wiring +
+ discovery surface — writing ~/.claude/settings.json (the old behavior) is NOT
+ where Claude Code discovers MCP servers, which caused the registration bug."""
+ return shutil.which("claude")
+
+ def _registered_via_cli(self) -> Optional[bool]:
+ """True/False if `claude mcp get ` reports the server; None if no CLI.
+ This is the source-of-truth detection once the `claude` CLI exists."""
+ if not self._claude_cli():
+ return None
+ rc, _o, _e = _run(["claude", "mcp", "get", self.MCP_NAME], timeout=15)
+ return rc == 0
+
+ _last_install_error: Optional[str] = None
+
+ def _install_hint(self) -> str:
+ """Append the captured install failure / PEP-668 instruction, if any,
+ to the generic 'not on PATH' message. CLI-11."""
+ return f"\n{self._last_install_error}" if self._last_install_error else ""
+
+ def _ensure_mcp_binary(self, *, prompt_fn: Optional[Callable[..., str]] = None) -> bool:
+ """Check for sibyl-memory-mcp binary; auto-install if missing.
+
+ Returns True if binary is available after the call, False otherwise.
+
+ CLI-11: respect PEP 668 — never silently `pip install` into an
+ externally-managed (or pipx-managed) environment; instruct instead.
+ On a plain install, capture pip output and surface it on failure rather
+ than discarding it to /dev/null (opaque failures).
+ """
+ if self._mcp_binary_found():
+ return True
+ self._last_install_error = _install_pkg_or_instruct(self.MCP_PACKAGE)
+ return self._mcp_binary_found()
+
+ def verify_mcp_starts(self) -> tuple:
+ """Smoke-test: spawn sibyl-memory-mcp and confirm it doesn't crash on startup.
+
+ Returns (ok: bool, message: str). Delegates to the module-level
+ ``_verify_mcp_starts`` helper (audit #19 B005) so the Claude and Codex
+ wirers share one implementation instead of cross-class dispatch.
+ """
+ binary = resolve_mcp_binary()
+ if not binary:
+ return False, f"'{self.MCP_BINARY}' is not installed"
+ return _verify_mcp_starts(binary)
+
+ def current_state(self) -> dict:
+ settings_exists = self.settings_path.exists()
+ mcp_servers: dict = {}
+ sibyl_block: Optional[dict] = None
+ settings_parse_error: Optional[str] = None
+ if settings_exists:
+ try:
+ cfg = json.loads(self.settings_path.read_text(encoding="utf-8"))
+ if isinstance(cfg, dict):
+ raw_servers = cfg.get("mcpServers", {})
+ if isinstance(raw_servers, dict):
+ mcp_servers = raw_servers
+ sibyl_block = mcp_servers.get("sibyl-memory")
+ except Exception as e:
+ settings_parse_error = f"{type(e).__name__}: {e}"
+ mcp_binary = self._mcp_binary_found()
+ cli_registered = self._registered_via_cli() # None when no `claude` CLI
+ # Source of truth: when the claude CLI exists, trust `claude mcp get` (where
+ # Claude Code actually discovers servers). Without it nothing is verifiable.
+ if cli_registered is None:
+ # Panel fix 10: without the CLI the registration cannot be seen,
+ # and settings.json is not where Claude Code reads servers from.
+ wired = False
+ else:
+ wired = bool(cli_registered and mcp_binary)
+ return {
+ "settings_path": str(self.settings_path),
+ "settings_exists": settings_exists,
+ "settings_parse_error": settings_parse_error,
+ "mcp_servers_count": len(mcp_servers),
+ "sibyl_mcp": sibyl_block,
+ "mcp_binary_found": mcp_binary,
+ "claude_cli": self._claude_cli() is not None,
+ "cli_registered": cli_registered,
+ "wired_with_sibyl": wired,
+ }
+
+ def _wire_via_cli(self, *, force: bool, dry_run: bool) -> WireOutcome:
+ """Register through `claude mcp add --scope user` — the reliable path that
+ writes where Claude Code actually discovers servers (fixes the settings.json
+ registration/discovery bug). `--scope user` makes it global across projects."""
+ if not dry_run and not self._ensure_mcp_binary():
+ return WireOutcome(self.name, "error",
+ f"'{self.MCP_BINARY}' is not installed. Install it: pip install {self.MCP_PACKAGE}"
+ + self._install_hint(), handoff=_binary_missing_handoff(self.name))
+ if self._registered_via_cli():
+ if not force:
+ return WireOutcome(self.name, "already",
+ "Claude Code already has the sibyl-memory MCP server (claude mcp).")
+ if not dry_run:
+ _run(["claude", "mcp", "remove", "-s", "user", self.MCP_NAME], timeout=15)
+ # Register the RESOLVED absolute path, not the bare name: a user-scope server
+ # is launched from Claude Code's own PATH, which may not include a venv's bin.
+ # Bare-name registration shows "✗ Failed to connect" for venv installs; the
+ # absolute path connects regardless of how PATH is set when claude launches it.
+ binpath = mcp_command_path()
+ cmd = ["claude", "mcp", "add", "--scope", "user", self.MCP_NAME, "--", binpath]
+ if dry_run:
+ return WireOutcome(self.name, "dry-run", "Would run: " + " ".join(cmd))
+ rc, out, err = _run(cmd, timeout=30)
+ if rc != 0:
+ return WireOutcome(self.name, "error",
+ f"`claude mcp add` failed (exit {rc}): {(err or out).strip()[:200]}",
+ handoff=(f"claude mcp add --scope user {self.MCP_NAME} -- {binpath}", None, ()))
+ # Post-wire verification (bug report, 2026-06-01): a 0 exit from
+ # `claude mcp add` has been observed to not guarantee discovery. Confirm the
+ # server actually shows in `claude mcp get`, and surface concrete remediation
+ # instead of reporting a false success that leaves the MCP absent from /mcp.
+ if self._registered_via_cli() is False:
+ return WireOutcome(self.name, "error",
+ "ran `claude mcp add` (exit 0) but the server is not in `claude mcp list`. "
+ "restart Claude Code, then run `claude mcp list`; if still absent, run "
+ f"`claude mcp add --scope user {self.MCP_NAME} -- {binpath}` manually.",
+ handoff=("claude mcp list", "restart Claude Code", ()))
+ return WireOutcome(self.name, "wired",
+ "Registered sibyl-memory with Claude Code via `claude mcp add --scope user` (verified in `claude mcp list`).")
+
+ # -- doctor (spec dsh-doctor v2, 4.1) -------------------------------------
+ @staticmethod
+ def _claude_user_config() -> Path:
+ d = os.environ.get("CLAUDE_CONFIG_DIR")
+ if d and d.strip():
+ return Path(d).expanduser() / ".claude.json"
+ return Path.home() / ".claude.json"
+
+ def _user_scope_entry(self) -> Optional[dict]:
+ """The user-scope sibyl-memory object from Claude Code's own config, or
+ None. Only that one object is read out of the file (it holds account
+ data); nothing else from it is ever returned or printed."""
+ try:
+ data = json.loads(self._claude_user_config().read_text(encoding="utf-8"))
+ except Exception:
+ return None
+ servers = data.get("mcpServers") if isinstance(data, dict) else None
+ entry = servers.get(self.MCP_NAME) if isinstance(servers, dict) else None
+ return entry if isinstance(entry, dict) else None
+
+ def doctor_probe(self) -> list:
+ cfgp = self._claude_user_config()
+ try:
+ if self._claude_cli() is None:
+ return [_probe("unverifiable", cfgp, detail=(
+ "the claude command is not on PATH, so the registration cannot be checked"))]
+ if not self._registered_via_cli():
+ return [_probe("absent", cfgp)]
+ entry = self._user_scope_entry()
+ if entry is None or not isinstance(entry.get("command"), str):
+ return [_probe("present", cfgp, detail=(
+ "registered (claude mcp) outside user scope or not readable; command path "
+ "not checked"))]
+ cmd = entry["command"]
+ if not _is_our_command(cmd):
+ return [_probe("foreign", cfgp, command=None,
+ detail="the sibyl-memory registration runs another command")]
+ extra = {}
+ if (any(k not in ("type", "command", "args", "env") for k in entry)
+ or entry.get("args") not in (None, []) or entry.get("env") not in (None, {})):
+ extra["customized"] = True
+ return [_probe("present", cfgp, command=cmd, **extra)]
+ except Exception as e:
+ return [_probe("unreadable", cfgp, detail=type(e).__name__)]
+
+ def repair_mcp(self, probe: dict) -> WireOutcome:
+ """Stale or broken plain user-scope entry: remove, then add again with
+ the resolved absolute path (verified with claude mcp get). A failed
+ add carries the manual command as its handoff."""
+ binpath = mcp_command_path()
+ manual = f"claude mcp add --scope user {self.MCP_NAME} -- {shlex.quote(binpath)}"
+ if self._claude_cli() is None:
+ return WireOutcome(self.name, "error", "the claude command is not on PATH",
+ handoff=(manual, None, ()))
+ if probe.get("customized"):
+ return WireOutcome(self.name, "error", (
+ "entry has custom env or args; update the path by hand: claude mcp remove -s user "
+ f"sibyl-memory, then {manual} with your settings"))
+ return self._wire_via_cli(force=True, dry_run=False)
+
+ # -- save / debloat wiring (spec plugin-save-debloat 3.5) ---------------
+ def skill_shim_targets(self) -> dict:
+ sk = _skills_mod()
+ names = sk.SHIM_NAMES if sk is not None else {}
+ return {n: self.settings_path.parent / "skills" / s / "SKILL.md" for n, s in names.items()}
+
+ def hooks_state(self) -> dict:
+ """{'present': n of our hook entries, 'error': parse error or None}."""
+ if not self.settings_path.exists():
+ return {"present": 0, "error": None}
+ try:
+ cfg = json.loads(self.settings_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as e:
+ return {"present": 0, "error": f"{type(e).__name__}"}
+ return {"present": count_our_hooks(cfg), "error": None}
+
+ def _read_settings_for_edit(self) -> dict:
+ cfg: dict = {}
+ if self.settings_path.exists():
+ if self.settings_path.is_symlink():
+ raise ValueError(f"{self.settings_path} is a symlink; not followed")
+ raw = self.settings_path.read_text(encoding="utf-8")
+ if raw.strip():
+ try:
+ loaded = json.loads(raw)
+ except ValueError as e:
+ raise ValueError(
+ f"{self.settings_path} is not valid JSON ({e}). Fix the file or move it "
+ "aside and re-run setup; your settings were not modified.") from e
+ if not isinstance(loaded, dict):
+ raise ValueError(f"{self.settings_path} top level is not a JSON object; "
+ "your settings were not modified.")
+ cfg = loaded
+ return cfg
+
+ def wire_hooks(self, *, dry_run: bool = False) -> list:
+ binary = sibyl_binary()
+ if dry_run:
+ try:
+ cfg = self._read_settings_for_edit()
+ if merge_hooks(cfg, binary) == cfg:
+ return [f"hooks: {len(HOOK_EVENTS)} already in {self.settings_path}"]
+ except ValueError as e:
+ return [f"hooks would not be written: {e}"]
+ return [f"would add hook {ev} -> {hook_command(binary, arg)} (timeout {HOOK_TIMEOUT_SECONDS}s)"
+ for ev, arg in HOOK_EVENTS]
+ try:
+ cfg = self._read_settings_for_edit()
+ new = merge_hooks(cfg, binary)
+ except ValueError as e:
+ return [f"hooks not written: {e}"]
+ if new == cfg:
+ return [f"hooks: {len(HOOK_EVENTS)} already in {self.settings_path}"]
+ try:
+ backup = self._backup_settings()
+ except (OSError, ValueError) as e:
+ return [f"hooks not written: backup failed ({type(e).__name__})"]
+ _atomic_text(self.settings_path, json.dumps(new, indent=2) + "\n")
+ lines = [f"hooks: {len(HOOK_EVENTS)} written to {self.settings_path} "
+ f"({', '.join(e for e, _a in HOOK_EVENTS)}; command {binary})"]
+ if backup:
+ lines.append(f" backup at {backup}")
+ return lines
+
+ def unwire_hooks(self) -> list:
+ try:
+ cfg = self._read_settings_for_edit()
+ except ValueError as e:
+ return [f"hooks not removed: {e}"]
+ new = remove_hooks(cfg)
+ if new == cfg:
+ return ["hooks: none of ours present"]
+ try:
+ self._backup_settings()
+ except (OSError, ValueError) as e:
+ return [f"hooks not removed: backup failed ({type(e).__name__})"]
+ _atomic_text(self.settings_path, json.dumps(new, indent=2) + "\n")
+ return [f"hooks: removed ours from {self.settings_path}"]
+
+ def wire_lifecycle(self, *, force: bool = False, dry_run: bool = False) -> list:
+ lines = install_canonical_skills(dry_run=dry_run)
+ lines += install_shims("claude-code", self.skill_shim_targets(), dry_run=dry_run, force=force)
+ lines += self.wire_hooks(dry_run=dry_run)
+ return lines
+
+ def wire(self, *, force: bool = False, dry_run: bool = False,
+ prompt_fn: Optional[Callable[..., str]] = None) -> WireOutcome:
+ cli_missing = self._claude_cli() is None
+ out = self._wire_mcp(force=force, dry_run=dry_run, prompt_fn=prompt_fn)
+ if out.status in ("wired", "already", "dry-run") or (
+ cli_missing and out.status == "skipped"):
+ try:
+ out.lifecycle = self.wire_lifecycle(force=force, dry_run=dry_run)
+ except Exception as e: # never fail the MCP wiring on the extras
+ out.lifecycle = [f"skills/hooks not installed: {type(e).__name__}: {e}"]
+ return out
+
+ def _wire_mcp(self, *, force: bool = False, dry_run: bool = False,
+ prompt_fn: Optional[Callable[..., str]] = None) -> WireOutcome:
+ # The `claude` CLI is the only surface that registers a server where
+ # Claude Code discovers it.
+ if self._claude_cli():
+ return self._wire_via_cli(force=force, dry_run=dry_run)
+ # Panel fix 10 (2026-11-14): without the CLI nothing is written for the
+ # MCP server (~/.claude/settings.json is not where Claude Code reads
+ # servers from, so an entry there was reported as wired while Claude
+ # Code never saw it). The outcome says so and carries the exact
+ # command; hooks and skills are still installed by wire().
+ binpath = mcp_command_path()
+ manual = f"claude mcp add --scope user {self.MCP_NAME} -- {shlex.quote(binpath)}"
+ if dry_run:
+ return WireOutcome(self.name, "dry-run",
+ f"Would not register the MCP server: the claude command is not on PATH. "
+ f"Run: {manual}")
+ if not self._ensure_mcp_binary(prompt_fn=prompt_fn):
+ return WireOutcome(
+ self.name, "error",
+ f"'{self.MCP_BINARY}' is not installed. "
+ f"Install it: pip install {self.MCP_PACKAGE}" + self._install_hint(),
+ handoff=_binary_missing_handoff(self.name),
+ )
+ return WireOutcome(
+ self.name, "skipped",
+ "the claude command is not on PATH, so the MCP server was not registered with "
+ f"Claude Code. Run: {manual}",
+ handoff=(manual, "if claude is not found in this shell, run that command in a "
+ "terminal where Claude Code is installed", ()),
+ )
+
+ def _backup_settings(self) -> Optional[Path]:
+ # B005 (audit #19): timestamped backup so repeated runs don't clobber it.
+ return _timestamped_backup(self.settings_path, "claude-code")
+
+
+# ----------------------------------------------------------------------
+# CodexWirer — Codex discovers MCP servers from ~/.codex/config.toml, so editing
+# that file IS the reliable method (unlike Claude's settings.json). Append the
+# [mcp_servers.sibyl_memory] table if absent. Atomic, .bak backup, idempotent.
+# ----------------------------------------------------------------------
+
+# Codex config.toml grammar for our one table (spec dsh-doctor v2, 4.3). Shared
+# by current_state, the doctor probe and the command update. Line based: a
+# commented-out header never counts, and any other mention of sibyl_memory (an
+# inline table, dotted keys) is a form setup does not edit.
+#
+# Panel fix 2 (2026-11-14): table headers are found structurally, not by a
+# character-class regex. A line is a header when it starts with '[' at array
+# depth 0 outside a multi-line string (a TOML value can never start a line
+# with '[' there). Its key path is parsed with bare, basic-quoted and
+# literal-quoted keys, so [projects."/home/u/repo"] (which Codex writes for
+# every trusted folder) and [mcp_servers."ctx@upstash"] are headers too, and
+# a [mcp_servers.sibyl_memory] line inside a """...""" value is not.
+_CODEX_OURS = ("mcp_servers", "sibyl_memory")
+_CODEX_COMMENT_RE = re.compile(r"^\s*#")
+# The command key, bare or quoted (panel fix 7): "command" and 'command' are
+# the same TOML key as command.
+_CODEX_CMD_RE = re.compile(r"""^(\s*)(command|"command"|'command')\s*=\s*(.*)$""")
+_TOML_BARE_KEY_RE = re.compile(r"[A-Za-z0-9_-]+")
+_TOML_ESCAPES = {"b": "\b", "t": "\t", "n": "\n", "f": "\f", "r": "\r", '"': '"', "\\": "\\"}
+
+
+def _strip_eol(line: str) -> str:
+ return line.rstrip("\r\n")
+
+
+def _toml_basic_key(s: str, i: int) -> Optional[tuple]:
+ """Parse a basic-quoted key starting at s[i] == '"'. (value, index after
+ the closing quote) or None."""
+ out = []
+ j = i + 1
+ while j < len(s):
+ c = s[j]
+ if c == '"':
+ return "".join(out), j + 1
+ if c == "\\":
+ e = s[j + 1:j + 2]
+ if e in _TOML_ESCAPES:
+ out.append(_TOML_ESCAPES[e])
+ j += 2
+ continue
+ if e in ("u", "U"):
+ n = 4 if e == "u" else 8
+ hexd = s[j + 2:j + 2 + n]
+ if len(hexd) != n or not re.fullmatch(r"[0-9A-Fa-f]+", hexd):
+ return None
+ try:
+ out.append(chr(int(hexd, 16)))
+ except ValueError:
+ return None
+ j += 2 + n
+ continue
+ return None
+ out.append(c)
+ j += 1
+ return None
+
+
+def _toml_header_path(raw: str) -> Optional[tuple]:
+ """(key path tuple, is_array_of_tables) when ``raw`` is a well-formed
+ table or array-of-tables header line, else None."""
+ s = raw.strip()
+ if not s.startswith("["):
+ return None
+ arr = s.startswith("[[")
+ i = 2 if arr else 1
+ n = len(s)
+ keys: list = []
+ while True:
+ while i < n and s[i] in " \t":
+ i += 1
+ if i >= n:
+ return None
+ c = s[i]
+ if c == '"':
+ got = _toml_basic_key(s, i)
+ if got is None:
+ return None
+ keys.append(got[0])
+ i = got[1]
+ elif c == "'":
+ end = s.find("'", i + 1)
+ if end == -1:
+ return None
+ keys.append(s[i + 1:end])
+ i = end + 1
+ else:
+ m = _TOML_BARE_KEY_RE.match(s, i)
+ if not m:
+ return None
+ keys.append(m.group())
+ i = m.end()
+ while i < n and s[i] in " \t":
+ i += 1
+ if i < n and s[i] == ".":
+ i += 1
+ continue
+ break
+ close = "]]" if arr else "]"
+ if not s.startswith(close, i):
+ return None
+ rest = s[i + len(close):].strip()
+ if rest and not rest.startswith("#"):
+ return None
+ return tuple(keys), arr
+
+
+def _codex_line_kinds(lines: list) -> list:
+ """Per line: None for a line that is not a table header, else
+ (key path or None when malformed, is_array). Headers are depth-0 lines
+ outside multi-line strings whose first character is '['."""
+ out = []
+ depth, ml = 0, None
+ for ln in lines:
+ raw = _strip_eol(ln)
+ if depth == 0 and ml is None and raw.lstrip().startswith("["):
+ hp = _toml_header_path(raw)
+ out.append(hp if hp is not None else (None, False))
+ depth, ml = 0, None
+ continue
+ out.append(None)
+ depth, ml = _toml_line_state(raw, depth, ml)
+ return out
+
+
+def _codex_root_mcp_servers_key(lines: list) -> bool:
+ """True when ``mcp_servers`` is assigned as a key before the first table
+ header (``mcp_servers = { ... }`` or ``mcp_servers.x = ...``): appending a
+ [mcp_servers.sibyl_memory] table to such a file is a TOML redefinition or
+ an edit setup cannot prove without a parser."""
+ depth, ml = 0, None
+ for ln in lines:
+ raw = _strip_eol(ln)
+ if depth == 0 and ml is None:
+ if raw.lstrip().startswith("["):
+ return False
+ if re.match(r"""^\s*(?:mcp_servers|"mcp_servers"|'mcp_servers')\s*[=.]""", raw):
+ return True
+ depth, ml = _toml_line_state(raw, depth, ml)
+ return False
+
+
+def _toml_text_open_at_end(text: str) -> bool:
+ """True when the text ends inside a multi-line string or an open array."""
+ depth, ml = 0, None
+ for ln in text.splitlines():
+ depth, ml = _toml_line_state(ln, depth, ml)
+ return depth != 0 or ml is not None
+
+
+def _toml_string_value(rest: str) -> Optional[tuple]:
+ """Parse a TOML basic ("...") or literal ('...') string at the start of
+ ``rest``. Returns (value, suffix): suffix is what follows the closing quote
+ (only whitespace and an optional comment are allowed). Returns None for any
+ other value (unparsed). In a basic string only the two escapes for a
+ backslash and a double quote are understood; any other escape leaves the
+ value unparsed."""
+ if not rest:
+ return None
+ q = rest[0]
+ if rest[:3] == q * 3:
+ return None # multi-line strings: not a form setup edits
+ if q == "'":
+ end = rest.find("'", 1)
+ if end == -1:
+ return None
+ value, tail = rest[1:end], rest[end + 1:]
+ elif q == '"':
+ out = []
+ i = 1
+ closed = False
+ while i < len(rest):
+ c = rest[i]
+ if c == "\\":
+ nxt = rest[i + 1:i + 2]
+ if nxt not in ("\\", '"'):
+ return None
+ out.append(nxt)
+ i += 2
+ continue
+ if c == '"':
+ closed = True
+ break
+ out.append(c)
+ i += 1
+ if not closed:
+ return None
+ value, tail = "".join(out), rest[i + 1:]
+ else:
+ return None
+ if tail.strip() and not tail.lstrip().startswith("#"):
+ return None
+ return value, tail.rstrip()
+
+
+def _toml_line_state(line: str, depth: int, ml: Optional[str]) -> tuple:
+ """Carry (array bracket depth, open multi-line string delimiter) across one
+ line of TOML text. Brackets inside strings and comments do not count."""
+ i, n = 0, len(line)
+ while i < n:
+ if ml is not None:
+ end = line.find(ml, i)
+ if end == -1:
+ return depth, ml
+ i = end + 3
+ ml = None
+ continue
+ c = line[i]
+ if c == "#":
+ break
+ if line.startswith('"""', i) or line.startswith("'''", i):
+ ml = line[i:i + 3]
+ i += 3
+ continue
+ if c == '"':
+ i += 1
+ while i < n and line[i] != '"':
+ i += 2 if line[i] == "\\" else 1
+ i += 1
+ continue
+ if c == "'":
+ end = line.find("'", i + 1)
+ i = n if end == -1 else end + 1
+ continue
+ if c == "[":
+ depth += 1
+ elif c == "]":
+ depth = max(0, depth - 1)
+ i += 1
+ return depth, ml
+
+
+def _codex_body_end(lines: list, start: int) -> int:
+ """Index of the first table header at or after ``start`` (a depth-0 line
+ outside a multi-line array or string whose first character is '['), or
+ len(lines). ``start`` is the line after a header."""
+ depth, ml = 0, None
+ j = start
+ while j < len(lines):
+ raw = _strip_eol(lines[j])
+ if depth == 0 and ml is None and raw.lstrip().startswith("["):
+ return j
+ depth, ml = _toml_line_state(raw, depth, ml)
+ j += 1
+ return j
+
+
+def _codex_body_command_lines(lines: list, b: int, e: int) -> list:
+ """(index, match) for every command key line in lines[b:e] that sits at
+ depth 0 outside a multi-line string (a line inside a value never counts)."""
+ out = []
+ depth, ml = 0, None
+ for k in range(b, e):
+ raw = _strip_eol(lines[k])
+ if depth == 0 and ml is None:
+ m = _CODEX_CMD_RE.match(raw)
+ if m:
+ out.append((k, m))
+ depth, ml = _toml_line_state(raw, depth, ml)
+ return out
+
+
+def _codex_scan(text: str) -> dict:
+ """Locate our table in a Codex config.toml text (no TOML parser needed)."""
+ lines = text.splitlines(keepends=True)
+ kinds = _codex_line_kinds(lines)
+ headers = [i for i, k in enumerate(kinds)
+ if k is not None and k[0] == _CODEX_OURS and not k[1]]
+ sub_heads = [i for i, k in enumerate(kinds)
+ if k is not None and k[0] is not None and len(k[0]) > 2
+ and k[0][:2] == _CODEX_OURS]
+
+ def _end(i: int) -> int:
+ return next((j for j in range(i + 1, len(lines)) if kinds[j] is not None), len(lines))
+
+ owned = set() # lines inside our table body or a subtable of ours
+ subtables = [] # (header line, body end) of [mcp_servers.sibyl_memory.*]
+ for i in headers + sub_heads:
+ e = _end(i)
+ owned.update(range(i + 1, e))
+ if i not in headers:
+ subtables.append((i, e))
+ other = False
+ for i, ln in enumerate(lines):
+ raw = _strip_eol(ln)
+ if "sibyl_memory" not in raw or _CODEX_COMMENT_RE.match(raw):
+ continue
+ if i in headers or i in sub_heads or i in owned:
+ continue
+ other = True
+ body = None
+ cmd = {"line": None, "indent": "", "key": "command", "value": None, "suffix": "",
+ "parsed": False}
+ n_cmd = 0
+ if headers:
+ h = headers[0]
+ e = _end(h)
+ body = (h + 1, e)
+ found = _codex_body_command_lines(lines, h + 1, e)
+ n_cmd = len(found)
+ if found:
+ k, m = found[0]
+ cmd["line"] = k
+ cmd["indent"] = m.group(1)
+ cmd["key"] = m.group(2)
+ parsed = _toml_string_value(m.group(3))
+ if parsed is not None:
+ cmd["value"], cmd["suffix"] = parsed
+ cmd["parsed"] = True
+ return {"lines": lines, "headers": headers, "other_mention": other, "body": body,
+ "command": cmd, "command_lines": n_cmd, "subtables": subtables}
+
+
+try: # Python 3.11+
+ import tomllib as _tomllib
+except ImportError: # pragma: no cover - Python 3.10
+ # Panel fix (2026-11-14): tomli is a declared dependency on Python < 3.11,
+ # so the parse-and-compare proof runs on every supported Python. The text
+ # checks stay as defense in depth and stand alone only if tomli is absent.
+ try:
+ import tomli as _tomllib # type: ignore[no-redef]
+ except ImportError:
+ _tomllib = None
+
+
+def _toml_loads(text: str) -> dict:
+ """tomllib.loads after one leading UTF-8 BOM is dropped (follow-up D4):
+ Codex reads a config saved with a BOM, tomllib rejects it. The text
+ edits keep the BOM; only the parse skips it."""
+ if text.startswith("\ufeff"):
+ text = text[1:]
+ return _tomllib.loads(text)
+
+
+class CodexWirer:
+ name = "codex"
+ display_name = "OpenAI Codex"
+ initial = "x"
+
+ MCP_BINARY = "sibyl-memory-mcp"
+ MCP_PACKAGE = "sibyl-memory-mcp"
+ BACKUP_LABEL = "codex"
+ HEADER = "[mcp_servers.sibyl_memory]"
+ # Fallback/canonical shape. The real block is built at wire time by
+ # _block_text() using the RESOLVED absolute path — codex spawns the server
+ # from its own captured environment, not the interactive shell, so a bare
+ # command name can fail to resolve. `codex mcp add -- ` itself writes
+ # the absolute path; we match that.
+ BLOCK = '\n[mcp_servers.sibyl_memory]\ncommand = "sibyl-memory-mcp"\n'
+
+ def __init__(self, *, config_path: Optional[Union[str, Path]] = None):
+ self.config_path = (
+ Path(config_path).expanduser() if config_path
+ else Path.home() / ".codex" / "config.toml"
+ )
+
+ def is_present(self) -> bool:
+ return self.config_path.exists() or shutil.which("codex") is not None
+
+ def _mcp_binary_found(self) -> bool:
+ return resolve_mcp_binary() is not None
+
+ def _mcp_command(self) -> str:
+ """Resolved absolute path to the MCP binary, falling back to the bare
+ name if it cannot be resolved (mirrors the Claude wirer fix)."""
+ return mcp_command_path()
+
+ @staticmethod
+ def _toml_escape(s: str) -> str:
+ return s.replace("\\", "\\\\").replace('"', '\\"')
+
+ def _block_text(self) -> str:
+ cmd = self._toml_escape(self._mcp_command())
+ return f'\n[mcp_servers.sibyl_memory]\ncommand = "{cmd}"\n'
+
+ _last_install_error: Optional[str] = None
+
+ def _install_hint(self) -> str:
+ return f"\n{self._last_install_error}" if self._last_install_error else ""
+
+ def _ensure_mcp_binary(self) -> bool:
+ # CLI-11: same hardening as the Claude wirer — respect PEP 668, surface
+ # pip output on failure instead of discarding it.
+ if self._mcp_binary_found():
+ return True
+ self._last_install_error = _install_pkg_or_instruct(self.MCP_PACKAGE)
+ return self._mcp_binary_found()
+
+ def _read_scan(self) -> Optional[dict]:
+ if not self.config_path.exists():
+ return None
+ return _codex_scan(self._read_raw())
+
+ def _read_raw(self) -> str:
+ """The file text with its line endings as written (CRLF survives)."""
+ with open(self.config_path, encoding="utf-8", newline="") as fh:
+ return fh.read()
+
+ def current_state(self) -> dict:
+ exists = self.config_path.exists()
+ wired = False
+ if exists:
+ try:
+ sc = self._read_scan()
+ cmd = sc["command"]
+ stale = bool(cmd["parsed"] and os.path.isabs(cmd["value"] or "")
+ and not _command_resolves(cmd["value"]))
+ # cli 0.7.0: a commented-out header, a second definition, another
+ # form of sibyl_memory or a stale absolute path is not "wired".
+ # Panel fix 15: nor is a table with no command line, an unparsed
+ # one or one that runs another server; panel fix 3: nor is a
+ # file a TOML parser rejects.
+ wired = (len(sc["headers"]) == 1 and not sc["other_mention"] and not stale
+ and sc["command_lines"] == 1 and cmd["parsed"]
+ and _is_our_command(cmd["value"])
+ and self._toml_error("".join(sc["lines"])) is None
+ and not _codex_root_mcp_servers_key(sc["lines"]))
+ except Exception:
+ pass
+ return {
+ "config_path": str(self.config_path),
+ "config_exists": exists,
+ "mcp_binary_found": self._mcp_binary_found(),
+ "wired_with_sibyl": wired,
+ }
+
+ def instructions(self) -> list[str]:
+ """Manual steps the guided flow prints if it can't (or won't) auto-edit."""
+ cmd = self._mcp_command()
+ return [
+ "Open a new terminal.",
+ f"Add this to {self.config_path} (create the file if needed):",
+ " [mcp_servers.sibyl_memory]",
+ f' command = "{cmd}"',
+ "Restart Codex, then come back here.",
+ ]
+
+ def verify_mcp_starts(self) -> tuple:
+ # reuse the same stdio smoke-test via the shared module-level helper
+ # (audit #19 B005 — no more cross-class dispatch).
+ binary = resolve_mcp_binary()
+ if not binary:
+ return False, f"'{self.MCP_BINARY}' is not installed"
+ return _verify_mcp_starts(binary)
+
+ # -- save / debloat wiring (spec plugin-save-debloat 3.5, D9) -----------
+ # Verified against the installed Codex CLI 0.135.0 (binary strings): it
+ # reads a global AGENTS.md from CODEX_HOME (~/.codex/AGENTS.md) and
+ # discovers skills under $CODEX_HOME/skills (~/.codex/skills when unset);
+ # there is no ~/.codex/prompts custom-prompt loader in that version, so
+ # the Codex delivery is the AGENTS.md block, two skill shims and the MCP
+ # prompts. The skill format is the one the binary's bundled skill-creator
+ # validates (scripts/quick_validate.py): SKILL.md in //, YAML
+ # frontmatter with a hyphen-case `name` (at most 64 characters) and a
+ # `description` (at most 1024, no angle brackets).
+ @property
+ def agents_path(self) -> Path:
+ return self.config_path.parent / "AGENTS.md"
+
+ def skill_shim_targets(self) -> dict:
+ sk = _skills_mod()
+ names = sk.SHIM_NAMES if sk is not None else {}
+ return {n: self.config_path.parent / "skills" / s / "SKILL.md" for n, s in names.items()}
+
+ def block_state(self) -> bool:
+ try:
+ return CODEX_BLOCK_BEGIN in self.agents_path.read_text(encoding="utf-8")
+ except OSError:
+ return False
+
+ def wire_block(self, *, dry_run: bool = False) -> list:
+ p = self.agents_path
+ if dry_run:
+ try:
+ if (not p.is_symlink() and p.is_file()
+ and upsert_block(p.read_text(encoding="utf-8"), codex_block())
+ == p.read_text(encoding="utf-8")):
+ return [f"block: already in {p}"]
+ except (OSError, UnicodeDecodeError):
+ pass
+ return [f"would add the Sibyl Memory block to {p}"]
+ if p.is_symlink():
+ return [f"block not written: {p} is a symlink"]
+ existing = ""
+ if p.exists():
+ try:
+ existing = p.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError) as e:
+ return [f"block not written: {p} unreadable ({type(e).__name__})"]
+ new = upsert_block(existing, codex_block())
+ if new == existing:
+ return [f"block: already in {p}"]
+ _atomic_text(p, new)
+ return [f"block: written to {p}"]
+
+ def unwire_block(self) -> list:
+ p = self.agents_path
+ if p.is_symlink() or not p.exists():
+ return []
+ existing = p.read_text(encoding="utf-8")
+ new = remove_block(existing)
+ if new == existing:
+ return []
+ _atomic_text(p, new)
+ return [f"block: removed from {p}"]
+
+ def wire_lifecycle(self, *, force: bool = False, dry_run: bool = False) -> list:
+ return (install_canonical_skills(dry_run=dry_run) + self.wire_block(dry_run=dry_run)
+ + install_shims("codex", self.skill_shim_targets(), dry_run=dry_run, force=force))
+
+ def wire(self, *, force: bool = False, dry_run: bool = False,
+ prompt_fn: Optional[Callable[..., str]] = None) -> WireOutcome:
+ out = self._wire_mcp(force=force, dry_run=dry_run, prompt_fn=prompt_fn)
+ if out.status in ("wired", "already", "dry-run"):
+ try:
+ out.lifecycle = self.wire_lifecycle(force=force, dry_run=dry_run)
+ except Exception as e:
+ out.lifecycle = [f"skills/block not installed: {type(e).__name__}: {e}"]
+ return out
+
+ def _wire_mcp(self, *, force: bool = False, dry_run: bool = False,
+ prompt_fn: Optional[Callable[..., str]] = None,
+ update_only: bool = False) -> WireOutcome:
+ state = self.current_state()
+ try:
+ sc = self._read_scan()
+ except (OSError, UnicodeDecodeError) as e:
+ return WireOutcome(self.name, "error",
+ f"{self.config_path} could not be read ({type(e).__name__}); it was not modified.")
+ if sc is not None and (sc["other_mention"] or len(sc["headers"]) > 1):
+ # Appending would be a TOML redefinition error (cli 0.7.0).
+ return WireOutcome(self.name, "error",
+ f"{self.config_path} already defines sibyl_memory in a form setup does not "
+ "edit; it was not modified.")
+ if sc is not None:
+ # Panel fix 3: never edit a file the TOML parser already rejects.
+ terr = self._toml_error("".join(sc["lines"]))
+ if terr is not None:
+ return WireOutcome(self.name, "error",
+ f"{self.config_path} is not valid TOML ({terr}); it was not modified. "
+ "Fix the file, then run sibyl setup codex again.",
+ handoff=("done", f"{self.config_path} is not valid TOML ({terr}); fix it, "
+ "then run sibyl setup codex", ()))
+ has_header = bool(sc and sc["headers"])
+ if update_only and not has_header:
+ return WireOutcome(self.name, "error",
+ f"{self.config_path} has no [mcp_servers.sibyl_memory] table to repair; "
+ "run sibyl setup codex to add one.")
+ cmd = sc["command"] if has_header else None
+ if has_header and cmd["line"] is not None and not cmd["parsed"]:
+ return WireOutcome(self.name, "error",
+ f"{self.config_path} has a sibyl_memory command value setup does not edit; "
+ "it was not modified.")
+ if has_header and sc["command_lines"] > 1:
+ return WireOutcome(self.name, "error",
+ f"{self.config_path} has more than one command line in the sibyl_memory table; "
+ "it was not modified.")
+ # The foreign gate runs before the "already" return (CHECK-FABLE N-1):
+ # a table of that name that runs another server is not ours.
+ foreign = bool(has_header and cmd["parsed"] and not _is_our_command(cmd["value"]))
+ if foreign and update_only:
+ return WireOutcome(self.name, "error",
+ f"the sibyl_memory table in {self.config_path} runs another command; "
+ "doctor does not change it.")
+ if foreign and not force:
+ # Another server under our table name: same rule as Cursor and Hermes.
+ if prompt_fn is None or prompt_fn(
+ "Codex has a 'sibyl_memory' MCP entry pointing elsewhere. Replace it?",
+ default="N") != "y":
+ return WireOutcome(self.name, "skipped",
+ f"Existing sibyl_memory entry in {self.config_path} points elsewhere. "
+ "Use --force to replace it.",
+ overwrite_of="a different sibyl_memory MCP entry")
+ if state["wired_with_sibyl"] and not force and not foreign:
+ return WireOutcome(self.name, "already",
+ f"Codex already has the sibyl-memory MCP server in {self.config_path}")
+ if dry_run:
+ if foreign:
+ return WireOutcome(self.name, "dry-run",
+ f"Would replace the sibyl_memory table in {self.config_path}")
+ if has_header:
+ return WireOutcome(self.name, "dry-run",
+ f"Would update the sibyl_memory command in {self.config_path}")
+ verb = "create + add" if not state["config_exists"] else "append"
+ return WireOutcome(self.name, "dry-run",
+ f"Would {verb} [mcp_servers.sibyl_memory] in {self.config_path}")
+ if not self._ensure_mcp_binary():
+ return WireOutcome(self.name, "error",
+ f"'{self.MCP_BINARY}' is not installed. Install it: pip install {self.MCP_PACKAGE}"
+ + self._install_hint(), handoff=_binary_missing_handoff(self.name))
+ new: Optional[str] = None
+ if has_header:
+ # Stale-path fix (cli 0.7.0): rewrite the command line in place; a
+ # foreign table is replaced whole (no inherited args or env, the
+ # same whole-entry rule as Cursor and DeepSeek Harness). The backup
+ # is taken only when the text will change.
+ existing = "".join(sc["lines"])
+ try:
+ new = (self._replace_table(existing) if foreign
+ else self._set_block_command(existing))
+ except ValueError as e:
+ return WireOutcome(self.name, "error", f"{self.config_path}: {e}; it was not modified.")
+ if new == existing:
+ return WireOutcome(self.name, "already",
+ f"Codex already has the sibyl-memory MCP server in {self.config_path}")
+ try:
+ if foreign:
+ self._verify_table_replace(existing, new)
+ else:
+ self._verify_command_edit(existing, new)
+ except ValueError as e:
+ return WireOutcome(self.name, "error", str(e))
+ else:
+ # Panel fix 3: the appended table is planned and proven before the
+ # backup; a file it cannot be added to safely gets the manual table.
+ try:
+ self._append_plan(self._read_raw() if self.config_path.exists() else "")
+ except ValueError as e:
+ return self._manual_table_error(str(e))
+ try:
+ backup = self._backup_config()
+ except (OSError, ValueError) as e:
+ return _backup_failed(self.name, self.config_path, self.BACKUP_LABEL, e)
+ try:
+ if new is not None:
+ if self._read_raw() != existing:
+ return WireOutcome(self.name, "error",
+ f"{self.config_path} changed while setup was running; it was not "
+ "modified. Run it again.", backup_path=backup)
+ _write_via_tmp(self.config_path, self.config_path.with_suffix(".toml.tmp"), new,
+ through_symlink=True)
+ else:
+ self._append_block()
+ except Exception as e:
+ return WireOutcome(self.name, "error",
+ f"config write failed: {type(e).__name__}", backup_path=backup)
+ if foreign:
+ return WireOutcome(self.name, "wired",
+ f"Replaced the sibyl_memory table in {self.config_path}", backup_path=backup)
+ if has_header:
+ return WireOutcome(self.name, "wired",
+ f"Updated the sibyl_memory command in {self.config_path}", backup_path=backup)
+ return WireOutcome(self.name, "wired",
+ f"Added [mcp_servers.sibyl_memory] to {self.config_path}", backup_path=backup)
+
+ # -- doctor (spec dsh-doctor v2, 4.3) -------------------------------------
+ def doctor_probe(self) -> list:
+ try:
+ if not self.config_path.exists():
+ return [_probe("absent", self.config_path)]
+ sc = self._read_scan()
+ if sc["other_mention"] or len(sc["headers"]) > 1:
+ return [_probe("unreadable", self.config_path,
+ detail="sibyl_memory is defined in a form setup does not edit")]
+ # Panel fix 3: a file Codex cannot parse is never reported healthy.
+ terr = self._toml_error("".join(sc["lines"]))
+ if terr is not None:
+ return [_probe("unreadable", self.config_path, detail=f"not valid TOML ({terr})")]
+ if sc["headers"] and _codex_root_mcp_servers_key(sc["lines"]):
+ return [_probe("unreadable", self.config_path,
+ detail="mcp_servers is also set as a key; the table cannot be read")]
+ if not sc["headers"]:
+ return [_probe("absent", self.config_path)]
+ cmd = sc["command"]
+ if not cmd["parsed"]:
+ # Panel fix 7: an insert is proven only with a TOML parser.
+ return [_probe("present", self.config_path, broken=True, detail="no command in the table",
+ fixable=cmd["line"] is None and sc["command_lines"] == 0
+ and _tomllib is not None)]
+ value = cmd["value"]
+ if not _is_our_command(value):
+ # Never the foreign command string (it can carry a credential).
+ return [_probe("foreign", self.config_path, command=None,
+ detail="the sibyl_memory table runs another command")]
+ return [_probe("present", self.config_path, command=value)]
+ except Exception as e:
+ return [_probe("unreadable", self.config_path, detail=type(e).__name__)]
+
+ def repair_mcp(self, probe: dict) -> WireOutcome:
+ """The same update path as setup --force, restricted to an existing
+ table; never appends."""
+ return self._wire_mcp(force=True, update_only=True)
+
+ def _set_block_command(self, existing: str) -> str:
+ """Set the command of our table to the resolved path. Only the one
+ command line changes (its indent and trailing comment are kept); with no
+ command line, one is inserted right after the header. Line endings are
+ preserved. Raises ValueError when there is not exactly one header or the
+ command value is in a form this does not edit."""
+ sc = _codex_scan(existing)
+ if len(sc["headers"]) != 1 or sc["other_mention"]:
+ raise ValueError("sibyl_memory is defined in a form setup does not edit")
+ lines = list(sc["lines"])
+ esc = self._toml_escape(self._mcp_command())
+ cmd = sc["command"]
+ if cmd["line"] is not None:
+ if not cmd["parsed"]:
+ raise ValueError("the sibyl_memory command value is in a form setup does not edit")
+ old = lines[cmd["line"]]
+ eol = old[len(_strip_eol(old)):]
+ lines[cmd["line"]] = f'{cmd["indent"]}{cmd["key"]} = "{esc}"{cmd["suffix"]}{eol}'
+ else:
+ h = sc["headers"][0]
+ hdr = lines[h]
+ eol = hdr[len(_strip_eol(hdr)):]
+ if not eol:
+ eol = "\r\n" if "\r\n" in existing else "\n"
+ lines[h] = hdr + eol
+ lines.insert(h + 1, f'command = "{esc}"{eol}')
+ return "".join(lines)
+
+ def _verify_command_edit(self, old: str, new: str) -> None:
+ """Prove the command update changed only the command. On Python 3.11+
+ both texts must load with tomllib and be equal except for that value;
+ on 3.10 the text checks stand alone."""
+ bad = f"could not change {self.config_path} safely; it was not modified."
+ sc = _codex_scan(new)
+ cmd = sc["command"]
+ if len(sc["headers"]) != 1 or cmd["line"] is None or not cmd["parsed"]:
+ raise ValueError(bad)
+ if sc["command_lines"] != 1 or cmd["value"] != self._mcp_command():
+ raise ValueError(bad)
+ # Without tomllib (Python 3.10) the text checks stand alone, so they
+ # are strict (CHECK-FABLE B-3): the old table held at most one command
+ # line, the new one exactly one, and nothing else changed.
+ osc = _codex_scan(old)
+ if len(osc["headers"]) != 1 or osc["command_lines"] > 1 or osc["other_mention"]:
+ raise ValueError(bad)
+ if sc["other_mention"]:
+ raise ValueError(bad)
+ kept_new = [_strip_eol(x) for i, x in enumerate(sc["lines"]) if i != cmd["line"]]
+ kept_old = [_strip_eol(x) for i, x in enumerate(osc["lines"])
+ if i != osc["command"]["line"]]
+ if kept_new != kept_old:
+ raise ValueError(bad)
+ # Panel fix 2: the edited line sits inside our own table, before the
+ # first depth-0 line starting with '[' after our header, whatever the
+ # header parser made of that line.
+ h = sc["headers"][0]
+ if not (h < cmd["line"] < _codex_body_end(sc["lines"], h + 1)):
+ raise ValueError(bad)
+ if _tomllib is None:
+ return
+ try:
+ old_doc = _toml_loads(old)
+ except Exception:
+ raise ValueError(f"{self.config_path} is not valid TOML; it was not modified.")
+ try:
+ new_doc = _toml_loads(new)
+ except Exception:
+ raise ValueError(bad)
+ import copy
+ want = copy.deepcopy(old_doc)
+ try:
+ want["mcp_servers"]["sibyl_memory"]["command"] = self._mcp_command()
+ except (KeyError, TypeError):
+ raise ValueError(bad)
+ if new_doc != want:
+ raise ValueError(bad)
+
+ def _replace_table(self, existing: str) -> str:
+ """Our whole table in place of a foreign one: the header line stays,
+ its body and every [mcp_servers.sibyl_memory.*] subtable go, and one
+ command line is written. Raises ValueError for a form this does not edit."""
+ sc = _codex_scan(existing)
+ if len(sc["headers"]) != 1 or sc["other_mention"] or sc["body"] is None:
+ raise ValueError("sibyl_memory is defined in a form setup does not edit")
+ lines = list(sc["lines"])
+ h = sc["headers"][0]
+ b, e = sc["body"]
+ hdr = lines[h]
+ eol = hdr[len(_strip_eol(hdr)):] or ("\r\n" if "\r\n" in existing else "\n")
+ drop = set(range(b, e))
+ for sh, se in sc["subtables"]:
+ drop.update(range(sh, se))
+ esc = self._toml_escape(self._mcp_command())
+ out = []
+ for i, ln in enumerate(lines):
+ if i in drop:
+ continue
+ if i == h:
+ out.append(_strip_eol(hdr) + eol)
+ out.append(f'command = "{esc}"{eol}')
+ # keep a blank line before what follows, as the body had
+ if e < len(lines) and b < e and not _strip_eol(lines[e - 1]).strip():
+ out.append(eol)
+ continue
+ out.append(ln)
+ return "".join(out)
+
+ def _verify_table_replace(self, old: str, new: str) -> None:
+ bad = f"could not change {self.config_path} safely; it was not modified."
+ sc = _codex_scan(new)
+ cmd = sc["command"]
+ if (len(sc["headers"]) != 1 or sc["other_mention"] or sc["subtables"]
+ or sc["command_lines"] != 1 or not cmd["parsed"]
+ or cmd["value"] != self._mcp_command()):
+ raise ValueError(bad)
+ b, e = sc["body"]
+ if any(_strip_eol(sc["lines"][k]).strip() and k != cmd["line"] for k in range(b, e)):
+ raise ValueError(bad)
+ # Panel fix 2: every old line outside our table and its subtables is
+ # still there, unchanged and in order (checked before the parser
+ # proof, so it also holds where no TOML parser is available).
+ osc = _codex_scan(old)
+ if len(osc["headers"]) != 1 or osc["body"] is None:
+ raise ValueError(bad)
+ oh = osc["headers"][0]
+ ob, oe = osc["body"]
+ odrop = set(range(oh, oe))
+ for sh, se in osc["subtables"]:
+ odrop.update(range(sh, se))
+ kept_old = [x for i, x in enumerate(osc["lines"]) if i not in odrop]
+ nh = sc["headers"][0]
+ kept_new = [x for i, x in enumerate(sc["lines"]) if not (nh <= i < e)]
+ if kept_old != kept_new or _strip_eol(sc["lines"][nh]) != _strip_eol(osc["lines"][oh]):
+ raise ValueError(bad)
+ if _tomllib is None:
+ return
+ try:
+ old_doc = _toml_loads(old)
+ except Exception:
+ raise ValueError(f"{self.config_path} is not valid TOML; it was not modified.")
+ try:
+ new_doc = _toml_loads(new)
+ except Exception:
+ raise ValueError(bad)
+ import copy
+ want = copy.deepcopy(old_doc)
+ try:
+ want["mcp_servers"]["sibyl_memory"] = {"command": self._mcp_command()}
+ except (KeyError, TypeError):
+ raise ValueError(bad)
+ if new_doc != want:
+ raise ValueError(bad)
+
+ def _backup_config(self) -> Optional[Path]:
+ # B005 (audit #19): timestamped backup so repeated runs don't clobber it.
+ return _timestamped_backup(self.config_path, self.BACKUP_LABEL)
+
+ @staticmethod
+ def _toml_error(text: str) -> Optional[str]:
+ """None when no TOML parser is available or ``text`` parses; else a
+ brief (error type plus line and column, never file text)."""
+ if _tomllib is None:
+ return None
+ try:
+ _toml_loads(text)
+ except Exception as e:
+ m = re.search(r"\(at line (\d+), column (\d+)\)", str(e))
+ where = f" at line {m.group(1)}, column {m.group(2)}" if m else ""
+ return f"{type(e).__name__}{where}"
+ return None
+
+ def _append_plan(self, existing: str) -> str:
+ """The file text with our table appended, proven before it is used
+ (panel fix 3). With a TOML parser: the old text must parse and the new
+ text must equal it plus mcp_servers.sibyl_memory = {command = path}.
+ Without one, a file that sets mcp_servers as a key or ends inside an
+ open string or array is refused. The file's line ending is kept.
+ Raises ValueError with the reason."""
+ bad = f"could not add the table to {self.config_path} safely; it was not modified."
+ lines = existing.splitlines(keepends=True)
+ if _codex_root_mcp_servers_key(lines):
+ raise ValueError(
+ f"{self.config_path} sets mcp_servers as a key (an inline table or dotted "
+ "keys), so a [mcp_servers.sibyl_memory] table cannot be added; it was not "
+ "modified.")
+ if _toml_text_open_at_end(existing):
+ raise ValueError(
+ f"{self.config_path} ends inside an unterminated string or array; it was not "
+ "modified.")
+ nl = "\r\n" if "\r\n" in existing else "\n"
+ cmd = self._mcp_command()
+ block = self._block_text().replace("\n", nl)
+ base = existing.rstrip("\r\n")
+ new = base + (nl if existing.strip() else "") + block
+ sc = _codex_scan(new)
+ c = sc["command"]
+ if (len(sc["headers"]) != 1 or sc["other_mention"] or sc["command_lines"] != 1
+ or not c["parsed"] or c["value"] != cmd or not new.startswith(base)):
+ raise ValueError(bad)
+ if _tomllib is not None:
+ try:
+ old_doc = _toml_loads(existing)
+ except Exception:
+ raise ValueError(f"{self.config_path} is not valid TOML "
+ f"({self._toml_error(existing)}); it was not modified.")
+ try:
+ new_doc = _toml_loads(new)
+ except Exception:
+ raise ValueError(bad)
+ import copy
+ want = copy.deepcopy(old_doc)
+ ms = want.setdefault("mcp_servers", {})
+ if not isinstance(ms, dict) or "sibyl_memory" in ms:
+ raise ValueError(bad)
+ ms["sibyl_memory"] = {"command": cmd}
+ if new_doc != want:
+ raise ValueError(bad)
+ return new
+
+ def _manual_table_error(self, reason: str) -> WireOutcome:
+ """Error outcome with the exact text to add by hand (panel fix 3)."""
+ cmd = self._toml_escape(self._mcp_command())
+ try:
+ inline = _codex_root_mcp_servers_key(self._read_raw().splitlines(keepends=True))
+ except (OSError, UnicodeDecodeError):
+ inline = False
+ if inline:
+ how = "Add this entry to the mcp_servers table in that file by hand:"
+ block = f'sibyl_memory = {{ command = "{cmd}" }}'
+ else:
+ how = "Add this table to that file by hand:"
+ block = f'[mcp_servers.sibyl_memory]\ncommand = "{cmd}"'
+ return WireOutcome(self.name, "error", f"{reason} {how}\n{block}", handoff=(
+ "done",
+ f"add the printed sibyl_memory entry to {self.config_path} by hand (setup could not "
+ "add it safely)", ()), manual_block=block)
+
+ def _append_block(self) -> bool:
+ """Add our table, or (cli 0.7.0), when it is already there, update its
+ command in place. Returns True when the file was written. Before 0.7.0
+ an existing header made this return early, so a stale path was never
+ fixed even with --force while the outcome said "wired". Panel fix 3:
+ the appended text is proven by _append_plan (ValueError otherwise)."""
+ self.config_path.parent.mkdir(parents=True, exist_ok=True)
+ existing = ""
+ if self.config_path.exists():
+ raw = self._read_raw()
+ if _codex_scan(raw)["headers"]:
+ existing = raw
+ new_text = self._set_block_command(existing)
+ if new_text == existing:
+ return False
+ self._verify_command_edit(existing, new_text)
+ tmp = self.config_path.with_suffix(".toml.tmp")
+ _write_via_tmp(self.config_path, tmp, new_text, through_symlink=True)
+ return True
+ existing = raw
+ new_text = self._append_plan(existing)
+ tmp = self.config_path.with_suffix(".toml.tmp")
+ _write_via_tmp(self.config_path, tmp, new_text, through_symlink=True)
+ return True
+
+
+# ----------------------------------------------------------------------
+# CursorWirer: Cursor (and Grok Bot, which runs on a Cursor cloud machine)
+# reads MCP servers from ~/.cursor/mcp.json. Format verified against Cursor's
+# docs (https://cursor.com/docs/context/mcp): top-level "mcpServers", each
+# stdio entry {"type": "stdio", "command": ..., "args": [...], "env": {...}}.
+# Same protocol as the other wirers: timestamped backup, atomic write, a
+# corrupt file is never replaced, foreign entries are never touched.
+# ----------------------------------------------------------------------
+
+MCP_BINARY_NAME = "sibyl-memory-mcp"
+
+
+def _mcp_search_dirs() -> list:
+ """Places the installer and pip put the MCP server binary that may not be
+ on PATH yet: the running interpreter's scripts directory (a venv that is
+ not activated) and the user bin directory (~/.local/bin, where
+ sibyllabs.org/install and `pip install --user` put it on a fresh machine)."""
+ return [Path(sys.executable).parent, Path.home() / ".local" / "bin"]
+
+
+def resolve_mcp_binary() -> Optional[str]:
+ """Absolute path of the installed MCP server binary, or None. PATH first,
+ then the known install directories, so a fresh shell whose PATH does not
+ yet include ~/.local/bin still finds it (cli 0.6.1)."""
+ w = shutil.which(MCP_BINARY_NAME)
+ if w:
+ return os.path.abspath(w)
+ for d in _mcp_search_dirs():
+ cand = d / MCP_BINARY_NAME
+ if cand.is_file() and os.access(cand, os.X_OK):
+ return str(cand)
+ return None
+
+
+def mcp_command_path() -> str:
+ """Absolute path of the MCP server binary for a client config (see
+ resolve_mcp_binary). Falls back to the bare name."""
+ return resolve_mcp_binary() or MCP_BINARY_NAME
+
+
+def _command_resolves(cmd: Any, *, strict: bool = False) -> bool:
+ """Whether a configured MCP command would start something (cli 0.7.0).
+ An absolute path must be a file with the execute bit; a bare name must be
+ on PATH, or (lenient mode, used by setup) be the server's own name while
+ the server is installed where resolve_mcp_binary() finds it. Doctor uses
+ strict=True: the harness spawns from its own PATH."""
+ if not isinstance(cmd, str) or not cmd:
+ return False
+ if os.path.isabs(cmd):
+ return os.path.isfile(cmd) and os.access(cmd, os.X_OK)
+ if shutil.which(cmd):
+ return True
+ if not strict and cmd == MCP_BINARY_NAME:
+ return resolve_mcp_binary() is not None
+ return False
+
+
+def mcp_servers_snippet(command: Optional[str] = None) -> str:
+ """Copy-paste ``mcpServers`` JSON any MCP client accepts for a stdio
+ server (A2: lets an agent wire itself from `sibyl setup` output)."""
+ cmd = command or mcp_command_path()
+ return json.dumps(
+ {"mcpServers": {"sibyl-memory": {"type": "stdio", "command": cmd}}}, indent=2)
+
+
+class CursorWirer:
+ name = "cursor"
+ display_name = "Cursor"
+ initial = "u"
+
+ MCP_BINARY = MCP_BINARY_NAME
+ MCP_PACKAGE = "sibyl-memory-mcp"
+ MCP_NAME = "sibyl-memory"
+
+ def __init__(self, *, config_path: Optional[Union[str, Path]] = None):
+ self.config_path = (
+ Path(config_path).expanduser() if config_path
+ else Path.home() / ".cursor" / "mcp.json"
+ )
+
+ def _entry(self) -> dict:
+ return {"type": "stdio", "command": mcp_command_path()}
+
+ def is_present(self) -> bool:
+ if self.config_path.exists() or self.config_path.parent.is_dir():
+ return True
+ return bool(shutil.which("cursor") or shutil.which("cursor-agent"))
+
+ def _mcp_binary_found(self) -> bool:
+ # Cursor's config stores the absolute path, so the server does not
+ # need to be on PATH; it only needs to be installed (cli 0.6.1).
+ return resolve_mcp_binary() is not None
+
+ _last_install_error: Optional[str] = None
+
+ def _install_hint(self) -> str:
+ return f"\n{self._last_install_error}" if self._last_install_error else ""
+
+ def _ensure_mcp_binary(self) -> bool:
+ if self._mcp_binary_found():
+ return True
+ self._last_install_error = _install_pkg_or_instruct(self.MCP_PACKAGE)
+ return self._mcp_binary_found()
+
+ def verify_mcp_starts(self) -> tuple:
+ binary = resolve_mcp_binary()
+ if not binary:
+ return False, f"'{self.MCP_BINARY}' is not installed"
+ return _verify_mcp_starts(binary)
+
+ def current_state(self) -> dict:
+ exists = self.config_path.exists()
+ block: Optional[dict] = None
+ parse_error: Optional[str] = None
+ if exists:
+ try:
+ cfg = json.loads(self.config_path.read_text(encoding="utf-8") or "{}")
+ servers = cfg.get("mcpServers") if isinstance(cfg, dict) else None
+ if isinstance(servers, dict) and isinstance(servers.get(self.MCP_NAME), dict):
+ block = servers[self.MCP_NAME]
+ except Exception as e:
+ parse_error = f"{type(e).__name__}: {e}"
+ cmd = (block or {}).get("command")
+ is_ours = self._is_ours(block)
+ return {
+ "settings_path": str(self.config_path),
+ "config_exists": exists,
+ "config_parse_error": parse_error,
+ "sibyl_mcp": block,
+ "is_ours": is_ours,
+ "mcp_binary_found": self._mcp_binary_found(),
+ # cli 0.7.0: a stale absolute path is not "already wired".
+ "wired_with_sibyl": bool(is_ours and _command_resolves(cmd)),
+ }
+
+ def _is_ours(self, block: Any) -> bool:
+ cmd = block.get("command") if isinstance(block, dict) else None
+ return bool(isinstance(cmd, str)
+ and Path(cmd.replace("\\", "/")).name.startswith(self.MCP_BINARY))
+
+ # -- doctor (spec dsh-doctor v2, 4.4) -------------------------------------
+ def _read_block_for_probe(self) -> dict:
+ if not self.config_path.exists():
+ return _probe("absent", self.config_path)
+ raw = self.config_path.read_text(encoding="utf-8")
+ try:
+ cfg = json.loads(raw or "{}")
+ except json.JSONDecodeError as e:
+ return _probe("unreadable", self.config_path,
+ detail=f"JSONDecodeError at line {e.lineno}, column {e.colno}")
+ if not isinstance(cfg, dict):
+ return _probe("unreadable", self.config_path, detail="top level is not a JSON object")
+ servers = cfg.get("mcpServers")
+ block = servers.get(self.MCP_NAME) if isinstance(servers, dict) else None
+ if block is None:
+ return _probe("absent", self.config_path)
+ if not isinstance(block, dict):
+ return _probe("unreadable", self.config_path, detail="the sibyl-memory entry is not an object")
+ cmd = block.get("command")
+ if not self._is_ours(block):
+ # Never the foreign command string (it can carry a credential).
+ return _probe("foreign", self.config_path, command=None,
+ detail="the sibyl-memory entry runs another command")
+ return _probe("present", self.config_path, command=cmd)
+
+ def doctor_probe(self) -> list:
+ try:
+ return [self._read_block_for_probe()]
+ except Exception as e:
+ return [_probe("unreadable", self.config_path, detail=type(e).__name__)]
+
+ def repair_mcp(self, probe: dict) -> WireOutcome:
+ """The merge path only: our own entry gets the resolved command, every
+ other key is kept. A foreign or missing entry is never touched."""
+ p = self._read_block_for_probe()
+ if p["entry"] != "present":
+ return WireOutcome(self.name, "error",
+ f"no sibyl-memory entry of ours in {self.config_path} to repair")
+ try:
+ backup = _timestamped_backup(self.config_path, "cursor")
+ except (OSError, ValueError) as e:
+ return _backup_failed(self.name, self.config_path, "cursor", e)
+ try:
+ self._write_config()
+ except Exception as e:
+ return WireOutcome(self.name, "error",
+ f"config write failed: {type(e).__name__}", backup_path=backup)
+ return WireOutcome(self.name, "wired",
+ f"Updated the sibyl-memory command in {self.config_path}", backup_path=backup)
+
+ def wire(self, *, force: bool = False, dry_run: bool = False,
+ prompt_fn: Optional[Callable[..., str]] = None) -> WireOutcome:
+ state = self.current_state()
+ if state["config_parse_error"]:
+ return WireOutcome(self.name, "error",
+ f"{self.config_path} is not valid JSON ({state['config_parse_error']}). "
+ "Fix the file or move it aside and re-run setup; it was not modified.")
+ if state["wired_with_sibyl"] and not force:
+ return WireOutcome(self.name, "already",
+ f"{self.display_name} already has the sibyl-memory MCP server in {self.config_path}")
+ block = state["sibyl_mcp"]
+ # cli 0.7.0: the "differs" gate is for an entry that is not ours. Our
+ # own entry with a stale path is updated without a prompt.
+ if block and not state["is_ours"] and not force:
+ if prompt_fn is None:
+ return WireOutcome(self.name, "skipped",
+ "Existing sibyl-memory MCP entry differs. Use --force to overwrite.",
+ overwrite_of="a different sibyl-memory MCP entry")
+ if prompt_fn("Cursor has a 'sibyl-memory' MCP entry pointing elsewhere. Update?",
+ default="N") != "y":
+ return WireOutcome(self.name, "skipped", "MCP entry update declined.",
+ overwrite_of="a different sibyl-memory MCP entry")
+ if dry_run:
+ verb = "update" if block else "add"
+ return WireOutcome(self.name, "dry-run",
+ f"Would {verb} mcpServers.sibyl-memory in {self.config_path}")
+ if not self._ensure_mcp_binary():
+ looked = ", ".join(str(d) for d in _mcp_search_dirs())
+ return WireOutcome(self.name, "error",
+ f"'{self.MCP_BINARY}' is not installed (looked on PATH and in {looked}). "
+ f"Install it: pip install {self.MCP_PACKAGE}"
+ + self._install_hint())
+ try:
+ backup = _timestamped_backup(self.config_path, "cursor")
+ except (OSError, ValueError) as e:
+ return _backup_failed(self.name, self.config_path, "cursor", e)
+ try:
+ self._write_config()
+ except Exception as e:
+ return WireOutcome(self.name, "error",
+ f"config write failed: {type(e).__name__}: {e}", backup_path=backup)
+ if block and state["is_ours"]:
+ return WireOutcome(self.name, "wired",
+ f"Updated the sibyl-memory command in {self.config_path}", backup_path=backup)
+ return WireOutcome(self.name, "wired",
+ f"Added SIBYL Memory MCP server to {self.config_path}", backup_path=backup)
+
+ def _write_config(self) -> None:
+ cfg: dict = {}
+ if self.config_path.exists():
+ raw = self.config_path.read_text(encoding="utf-8")
+ if raw.strip():
+ try:
+ loaded = json.loads(raw)
+ except ValueError as e:
+ raise ValueError(
+ f"{self.config_path} is not valid JSON ({e}). Fix the file or move "
+ "it aside and re-run setup; it was not modified.") from e
+ if not isinstance(loaded, dict):
+ raise ValueError(
+ f"{self.config_path} top level is not a JSON object "
+ f"(got {type(loaded).__name__}); it was not modified.")
+ cfg = loaded
+ if not isinstance(cfg.get("mcpServers"), dict):
+ cfg["mcpServers"] = {}
+ cur = cfg["mcpServers"].get(self.MCP_NAME)
+ if self._is_ours(cur):
+ # cli 0.7.0: merge into our own entry; env, args and every other key
+ # the person set are kept, only the command (and a missing type) change.
+ merged = dict(cur)
+ merged["command"] = mcp_command_path()
+ merged.setdefault("type", "stdio")
+ cfg["mcpServers"][self.MCP_NAME] = merged
+ else:
+ cfg["mcpServers"][self.MCP_NAME] = self._entry()
+ self.config_path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = self.config_path.with_suffix(".json.tmp")
+ _write_via_tmp(self.config_path, tmp, json.dumps(cfg, indent=2) + "\n",
+ through_symlink=True)
+
+
+class GrokBotWirer(CursorWirer):
+ """`sibyl setup grokbot`: Grok Bot runs on a Cursor cloud machine with local
+ stdio MCP, so it is the Cursor wiring plus a printed confirmation. Explicit
+ target only (never auto-detected, so Cursor is not wired twice)."""
+ name = "grokbot"
+ display_name = "Grok Bot (Cursor)"
+ initial = "g"
+
+
+# ----------------------------------------------------------------------
+# DeepSeekWirer: DeepSeek Harness (developer preview) loads MCP servers from
+# loader patch files: /cordis.patch.yml (covers every profile) and
+# /profiles//cordis.patch.yml. One `@deepseek-ai/dsh-mcp-client`
+# insert row is added as TEXT (never re-serialized), verified by parsing the
+# result before any write. Detection is by DeepSeek Harness's own files only;
+# no binary named dsh is ever looked up or run (the Debian dsh package, a
+# distributed shell, also uses ~/.dsh). Spec dsh-doctor v2, section 3.
+# ----------------------------------------------------------------------
+
+class DeepSeekWirer:
+ name = "deepseek"
+ display_name = "DeepSeek Harness"
+ initial = "d"
+
+ MCP_BINARY = MCP_BINARY_NAME
+ MCP_PACKAGE = "sibyl-memory-mcp"
+ PLUGIN = "@deepseek-ai/dsh-mcp-client"
+ ENTRY_ID = "sibyl-memory"
+ SERVER_NAME = "sibyl-memory"
+ PATCH_FILENAME = "cordis.patch.yml"
+ PASS_ENV = ("SIBYL_MEMORY_MCP_OUTPUT_TOKENS", "SIBYL_MEMORY_RANKED_MIN_TOKENS")
+ FOREIGN_HOME_MARKERS = ("dsh.conf", "machines.list", "group")
+ BLOCK_COMMENT = ('# Sibyl Memory MCP server (added by "sibyl setup deepseek"; '
+ 're-run it to update the path)')
+ FILE_HEADER = ("# DeepSeek Harness user patch layer: a top-level YAML list of loader patch entries.",
+ "# Add your own entries above or below the Sibyl Memory block.")
+ _PASS_ENV_VALUE = re.compile(r"^[0-9]{1,7}$")
+
+ def __init__(self, *, dsh_home: Optional[Union[str, Path]] = None,
+ profile: Optional[str] = None):
+ self.dsh_home = self._auto_dsh_home(dsh_home)
+ if profile is not None:
+ self._check_profile(profile)
+ self.profile = profile
+ self.home_patch = self.dsh_home / self.PATCH_FILENAME
+ if profile:
+ self.target_path = self.dsh_home / "profiles" / profile / self.PATCH_FILENAME
+ else:
+ self.target_path = self.home_patch
+ self.config_path = self.target_path
+
+ # -- paths and detection -------------------------------------------------
+ @staticmethod
+ def _auto_dsh_home(explicit: Optional[Union[str, Path]] = None) -> Path:
+ """Mirror DeepSeek Harness: $DSH_HOME when set and not blank, else
+ ~/.dsh; a leading ~ is expanded; the result is absolute."""
+ if explicit:
+ raw = str(explicit)
+ else:
+ env = os.environ.get("DSH_HOME")
+ raw = env if env is not None and env.strip() else str(Path.home() / ".dsh")
+ return Path(os.path.abspath(os.path.expanduser(raw)))
+
+ @staticmethod
+ def _check_profile(name: str) -> None:
+ if (not name or "/" in name or "\\" in name
+ or name in (".", "..", "node_modules")):
+ raise ValueError(
+ f"'{name}' is not a valid DeepSeek Harness profile name (it must be a folder "
+ "name under the profiles directory: not empty, no slashes, not '.', '..' or "
+ "'node_modules').")
+
+ def is_present(self) -> bool:
+ # DeepSeek Harness's own files only: never ~/.dsh existing, never PATH.
+ try:
+ return (self.dsh_home / "profiles").is_dir() or self.home_patch.is_file()
+ except OSError:
+ return False
+
+ def _home_shape(self) -> str:
+ h = self.dsh_home
+ if not h.exists() and not h.is_symlink():
+ return "missing"
+ if not h.is_dir():
+ return "not-a-dir"
+ if self.is_present():
+ return "dsh"
+ try:
+ empty = not any(h.iterdir())
+ except OSError:
+ return "foreign"
+ return "empty" if empty else "foreign"
+
+ def _profile_names(self) -> list:
+ d = self.dsh_home / "profiles"
+ try:
+ names = [c.name for c in d.iterdir() if c.is_dir()]
+ except OSError:
+ return []
+ return sorted(n for n in names if not n.startswith(".") and n != "node_modules")
+
+ def _layer_path(self, layer: str) -> Path:
+ if layer == "home":
+ return self.home_patch
+ return self.dsh_home / "profiles" / layer.split(":", 1)[1] / self.PATCH_FILENAME
+
+ # -- the row -------------------------------------------------------------
+ def _pass_env(self) -> dict:
+ """The two variables DeepSeek Harness's environment scrub drops
+ (their names contain TOKEN), copied into the row's env only when set
+ to a plain number at setup time. Nothing else is ever copied."""
+ env = {}
+ for n in self.PASS_ENV:
+ v = os.environ.get(n)
+ if v is not None and self._PASS_ENV_VALUE.match(v):
+ env[n] = v
+ return env
+
+ def _row_lines(self, command: str, env: Optional[dict]) -> list:
+ """The nine row lines, `id:` through `cwd:`, indented relative to the
+ row's first key."""
+ env_text = json.dumps(env, ensure_ascii=False) if env else "{}"
+ return [
+ f"id: {self.ENTRY_ID}",
+ f"name: '{self.PLUGIN}'",
+ "config:",
+ f" serverName: {self.SERVER_NAME}",
+ " transport: stdio",
+ f" command: {json.dumps(command, ensure_ascii=False)}",
+ " args: []",
+ f" env: {env_text}",
+ " cwd: !!js process.cwd()",
+ ]
+
+ def _entry_text(self, command: str, nl: str = "\n", env: Optional[dict] = None) -> str:
+ rows = self._row_lines(command, env)
+ lines = [self.BLOCK_COMMENT, "- insert:", " - " + rows[0]]
+ lines += [" " + r for r in rows[1:]]
+ return nl.join(lines) + nl
+
+ def _expected_row(self, command: str, env: Optional[dict] = None) -> dict:
+ return {
+ "id": self.ENTRY_ID,
+ "name": self.PLUGIN,
+ "config": {
+ "serverName": self.SERVER_NAME,
+ "transport": "stdio",
+ "command": command,
+ "args": [],
+ "env": dict(env or {}),
+ "cwd": _JsExpr("process.cwd()"),
+ },
+ }
+
+ # -- scanning ------------------------------------------------------------
+ JS_NOTE = "the command is a !!js expression; not checked"
+
+ def _is_candidate(self, row: dict) -> tuple:
+ """(candidate, ours) for one row mapping (3.4)."""
+ cfg = row.get("config") if isinstance(row.get("config"), dict) else {}
+ c1 = row.get("id") == self.ENTRY_ID
+ c2 = row.get("name") == self.PLUGIN and cfg.get("serverName") == self.SERVER_NAME
+ cmd = cfg.get("command")
+ c3 = bool(row.get("name") == self.PLUGIN and cmd is not None
+ and Path(str(cmd).replace("\\", "/")).name.startswith(self.MCP_BINARY))
+ return (c1 or c2 or c3), c3
+
+ @staticmethod
+ def _map_child(node, key: str):
+ """The value node for ``key`` in a MappingNode (the last one wins, as
+ when loading), or None."""
+ found = None
+ for k, v in getattr(node, "value", None) or []:
+ if getattr(k, "value", None) == key and type(k).__name__ == "ScalarNode":
+ found = v
+ return found
+
+ def _walk_rows(self, rows: Any, nodes: Any, path: list, out: list) -> None:
+ if not isinstance(rows, list):
+ return
+ node_items = list(getattr(nodes, "value", None) or []) \
+ if type(nodes).__name__ == "SequenceNode" else []
+ for j, row in enumerate(rows):
+ node = node_items[j] if j < len(node_items) else None
+ if not isinstance(row, dict):
+ continue
+ here = path + [j]
+ if row.get("group") and isinstance(row.get("config"), list):
+ self._walk_rows(row["config"], self._map_child(node, "config"),
+ here + ["config"], out)
+ continue
+ cand, ours = self._is_candidate(row)
+ if not cand:
+ continue
+ cfg = row.get("config") if isinstance(row.get("config"), dict) else {}
+ cfg_node = self._map_child(node, "config")
+ cmd_node = self._map_child(cfg_node, "command") if cfg_node is not None else None
+ if cmd_node is not None and type(cmd_node).__name__ != "ScalarNode":
+ cmd_node = None
+ out.append({
+ "id": row.get("id"),
+ "serverName": cfg.get("serverName"),
+ "command": cfg.get("command") if isinstance(cfg.get("command"), str) else None,
+ # A `!!js` expression is evaluated by the harness at load time:
+ # it is not a path, so it is never judged stale and never
+ # rewritten without --force (CHECK-FABLE B-2, spec 3.2).
+ "command_js": type(cfg.get("command")) is _JsExpr,
+ "ours": ours,
+ "disabled": row.get("disabled") is True,
+ "path": here,
+ "row_node": node,
+ "command_node": cmd_node,
+ })
+
+ def _scan_text(self, text: str) -> dict:
+ """Parse one patch file's text. Raises on a YAML error."""
+ root = _dsh_yaml_compose(text)
+ data = _dsh_yaml_load(text)
+ res = {"top": None, "error": None, "data": data, "root": root,
+ "candidates": [], "overrides": [], "manager": []}
+ if data is None:
+ res["top"] = "empty"
+ return res
+ if not isinstance(data, list):
+ res["top"] = "other"
+ res["error"] = "top level is not a YAML list"
+ return res
+ res["top"] = "list"
+ items = list(root.value) if type(root).__name__ == "SequenceNode" else []
+ for i, patch in enumerate(data):
+ if not isinstance(patch, dict):
+ continue
+ node = items[i] if i < len(items) else None
+ if "insert" in patch:
+ self._walk_rows(patch.get("insert"), self._map_child(node, "insert"),
+ [i, "insert"], res["candidates"])
+ elif "id" in patch:
+ # Position kept: an override only reaches a row inserted
+ # earlier in the composed list (sandbox M1).
+ res["overrides"].append((patch.get("id"), i))
+ if patch.get("id") == self.MANAGER_ID:
+ servers = self._manager_servers(patch)
+ if servers is not None:
+ res["manager"].append((i, servers))
+ return res
+
+ def _scan_file(self, path: Path, layer: str) -> dict:
+ scan = {"layer": layer, "path": str(path), "exists": False, "error": None,
+ "top": None, "text": None, "data": None, "root": None,
+ "candidates": [], "overrides": [], "manager": [], "mentions": False}
+ try:
+ if not path.exists():
+ return scan
+ except OSError as e:
+ scan["exists"] = True
+ scan["error"] = type(e).__name__
+ return scan
+ scan["exists"] = True
+ try:
+ with open(path, encoding="utf-8", newline="") as fh:
+ text = fh.read()
+ except (OSError, UnicodeDecodeError) as e:
+ scan["error"] = type(e).__name__
+ return scan
+ scan["text"] = text
+ scan["mentions"] = "sibyl-memory" in text
+ try:
+ scan.update(self._scan_text(text))
+ except Exception as e:
+ scan["error"] = _yaml_error_brief(e)
+ return scan
+
+ def _scan_layers(self) -> list:
+ layers = [self._scan_file(self.home_patch, "home")]
+ for n in self._profile_names():
+ layers.append(self._scan_file(self._layer_path("profile:" + n), "profile:" + n))
+ if self.profile and not any(l["layer"] == "profile:" + self.profile for l in layers):
+ layers.append(self._scan_file(self.target_path, "profile:" + self.profile))
+ return layers
+
+ def _target_layer(self) -> str:
+ return "profile:" + self.profile if self.profile else "home"
+
+ def _relevant(self, layers: list) -> list:
+ if not self.profile:
+ return layers
+ keep = ("home", "profile:" + self.profile)
+ return [l for l in layers if l["layer"] in keep]
+
+ @staticmethod
+ def _duplicate_in(layers: list) -> bool:
+ """Judged per effective stack (the home patch plus one profile): two
+ rows in one file, or one in home and one in a profile. Rows in two
+ different profiles with nothing in home are not duplicates."""
+ if any(len(l["candidates"]) > 1 for l in layers):
+ return True
+ home = [l for l in layers if l["layer"] == "home"]
+ has_home = bool(home and home[0]["candidates"])
+ return has_home and any(l["candidates"] for l in layers if l["layer"] != "home")
+
+ @staticmethod
+ def _stacks_for(layers: list, layer: str) -> list:
+ """The effective stacks a file in ``layer`` takes part in, each in
+ DeepSeek Harness's composition order (F6: the profile patch, then the
+ home patch). A profile file is in one stack; the home patch is in one
+ per profile (or alone when there is none)."""
+ home = [l for l in layers if l["layer"] == "home"]
+ profiles = [l for l in layers if l["layer"] != "home"]
+ if layer != "home":
+ return [[l for l in profiles if l["layer"] == layer] + home]
+ return [[p] + home for p in profiles] or [home]
+
+ @classmethod
+ def _overridden(cls, cand: dict, layers: list, layer: str) -> bool:
+ """A top-level `{id: , ...}` patch without `insert` that comes
+ AFTER the row in the composed list: later in the same file, or in a
+ later layer of the same stack (the home patch follows a profile patch).
+ An override placed before the row is applied before the row exists
+ and does not reach it (sandbox M1, observed: the server still starts)."""
+ rid = cand.get("id")
+ if rid is None or not cand.get("path"):
+ return False
+ top = cand["path"][0]
+ for stack in cls._stacks_for(layers, layer):
+ rank = next((k for k, l in enumerate(stack) if l["layer"] == layer), None)
+ if rank is None:
+ continue
+ for k, l in enumerate(stack):
+ for oid, idx in l["overrides"]:
+ if oid == rid and (k > rank or (k == rank and idx > top)):
+ return True
+ return False
+
+ MANAGER_ID = "mcp-manager"
+ MANAGER_CLASH_TEXT = ("DeepSeek Harness's own MCP settings also define a server named "
+ "sibyl-memory ({path}, mcp-manager servers); two servers with one name "
+ "make DeepSeek Harness fail one of them (serverName already in use).")
+
+ @classmethod
+ def _manager_servers(cls, patch: dict) -> Optional[dict]:
+ """For a top-level `{id: mcp-manager, config: {servers: {...}}}` patch
+ (what DeepSeek Harness's own MCP settings write), the servers map as
+ {name: enabled}; None when the patch does not set `servers`."""
+ cfg = patch.get("config")
+ if not isinstance(cfg, dict) or "servers" not in cfg:
+ return None
+ servers = cfg.get("servers")
+ if not isinstance(servers, dict):
+ return {}
+ out = {}
+ for name, entry in servers.items():
+ enabled = not (isinstance(entry, dict) and entry.get("enabled") is False)
+ out[str(name)] = enabled
+ return out
+
+ @classmethod
+ def _manager_clash(cls, layers: list, layer: str) -> Optional[str]:
+ """The path of the file whose DeepSeek Harness MCP settings
+ (`mcp-manager` `servers`) also define an enabled server named
+ sibyl-memory in a stack that ``layer`` belongs to, else None. The
+ servers map is replaced whole when set from a patch, so the last
+ `servers` in composition order is the one that counts. Two servers
+ with one serverName: the harness fails one of them ("serverName ...
+ is already in use")."""
+ for stack in cls._stacks_for(layers, layer):
+ last = None
+ for l in stack:
+ for _idx, servers in l.get("manager") or []:
+ last = (l["path"], servers)
+ if last is not None and last[1].get(cls.SERVER_NAME):
+ return last[0]
+ return None
+
+ @staticmethod
+ def _plain(cand: dict, layer: str) -> dict:
+ out = {k: cand.get(k) for k in ("id", "serverName", "command", "command_js", "ours",
+ "disabled")}
+ out["layer"] = layer
+ return out
+
+ def current_state(self) -> dict:
+ state = {
+ "settings_path": str(self.target_path),
+ "dsh_home": str(self.dsh_home),
+ "profile": self.profile,
+ "config_exists": False,
+ "config_parse_error": None,
+ "layers": [],
+ "sibyl_mcp": None,
+ "entry_layer": None,
+ "duplicate": False,
+ "command": None,
+ "mcp_binary_found": False,
+ "wired_with_sibyl": False,
+ }
+ try:
+ state["config_exists"] = self.target_path.exists()
+ state["mcp_binary_found"] = self._mcp_binary_found()
+ if _import_yaml() is None:
+ return state
+ layers = self._scan_layers()
+ rel = self._relevant(layers)
+ tgt = self._target_layer()
+ for l in layers:
+ state["layers"].append({
+ "layer": l["layer"], "path": l["path"], "exists": l["exists"],
+ "error": l["error"], "top": l["top"], "mentions": l["mentions"],
+ "candidates": [self._plain(c, l["layer"]) for c in l["candidates"]]})
+ if l["layer"] == tgt:
+ state["config_parse_error"] = l["error"]
+ cands = [(l["layer"], c) for l in rel for c in l["candidates"]]
+ ok_rel = [l for l in rel if not l["error"]]
+ state["duplicate"] = self._duplicate_in(rel) or any(
+ self._manager_clash(ok_rel, l["layer"]) for l in ok_rel if l["candidates"])
+ if cands:
+ layer, c = cands[0]
+ state["sibyl_mcp"] = self._plain(c, layer)
+ state["entry_layer"] = layer
+ state["command"] = c["command"]
+ state["wired_with_sibyl"] = bool(
+ cands and not state["duplicate"]
+ and all(c["ours"] and not c["disabled"]
+ and (c.get("command_js") or _command_resolves(c["command"]))
+ for _l, c in cands))
+ except Exception:
+ pass
+ return state
+
+ # -- planning and verification (3.7) -------------------------------------
+ @staticmethod
+ def _set_at(obj: Any, path: list, value: Any) -> None:
+ for k in path[:-1]:
+ obj = obj[k]
+ obj[path[-1]] = value
+
+ @staticmethod
+ def _get_at(obj: Any, path: list) -> Any:
+ for k in path:
+ obj = obj[k]
+ return obj
+
+ @staticmethod
+ def _last_leaf_end(node) -> int:
+ while True:
+ kind = type(node).__name__
+ if kind == "MappingNode" and not node.flow_style and node.value:
+ node = node.value[-1][1]
+ elif kind == "SequenceNode" and not node.flow_style and node.value:
+ node = node.value[-1]
+ else:
+ return node.end_mark.index
+
+ def _plan_text(self, scan: dict, change: tuple) -> Optional[str]:
+ """New text for one file, or None when the change cannot be proven
+ correct. Every case is verified by parsing the result."""
+ try:
+ return self._plan_text_inner(scan, change)
+ except Exception:
+ return None
+
+ def _plan_text_inner(self, scan: dict, change: tuple) -> Optional[str]:
+ import copy
+ kind = change[0]
+ text = scan.get("text") if scan.get("exists") else None
+ nl = "\r\n" if text and "\r\n" in text else "\n"
+ old = scan.get("data")
+ expected = None
+ if kind == "add":
+ _k, command, env = change
+ expected = self._expected_row(command, env)
+ block = self._entry_text(command, nl, env)
+ if not scan.get("exists"): # A
+ case = "A"
+ new = nl.join(self.FILE_HEADER) + nl + block
+ elif scan.get("error"):
+ return None
+ elif scan.get("top") == "empty": # B
+ case = "B"
+ sep = "" if (text == "" or text.endswith("\n")) else nl
+ new = text + sep + block
+ else:
+ root = scan.get("root")
+ if type(root).__name__ != "SequenceNode":
+ return None
+ if root.flow_style and not root.value: # C
+ case = "C"
+ a, b = root.start_mark.index, root.end_mark.index
+ if text[a:b].strip() != "[]" and not text[a:b].startswith("["):
+ return None
+ new = text[:a] + block[:-len(nl)] + text[b:]
+ elif not root.flow_style and root.value and root.start_mark.column == 0: # D
+ case = "D"
+ sep = "" if text.endswith("\n") else nl
+ new = text + sep + nl + block
+ else:
+ return None
+ elif kind == "command": # E
+ case = "E"
+ _k, cand, command = change[:3]
+ allow_js = len(change) > 3 and change[3] is True
+ if cand.get("command_js") and not allow_js:
+ return None # a !!js command changes only on --force (B-2)
+ node = cand.get("command_node")
+ if node is None or text is None:
+ return None
+ a, b = node.start_mark.index, node.end_mark.index
+ new = text[:a] + json.dumps(command, ensure_ascii=False) + text[b:]
+ elif kind == "replace": # F
+ case = "F"
+ _k, cand, command, env = change
+ expected = self._expected_row(command, env)
+ node = cand.get("row_node")
+ if text is None or type(node).__name__ != "MappingNode" or node.flow_style:
+ return None
+ a = node.start_mark.index
+ b = self._last_leaf_end(node)
+ col = node.start_mark.column
+ rows = self._row_lines(command, env)
+ new_row = rows[0] + "".join(nl + " " * col + r for r in rows[1:])
+ new = text[:a] + new_row + text[b:]
+ else:
+ return None
+
+ # -- verification: the new text must parse to exactly the intent.
+ got = _dsh_yaml_load(new)
+ if not isinstance(got, list):
+ return None
+ if case in ("A", "B", "C"):
+ if got != [{"insert": [expected]}]:
+ return None
+ new_row_obj = got[0]["insert"][0]
+ elif case == "D":
+ if not isinstance(old, list) or got != old + [{"insert": [expected]}]:
+ return None
+ new_row_obj = got[-1]["insert"][0]
+ elif case == "E":
+ want = copy.deepcopy(old)
+ self._set_at(want, cand["path"] + ["config", "command"], command)
+ if got != want:
+ return None
+ new_row_obj = None
+ else:
+ want = copy.deepcopy(old)
+ self._set_at(want, cand["path"], expected)
+ if got != want:
+ return None
+ new_row_obj = self._get_at(got, cand["path"])
+ if new_row_obj is not None and type(new_row_obj["config"]["cwd"]) is not _JsExpr:
+ return None
+ rescan = self._scan_text(new)
+ before = len(scan.get("candidates") or [])
+ after = rescan["candidates"]
+ if len(after) != before + (1 if kind == "add" else 0):
+ return None
+ if kind == "add":
+ mine = [c for c in after if c["path"] not in [x["path"] for x in scan.get("candidates") or []]]
+ else:
+ mine = [c for c in after if c["path"] == cand["path"]]
+ if len(mine) != 1 or not mine[0]["ours"] or mine[0]["command"] != command:
+ return None
+ return new
+
+ # -- binary helpers (same behavior as CursorWirer) -------------------------
+ def _mcp_binary_found(self) -> bool:
+ return resolve_mcp_binary() is not None
+
+ _last_install_error: Optional[str] = None
+
+ def _install_hint(self) -> str:
+ return f"\n{self._last_install_error}" if self._last_install_error else ""
+
+ def _ensure_mcp_binary(self) -> bool:
+ if self._mcp_binary_found():
+ return True
+ self._last_install_error = _install_pkg_or_instruct(self.MCP_PACKAGE)
+ return self._mcp_binary_found()
+
+ def verify_mcp_starts(self) -> tuple:
+ binary = resolve_mcp_binary()
+ if not binary:
+ return False, f"'{self.MCP_BINARY}' is not installed"
+ return _verify_mcp_starts(binary)
+
+ def print_config_text(self) -> str:
+ cmd = mcp_command_path()
+ lines = [
+ "DeepSeek Harness (developer preview): add this block to a patch file. The home patch",
+ "covers every profile; a profile patch covers one.",
+ f" home patch: {self.home_patch}",
+ f" profile patch: {self.dsh_home / 'profiles' / '' / self.PATCH_FILENAME}",
+ "The file is a top-level YAML list; append the block (or replace a lone [] with it).",
+ "",
+ self._entry_text(cmd).rstrip("\n"),
+ "",
+ "DeepSeek Harness does not pass variables whose names contain TOKEN to the server, so",
+ f"{' and '.join(self.PASS_ENV)} reach it only through the row's env.",
+ "sibyl setup deepseek copies them there when they are set to a number at setup time;",
+ "after that it never changes the row's env.",
+ ]
+ return "\n".join(lines)
+
+ # -- wire (3.6) ----------------------------------------------------------
+ def refusal(self) -> Optional[WireOutcome]:
+ """The outcome when setup will refuse this home before reading any
+ patch file, else None. cmd_setup asks first, so a home it is about to
+ refuse is never shown as detected or offered with a Y/n (sandbox M3)."""
+ # The home shape gate (explicit setup is the only path that writes)
+ shape = self._home_shape()
+ if shape in ("foreign", "not-a-dir"):
+ return self._gate_error(shape)
+ # A named profile must exist
+ if self.profile and not (self.dsh_home / "profiles" / self.profile).is_dir():
+ return WireOutcome(self.name, "error",
+ f"profile '{self.profile}' does not exist under {self.dsh_home / 'profiles'}. "
+ "Start DeepSeek Harness with that profile once, then re-run.")
+ return None
+
+ def _gate_error(self, shape: str) -> WireOutcome:
+ h = self.dsh_home
+ markers = False
+ if shape == "foreign":
+ markers = any((h / m).exists() for m in self.FOREIGN_HOME_MARKERS)
+ msg = (f"{h} does not look like a DeepSeek Harness home (no profiles folder, no "
+ f"{self.PATCH_FILENAME}).")
+ if markers:
+ msg += " It holds files of the unrelated 'dsh' distributed shell package."
+ msg += (" Nothing was written. If DeepSeek Harness keeps its files elsewhere, run: "
+ "sibyl setup deepseek --dsh-home . Otherwise start DeepSeek Harness once "
+ "so it creates its profiles folder, then run sibyl setup deepseek again.")
+ return WireOutcome(self.name, "error", msg, handoff=(
+ "sibyl setup deepseek --dsh-home ",
+ f"the DeepSeek Harness home (the one that holds profiles/); {h} belongs to "
+ "something else", ()))
+
+ def _manual_block_error(self, path: Path, lead: str, mode: str = "add",
+ env: Optional[dict] = None) -> WireOutcome:
+ """Error outcome with what to change by hand (panel fix 8). ``mode``:
+ "add" (no row of ours yet: the whole insert block), "command" (our row
+ exists: only its command line) or "replace" (a row with our id exists:
+ the row to put in its place). Every printed block is valid YAML."""
+ cmd = mcp_command_path()
+ if mode == "command":
+ block = f"command: {json.dumps(cmd, ensure_ascii=False)}"
+ how = f"Change the command of the existing sibyl-memory row in {path} to:"
+ human = (f"change the command of the existing sibyl-memory row in {path} to the "
+ "printed line (do not add a second row)")
+ elif mode == "replace":
+ rows = self._row_lines(cmd, env)
+ block = "\n".join(["- " + rows[0]] + [" " + r for r in rows[1:]])
+ how = f"Replace the existing sibyl-memory row in {path} with:"
+ human = (f"replace the existing sibyl-memory row in {path} with the printed row "
+ "(do not add a second row)")
+ else:
+ block = self._entry_text(cmd, env=env).rstrip()
+ how = f"Add this block to {path}:"
+ human = (f"add the printed block to {path}, or move that file aside and run "
+ "sibyl setup deepseek")
+ return WireOutcome(self.name, "error", f"{lead} {how}\n{block}",
+ handoff=("done", human, ()), manual_block=block)
+
+ def _backup_sub(self, layer: str) -> str:
+ return "" if layer == "home" else "profile-" + layer.split(":", 1)[1]
+
+ def _apply(self, plans: list, notes: list, verb: str) -> WireOutcome:
+ """Backup then atomic write for each planned file (steps 14 and 15).
+ Each plan is (layer, path, new text, the text the plan was built from).
+ A read-only file is never replaced (CHECK-FABLE N-5), and the file is
+ read again right before the write: if it changed since the plan was
+ built (DeepSeek Harness rewrote it, or a pip install ran in between),
+ nothing is written (N-4)."""
+ done: list = []
+ backups: list = []
+
+ def _fail(msg: str) -> WireOutcome:
+ if done:
+ msg += "; already written: " + ", ".join(str(d) for d in done)
+ return WireOutcome(self.name, "error", msg,
+ backup_path=backups[0] if backups else None)
+
+ for layer, path, new, base in plans:
+ if base is not None and path.exists() and not os.access(str(path), os.W_OK):
+ return _fail(f"{path} is read-only; setup does not replace a read-only file. "
+ "It was not modified")
+ try:
+ b = _timestamped_backup(path, "deepseek", self._backup_sub(layer))
+ except (OSError, ValueError) as e:
+ msg = (f"could not back up {path} to {backups_root() / 'deepseek'} "
+ f"({type(e).__name__}); {path} was not modified")
+ if done:
+ msg += "; already written: " + ", ".join(str(d) for d in done)
+ return WireOutcome(self.name, "error", msg,
+ backup_path=backups[0] if backups else None)
+ if b:
+ backups.append(b)
+ try:
+ with open(path, encoding="utf-8", newline="") as fh:
+ now = fh.read()
+ except FileNotFoundError:
+ now = None
+ except (OSError, UnicodeDecodeError) as e:
+ return _fail(f"could not read {path} again before writing ({type(e).__name__}); "
+ "it was not modified")
+ if now != base:
+ return _fail(f"{path} changed while setup was running; it was not modified. "
+ "Run it again")
+ try:
+ _atomic_text(path, new)
+ except Exception as e:
+ msg = f"could not write {path} ({type(e).__name__}); it was not modified"
+ if done:
+ msg += "; already written: " + ", ".join(str(d) for d in done)
+ return WireOutcome(self.name, "error", msg,
+ backup_path=backups[0] if backups else None)
+ done.append(path)
+ where = ", ".join(str(d) for d in done)
+ if verb == "Updated":
+ msg = f"Updated the sibyl-memory command in {where}"
+ else:
+ msg = f"{verb} the SIBYL Memory MCP server in {where}"
+ if len(backups) > 1:
+ msg += "; more backups at " + ", ".join(str(b) for b in backups[1:])
+ msg += "".join(notes)
+ return WireOutcome(self.name, "wired", msg,
+ backup_path=backups[0] if backups else None)
+
+ def wire(self, *, force: bool = False, dry_run: bool = False,
+ prompt_fn: Optional[Callable[..., str]] = None) -> WireOutcome:
+ # 1. PyYAML
+ if _import_yaml() is None:
+ return WireOutcome(self.name, "error",
+ "PyYAML not installed. Run `pip install pyyaml` and retry.",
+ handoff=("pip install pyyaml", None, ("sibyl setup deepseek",)))
+ # 2. and 3. The home shape gate and the named profile
+ refused = self.refusal()
+ if refused is not None:
+ return refused
+ layers = self._scan_layers()
+ rel = self._relevant(layers)
+ tgt_name = self._target_layer()
+ tgt = next(l for l in rel if l["layer"] == tgt_name)
+ # 4. The target layer must parse
+ if tgt["error"]:
+ return WireOutcome(self.name, "error",
+ f"{tgt['path']} is not a valid DeepSeek Harness patch file ({tgt['error']}). "
+ "Fix the file or move it aside and re-run setup; it was not modified.")
+ # 5. Another layer of the stack that does not parse
+ notes: list = []
+ for l in rel:
+ if l is tgt or not l["error"]:
+ continue
+ if l["mentions"]:
+ return WireOutcome(self.name, "error",
+ f"{l['path']} does not parse ({l['error']}) and mentions sibyl-memory. "
+ "Fix it first; nothing was changed.")
+ notes.append(f" (note: {l['path']} does not parse and was skipped)")
+ ok_layers = [l for l in rel if not l["error"]]
+ # 6. Duplicates: which one to keep is not ours to guess (no --force)
+ if self._duplicate_in(ok_layers):
+ paths = [l["path"] for l in ok_layers if l["candidates"]]
+ n = sum(len(l["candidates"]) for l in ok_layers)
+ return WireOutcome(self.name, "skipped",
+ f"{n} sibyl-memory entries found in one DeepSeek Harness stack "
+ f"({', '.join(paths)}). Remove the extras, then re-run. Nothing was changed.")
+ # 6b. A server named sibyl-memory in DeepSeek Harness's own MCP
+ # settings (mcp-manager servers): a row of ours beside it would make
+ # the harness fail one of the two. Setup never writes that map.
+ clash = next((p for p in (self._manager_clash(ok_layers, l["layer"])
+ for l in ok_layers if l is tgt or l["candidates"]) if p), None)
+ if clash:
+ return WireOutcome(self.name, "skipped", self.MANAGER_CLASH_TEXT.format(path=clash)
+ + " Remove one of them, then re-run. Nothing was changed.")
+ changes: list = [] # (layer scan, change tuple, verb)
+ if not tgt["candidates"]:
+ others = [(l, c) for l in ok_layers if l is not tgt for c in l["candidates"]]
+ if others:
+ # 7. Never add a second row to a stack.
+ left_alone: list = []
+ for l, c in others:
+ if not c["ours"]:
+ out = self._foreign_gate(l, force, prompt_fn)
+ if out is not None:
+ return out
+ changes.append((l, ("replace", c, None, self._pass_env()), "Replaced"))
+ elif c["disabled"]:
+ left_alone.append(f" ({l['path']} has the row with disabled: true; "
+ "setup leaves that alone)")
+ elif c.get("command_js"):
+ left_alone.append(f" ({l['path']}: {self.JS_NOTE})")
+ elif not _command_resolves(c["command"]):
+ changes.append((l, ("command", c, None), "Updated"))
+ if not changes:
+ if self.profile:
+ msg = (f"DeepSeek Harness already has the sibyl-memory MCP server: the home "
+ f"patch {self.home_patch} already covers every profile.")
+ else:
+ names = [l["layer"].split(":", 1)[1] for l, _c in others]
+ msg = ("DeepSeek Harness already has the sibyl-memory MCP server in "
+ f"profile(s) {', '.join(names)} "
+ f"({', '.join(l['path'] for l, _c in others)}). To cover every "
+ "profile, remove those rows and run sibyl setup deepseek again.")
+ return WireOutcome(self.name, "already", msg + "".join(left_alone + notes))
+ else:
+ # 10. Nothing anywhere relevant: add.
+ changes.append((tgt, ("add", None, self._pass_env()), "Added"))
+ else:
+ c = tgt["candidates"][0]
+ if c["ours"]:
+ # 8.
+ if c["disabled"]:
+ return WireOutcome(self.name, "already",
+ f"The sibyl-memory row is present but disabled: true in {tgt['path']}; "
+ "setup leaves that alone."
+ + "".join(notes))
+ if c.get("command_js") and not force:
+ return WireOutcome(self.name, "already",
+ f"DeepSeek Harness already has the sibyl-memory MCP server in {tgt['path']} "
+ f"({self.JS_NOTE}; --force repoints it)" + "".join(notes))
+ resolves = _command_resolves(c["command"])
+ if resolves and not force:
+ msg = f"DeepSeek Harness already has the sibyl-memory MCP server in {tgt['path']}"
+ if c["command"] != mcp_command_path():
+ msg += f" (uses a different install: {c['command']}; --force repoints it)"
+ return WireOutcome(self.name, "already", msg + "".join(notes))
+ if c["command"] == mcp_command_path() and resolves:
+ return WireOutcome(self.name, "already",
+ f"DeepSeek Harness already has the sibyl-memory MCP server in {tgt['path']}"
+ + "".join(notes))
+ changes.append((tgt, ("command", c, None), "Updated"))
+ else:
+ # 9.
+ out = self._foreign_gate(tgt, force, prompt_fn)
+ if out is not None:
+ return out
+ changes.append((tgt, ("replace", c, None, self._pass_env()), "Replaced"))
+ # 11. Dry run: before any install, directory creation or write.
+ if dry_run:
+ verbs = {v for _l, _c, v in changes}
+ word = "add" if verbs == {"Added"} else ("update" if verbs == {"Updated"} else "replace")
+ where = ", ".join(l["path"] for l, _c, _v in changes)
+ return WireOutcome(self.name, "dry-run", f"Would {word} the sibyl-memory row in {where}")
+ # 12. The server binary
+ if not self._ensure_mcp_binary():
+ looked = ", ".join(str(d) for d in _mcp_search_dirs())
+ return WireOutcome(self.name, "error",
+ f"'{self.MCP_BINARY}' is not installed (looked on PATH and in {looked}). "
+ f"Install it: pip install {self.MCP_PACKAGE}" + self._install_hint(),
+ handoff=_binary_missing_handoff(self.name))
+ command = mcp_command_path()
+ # 13. Plan every file; nothing is written unless every plan succeeded.
+ plans: list = []
+ env_lines: list = []
+ for l, ch, _v in changes:
+ path = Path(l["path"])
+ if path.is_symlink():
+ return self._manual_block_error(path,
+ f"{path} is a symlink; setup does not write through symlinks, so make this "
+ "change in the file it points at.",
+ mode=ch[0],
+ env=ch[3] if ch[0] == "replace" else ch[2] if ch[0] == "add" else None)
+ if ch[0] == "add":
+ ch = ("add", command, ch[2])
+ env = ch[2]
+ elif ch[0] == "command":
+ # Only the target row reaches here with a !!js command, and
+ # only under --force (B-2).
+ ch = ("command", ch[1], command, bool(force))
+ env = {}
+ else:
+ ch = ("replace", ch[1], command, ch[3])
+ env = ch[3]
+ for n in sorted(env or {}):
+ env_lines.append(f"kept {n} in the row's env (DeepSeek Harness does not pass it "
+ "through otherwise)")
+ new = self._plan_text(l, ch)
+ if new is None:
+ return self._manual_block_error(path,
+ f"could not change {path} safely; it was not modified.",
+ mode=ch[0],
+ env=ch[3] if ch[0] == "replace" else ch[2] if ch[0] == "add" else None)
+ plans.append((l["layer"], path, new, l["text"] if l.get("exists") else None))
+ verbs = [v for _l, _c, v in changes]
+ out = self._apply(plans, notes, verbs[0] if len(set(verbs)) == 1 else "Changed")
+ if out.status == "wired":
+ out.lifecycle = list(dict.fromkeys(env_lines))
+ return out
+
+ # -- doctor (spec dsh-doctor v2, 4.5) -------------------------------------
+ def doctor_probe(self) -> list:
+ try:
+ if _import_yaml() is None:
+ return [_probe("unreadable", self.home_patch, location="home",
+ detail="PyYAML is not installed, so the patch files cannot be read")]
+ layers = self._scan_layers()
+ ok = [l for l in layers if not l["error"]]
+ home = next((l for l in ok if l["layer"] == "home"), None)
+ dup: dict = {}
+ for l in ok:
+ if len(l["candidates"]) > 1:
+ dup.setdefault(l["layer"], set()).add(l["path"])
+ if home is not None and home["candidates"]:
+ for l in ok:
+ if l["layer"] != "home" and l["candidates"]:
+ pair = {home["path"], l["path"]}
+ dup.setdefault("home", set()).update(pair)
+ dup.setdefault(l["layer"], set()).update(pair)
+ probes = []
+ for l in layers:
+ if l["error"]:
+ if l["mentions"]:
+ probes.append(_probe("unreadable", l["path"], location=l["layer"],
+ detail=l["error"]))
+ continue
+ if not l["candidates"]:
+ continue
+ if l["layer"] in dup:
+ probes.append(_probe("duplicate", l["path"], location=l["layer"], detail=(
+ "more than one sibyl-memory row in one DeepSeek Harness stack: "
+ + ", ".join(sorted(dup[l["layer"]])))))
+ continue
+ clash = self._manager_clash(ok, l["layer"])
+ if clash:
+ probes.append(_probe("duplicate", l["path"], location=l["layer"],
+ detail=self.MANAGER_CLASH_TEXT.format(path=clash)))
+ continue
+ c = l["candidates"][0]
+ js = bool(c.get("command_js"))
+ cmd = None if js else c["command"]
+ if not c["ours"]:
+ probes.append(_probe("foreign", l["path"], location=l["layer"],
+ command=None,
+ detail="another server holds the sibyl-memory id or name"))
+ elif c["disabled"]:
+ probes.append(_probe("disabled", l["path"], location=l["layer"],
+ command=cmd, detail="the row has disabled: true"))
+ elif self._overridden(c, ok, l["layer"]):
+ probes.append(_probe("overridden", l["path"], location=l["layer"],
+ command=cmd,
+ detail="a patch with id sibyl-memory overrides the row"))
+ elif js:
+ probes.append(_probe("present", l["path"], location=l["layer"],
+ command=None, detail=self.JS_NOTE))
+ else:
+ probes.append(_probe("present", l["path"], location=l["layer"],
+ command=c["command"]))
+ if not probes:
+ probes.append(_probe("absent", self.home_patch, location="home"))
+ return probes
+ except Exception as e:
+ return [_probe("unreadable", self.home_patch, location="home", detail=type(e).__name__)]
+
+ def repair_mcp(self, probe: dict) -> WireOutcome:
+ """Point our one row in the file the probe names at the resolved
+ command: the same plan, verification, backup and write as setup."""
+ layer = probe.get("location") or "home"
+ path = self._layer_path(layer)
+ scan = self._scan_file(path, layer)
+ if scan["error"] or len(scan["candidates"]) != 1 or not scan["candidates"][0]["ours"]:
+ return WireOutcome(self.name, "error",
+ f"no single sibyl-memory row of ours in {path} to repair")
+ if scan["candidates"][0].get("command_js"):
+ return WireOutcome(self.name, "error",
+ f"the sibyl-memory command in {path} is a !!js expression; doctor does not "
+ "change it (sibyl setup deepseek --force repoints it)")
+ if path.is_symlink():
+ return self._manual_block_error(path,
+ f"{path} is a symlink; setup does not write through symlinks, so make this "
+ "change in the file it points at.", mode="command")
+ new = self._plan_text(scan, ("command", scan["candidates"][0], mcp_command_path()))
+ if new is None:
+ return self._manual_block_error(path,
+ f"could not change {path} safely; it was not modified.", mode="command")
+ return self._apply([(layer, path, new, scan["text"])], [], "Updated")
+
+ def _foreign_gate(self, layer: dict, force: bool,
+ prompt_fn: Optional[Callable[..., str]]) -> Optional[WireOutcome]:
+ if force:
+ return None
+ if prompt_fn is None:
+ return WireOutcome(self.name, "skipped",
+ f"Existing 'sibyl-memory' entry in {layer['path']} points elsewhere. "
+ "Use --force to replace it.",
+ overwrite_of="a different sibyl-memory MCP entry")
+ if prompt_fn("DeepSeek Harness has a 'sibyl-memory' entry pointing elsewhere. Replace it?",
+ default="N") != "y":
+ return WireOutcome(self.name, "skipped", "MCP entry replacement declined.",
+ overwrite_of="a different sibyl-memory MCP entry")
+ return None
+
+
+# ----------------------------------------------------------------------
+# Registry + dispatch
+# ----------------------------------------------------------------------
+
+ALL_WIRERS: dict = {
+ "hermes": HermesWirer,
+ "claude-code": ClaudeCodeWirer,
+ "codex": CodexWirer,
+ "cursor": CursorWirer,
+ "deepseek": DeepSeekWirer,
+}
+
+# Explicit-target-only wirers (never part of auto-detect).
+EXPLICIT_WIRERS: dict = {
+ "grokbot": GrokBotWirer,
+}
+# Aliases accepted as a setup target (and by doctor --harness); they map to a
+# wirer name before anything else runs.
+SETUP_ALIASES: dict = {"dsh": "deepseek"}
+SETUP_TARGETS: tuple = tuple(ALL_WIRERS) + tuple(EXPLICIT_WIRERS) + tuple(SETUP_ALIASES)
+
+
+# True once a prompt in this run met end of input (no terminal): an overwrite
+# the person never answered is then handed back as a question (row X6).
+_PROMPT_EOF = False
+
+
+def _interactive_prompt(question: str, *, default: str = "Y") -> str:
+ """Yes/no prompt. default 'Y' or 'N'. Returns 'y' or 'n'."""
+ global _PROMPT_EOF
+ default_label = "[Y/n]" if default.upper() == "Y" else "[y/N]"
+ try:
+ ans = input(f"{question} {default_label}: ").strip()
+ except EOFError:
+ # Row X5: say which default the transcript shows was taken.
+ print(f"no terminal: default {default.upper()} taken")
+ _PROMPT_EOF = True
+ return default.lower()
+ if not ans:
+ return default.lower()
+ return "y" if ans[:1].lower() == "y" else "n"
+
+
+def _accept_defaults_prompt(question: str, *, default: str = "Y") -> str:
+ """Non-interactive prompt. Returns the default. Used with --yes."""
+ return default.lower()
+
+
+def _wirer_kwargs(args: argparse.Namespace, name: str) -> dict:
+ kw: dict = {}
+ if name == "hermes" and getattr(args, "hermes_home", None):
+ kw["hermes_home"] = args.hermes_home
+ if name == "claude-code" and getattr(args, "claude_settings", None):
+ kw["settings_path"] = args.claude_settings
+ if name == "codex" and getattr(args, "codex_config", None):
+ kw["config_path"] = args.codex_config
+ if name in ("cursor", "grokbot") and getattr(args, "cursor_config", None):
+ kw["config_path"] = args.cursor_config
+ if name == "deepseek":
+ if getattr(args, "dsh_home", None):
+ kw["dsh_home"] = args.dsh_home
+ if getattr(args, "dsh_profile", None) is not None:
+ kw["profile"] = args.dsh_profile
+ return kw
+
+
+def _print_generic_config(dim, cyan) -> None:
+ """A2: any MCP client (Grok Bot included) can wire itself from this."""
+ cmd = mcp_command_path()
+ print(dim("Any MCP client can use the server directly. Command (absolute path):"))
+ print(f" {cyan(cmd)}")
+ if cmd == MCP_BINARY_NAME:
+ print(dim(f" ('{MCP_BINARY_NAME}' is not installed yet: pip install sibyl-memory-mcp)"))
+ print()
+ print(dim("Add this to the client's MCP config (the mcpServers block):"))
+ print(mcp_servers_snippet(cmd))
+ print()
+ print(dim("Cursor or Grok Bot: sibyl setup cursor | sibyl setup grokbot"))
+ print(dim("DeepSeek Harness: sibyl setup deepseek (or: sibyl setup deepseek --print-config)"))
+ print()
+
+
+def _state_location(wirer: Any) -> Optional[str]:
+ """Where a wirer looks for its config, for the setup summary: the Hermes
+ home, else the settings or config file (Codex reports config_path).
+ None when the state names none (sandbox M5: never print "None")."""
+ try:
+ st = wirer.current_state()
+ except Exception:
+ st = {}
+ loc = st.get("hermes_home") or st.get("settings_path") or st.get("config_path")
+ if not loc:
+ loc = getattr(wirer, "config_path", None) or getattr(wirer, "settings_path", None)
+ return str(loc) if loc else None
+
+
+def cmd_setup(args: argparse.Namespace) -> int:
+ """`sibyl setup` entry point. Auto-detect, then wire."""
+ from . import _handoff as _h
+ global _PROMPT_EOF
+ _PROMPT_EOF = False
+ bold, cyan, dim, green, red, yellow = _color_fns()
+ which_human = ("which agent you use (Claude Code, Codex, Cursor, Hermes, DeepSeek Harness) "
+ "and where its config lives, if not in the default place")
+
+ # Resolve target wirers
+ target = getattr(args, "target", None)
+ target = SETUP_ALIASES.get(target, target)
+ try:
+ if target:
+ cls = ALL_WIRERS.get(target) or EXPLICIT_WIRERS.get(target)
+ if cls is None:
+ print(red(f"Unknown setup target: {target}"))
+ print(f"Available: {', '.join(SETUP_TARGETS)}")
+ names = [t for t in SETUP_TARGETS if t not in SETUP_ALIASES]
+ _h.handoff("sibyl setup <" + "|".join(names) + ">", human=which_human)
+ return 1
+ wirers: dict = {target: cls(**_wirer_kwargs(args, target))}
+ skip_present_check = True # explicit target = wire it even if not detected on PATH
+ else:
+ wirers = {name: cls(**_wirer_kwargs(args, name)) for name, cls in ALL_WIRERS.items()}
+ skip_present_check = False
+ except ValueError as e:
+ # A bad --dsh-profile name (DeepSeekWirer validates it).
+ print(red(str(e)))
+ _h.handoff("sibyl setup deepseek --dsh-profile ",
+ human="the DeepSeek Harness profile (a folder under its profiles directory)")
+ return 1
+
+ print()
+ print(bold("Sibyl Memory Plugin setup"))
+ print()
+
+ # Platform gate. `setup` wires a new machine, so it is one of the two
+ # commands the native-Windows block applies to (see cli.NATIVE_WINDOWS_POLICY).
+ from .cli import WINDOWS_HUMAN, print_platform_line
+ if print_platform_line(gate=True) != 0:
+ _h.handoff("done", human=WINDOWS_HUMAN)
+ return 1
+ print()
+
+ # Detection
+ if skip_present_check:
+ detected = wirers
+ else:
+ detected = {n: w for n, w in wirers.items() if w.is_present()}
+
+ if getattr(args, "print_config", False):
+ _print_generic_config(dim, cyan)
+ if target == "deepseek":
+ print(wirers["deepseek"].print_config_text())
+ print()
+ return 0
+
+ # A target setup will refuse before reading anything (a DeepSeek Harness
+ # home that belongs to something else) is reported, never shown as
+ # detected or asked about (sandbox M3).
+ refused: list = []
+ for name in list(detected):
+ check = getattr(detected[name], "refusal", None)
+ out = check() if callable(check) else None
+ if out is not None:
+ refused.append(out)
+ del detected[name]
+
+ if not detected and not refused:
+ print(yellow("No agent frameworks detected on this machine."))
+ print()
+ print(dim("Looked for:"))
+ for name, w in wirers.items():
+ loc = _state_location(w)
+ print(f" {w.display_name}: {loc}" if loc else f" {w.display_name}")
+ print()
+ print(dim("To override detection, point setup at a custom path:"))
+ print(f" {cyan('sibyl setup --hermes-home /custom/path')}")
+ print(f" {cyan('sibyl setup --claude-settings /custom/settings.json')}")
+ print(f" {cyan('sibyl setup --cursor-config /custom/mcp.json')}")
+ print(f" {cyan('sibyl setup deepseek --dsh-home /custom/folder')}")
+ print()
+ _print_generic_config(dim, cyan)
+ # Row X3: nothing to wire is not a stop for the account; the agent
+ # moves on and keeps the targeted setup for when its person answers.
+ _h.handoff("sibyl status", human=which_human, later=("sibyl setup ",))
+ return 0
+
+ # Detection summary
+ if detected:
+ print(dim("Detected:"))
+ for name, w in detected.items():
+ loc = _state_location(w)
+ print(f" {w.display_name} at {loc}" if loc else f" {w.display_name}")
+ print()
+
+ # Multi-framework picker
+ selected = list(detected.keys())
+ if len(detected) > 1 and not args.yes:
+ choices = ", ".join(f"[{w.initial}]{w.display_name}" for w in detected.values())
+ try:
+ # Grok Bot onboarding (2026-10-28): never read a non-terminal stdin
+ # (under `curl | sh` it is the installer script itself).
+ if not sys.stdin.isatty():
+ raise EOFError
+ ans = input(
+ f"Wire which? {choices}, [a]ll, [n]one (default: all): "
+ ).strip().lower()
+ except EOFError:
+ # Finding 5.3.1 (handoff spec 2026-10-03): no terminal used to raise
+ # a traceback here. The default is the same as --yes (row X4).
+ ans = ""
+ print("no terminal: wiring all detected (same as --yes)")
+ if ans in ("n", "none"):
+ print(dim("Skipping all."))
+ print()
+ _h.handoff("done")
+ return 0
+ elif ans in ("", "a", "all"):
+ pass
+ else:
+ picked = [n for n, w in detected.items() if w.initial == ans[:1]]
+ if not picked:
+ print(red(f"No match for '{ans}'. Aborting."))
+ _h.handoff("sibyl setup ", human=which_human)
+ return 1
+ selected = picked
+
+ # Per-stack execution
+ outcomes: list = list(refused)
+ prompt_fn = _accept_defaults_prompt if args.yes else _interactive_prompt
+
+ for name in selected:
+ wirer = detected[name]
+ st = wirer.current_state()
+
+ # Pre-prompt for fresh adds (interactive only). Already-wired and
+ # existing-other-provider are handled inside wire() itself.
+ if (
+ not args.yes
+ and not st.get("wired_with_sibyl")
+ and not st.get("memory_provider")
+ and not st.get("sibyl_mcp")
+ ):
+ if name == "hermes":
+ q = f"Set SIBYL as default memory provider in {wirer.display_name}?"
+ else:
+ q = f"Add SIBYL Memory as an MCP server in {wirer.display_name}?"
+ ans = _interactive_prompt(q, default="Y")
+ if ans != "y":
+ outcomes.append(WireOutcome(name, "skipped", "Declined by user."))
+ continue
+
+ outcomes.append(
+ wirer.wire(force=args.force, dry_run=args.dry_run, prompt_fn=prompt_fn)
+ )
+
+ # Report
+ print()
+ any_wired = False
+ any_verify_fail = False
+ for o in outcomes:
+ marker = {
+ "wired": green("✓"),
+ "already": green("·"),
+ "skipped": yellow("·"),
+ "dry-run": cyan("→"),
+ "error": red("✗"),
+ }.get(o.status, "?")
+ print(f" {marker} {o.name}: {o.message}")
+ if o.backup_path:
+ print(f" {dim('backup at')} {o.backup_path}")
+ for ln in getattr(o, "lifecycle", None) or []:
+ print(f" {dim(ln)}")
+ if o.status == "wired":
+ any_wired = True
+
+ # Post-wire verification: confirm MCP server actually boots
+ verify_msgs: list = []
+ for o in outcomes:
+ if o.status not in ("wired", "already"):
+ continue
+ wirer = detected.get(o.name)
+ if wirer and hasattr(wirer, "verify_mcp_starts"):
+ ok, msg = wirer.verify_mcp_starts()
+ if ok:
+ print(f" {green('✓')} {o.name}: {msg}")
+ else:
+ print(f" {red('✗')} {o.name}: {msg}")
+ any_verify_fail = True
+ verify_msgs.append(msg)
+ print()
+
+ if any_wired or any(o.status == "already" for o in outcomes):
+ if any_verify_fail:
+ print(yellow("MCP server could not start. Fix the error above, then reconnect."))
+ else:
+ print(green("MCP server is ready."))
+ print()
+ # Claude Code specific reconnect instructions
+ cc_active = any(
+ o.name == "claude-code" and o.status in ("wired", "already")
+ for o in outcomes
+ )
+ if cc_active:
+ if any_wired:
+ print(dim(" Claude Code: restart, or type /mcp and reconnect sibyl-memory."))
+ else:
+ print(dim(" Claude Code: if not connected, type /mcp and reconnect sibyl-memory."))
+ print()
+
+ nxt, human, later = _setup_handoff(outcomes, detected, verify_msgs,
+ unanswered=bool(args.yes) or _PROMPT_EOF)
+ for o in outcomes:
+ if o.name == "grokbot" and o.status in ("wired", "already"):
+ w = detected["grokbot"]
+ print(bold("Grok Bot confirmation"))
+ print(f" server name : {w.MCP_NAME}")
+ print(f" command : {mcp_command_path()}")
+ print(f" config file : {w.config_path}")
+ print(dim(" Reload MCP servers in Cursor (or start a new Grok Bot session), then "
+ "run: sibyl doctor"))
+ print()
+
+ _h.handoff(nxt, human=human, later=later)
+ return 0 if all(o.status != "error" for o in outcomes) and not any_verify_fail else 2
+
+
+_RESTART_HUMAN = {
+ "claude-code": "restart Claude Code, or type /mcp and reconnect sibyl-memory",
+ "hermes": "restart Hermes so it loads the sibyl memory provider",
+ "codex": "restart Codex so it loads the sibyl_memory MCP server",
+ "deepseek": ("start a new DeepSeek Harness session; if the memory tools do not appear, "
+ "restart DeepSeek Harness"),
+ "cursor": "reload MCP servers in Cursor",
+}
+
+
+def _setup_handoff(outcomes: list, detected: dict, verify_msgs: list, *, unanswered: bool) -> tuple:
+ """(next, human, later) for the end of `sibyl setup` (rows X6 to X16):
+ the first error, then a server that did not start, then an overwrite the
+ person has not answered, then the restart of what was wired."""
+ for o in outcomes:
+ if o.status == "error":
+ if o.handoff:
+ return o.handoff
+ # A config write or plugin install that failed is a permission or
+ # disk problem, not a transient one: re-running would fail the same
+ # way, so a person fixes it first.
+ who = getattr(detected.get(o.name), "display_name", o.name)
+ why = " ".join(str(o.message or "").split())[:200] or "an error"
+ return ("done", f"{who} could not be wired ({why}); fix that, then run "
+ f"sibyl setup {o.name}", ())
+ if verify_msgs:
+ cred = any("credential" in str(m).lower() for m in verify_msgs)
+ if cred:
+ return ("sibyl status",
+ "the memory server reports a missing credential (above); sign this computer in "
+ "with sibyl init if it is not", ())
+ return ("done", "run sibyl-memory-mcp in a terminal and tell me the first error line", ())
+ if unanswered:
+ for o in outcomes:
+ if o.status == "skipped" and o.overwrite_of:
+ w = detected.get(o.name)
+ who = getattr(w, "display_name", o.name)
+ return (f"sibyl setup {o.name} --force",
+ f"{who} already has {o.overwrite_of}; confirm replacing it with Sibyl", ())
+ for o in outcomes:
+ # Panel fix 10: a skipped outcome that carries its own command (Claude
+ # Code with no claude CLI on PATH) hands that command over.
+ if o.status == "skipped" and o.handoff and not o.overwrite_of:
+ return o.handoff
+ active = [o.name for o in outcomes if o.status in ("wired", "already")]
+ if active:
+ # Only a harness whose config changed needs a restart; an "already"
+ # outcome wrote nothing, so it gets no restart ask.
+ changed = [o.name for o in outcomes if o.status == "wired"]
+ if not changed:
+ human = None
+ elif len(changed) == 1:
+ human = _RESTART_HUMAN.get(changed[0])
+ else:
+ names = " / ".join(getattr(detected.get(n), "display_name", n) for n in changed)
+ human = (f"restart {names} (in Claude Code: type /mcp and reconnect sibyl-memory) so it "
+ "loads the memory server")
+ return ("sibyl status", human, ())
+ return ("done", None, ())
diff --git a/sibyl-memory-cli/tests/_harness_fixtures.py b/sibyl-memory-cli/tests/_harness_fixtures.py
new file mode 100644
index 0000000000000000000000000000000000000000..25de289cd7c7989c1a8df402a8060c8fbfb6cd24
--- /dev/null
+++ b/sibyl-memory-cli/tests/_harness_fixtures.py
@@ -0,0 +1,52 @@
+"""Shared helpers for the 2026-11-13 harness tests (DeepSeek Harness wirer,
+doctor harness checks, backups under the plugin home, Codex stale path).
+
+``isolate_path`` gives a test an isolated PATH: a temp bin directory holding
+only a fake ``sibyl-memory-mcp``, then /usr/bin and /bin. ``shutil.which`` is
+wrapped so the harness binaries (claude, codex, cursor, cursor-agent, hermes,
+dsh) are never found, whatever is installed on the machine running the suite:
+the real ``claude`` is on PATH on the build box, and the harness section of
+doctor would otherwise depend on it. Nothing here runs a harness binary."""
+from __future__ import annotations
+
+import os
+import shutil
+from pathlib import Path
+
+HIDDEN_BINARIES = ("claude", "codex", "cursor", "cursor-agent", "hermes", "dsh")
+SCRUBBED_ENV = ("DSH_HOME", "SIBYL_MEMORY_MCP_OUTPUT_TOKENS", "SIBYL_MEMORY_RANKED_MIN_TOKENS",
+ "CLAUDE_CONFIG_DIR", "SIBYL_MEMORY_INSTRUCTIONS")
+
+_REAL_WHICH = shutil.which
+
+
+def isolate_path(monkeypatch, tmp_path: Path) -> Path:
+ bindir = tmp_path / "isolated-bin"
+ bindir.mkdir(exist_ok=True)
+ fake = bindir / "sibyl-memory-mcp"
+ fake.write_text("#!/bin/sh\nexit 0\n")
+ fake.chmod(0o755)
+ monkeypatch.setenv("PATH", f"{bindir}:/usr/bin:/bin")
+
+ def which(cmd, mode=os.F_OK | os.X_OK, path=None):
+ if os.path.basename(str(cmd)) in HIDDEN_BINARIES:
+ return None
+ return _REAL_WHICH(cmd, mode=mode, path=path)
+
+ monkeypatch.setattr(shutil, "which", which)
+ for name in SCRUBBED_ENV:
+ monkeypatch.delenv(name, raising=False)
+ return fake
+
+
+def backups_dir(harness: str, sub: str = "") -> Path:
+ d = Path.home() / ".sibyl-memory" / "backups" / harness
+ return d / sub if sub else d
+
+
+def leftovers(directory: Path) -> list:
+ """Temp files or .bak files of ours left in a harness directory."""
+ if not directory.is_dir():
+ return []
+ return sorted(p.name for p in directory.iterdir()
+ if p.name.endswith((".tmp", ".sibyl-tmp", ".bak")))
diff --git a/sibyl-memory-cli/tests/conftest.py b/sibyl-memory-cli/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8dccbb311f2c76939d109cf1081d5d18153ba7b
--- /dev/null
+++ b/sibyl-memory-cli/tests/conftest.py
@@ -0,0 +1,203 @@
+import pytest
+from sibyl_memory_cli import setup as _setup
+from sibyl_memory_client.testing import (
+ TestSigner,
+ forbid_external_network,
+ install_entitled_home,
+ patch_trusted_keys,
+)
+
+
+@pytest.fixture(autouse=True)
+def _no_real_claude_cli(monkeypatch):
+ """SAFETY + determinism: by default pretend the `claude` CLI is absent, so the
+ settings.json-fallback tests are deterministic and NO test ever shells out to the
+ real `claude mcp` (which would mutate this machine's actual MCP config). Tests that
+ exercise the CLI path re-patch _claude_cli + _run explicitly."""
+ monkeypatch.setattr(_setup.ClaudeCodeWirer, "_claude_cli", staticmethod(lambda: None))
+ yield
+
+
+# ---- 0.5.0 account gate (spec 4.4) -----------------------------------------
+# The gate (sibyl-memory-client) reads entitlement.json beside the credentials
+# file and may refresh it over the network. In tests: a throwaway Ed25519 key is
+# monkeypatched into TRUSTED_KEYS (the production pinned key is untouched),
+# every refresh is routed to that test signer, non-loopback sockets are refused,
+# and HOME plus the CLI's import-time default paths point at a per-test fake
+# home, so no test can read or write a real ~/.sibyl-memory or reach an api.
+
+@pytest.fixture(scope="session")
+def test_signer() -> TestSigner:
+ return TestSigner()
+
+
+@pytest.fixture(scope="session", autouse=True)
+def _session_gate_guard(test_signer):
+ mp = pytest.MonkeyPatch()
+ patch_trusted_keys(mp, test_signer)
+ forbid_external_network(mp)
+ yield
+ mp.undo()
+
+
+@pytest.fixture
+def entitled_home(_isolated_home):
+ """The activated fake home's ~/.sibyl-memory directory."""
+ return _isolated_home / ".sibyl-memory"
+
+
+@pytest.fixture(autouse=True)
+def _isolated_home(tmp_path_factory, monkeypatch, test_signer):
+ from sibyl_memory_cli import cli
+ home = tmp_path_factory.mktemp("cli-home")
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.setenv("HERMES_HOME", str(home / ".hermes"))
+ monkeypatch.delenv("SIBYL_MEMORY_DB", raising=False)
+ patch_trusted_keys(monkeypatch, test_signer)
+ # The CLI's own defaults point at an EMPTY directory (as the suite always
+ # had: no credentials unless a test writes them), while the SDK's default
+ # home (~/.sibyl-memory) is activated, because test code that SEEDS a store
+ # through MemoryClient (what an agent does) needs an account.
+ d = home / "cli-default"
+ monkeypatch.setattr(cli, "DEFAULT_CRED_PATH", d / "credentials.json")
+ monkeypatch.setattr(cli, "DEFAULT_DB_PATH", d / "memory.db")
+ monkeypatch.setattr(cli, "DEFAULT_TIER_CACHE_PATH", d / "tier_cache.json")
+ monkeypatch.setattr(cli, "_ENT_CRED_PATH", d / "credentials.json")
+ install_entitled_home(home, test_signer)
+ return home
+
+
+# ---- network guard (0.9.0 gate fix) -----------------------------------------
+# A previous build's suite reached the production api by accident. The guard is
+# installed at conftest import (so collection-time code is covered too), stays
+# installed for the whole session (the session fixture above re-applies it), and
+# EVERY test fails if it made a refused non-loopback connection or name lookup,
+# even one it caught and ignored. tests/test_network_guard_2026_09_27.py proves
+# the guard itself.
+from sibyl_memory_client.testing import ( # noqa: E402
+ assert_no_external_attempts as _assert_no_external_attempts,
+ forbid_external_network as _forbid_external_network,
+ refused_connections as _refused_connections,
+)
+
+_IMPORT_TIME_GUARD = pytest.MonkeyPatch()
+_forbid_external_network(_IMPORT_TIME_GUARD)
+
+
+@pytest.fixture(autouse=True)
+def _no_external_network_attempts():
+ start = len(_refused_connections())
+ yield
+ _assert_no_external_attempts(start)
+
+
+# ---- real-home guard (save/debloat build 2026-09-27) --------------------------
+# Every test must see a temporary HOME (asserted per test), and at session end
+# none of the paths the save/debloat build writes (skills, lifecycle, hooks,
+# shims) may have changed under the account's real home.
+from sibyl_memory_client.testing import ( # noqa: E402
+ assert_home_is_not_real as _assert_home_is_not_real,
+ real_home_changes as _real_home_changes,
+ real_home_snapshot as _real_home_snapshot,
+)
+
+_REAL_HOME_BEFORE = _real_home_snapshot()
+
+
+@pytest.fixture(autouse=True)
+def _home_is_never_the_real_home(_isolated_home):
+ _assert_home_is_not_real()
+ yield
+ _assert_home_is_not_real()
+
+
+def pytest_sessionfinish(session, exitstatus):
+ changed = _real_home_changes(_REAL_HOME_BEFORE)
+ if changed:
+ print(f"\nREAL HOME CHANGED during the test session: {changed}")
+ session.exitstatus = 1
+
+
+# ---- agent handoff (spec agent-handoff-messages 2026-10-03, 4.1 / 4.2) -------
+# `handoff(out)` parses the convention block from captured stdout;
+# `assert_convention(out, err)` is the lint every stop must pass.
+import re as _re # noqa: E402
+
+HANDOFF_KEYS = ("later: ", "ask your human: ", "next: ")
+_NEXT_PREFIXES = ("sibyl ", "pip ", "pipx ", "claude ", "sibyl-memory-hermes ")
+_NEXT_WORDS = ("done", "retry", "sibyl-memory-mcp")
+_PLACEHOLDER = _re.compile(r"<[a-z_|\-]+>")
+
+
+def handoff(out: str) -> dict:
+ """Parse the convention block from captured stdout. Raises if the last
+ non-empty line is not `next:`; returns {next, human, later: [...], waiting,
+ block: [lines]}. `waiting` lists every `waiting:` line anywhere in out."""
+ lines = [ln for ln in out.splitlines()]
+ while lines and not lines[-1].strip():
+ lines.pop()
+ if not lines or not lines[-1].startswith("next: "):
+ raise AssertionError(f"last non-empty line is not `next:`: {lines[-1:]!r}")
+ block = []
+ for ln in reversed(lines):
+ if ln.startswith(HANDOFF_KEYS):
+ block.insert(0, ln)
+ else:
+ break
+ human = [ln[len("ask your human: "):] for ln in block if ln.startswith("ask your human: ")]
+ return {
+ "next": block[-1][len("next: "):],
+ "human": human[0] if human else None,
+ "later": [ln[len("later: "):] for ln in block if ln.startswith("later: ")],
+ "waiting": [ln for ln in out.splitlines() if ln.startswith("waiting: ")],
+ "block": block,
+ }
+
+
+def json_handoff(payload: dict) -> dict:
+ assert "next" in payload and "human_action" in payload, payload
+ return payload
+
+
+def _next_ok(value: str) -> bool:
+ if value in _NEXT_WORDS:
+ return True
+ if _re.fullmatch(r"retry in \d+ minutes", value):
+ return True
+ return value.startswith(_NEXT_PREFIXES)
+
+
+def assert_convention(out: str, err: str = "") -> dict:
+ """The 4.2 lint: last line `next:`; at most one `ask your human:`, directly
+ above `next:`; `later:` lines first; a placeholder needs an ask line; no
+ ANSI, no indentation, no em dash in the block; the `next` grammar; nothing
+ on stderr."""
+ h = handoff(out)
+ block = h["block"]
+ kinds = ["later" if b.startswith("later: ") else "ask" if b.startswith("ask your human: ")
+ else "next" for b in block]
+ assert kinds.count("next") == 1, block
+ assert kinds.count("ask") <= 1, block
+ if "ask" in kinds:
+ assert kinds[-2] == "ask", block
+ assert kinds == sorted(kinds, key=["later", "ask", "next"].index), block
+ for b in block:
+ assert "\x1b" not in b and b == b.lstrip() and "\u2014" not in b, b
+ for b in block:
+ if b.startswith(("later: ", "next: ")) and _PLACEHOLDER.search(b):
+ assert h["human"], f"placeholder without an ask line: {block}"
+ assert _next_ok(h["next"]), h["next"]
+ assert err == "", err
+ return h
+
+
+@pytest.fixture(autouse=True)
+def _reset_untrusted_base_note(monkeypatch):
+ """The untrusted-base explanation prints once per process (follow-up D1);
+ each test is its own process for that purpose."""
+ try:
+ from sibyl_memory_cli import cli as _cli
+ except Exception: # pragma: no cover
+ return
+ monkeypatch.setattr(_cli, "_UNTRUSTED_NOTED", set())
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/bom.yml b/sibyl-memory-cli/tests/fixtures/deepseek/bom.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f9e3fc60adfa32ae6f4a93e687585e18b0fe6c6a
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/bom.yml
@@ -0,0 +1,2 @@
+# with a BOM
+[]
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/broken.yml b/sibyl-memory-cli/tests/fixtures/deepseek/broken.yml
new file mode 100644
index 0000000000000000000000000000000000000000..b53fbb3bf730d02289543f20bab5a59432023abb
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/broken.yml
@@ -0,0 +1,2 @@
+- insert: [
+ - id: x
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/broken_with_fake_value.yml b/sibyl-memory-cli/tests/fixtures/deepseek/broken_with_fake_value.yml
new file mode 100644
index 0000000000000000000000000000000000000000..30999f6985a107576e066b4cd409b3e5e080c494
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/broken_with_fake_value.yml
@@ -0,0 +1,3 @@
+- insert:
+ - id: sibyl-memory
+ config: {env: {GITHUB_TOKEN: FAKESECRET123 ]]]
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/comment_only.yml b/sibyl-memory-cli/tests/fixtures/deepseek/comment_only.yml
new file mode 100644
index 0000000000000000000000000000000000000000..5f904fa463a8fa6fbe2f65055e6eaab4118e6633
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/comment_only.yml
@@ -0,0 +1,2 @@
+# only comments here
+# nothing else
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/crlf.yml b/sibyl-memory-cli/tests/fixtures/deepseek/crlf.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f1eca75461c58e0fcf733b49e5accd5dee3c9763
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/crlf.yml
@@ -0,0 +1,3 @@
+- id: some-builtin-row
+ config:
+ theme: dark
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/debian_dsh_home/dsh.conf b/sibyl-memory-cli/tests/fixtures/deepseek/debian_dsh_home/dsh.conf
new file mode 100644
index 0000000000000000000000000000000000000000..69d93d02f8f4de83304aade13de43122c12943ae
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/debian_dsh_home/dsh.conf
@@ -0,0 +1 @@
+verbose = 1
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/debian_dsh_home/group/all b/sibyl-memory-cli/tests/fixtures/deepseek/debian_dsh_home/group/all
new file mode 100644
index 0000000000000000000000000000000000000000..c1ed0a24cfeb2665b110f238c4adfe392175d740
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/debian_dsh_home/group/all
@@ -0,0 +1 @@
+host1
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/debian_dsh_home/machines.list b/sibyl-memory-cli/tests/fixtures/deepseek/debian_dsh_home/machines.list
new file mode 100644
index 0000000000000000000000000000000000000000..994b3e2cfc4f4d71b8c834d1812461b3fdd62ee1
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/debian_dsh_home/machines.list
@@ -0,0 +1,2 @@
+host1
+host2
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/duplicate_in_file.yml b/sibyl-memory-cli/tests/fixtures/deepseek/duplicate_in_file.yml
new file mode 100644
index 0000000000000000000000000000000000000000..df725b9ac81d1e91531904f1ec5244b64d9f4404
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/duplicate_in_file.yml
@@ -0,0 +1,11 @@
+- insert:
+ - id: sibyl-memory
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: sibyl-memory
+ command: "/a/sibyl-memory-mcp"
+ - id: sibyl-memory-2
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: sibyl-memory-2
+ command: "/b/sibyl-memory-mcp"
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/flow_list.yml b/sibyl-memory-cli/tests/fixtures/deepseek/flow_list.yml
new file mode 100644
index 0000000000000000000000000000000000000000..2e3662358820a63dd3ad9bec11d7fb65dd03d2d3
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/flow_list.yml
@@ -0,0 +1 @@
+[{id: x, disabled: true}]
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/foreign_flow_row.yml b/sibyl-memory-cli/tests/fixtures/deepseek/foreign_flow_row.yml
new file mode 100644
index 0000000000000000000000000000000000000000..cf184c18086fceb73c250b6cbc1d53a4a9c2c857
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/foreign_flow_row.yml
@@ -0,0 +1,2 @@
+- insert:
+ - {id: sibyl-memory, name: '@deepseek-ai/dsh-mcp-client', config: {serverName: engram, command: engram}}
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/foreign_same_id.yml b/sibyl-memory-cli/tests/fixtures/deepseek/foreign_same_id.yml
new file mode 100644
index 0000000000000000000000000000000000000000..768fb2eb7524a5df1d658b1032005be25e5abf69
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/foreign_same_id.yml
@@ -0,0 +1,16 @@
+# keep this comment
+- insert:
+ - id: sibyl-memory
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: engram
+ transport: stdio
+ command: engram
+ args: [mcp]
+ env:
+ ENGRAM_DIR: /data/engram
+ cwd: !!js process.cwd()
+ - id: after-row
+ name: other
+- id: tail-override
+ config: {a: 1}
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/indented_list.yml b/sibyl-memory-cli/tests/fixtures/deepseek/indented_list.yml
new file mode 100644
index 0000000000000000000000000000000000000000..d61a0d36097e8d0268e0e6ff2beffa64728991d7
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/indented_list.yml
@@ -0,0 +1,2 @@
+ - id: indented
+ config: {a: 1}
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/no_trailing_newline.yml b/sibyl-memory-cli/tests/fixtures/deepseek/no_trailing_newline.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f4f260fc42fc11c8751563ce027668df891e75ee
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/no_trailing_newline.yml
@@ -0,0 +1,3 @@
+- id: some-builtin-row
+ config:
+ theme: dark
\ No newline at end of file
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/not_a_list.yml b/sibyl-memory-cli/tests/fixtures/deepseek/not_a_list.yml
new file mode 100644
index 0000000000000000000000000000000000000000..b05a89495f12e31b4bcd7d5d7ceaab9243a4a749
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/not_a_list.yml
@@ -0,0 +1,2 @@
+key: value
+other: 1
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/ours_disabled.yml b/sibyl-memory-cli/tests/fixtures/deepseek/ours_disabled.yml
new file mode 100644
index 0000000000000000000000000000000000000000..307c90457482b49b787ec581861264ea514d4b27
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/ours_disabled.yml
@@ -0,0 +1,9 @@
+- insert:
+ - id: sibyl-memory
+ name: '@deepseek-ai/dsh-mcp-client'
+ disabled: true
+ config:
+ serverName: sibyl-memory
+ transport: stdio
+ command: "/old/venv/bin/sibyl-memory-mcp"
+ cwd: !!js process.cwd()
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/ours_flow_row.yml b/sibyl-memory-cli/tests/fixtures/deepseek/ours_flow_row.yml
new file mode 100644
index 0000000000000000000000000000000000000000..aeb17279e7d3fa698ee632cb4919191b2ba2a04d
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/ours_flow_row.yml
@@ -0,0 +1,2 @@
+- insert:
+ - {id: sibyl-memory, name: '@deepseek-ai/dsh-mcp-client', config: {serverName: sibyl-memory, transport: stdio, command: /old/bin/sibyl-memory-mcp, cwd: !!js process.cwd()}}
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/ours_nested_in_group.yml b/sibyl-memory-cli/tests/fixtures/deepseek/ours_nested_in_group.yml
new file mode 100644
index 0000000000000000000000000000000000000000..17c8d71c86c5d8d3e09b11d72c7d528090b3bd71
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/ours_nested_in_group.yml
@@ -0,0 +1,11 @@
+- insert:
+ - id: my-group
+ group: true
+ config:
+ - id: memory-sibyl-nested
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: sibyl-memory
+ transport: stdio
+ command: '/old/bin/sibyl-memory-mcp'
+ cwd: !!js process.cwd()
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/ours_overridden.yml b/sibyl-memory-cli/tests/fixtures/deepseek/ours_overridden.yml
new file mode 100644
index 0000000000000000000000000000000000000000..cfd67e5f9670360a52846285c51df933f692b384
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/ours_overridden.yml
@@ -0,0 +1,9 @@
+- insert:
+ - id: sibyl-memory
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: sibyl-memory
+ transport: stdio
+ command: "/old/venv/bin/sibyl-memory-mcp"
+ cwd: !!js process.cwd()
+- {id: sibyl-memory, disabled: true}
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/ours_stale.yml b/sibyl-memory-cli/tests/fixtures/deepseek/ours_stale.yml
new file mode 100644
index 0000000000000000000000000000000000000000..2ef830840f366b6c9bb93f035316f3e6a259373e
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/ours_stale.yml
@@ -0,0 +1,11 @@
+# Sibyl Memory MCP server (added by "sibyl setup deepseek"; re-run it to update the path)
+- insert:
+ - id: sibyl-memory
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: sibyl-memory
+ transport: stdio
+ command: "/old/venv/bin/sibyl-memory-mcp"
+ args: []
+ env: {}
+ cwd: !!js process.cwd()
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/ours_stale_custom.yml b/sibyl-memory-cli/tests/fixtures/deepseek/ours_stale_custom.yml
new file mode 100644
index 0000000000000000000000000000000000000000..fac12a483d45b417569374df59c332e934886002
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/ours_stale_custom.yml
@@ -0,0 +1,12 @@
+- insert:
+ - id: sibyl-memory
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: sibyl-memory
+ transport: stdio
+ command: /old/venv/bin/sibyl-memory-mcp # moved when I rebuilt the venv
+ args: []
+ env: {SIBYL_MEMORY_MCP_OUTPUT_TOKENS: "9000"}
+ cwd: !!js process.cwd()
+ startupTimeoutMs: 9000
+ toolCallTimeoutMs: 120000
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/template.yml b/sibyl-memory-cli/tests/fixtures/deepseek/template.yml
new file mode 100644
index 0000000000000000000000000000000000000000..10c95b72e619147d513b8e09f40cda262625bc64
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/template.yml
@@ -0,0 +1,4 @@
+# User patch layer for this profile.
+# A top-level YAML list of loader patch entries.
+# See docs/user/guide for examples.
+[]
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/unknown_tag.yml b/sibyl-memory-cli/tests/fixtures/deepseek/unknown_tag.yml
new file mode 100644
index 0000000000000000000000000000000000000000..b84ec228861830adf8da1db29fcc7dcfb8afa8e7
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/unknown_tag.yml
@@ -0,0 +1,2 @@
+- id: x
+ config: !!python/object:os.system {}
diff --git a/sibyl-memory-cli/tests/fixtures/deepseek/user_patches.yml b/sibyl-memory-cli/tests/fixtures/deepseek/user_patches.yml
new file mode 100644
index 0000000000000000000000000000000000000000..b24b941d034f4fbe199ae5afb32177c608a1167f
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/deepseek/user_patches.yml
@@ -0,0 +1,19 @@
+# my patches
+- id: some-builtin-row
+ config:
+ theme: dark
+
+- insert:
+ - id: memory-github
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: github
+ transport: stdio
+ command: npx
+ args: [-y, '@modelcontextprotocol/server-github']
+ env: {GITHUB_TOKEN: !!js process.env.GITHUB_TOKEN}
+ cwd: !!js process.cwd()
+ - id: note-row
+ name: some-plugin
+ config:
+ greeting: !!js '`hello ${process.env.USER}`'
diff --git a/sibyl-memory-cli/tests/fixtures/device_limit_r1.json b/sibyl-memory-cli/tests/fixtures/device_limit_r1.json
new file mode 100644
index 0000000000000000000000000000000000000000..5a27ea75e39de5001a8b4d935d127ec5f5d7fa06
--- /dev/null
+++ b/sibyl-memory-cli/tests/fixtures/device_limit_r1.json
@@ -0,0 +1,51 @@
+{
+ "_source": "plan plugin-paid-tier-2026-09-29 section 4.2 (the contract Track A implements). Labels only, never tokens.",
+ "limit_object": {
+ "code": "device_limit",
+ "limit": 1,
+ "tier": "free",
+ "devices": [
+ {"label": "work-laptop", "os_family": "macos", "last_seen_at": "2026-09-28T17:02:11.000Z"}
+ ],
+ "manage_url": "https://account.sibyllabs.org/security",
+ "upgrade_url": "https://sibyllabs.org/pro"
+ },
+ "check_at_limit": {
+ "bound": false,
+ "limit": {
+ "code": "device_limit",
+ "limit": 1,
+ "tier": "free",
+ "devices": [
+ {"label": "work-laptop", "os_family": "macos", "last_seen_at": "2026-09-28T17:02:11.000Z"}
+ ],
+ "manage_url": "https://account.sibyllabs.org/security",
+ "upgrade_url": "https://sibyllabs.org/pro"
+ }
+ },
+ "bind_409_body": {
+ "code": "device_limit",
+ "limit": 1,
+ "tier": "free",
+ "devices": [
+ {"label": "work-laptop", "os_family": "macos", "last_seen_at": "2026-09-28T17:02:11.000Z"}
+ ],
+ "manage_url": "https://account.sibyllabs.org/security",
+ "upgrade_url": "https://sibyllabs.org/pro"
+ },
+ "_r1b4_optional_pro_limit": "NOT in plan 4.2: an optional integer the CLI names in the Free upgrade line when an api sends it; without it the line says 'every computer you use' with no number. Track A to confirm or leave out.",
+ "bind_409_body_with_pro_limit": {
+ "code": "device_limit",
+ "limit": 1,
+ "tier": "free",
+ "pro_limit": 10,
+ "devices": [
+ {"label": "work-laptop", "os_family": "macos", "last_seen_at": "2026-09-28T17:02:11.000Z"}
+ ],
+ "manage_url": "https://account.sibyllabs.org/security",
+ "upgrade_url": "https://sibyllabs.org/pro"
+ },
+ "entitlement_acct_devices_ok": {"n": 1, "limit": 1, "over": false},
+ "entitlement_acct_devices_over": {"n": 3, "limit": 1, "over": true},
+ "entitlement_acct_devices_pro": {"n": 2, "limit": 10, "over": false}
+}
diff --git a/sibyl-memory-cli/tests/smoke/venv-compat.sh b/sibyl-memory-cli/tests/smoke/venv-compat.sh
new file mode 100755
index 0000000000000000000000000000000000000000..59f77bed20a17c42ea75b380e33c1507514c6d7a
--- /dev/null
+++ b/sibyl-memory-cli/tests/smoke/venv-compat.sh
@@ -0,0 +1,439 @@
+#!/usr/bin/env bash
+# Fresh-venv release gate for the coordinated plugin release (account-gated spec
+# 6.3 / 7.1 step 10; extends the cli 0.5.0 CLI-3 gate). Not a pytest.
+#
+# Creates a clean venv, installs ALL FIVE built wheels from (client,
+# hermes, mcp, langgraph, cli; never the PyPI copies of these) plus the CURRENT
+# hermes-agent from PyPI, then asserts:
+# * every command below exits 0 with no credentials;
+# * `sibyl memory list` exits 0 on a store and prints the no-account line;
+# * `sibyl memory neighbors` lists a v6 edge on that store (0.10.0 graph line);
+# * the MCP server answers memory_list with an isError result whose text is
+# JSON with code == "ACCOUNT_REQUIRED" (a ToolError envelope, NOT a Python
+# exception);
+# * the hermes adapter instantiates against the live hermes-agent
+# MemoryProvider ABC AND handle_tool_call("sibyl_list", {}) returns the
+# tool_error JSON (not an exception);
+# * SibylStore().put raises EntitlementError (langgraph propagates by design);
+# * fabricated credentials with the api unreachable (a closed loopback port)
+# are refused with setup_incomplete, also after entitlement.json is deleted
+# (no bootstrap grace);
+# * rows written under DEFAULT_TENANT before sign-in are readable and
+# searchable after sign-in (a throwaway test key, this process only);
+# * `import cryptography` resolves and is a declared client dependency;
+# * save/debloat (spec plugin-save-debloat 8.6): `sibyl debloat --fyi` on an
+# empty HOME, bare `sibyl save`, `sibyl skills install` + `status`,
+# `sibyl setup claude-code --dry-run` (two shims, five hooks, nothing
+# written), install-plugin writes the hermes skills, `sibyl setup codex
+# --dry-run` (two skill shims, nothing written), the console script starts
+# at _entry, `sibyl hook stop` exits 0 silently, the installed hook
+# command exits 0 silently once the binary is gone, the MCP server lists
+# the save/debloat prompts and four resources with no credentials and the
+# save prompt starts with the watermark, the adapter's prompt block names
+# SAVE.md; the hermes-agent skills dir is printed (informational);
+# * paid tier R1 (plan plugin-paid-tier-2026-09-29 9.2): `sibyl refresh` with
+# no account exits 0 and says to run sibyl init; `sibyl autosave status`;
+# `sibyl skills proposals` with no account exits 0 (nothing proposed); a
+# recorded 409 device_limit answer makes `sibyl init` print the computers
+# and the replace prompt (no network: the CLI's HTTP call is replaced);
+# * paid tier R2 (spec plugin-paid-tier-r2 1.6): `sibyl skills signals status` with
+# no account says Pro and writes nothing; `sibyl hook stop` with a transcript and
+# no account exits 0 silently and records nothing; with a throwaway test key in one
+# process (Pro), the Stop slice, an MCP tool call and the client's entity write
+# record tool names and hashes only in a 0600 signals.json, with no connection;
+# * tier convention (spec tier-convention 2026-10-05): `sibyl status` with an
+# elite entitlement (a throwaway test key, this process only, no network)
+# prints `Tier Elite` and exits 0;
+# * the pinned kid set in sibyl_memory_client/_entitlement_keys.py equals the
+# kids the operator read from production /api/plugin/health
+# (--expect-kids; no network in this script) and is not a PLACEHOLDER.
+#
+# Usage:
+# venv-compat.sh --expect-kids [,] [--venv ]
+# venv-compat.sh --allow-placeholder-key [--venv ] # rehearsal only
+# --allow-placeholder-key turns the pinned-key check into a WARN so the rest of
+# the gate can be rehearsed before the production key exists; a release run
+# must pass --expect-kids and must not pass --allow-placeholder-key.
+#
+# Runs with a throwaway HOME, so no real credentials, config or HERMES_HOME are
+# read or written. Network: PyPI only (pip). No Sibyl service is called: with
+# no credentials the account gate never reaches the network.
+set -euo pipefail
+
+DIST="${1:?usage: venv-compat.sh (--expect-kids | --allow-placeholder-key) [--venv ]}"
+shift
+EXPECT_KIDS=""
+ALLOW_PLACEHOLDER=0
+VENV=""
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --expect-kids) EXPECT_KIDS="${2:?--expect-kids needs a value}"; shift 2 ;;
+ --allow-placeholder-key) ALLOW_PLACEHOLDER=1; shift ;;
+ --venv) VENV="${2:?--venv needs a value}"; shift 2 ;;
+ *) echo "unknown argument: $1"; exit 2 ;;
+ esac
+done
+if [ -z "$EXPECT_KIDS" ] && [ "$ALLOW_PLACEHOLDER" -ne 1 ]; then
+ echo "pass --expect-kids [,] (production /api/plugin/health), or --allow-placeholder-key for a rehearsal"
+ exit 2
+fi
+VENV="${VENV:-$(mktemp -d)/venv}"
+PY="${PYTHON:-python3}"
+
+DIST="$(cd "$DIST" && pwd)"
+WHEELS=()
+for pkg in sibyl_memory_client sibyl_memory_hermes sibyl_memory_mcp sibyl_memory_langgraph sibyl_memory_cli; do
+ w="$(ls "$DIST"/${pkg}-*-py3-none-any.whl 2>/dev/null | sort | tail -1 || true)"
+ if [ -z "$w" ]; then echo "missing wheel for $pkg in $DIST"; exit 2; fi
+ WHEELS+=("$w")
+done
+CLI_WHEEL="${WHEELS[4]}"
+
+FAKE_HOME="$(mktemp -d)"
+export HOME="$FAKE_HOME"
+export HERMES_HOME="$FAKE_HOME/.hermes"
+export SIBYL_NONINTERACTIVE=1
+export NO_COLOR=1
+unset SIBYL_API_BASE SIBYL_ACCOUNT_BASE SIBYL_DASHBOARD_BASE SIBYL_MEMORY_DB SIBYL_CREDENTIALS SIBYL_TENANT_ID || true
+
+echo "== venv: $VENV"
+"$PY" -m venv "$VENV"
+"$VENV/bin/python" -m pip install -q --upgrade pip
+
+echo "== hermes-agent versions on PyPI (latest first):"
+"$VENV/bin/python" -m pip index versions hermes-agent 2>/dev/null | head -2 || echo " (pip index unavailable)"
+
+echo "== install: the five built wheels + current hermes-agent"
+"$VENV/bin/python" -m pip install -q --find-links "$DIST" "${WHEELS[@]}" hermes-agent
+
+"$VENV/bin/python" -m pip list 2>/dev/null | grep -Ei '^(sibyl-memory-[a-z]+|hermes-agent|cryptography) ' | sed 's/^/ /'
+
+fail=0
+run() {
+ local label="$1"; shift
+ if out="$("$@" 2>&1)"; then
+ echo " ok $label"
+ else
+ echo " FAIL $label (exit $?)"; echo "$out" | tail -15 | sed 's/^/ /'; fail=1
+ fi
+}
+
+B="$VENV/bin"
+echo "== commands (no credentials)"
+run "sibyl --help" "$B/sibyl" --help
+run "sibyl status --help" "$B/sibyl" status --help
+run "sibyl email --help" "$B/sibyl" email --help
+run "sibyl init --help (--no-email)" bash -c "'$B/sibyl' init --help | grep -q -- --no-email"
+run "sibyl status (no creds)" "$B/sibyl" status
+run "sibyl email (no creds)" "$B/sibyl" email
+run "sibyl health" "$B/sibyl" health
+run "sibyl setup --help" "$B/sibyl" setup --help
+run "cli version is the wheel's" "$B/python" -c "import sibyl_memory_cli as m, sys; w='$(basename "$CLI_WHEEL")'; sys.exit(0 if w.split('-')[1]==m.__version__ else 1)"
+run "adapters import" "$B/python" -c "import sibyl_memory_client, sibyl_memory_hermes, sibyl_memory_mcp, sibyl_memory_langgraph"
+run "sibyl status says agents need an account" bash -c "'$B/sibyl' status | grep -q 'agents cannot use memory until you do'"
+
+echo "== account gate"
+run "cryptography is a declared client dependency and imports" "$B/python" - <<'PYEOF'
+import importlib.metadata as md
+reqs = md.requires("sibyl-memory-client") or []
+assert any(r.split(";")[0].replace(" ", "").lower().startswith("cryptography") for r in reqs), reqs
+import cryptography
+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey # noqa: F401
+print(" cryptography", cryptography.__version__)
+PYEOF
+
+run "sibyl memory list reads without an account" bash -c "
+'$B/python' - <<'PYEOF'
+from sibyl_memory_client import DEFAULT_TENANT, MemoryClient
+from sibyl_memory_client.testing import NullEntitlementGate
+c = MemoryClient.local('$FAKE_HOME/.sibyl-memory/memory.db', tenant_id=DEFAULT_TENANT,
+ entitlement_gate=NullEntitlementGate())
+c.set_entity('compat', 'probe', {'note': 'written before an account existed'})
+PYEOF
+out=\$('$B/sibyl' memory list) && echo \"\$out\" | grep -q 'compat/probe' && echo \"\$out\" | grep -q 'reading local data without an account'"
+
+run "sibyl memory neighbors reads a v6 edge without an account" bash -c "
+'$B/python' - <<'PYEOF'
+from sibyl_memory_client import DEFAULT_TENANT, MemoryClient, entity_ref
+from sibyl_memory_client.testing import NullEntitlementGate
+c = MemoryClient.local('$FAKE_HOME/.sibyl-memory/memory.db', tenant_id=DEFAULT_TENANT,
+ entitlement_gate=NullEntitlementGate())
+c.set_entity('compat', 'hub', {'note': 'hub'})
+c.link(entity_ref('compat', 'hub'), entity_ref('compat', 'probe'), 'source_of')
+PYEOF
+out=\$('$B/sibyl' memory neighbors --entity compat hub) && echo \"\$out\" | grep -q 'source_of' && echo \"\$out\" | grep -q 'probe'"
+
+run "mcp: memory_list -> isError ACCOUNT_REQUIRED (not an exception)" "$B/python" - <<'PYEOF'
+import asyncio, json
+from mcp.types import CallToolRequest
+from sibyl_memory_mcp.server import build_server
+mcp = build_server()
+handler = mcp._mcp_server.request_handlers[CallToolRequest]
+res = asyncio.run(handler(CallToolRequest(method="tools/call",
+ params={"name": "memory_list", "arguments": {}})))
+root = res.root
+assert root.isError is True, root
+payload = json.loads(root.content[0].text)
+assert payload["code"] == "ACCOUNT_REQUIRED" and payload["reason"] == "no_account", payload
+tools = asyncio.run(mcp.list_tools())
+# 0.10.0: the eight memory tools plus the graph line's seven (links + reference read side)
+assert sorted(t.name for t in tools) == sorted([
+ "memory_remember", "memory_recall", "memory_search", "memory_list", "memory_forget",
+ "memory_set_state", "memory_get_state", "memory_record_event", "memory_set_reference",
+ "memory_get_reference", "memory_list_references", "memory_delete_reference",
+ "memory_link", "memory_unlink", "memory_neighbors"]), [t.name for t in tools]
+print(" mcp", payload["code"], payload["reason"], "| tools listed:", len(tools))
+PYEOF
+
+run "sibyl-memory-hermes install-plugin" "$B/sibyl-memory-hermes" install-plugin --hermes-home "$HERMES_HOME"
+run "adapter vs live hermes-agent ABC + signed-out tool call" "$B/python" - <", type(inst).__name__, "name =", inst.name, "| tool_error:", body,
+ "| prompt block names SAVE.md")
+PYEOF
+
+echo "== save and debloat (spec plugin-save-debloat 8.6)"
+# PATH without the operator's own tools, so no real `claude` binary is ever
+# consulted from this throwaway HOME.
+SPATH="$VENV/bin:/usr/bin:/bin"
+run "sibyl debloat --fyi on an empty HOME" bash -c "cd '$FAKE_HOME' && out=\$(env PATH='$SPATH' '$B/sibyl' debloat --fyi) && echo \"\$out\" | grep -q 'no always-load files found'"
+run "sibyl save (bare) exits 0 and writes nothing" bash -c "cd '$FAKE_HOME' && before=\$(ls -la --time-style=full-iso '$FAKE_HOME/.sibyl-memory' 2>/dev/null | sha256sum) && env PATH='$SPATH' '$B/sibyl' save | grep -q '/sibyl-save' && after=\$(ls -la --time-style=full-iso '$FAKE_HOME/.sibyl-memory' 2>/dev/null | sha256sum) && test \"\$before\" = \"\$after\""
+run "sibyl skills install + status list both files" bash -c "cd '$FAKE_HOME' && env PATH='$SPATH' '$B/sibyl' skills install >/dev/null && out=\$(env PATH='$SPATH' '$B/sibyl' skills status) && echo \"\$out\" | grep -q 'SAVE.md' && echo \"\$out\" | grep -q 'DEBLOAT.md' && test -f '$FAKE_HOME/.sibyl-memory/skills/SAVE.md'"
+run "sibyl setup claude-code --dry-run: two shims, five hooks, nothing written" bash -c "cd '$FAKE_HOME' && mkdir -p '$FAKE_HOME/.claude' && out=\$(env PATH='$SPATH' '$B/sibyl' setup claude-code --dry-run --yes) ; echo \"\$out\" | grep -c 'would write shim' | grep -qx 2 && echo \"\$out\" | grep -c 'would add hook' | grep -qx 5 && test ! -e '$FAKE_HOME/.claude/settings.json' && test ! -e '$FAKE_HOME/.claude/skills'"
+run "install-plugin wrote the hermes skills" bash -c "test -f '$HERMES_HOME/skills/sibyl-save/SKILL.md' && test -f '$HERMES_HOME/skills/sibyl-debloat/SKILL.md'"
+run "sibyl setup codex --dry-run: two skill shims, nothing written" bash -c "cd '$FAKE_HOME' && mkdir -p '$FAKE_HOME/.codex' && out=\$(env PATH='$SPATH' '$B/sibyl' setup codex --dry-run --yes) ; echo \"\$out\" | grep -c 'would write shim .*/.codex/skills/sibyl-' | grep -qx 2 && test ! -e '$FAKE_HOME/.codex/skills' && test ! -e '$FAKE_HOME/.codex/AGENTS.md'"
+run "the sibyl console script starts at sibyl_memory_cli._entry" grep -q 'sibyl_memory_cli._entry' "$B/sibyl"
+run "sibyl hook stop from the wheel: exit 0, prints nothing" bash -c "cd '$FAKE_HOME' && out=\$(echo '{\"session_id\": \"compat\", \"stop_hook_active\": false}' | env PATH='$SPATH' '$B/sibyl' hook stop) && test -z \"\$out\""
+run "the installed hook command exits 0 silently once sibyl is gone" bash -c "cmd=\$('$B/python' -c 'from sibyl_memory_cli.setup import hook_command; print(hook_command(\"/nonexistent-sibyl-compat/bin/sibyl\", \"stop\"))') && out=\$(echo '{}' | bash -c \"\$cmd\" 2>&1) && test -z \"\$out\""
+run "mcp: prompts save/debloat and four resources with no credentials" "$B/python" - <<'PYEOF'
+import asyncio
+from sibyl_memory_mcp.server import build_server
+m = build_server()
+names = {p.name for p in asyncio.run(m.list_prompts())}
+assert {"save", "debloat"} <= names, names
+uris = {str(r.uri) for r in asyncio.run(m.list_resources())}
+want = {"sibyl://skills/SAVE.md", "sibyl://skills/DEBLOAT.md", "sibyl://skills/manifest", "sibyl://context/weight"}
+assert want <= uris, uris
+text = asyncio.run(m.get_prompt("save", {})).messages[0].content.text
+assert text.startswith("\nCORE RULES\n\nmore junk\n"
+ lean = M.heuristic_lean(t)
+ assert "CORE RULES" in lean and "junk" not in lean
+ # else keep first ## section, trim later ones
+ lean2 = M.heuristic_lean(BLOATED_CLAUDE)
+ assert "Identity" in lean2
+ assert "Accumulated memory" not in lean2 # later section trimmed
+ assert len(lean2) < len(BLOATED_CLAUDE)
+ assert "stored entries in Sibyl Memory" in lean2 # pointer appended (SD-10 wording)
+
+
+def test_debloat_refuses_without_backup(tmp_path):
+ f = tmp_path / "CLAUDE.md"; f.write_text(BLOATED_CLAUDE, encoding="utf-8")
+ out = M.debloat_file(f, "lean", backup_exists=False)
+ assert not out["written"] and "refused" in out["error"]
+ assert f.read_text(encoding="utf-8") == BLOATED_CLAUDE # untouched
+
+
+def test_debloat_trims_with_backup_and_dry_run(tmp_path):
+ f = tmp_path / "CLAUDE.md"; f.write_text(BLOATED_CLAUDE, encoding="utf-8")
+ lean = M.heuristic_lean(BLOATED_CLAUDE)
+ # dry-run does not write
+ dry = M.debloat_file(f, lean, backup_exists=True, dry_run=True)
+ assert not dry["written"] and f.read_text(encoding="utf-8") == BLOATED_CLAUDE
+ assert dry["after"] < dry["before"]
+ # real write trims
+ real = M.debloat_file(f, lean, backup_exists=True)
+ assert real["written"] and f.read_text(encoding="utf-8") == lean
+ assert f.stat().st_size < real["before"]
+
+
+def test_detect_state_snapshot(tmp_path):
+ home = _fake_home(tmp_path)
+ st = M.detect_state(home, cwd=home / "myproj", db_path=home / ".sibyl-memory" / "memory.db")
+ assert "files" in st and len(st["files"]) >= 4
+ assert set(st["harnesses"]) == {"claude-code", "codex", "hermes"}
+ assert st["db_entries"] == 0
diff --git a/sibyl-memory-cli/tests/test_migrate_adversarial.py b/sibyl-memory-cli/tests/test_migrate_adversarial.py
new file mode 100644
index 0000000000000000000000000000000000000000..593de690647ed209a8f6382413e8a00a97ebfce0
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_migrate_adversarial.py
@@ -0,0 +1,231 @@
+"""Adversarial / edge-case tests for the sibyl setup migration phases.
+
+Hunts for the failure modes a hand-written happy-path suite misses: large/many/
+nested/unicode/binary files, symlinks, corrupted/locked DBs, permission errors,
+backup integrity under stress, atomic + idempotent debloat, and a fuzz loop over
+random file trees asserting (a) byte-exact backup, (b) sources never modified,
+(c) debloat refuses without a backup and round-trips with one.
+"""
+import os
+import random
+import sqlite3
+import string
+import sys
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import migrate as M
+from sibyl_memory_client import MemoryClient
+
+
+# ---------------------------------------------------------------- backup stress
+
+def test_backup_large_file(tmp_path):
+ home = tmp_path / "h"; home.mkdir()
+ big = home / "CLAUDE.md"; big.write_bytes(b"x" * (5 * 1024 * 1024)) # 5 MB
+ res = M.run_backup(M.scan_memory_files(home, cwd=home), tmp_path / "b")
+ assert res.ok and res.total_bytes >= 5 * 1024 * 1024
+ assert (res.backup_dir / "CLAUDE.md").stat().st_size == big.stat().st_size
+
+
+def test_backup_many_files_nested(tmp_path):
+ home = tmp_path / "h"; (home / ".hermes" / "memory" / "deep" / "deeper").mkdir(parents=True)
+ for i in range(120):
+ (home / ".hermes" / "memory" / "deep" / "deeper" / f"n{i}.md").write_text(f"note {i}\n")
+ res = M.run_backup(M.scan_memory_files(home, cwd=home), tmp_path / "b")
+ assert res.ok
+ copied = list((res.backup_dir).rglob("n*.md"))
+ assert len(copied) == 120
+
+
+def test_backup_unicode_and_binary_content(tmp_path):
+ home = tmp_path / "h"; home.mkdir()
+ (home / "CLAUDE.md").write_text("# café ☕ 你好 \U0001f9e0\nkeep: π=3.14159\n", encoding="utf-8")
+ (home / "AGENTS.md").write_bytes(bytes(range(256))) # raw binary
+ res = M.run_backup(M.scan_memory_files(home, cwd=home), tmp_path / "b")
+ assert res.ok
+ assert (res.backup_dir / "CLAUDE.md").read_text(encoding="utf-8").startswith("# café")
+ assert (res.backup_dir / "AGENTS.md").read_bytes() == bytes(range(256))
+
+
+def test_backup_never_modifies_sources(tmp_path):
+ home = tmp_path / "h"; home.mkdir()
+ files = {}
+ for n in ("CLAUDE.md", "AGENTS.md"):
+ p = home / n; p.write_text("content " * 50); files[p] = (p.read_bytes(), p.stat().st_mtime_ns)
+ M.run_backup(M.scan_memory_files(home, cwd=home), tmp_path / "b")
+ for p, (b, mt) in files.items():
+ assert p.read_bytes() == b and p.stat().st_mtime_ns == mt
+
+
+def test_backup_dir_collision_errors_cleanly(tmp_path):
+ home = tmp_path / "h"; home.mkdir(); (home / "CLAUDE.md").write_text("x")
+ files = M.scan_memory_files(home, cwd=home)
+ fixed = M.run_backup(files, tmp_path / "b")
+ # forcing the SAME backup dir name must not silently overwrite
+ same = tmp_path / "b2"
+ r1 = M.run_backup(files, same)
+ from datetime import datetime
+ # re-run into a pre-created dir of the same timestamp name -> clean error, no crash
+ dirname = r1.backup_dir.name
+ (tmp_path / "b3").mkdir(); (tmp_path / "b3" / dirname).mkdir()
+ # monkey the name fn by writing into existing dir: simulate by calling with now fixed
+ res = M.run_backup(files, tmp_path / "b3", now=datetime.fromisoformat(dirname.replace("sibyl-migration-backup-","").replace("_",":")))
+ assert (res.ok is False) and "backup dir" in (res.error or "")
+
+
+@pytest.mark.skipif(os.geteuid() == 0, reason="root bypasses file permissions")
+def test_backup_permission_denied_source_aborts(tmp_path):
+ home = tmp_path / "h"; home.mkdir()
+ p = home / "CLAUDE.md"; p.write_text("secret")
+ files = M.scan_memory_files(home, cwd=home)
+ os.chmod(p, 0o000)
+ try:
+ res = M.run_backup(files, tmp_path / "b")
+ # either it copies (some FS) or aborts cleanly — must NOT raise
+ assert res.ok in (True, False)
+ if not res.ok:
+ assert "copy failed" in (res.error or "")
+ finally:
+ os.chmod(p, 0o644)
+
+
+# ---------------------------------------------------------------- scan edge
+
+def test_scan_handles_broken_symlink(tmp_path):
+ home = tmp_path / "h"; home.mkdir()
+ (home / "CLAUDE.md").symlink_to(home / "does-not-exist") # broken symlink
+ # must not raise; broken link .exists() is False so it's skipped
+ found = M.scan_memory_files(home, cwd=home)
+ assert isinstance(found, list)
+
+
+def test_scan_no_files_returns_empty(tmp_path):
+ home = tmp_path / "empty"; home.mkdir()
+ assert M.scan_memory_files(home, cwd=home) == []
+
+
+# ---------------------------------------------------------------- verify / DB
+
+def test_verify_corrupt_db_is_contained(tmp_path):
+ # CLI-3: a corrupt/non-SQLite file that EXISTS is now flagged as unreadable
+ # (DB_UNREADABLE sentinel), distinct from 0 (no DB / empty DB), so the
+ # orchestrator can abort verify/debloat instead of treating it as 0 rows.
+ db = tmp_path / "memory.db"; db.write_bytes(os.urandom(4096)) # not a sqlite file
+ assert M.db_baseline(db) == M.DB_UNREADABLE # contained, no raise, flagged
+ v = M.verify_new_entries(db, 0)
+ assert v["ok"] is False # contained, no raise
+ assert v.get("unreadable") is True
+
+
+def test_verify_empty_schema_db(tmp_path):
+ db = tmp_path / "memory.db"
+ MemoryClient.local(str(db), tenant_id="qa") # creates schema, 0 rows
+ assert M.db_baseline(db) == 0
+ assert M.verify_new_entries(db, 0)["ok"] is False
+
+
+def test_verify_counts_after_writes(tmp_path):
+ db = tmp_path / "memory.db"
+ c = MemoryClient.local(str(db), tenant_id="qa")
+ base = M.db_baseline(db)
+ for i in range(25):
+ c.set_entity("facts", f"f{i}", {"value": i})
+ v = M.verify_new_entries(db, base)
+ assert v["new_total"] == 25 and v["by_category"]["facts"] == 25
+
+
+# ---------------------------------------------------------------- debloat safety
+
+def test_debloat_atomic_no_partial_on_success(tmp_path):
+ f = tmp_path / "CLAUDE.md"; f.write_text("# A\n" + "junk\n" * 1000)
+ lean = M.heuristic_lean(f.read_text())
+ out = M.debloat_file(f, lean, backup_exists=True)
+ assert out["written"] and f.read_text() == lean
+ assert not list(tmp_path.glob("*.sibyl-tmp")) # no temp left behind
+
+
+def test_debloat_idempotent_rerun(tmp_path):
+ f = tmp_path / "CLAUDE.md"; f.write_text("# A\nidentity\n## later\njunk\n")
+ lean = M.heuristic_lean(f.read_text())
+ M.debloat_file(f, lean, backup_exists=True)
+ first = f.read_text()
+ # re-run with the lean of the now-lean file: should be stable
+ M.debloat_file(f, M.heuristic_lean(first), backup_exists=True)
+ assert "identity" in f.read_text()
+
+
+def test_debloat_preserves_unicode(tmp_path):
+ f = tmp_path / "CLAUDE.md"; f.write_text("# café ☕\nrule π\n", encoding="utf-8")
+ lean = "# café ☕\nrule π\n"
+ M.debloat_file(f, lean, backup_exists=True)
+ assert f.read_text(encoding="utf-8") == lean
+
+
+def test_debloat_refuses_no_backup_under_all_inputs(tmp_path):
+ f = tmp_path / "CLAUDE.md"; orig = "# keep\n" * 10; f.write_text(orig)
+ for lean in ("", "x", orig, "a" * 10000):
+ out = M.debloat_file(f, lean, backup_exists=False)
+ assert not out["written"] and f.read_text() == orig
+
+
+# ---------------------------------------------------------------- heuristic_lean edge
+
+def test_lean_empty_and_no_sections(tmp_path):
+ assert "Sibyl Memory" in M.heuristic_lean("")
+ flat = "just one line, no headings at all\nsecond line\n"
+ out = M.heuristic_lean(flat)
+ assert "just one line" in out
+
+
+def test_lean_keepblock_exact(tmp_path):
+ t = "x\n\nONLY THIS\n\ny\n"
+ assert M.heuristic_lean(t).split("\n")[0] == "ONLY THIS"
+
+
+# ---------------------------------------------------------------- codex wirer edge
+
+def test_codex_malformed_toml_no_crash(tmp_path):
+ cfg = tmp_path / "config.toml"; cfg.write_text("this is = = not valid toml [[[\n")
+ w = M.CodexWirer(config_path=cfg)
+ st = w.current_state() # must not raise
+ assert st["config_exists"] and st["wired_with_sibyl"] is False
+
+
+def test_codex_already_wired_detected(tmp_path):
+ cfg = tmp_path / "config.toml"; cfg.write_text('model="o4"\n[mcp_servers.sibyl_memory]\ncommand = "sibyl-memory-mcp"\n')
+ assert M.CodexWirer(config_path=cfg).current_state()["wired_with_sibyl"] is True
+
+
+# ---------------------------------------------------------------- FUZZ
+
+def _rand_text(rng, n):
+ return "".join(rng.choice(string.printable) for _ in range(n))
+
+
+def test_fuzz_backup_roundtrip_and_source_immutability(tmp_path):
+ rng = random.Random(20260531)
+ for it in range(60):
+ home = tmp_path / f"h{it}"; home.mkdir()
+ snap = {}
+ # random subset of known memory files with random content
+ for rel in ("CLAUDE.md", "AGENTS.md", ".codex/config.toml", "MEMORY.md"):
+ if rng.random() < 0.6:
+ p = home / rel; p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(_rand_text(rng, rng.randint(0, 4000)), encoding="utf-8")
+ snap[p] = (p.read_bytes(), p.stat().st_mtime_ns)
+ files = M.scan_memory_files(home, cwd=home)
+ res = M.run_backup(files, tmp_path / f"b{it}")
+ assert res.ok, res.error
+ # byte-exact copies
+ for f in files:
+ assert (res.backup_dir / f.rel).read_bytes() == f.path.read_bytes()
+ # sources untouched
+ for p, (b, mt) in snap.items():
+ assert p.read_bytes() == b and p.stat().st_mtime_ns == mt
+ # debloat round-trip on CLAUDE.md if present
+ cm = home / "CLAUDE.md"
+ if cm.exists():
+ assert not M.debloat_file(cm, "lean", backup_exists=False)["written"]
+ M.debloat_file(cm, M.heuristic_lean(cm.read_text(encoding="utf-8", errors="replace")), backup_exists=res.ok)
diff --git a/sibyl-memory-cli/tests/test_migrate_force_2026_06_05.py b/sibyl-memory-cli/tests/test_migrate_force_2026_06_05.py
new file mode 100644
index 0000000000000000000000000000000000000000..40373401414848e1890e7c77c236a8eb1b63f03e
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_migrate_force_2026_06_05.py
@@ -0,0 +1,67 @@
+"""Regression (bugflow 2026-06-05): `sibyl migrate --force` must reach the wirers.
+
+Onboarding dead-end: when a detected harness already had a non-sibyl memory
+provider, the wirer refused with "Use --force to overwrite." but
+`run_guided_setup` called `wire()` with no `force`, and `sibyl migrate` had no
+`--force` flag to pass. The flag now threads cli -> run_guided_setup(force=) ->
+wire(force=force).
+"""
+from __future__ import annotations
+
+from sibyl_memory_cli import migrate as M
+from sibyl_memory_cli.setup import WireOutcome
+from sibyl_memory_client import MemoryClient
+
+
+class _RecordingWirer:
+ """A fake harness wirer that records the `force` kwarg it was called with."""
+
+ name = "rec"
+
+ def __init__(self):
+ self.seen_force = None
+
+ def is_present(self):
+ return True
+
+ def current_state(self):
+ return {"wired_with_sibyl": False}
+
+ def wire(self, *, force: bool = False, dry_run: bool = False, prompt_fn=None):
+ self.seen_force = force
+ return WireOutcome(self.name, "wired", "ok")
+
+
+def _home_with_memory(tmp_path):
+ h = tmp_path / "home"
+ (h / "proj").mkdir(parents=True)
+ (h / "proj" / "CLAUDE.md").write_text("# memory\n- a fact worth keeping\n")
+ db = h / ".sibyl-memory" / "memory.db"
+ db.parent.mkdir(parents=True)
+ return h, db
+
+
+def _fake_extract(_backup_dir, db_path):
+ MemoryClient.local(str(db_path), tenant_id="qa").set_entity("f", "a", {"v": 1})
+
+
+def test_force_true_threads_to_wirer(tmp_path):
+ h, db = _home_with_memory(tmp_path)
+ rec = _RecordingWirer()
+ M.run_guided_setup(
+ home=h, cwd=h / "proj", db_path=db, backup_parent=tmp_path / "bk",
+ io=M.GuidedIO(scripted=["n"]), wirers={"rec": rec},
+ extract_fn=_fake_extract, force=True,
+ )
+ assert rec.seen_force is True
+
+
+def test_force_defaults_false(tmp_path):
+ h, db = _home_with_memory(tmp_path)
+ rec = _RecordingWirer()
+ M.run_guided_setup(
+ home=h, cwd=h / "proj", db_path=db, backup_parent=tmp_path / "bk",
+ io=M.GuidedIO(scripted=["n"]), wirers={"rec": rec},
+ extract_fn=_fake_extract,
+ )
+ assert rec.seen_force is False
diff --git a/sibyl-memory-cli/tests/test_migrate_trim_2026_09_27.py b/sibyl-memory-cli/tests/test_migrate_trim_2026_09_27.py
new file mode 100644
index 0000000000000000000000000000000000000000..3af4d719340f8941fc1a90a11c634eb1019b54fe
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_migrate_trim_2026_09_27.py
@@ -0,0 +1,197 @@
+"""`sibyl migrate` trim step: every instruction file the scan found, not a
+hardcoded CLAUDE.md (spec plugin-save-debloat 6.1-6.2, tests 8.4 items 27-29
+and the Codex-only adversarial case).
+
+On the pre-change tree: the Codex-only, two-file, .debloat.json-surface and
+second-file backup tests FAIL (only CLAUDE.md was ever considered and the
+phase was a single dict); CONTEXT_FILES / trim_candidates did not exist
+(ImportError). test_29 and test_config_files_are_never_candidates have no
+pre-change equivalent beyond the ImportError."""
+from __future__ import annotations
+
+import builtins
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_client import MemoryClient
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import migrate as M
+
+HISTORY = "".join(f"- 2025-0{1 + i % 8}-1{i % 9} decided thing {i} for the project history\n"
+ for i in range(8))
+CURRENT = "# Agent rules\n\nRun the tests first.\nUse the venv.\nKeep answers short.\nNo secrets.\n\n"
+BIG = CURRENT + "## Changelog\n" + HISTORY
+
+
+def _extract_ok(backup_dir, db_path):
+ c = MemoryClient.local(str(db_path), tenant_id="qa")
+ c.set_entity("facts", "a", {"v": 1})
+
+
+def _run(home: Path, proj: Path, tmp_path: Path, answers, **kw):
+ db = home / ".sibyl-memory" / "memory.db"
+ db.parent.mkdir(parents=True, exist_ok=True)
+ io = M.GuidedIO(scripted=list(answers))
+ rep = M.run_guided_setup(home=home, cwd=proj, db_path=db, backup_parent=tmp_path / "bk",
+ io=io, wirers={}, extract_fn=_extract_ok, **kw)
+ return rep, io
+
+
+def _asked(io: M.GuidedIO) -> list[str]:
+ return [ln for ln in io.lines if ln.startswith("Trimmed ")]
+
+
+def test_adv_codex_only_project_gets_agents_md_trimmed(tmp_path):
+ home = tmp_path / "home"
+ proj = home / "proj"
+ proj.mkdir(parents=True)
+ (proj / "AGENTS.md").write_text(BIG)
+ questions: list[str] = []
+
+ class IO(M.GuidedIO):
+ def confirm(self, q, *, default=True):
+ questions.append(q)
+ return True
+
+ db = home / ".sibyl-memory" / "memory.db"
+ db.parent.mkdir(parents=True)
+ rep = M.run_guided_setup(home=home, cwd=proj, db_path=db, backup_parent=tmp_path / "bk",
+ io=IO(), wirers={}, extract_fn=_extract_ok)
+ assert any(q.startswith("Trim AGENTS.md to lean now?") for q in questions), questions
+ recs = rep["phases"]["debloat"]
+ assert recs == [dict(recs[0], file="AGENTS.md", written=True)]
+ txt = (proj / "AGENTS.md").read_text()
+ assert "decided thing 5" not in txt and "Run the tests first." in txt
+ assert "sibyl migrate" in txt and str(tmp_path / "bk") in txt
+
+
+def test_27_claude_md_and_cursorrules_two_questions_two_records(tmp_path, capsys, monkeypatch):
+ home = tmp_path / "home"
+ proj = home / "proj"
+ proj.mkdir(parents=True)
+ (proj / "CLAUDE.md").write_text(BIG)
+ (proj / ".cursorrules").write_text("".join(f"Rule {i}: keep this current rule exactly as written.\n"
+ for i in range(5)) + "\n"
+ "History\n" + "old rule text that was replaced long ago\n" * 12)
+ rep, io = _run(home, proj, tmp_path, ["y", "y"])
+ recs = {r["file"]: r for r in rep["phases"]["debloat"]}
+ assert set(recs) == {"CLAUDE.md", ".cursorrules"} and all(r["written"] for r in recs.values())
+ # The summary prints one `trimmed` line per file, with its name.
+ monkeypatch.setattr(M, "run_guided_setup", lambda **kw: rep)
+ monkeypatch.setattr(M, "scan_memory_files", lambda h, c: [M.FoundFile("x", proj / "CLAUDE.md",
+ "proj/CLAUDE.md", False, 1)])
+ monkeypatch.setattr(builtins, "input", lambda *a, **k: "y")
+ monkeypatch.chdir(proj)
+ cli.main(["migrate", "--yes"])
+ out = capsys.readouterr().out
+ trimmed = [ln for ln in out.splitlines() if "trimmed" in ln]
+ assert len(trimmed) == 2
+ assert any("CLAUDE.md" in ln for ln in trimmed) and any(".cursorrules" in ln for ln in trimmed)
+
+
+def test_config_files_are_never_candidates_and_cursor_rules_dir_is_not_trimmed(tmp_path):
+ home = tmp_path / "home"
+ proj = home / "proj"
+ (proj / ".cursor" / "rules").mkdir(parents=True)
+ (home / ".codex").mkdir(parents=True)
+ (home / ".claude").mkdir(parents=True)
+ (home / ".codex" / "config.toml").write_text('model = "x"\n' * 200)
+ (home / ".claude" / "settings.json").write_text(json.dumps({"k": "v" * 5000}))
+ (proj / ".cursor" / "rules" / "a.mdc").write_text(BIG)
+ files = M.scan_memory_files(home, proj)
+ cands = M.trim_candidates(files, home=home, cwd=proj)
+ names = {f.matched: why for f, why in cands}
+ assert ".codex/config.toml" not in names and ".claude/settings.json" not in names
+ assert names[".cursor/rules"].startswith("a directory")
+ rep, io = _run(home, proj, tmp_path, [])
+ assert "debloat" not in rep["phases"]
+ assert (proj / ".cursor" / "rules" / "a.mdc").read_text() == BIG
+
+
+def test_27_debloat_json_surface_restricts_and_outside_entries_are_ignored(tmp_path):
+ home = tmp_path / "home"
+ proj = home / "proj"
+ proj.mkdir(parents=True)
+ other = tmp_path / "other"
+ other.mkdir()
+ (other / "file.md").write_text(BIG)
+ (proj / "CLAUDE.md").write_text(BIG)
+ (proj / "AGENTS.md").write_text(BIG)
+ (proj / ".debloat.json").write_text(json.dumps({"surface": ["AGENTS.md", "../../other/file.md",
+ str(other / "file.md")]}))
+ rep, io = _run(home, proj, tmp_path, ["y"])
+ assert [r["file"] for r in rep["phases"]["debloat"]] == ["AGENTS.md"]
+ assert (proj / "CLAUDE.md").read_text() == BIG
+ assert (other / "file.md").read_text() == BIG
+
+
+def test_27_no_debloat_asks_nothing(tmp_path):
+ home = tmp_path / "home"
+ proj = home / "proj"
+ proj.mkdir(parents=True)
+ (proj / "AGENTS.md").write_text(BIG)
+
+ class IO(M.GuidedIO):
+ def confirm(self, q, *, default=True):
+ raise AssertionError("asked: " + q)
+
+ db = home / ".sibyl-memory" / "memory.db"
+ db.parent.mkdir(parents=True)
+ rep = M.run_guided_setup(home=home, cwd=proj, db_path=db, backup_parent=tmp_path / "bk",
+ io=IO(), wirers={}, extract_fn=_extract_ok, debloat=False)
+ assert "debloat" not in rep["phases"] and (proj / "AGENTS.md").read_text() == BIG
+
+
+def test_27_small_file_is_no_safe_trim_and_not_asked(tmp_path):
+ home = tmp_path / "home"
+ proj = home / "proj"
+ proj.mkdir(parents=True)
+ (proj / "AGENTS.md").write_text("# one\nline\n")
+ rep, io = _run(home, proj, tmp_path, [])
+ assert "debloat" not in rep["phases"]
+ assert any("no safe trim found" in ln for ln in io.lines)
+
+
+def test_28_backup_reverification_guards_the_second_file(tmp_path):
+ home = tmp_path / "home"
+ proj = home / "proj"
+ proj.mkdir(parents=True)
+ (proj / "CLAUDE.md").write_text(BIG)
+ (proj / "AGENTS.md").write_text(BIG)
+
+ class IO(M.GuidedIO):
+ def confirm(self, q, *, default=True):
+ if "AGENTS.md" in q:
+ for d in (tmp_path / "bk").glob("sibyl-migration-backup-*"):
+ bc = d / "proj" / "AGENTS.md"
+ if bc.exists():
+ bc.unlink()
+ return True
+
+ db = home / ".sibyl-memory" / "memory.db"
+ db.parent.mkdir(parents=True)
+ rep = M.run_guided_setup(home=home, cwd=proj, db_path=db, backup_parent=tmp_path / "bk",
+ io=IO(), wirers={}, extract_fn=_extract_ok)
+ recs = {r["file"]: r for r in rep["phases"]["debloat"]}
+ assert recs["CLAUDE.md"]["written"] is True
+ assert recs["AGENTS.md"]["written"] is False
+ assert recs["AGENTS.md"]["error"] == "backup re-verification failed"
+ assert (proj / "AGENTS.md").read_text() == BIG
+
+
+def test_29_context_and_config_files_cover_harness_files_exactly():
+ every = {rel for rels in M.HARNESS_FILES.values() for rel in rels}
+ assert M.CONTEXT_FILES | M.CONFIG_FILES == every
+ assert not (M.CONTEXT_FILES & M.CONFIG_FILES)
+
+
+def test_lean_text_for_prefers_the_splitter_and_falls_back(tmp_path):
+ lean = M.lean_text_for(BIG, "CLAUDE.md", tmp_path / "bk")
+ assert lean is not None and "Run the tests first." in lean and "decided thing" not in lean
+ assert M.lean_text_for(BIG, "notes.json", tmp_path) is None
+ flat = "# T\n## identity\nx\n## later\n" + "later stuff that is not history\n" * 20
+ lean2 = M.lean_text_for(flat, "CLAUDE.md", tmp_path)
+ assert lean2 is not None and "later stuff" not in lean2 and "a full copy of this file is in the pre-migration backup" in lean2
diff --git a/sibyl-memory-cli/tests/test_network_guard_2026_09_27.py b/sibyl-memory-cli/tests/test_network_guard_2026_09_27.py
new file mode 100644
index 0000000000000000000000000000000000000000..c477a09fd073ec8866f9013d2dfb7a3484923de9
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_network_guard_2026_09_27.py
@@ -0,0 +1,92 @@
+"""The test network guard (conftest) refuses every non-loopback connection and
+name lookup, records it, and fails the test that made it. A previous build's
+suite hit the production api by accident; this file fails if the guard is
+missing, loosened, or no longer records."""
+from __future__ import annotations
+
+import http.server
+import socket
+import threading
+import urllib.error
+import urllib.request
+
+import pytest
+
+from sibyl_memory_client.testing import (
+ assert_no_external_attempts,
+ clear_refused_connections,
+ refused_connections,
+)
+
+
+@pytest.mark.parametrize("address", [
+ ("203.0.113.9", 443), # TEST-NET-3
+ ("8.8.8.8", 53),
+ ("api.sibyllabs.org", 443),
+ ("localhost.sibyllabs.org", 443), # a prefix check would pass this
+ ("127.evil.example", 80),
+ ("::ffff:8.8.8.8", 53),
+])
+def test_non_loopback_connect_is_refused_and_recorded(address) -> None:
+ start = len(refused_connections())
+ fam = socket.AF_INET6 if ":" in address[0] else socket.AF_INET
+ s = socket.socket(fam, socket.SOCK_STREAM)
+ try:
+ with pytest.raises(ConnectionRefusedError):
+ s.connect(address)
+ assert s.connect_ex is not None
+ with pytest.raises(ConnectionRefusedError):
+ s.connect_ex(address)
+ finally:
+ s.close()
+ assert refused_connections()[start:] == [address[0], address[0]]
+ clear_refused_connections(start)
+
+
+def test_lookups_and_http_are_refused() -> None:
+ start = len(refused_connections())
+ with pytest.raises(socket.gaierror):
+ socket.getaddrinfo("api.sibyllabs.org", 443)
+ with pytest.raises(OSError):
+ socket.create_connection(("api.sibyllabs.org", 443), timeout=1)
+ with pytest.raises(urllib.error.URLError):
+ urllib.request.urlopen("https://api.sibyllabs.org/api/plugin/health", timeout=1)
+ assert "api.sibyllabs.org" in refused_connections()[start:]
+ clear_refused_connections(start)
+
+
+def test_a_swallowed_attempt_still_fails_the_test() -> None:
+ start = len(refused_connections())
+ try:
+ socket.create_connection(("203.0.113.10", 80), timeout=1)
+ except OSError:
+ pass # what a careless test would do
+ with pytest.raises(AssertionError, match="non-loopback"):
+ assert_no_external_attempts(start)
+ assert refused_connections()[start:] == []
+
+
+def test_loopback_still_works() -> None:
+ class H(http.server.BaseHTTPRequestHandler):
+ def do_GET(self): # noqa: N802
+ self.send_response(204)
+ self.end_headers()
+
+ def log_message(self, *a):
+ pass
+ srv = http.server.HTTPServer(("127.0.0.1", 0), H)
+ t = threading.Thread(target=srv.serve_forever, daemon=True)
+ t.start()
+ try:
+ port = srv.server_address[1]
+ for host in ("127.0.0.1", "localhost"):
+ with urllib.request.urlopen(f"http://{host}:{port}/", timeout=5) as r:
+ assert r.status == 204
+ finally:
+ srv.shutdown()
+
+
+def test_guard_is_installed() -> None:
+ for fn in (socket.socket.connect, socket.socket.connect_ex, socket.getaddrinfo,
+ socket.create_connection):
+ assert "forbid_external_network" in fn.__qualname__, fn
diff --git a/sibyl-memory-cli/tests/test_orchestrator.py b/sibyl-memory-cli/tests/test_orchestrator.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc8fc30a14ccd782122c72c5ada4aa64a5b92303
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_orchestrator.py
@@ -0,0 +1,111 @@
+"""End-to-end tests for the assembled `run_guided_setup` flow (the orchestrator).
+Wirers are injected at fake paths; extraction is stubbed (the real-agent extraction is
+validated separately by the live `claude -p` trial). conftest forces no-claude-CLI so
+the Claude wirer uses the settings.json fallback at the fake path — never real config."""
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import migrate as M
+from sibyl_memory_cli.setup import ClaudeCodeWirer, CodexWirer
+from sibyl_memory_client import MemoryClient
+
+BLOAT = """# Project Atlas
+
+## Identity
+Atlas build agent. Stay in scope.
+
+## Rules
+- run tests before commit
+
+## Accumulated memory
+- user prefers tabs over spaces
+- API base is https://api.atlas.local
+- met Jordan about the Q3 roadmap
+""" + "".join(f"- accumulated note {i} about the Atlas project history\n" for i in range(20))
+# (2026-09-27 save/debloat build: the trim step now skips a file whose lean
+# version would keep over 90 % of it, so the fixture carries enough memory to
+# be worth trimming; the report's "debloat" phase is a list of per-file records.)
+
+
+def _home(tmp_path):
+ h = tmp_path / "home"
+ (h / "proj").mkdir(parents=True)
+ (h / "proj" / "CLAUDE.md").write_text(BLOAT)
+ (h / "AGENTS.md").write_text("user likes concise answers\n")
+ (h / ".codex").mkdir()
+ (h / ".codex" / "config.toml").write_text('model = "o4"\n')
+ return h
+
+
+def _fake_wirers(h):
+ return {
+ "claude-code": ClaudeCodeWirer(settings_path=h / ".claude" / "settings.json"),
+ "codex": CodexWirer(config_path=h / ".codex" / "config.toml"),
+ }
+
+
+def test_orchestrator_full_flow(tmp_path):
+ h = _home(tmp_path); proj = h / "proj"
+ db = h / ".sibyl-memory" / "memory.db"; db.parent.mkdir(parents=True)
+ original = (proj / "CLAUDE.md").read_text()
+
+ def fake_extract(backup_dir, db_path):
+ # the agent reads from the BACKUP (never the live file) and writes to Sibyl
+ assert (backup_dir / "proj" / "CLAUDE.md").read_text() == original
+ c = MemoryClient.local(str(db_path), tenant_id="qa")
+ c.set_entity("preferences", "indent", {"value": "tabs"})
+ c.set_entity("facts", "api_base", {"value": "https://api.atlas.local"})
+ c.set_entity("relationships", "jordan", {"note": "Q3 roadmap"})
+
+ io = M.GuidedIO(scripted=["y"]) # confirm debloat = yes
+ rep = M.run_guided_setup(home=h, cwd=proj, db_path=db, backup_parent=tmp_path / "bk",
+ io=io, wirers=_fake_wirers(h), extract_fn=fake_extract)
+
+ assert rep["ok"]
+ assert rep["phases"]["backup"]["ok"] and rep["phases"]["backup"]["files"] >= 3
+ assert rep["phases"]["wire"]["codex"] in ("wired", "already")
+ assert rep["phases"]["wire"]["claude-code"] in ("wired", "already")
+ assert rep["phases"]["verify"]["new_total"] == 3
+ trims = {r["file"]: r for r in rep["phases"]["debloat"]}
+ assert trims["CLAUDE.md"]["written"]
+ # live file trimmed, backup holds the full original
+ assert (proj / "CLAUDE.md").stat().st_size < trims["CLAUDE.md"]["before"]
+ bdir = Path(rep["phases"]["backup"]["dir"])
+ assert "API base" in (bdir / "proj" / "CLAUDE.md").read_text()
+ # codex config really got the block
+ assert "[mcp_servers.sibyl_memory]" in (h / ".codex" / "config.toml").read_text()
+
+
+def test_orchestrator_no_files_aborts(tmp_path):
+ h = tmp_path / "empty"; h.mkdir()
+ rep = M.run_guided_setup(home=h, cwd=h, db_path=h / "m.db",
+ backup_parent=tmp_path / "bk", io=M.GuidedIO())
+ assert rep["ok"] is False
+
+
+def test_orchestrator_backup_failure_blocks_everything(tmp_path, monkeypatch):
+ h = _home(tmp_path); proj = h / "proj"; orig = (proj / "CLAUDE.md").read_text()
+ monkeypatch.setattr(M, "run_backup",
+ lambda files, parent, now=None: M.BackupResult(backup_dir=parent / "x", ok=False, error="disk full"))
+ rep = M.run_guided_setup(home=h, cwd=proj, db_path=h / "m.db",
+ backup_parent=tmp_path / "bk", io=M.GuidedIO(["y"]))
+ assert rep["ok"] is False
+ assert "wire" not in rep["phases"] and "debloat" not in rep["phases"]
+ assert (proj / "CLAUDE.md").read_text() == orig # never touched
+
+
+def test_orchestrator_declined_debloat_keeps_file(tmp_path):
+ h = _home(tmp_path); proj = h / "proj"; orig = (proj / "CLAUDE.md").read_text()
+ db = h / ".sibyl-memory" / "memory.db"; db.parent.mkdir(parents=True)
+
+ def fx(bk, dbp):
+ MemoryClient.local(str(dbp), tenant_id="qa").set_entity("f", "a", {"v": 1})
+
+ rep = M.run_guided_setup(home=h, cwd=proj, db_path=db, backup_parent=tmp_path / "bk",
+ io=M.GuidedIO(scripted=["n"]), # decline debloat
+ wirers={"codex": CodexWirer(config_path=h / ".codex" / "config.toml")},
+ extract_fn=fx)
+ assert rep["phases"]["verify"]["new_total"] == 1
+ assert not any(r["written"] for r in rep["phases"].get("debloat", []))
+ assert (proj / "CLAUDE.md").read_text() == orig # declined -> untouched
diff --git a/sibyl-memory-cli/tests/test_panel_fixes_2026_11_14.py b/sibyl-memory-cli/tests/test_panel_fixes_2026_11_14.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8fb87447f4bdcb52a8f70d15508f4b62e304ded
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_panel_fixes_2026_11_14.py
@@ -0,0 +1,719 @@
+"""Regression tests for the 2026-11-14 review panel fixes (PANEL-FINDINGS.md
+findings 1 to 8, 10, 15 and the tomli fallback). Temp HOME and an isolated
+PATH only; nothing here runs a harness binary or reaches the network."""
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import os
+import stat
+import sys
+from pathlib import Path
+
+import pytest
+import yaml
+
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import doctor as D
+from sibyl_memory_cli import setup as S
+from sibyl_memory_cli.setup import CodexWirer, DeepSeekWirer, HermesWirer
+
+from _harness_fixtures import backups_dir, isolate_path, leftovers
+
+REAL_TOML = S._tomllib
+FIX = Path(__file__).resolve().parent / "fixtures" / "deepseek"
+
+
+@pytest.fixture(autouse=True)
+def _isolated_path(monkeypatch, tmp_path):
+ fake = isolate_path(monkeypatch, tmp_path)
+ monkeypatch.setattr(S, "_verify_mcp_starts", lambda b: (True, "MCP server verified (stub)"))
+ return fake
+
+
+def _stub_plugin(self):
+ d = Path(self.hermes_home) / "plugins" / "sibyl"
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "__init__.py").write_text("# stub\n")
+
+
+@pytest.fixture(params=["parser", "no-parser"])
+def toml_mode(request, monkeypatch):
+ if request.param == "parser":
+ if REAL_TOML is None:
+ pytest.skip("no TOML parser in this environment")
+ else:
+ monkeypatch.setattr(S, "_tomllib", None)
+ return request.param
+
+
+def _toml(text: str):
+ if REAL_TOML is None:
+ pytest.skip("no TOML parser to check the result")
+ return REAL_TOML.loads(text)
+
+
+# =========================================================================
+# tomli fallback
+# =========================================================================
+
+def test_toml_parser_available_on_every_supported_python():
+ assert S._tomllib is not None
+ want = "tomllib" if sys.version_info >= (3, 11) else "tomli"
+ assert S._tomllib.__name__ == want
+
+
+def test_pyproject_declares_tomli_below_311():
+ text = (Path(__file__).resolve().parents[1] / "pyproject.toml").read_text()
+ assert "'tomli>=2; python_version < \"3.11\"'" in text
+
+
+# =========================================================================
+# 1. Hermes config.yaml is edited as text
+# =========================================================================
+
+HERMES_CFG = """\
+# Hermes config (hand-written)
+model: &m gpt-x # the default model
+fallback: *m
+prompt: "caf\u00e9 au lait"
+memory:
+ # which memory provider to use
+ provider: honcho
+ options: {a: 1}
+tools:
+ - web
+"""
+
+
+def _hermes(tmp_path, monkeypatch, text, *, plugin=True):
+ h = tmp_path / "hermes-home"
+ h.mkdir(exist_ok=True)
+ cfg = h / "config.yaml"
+ if text is not None:
+ cfg.write_bytes(text.encode("utf-8"))
+ if plugin:
+ monkeypatch.setattr(HermesWirer, "_install_plugin", _stub_plugin)
+ return HermesWirer(hermes_home=h), cfg
+
+
+def test_hermes_edit_keeps_comments_anchors_and_unicode(tmp_path, monkeypatch):
+ w, cfg = _hermes(tmp_path, monkeypatch, HERMES_CFG)
+ out = w.wire(force=True)
+ assert out.status == "wired", out.message
+ new = cfg.read_text(encoding="utf-8")
+ assert new == HERMES_CFG.replace("provider: honcho", "provider: sibyl")
+ want = yaml.safe_load(HERMES_CFG)
+ want["memory"]["provider"] = "sibyl"
+ assert yaml.safe_load(new) == want
+
+
+@pytest.mark.parametrize("text,expected", [
+ ("model: x\n", "model: x\nmemory:\n provider: sibyl\n"),
+ ("model: x", "model: x\nmemory:\n provider: sibyl\n"),
+ ("# only a comment\n", "# only a comment\nmemory:\n provider: sibyl\n"),
+ ("", "memory:\n provider: sibyl\n"),
+ ("memory:\n # c\n other: 1\nz: 2\n", "memory:\n # c\n provider: sibyl\n other: 1\nz: 2\n"),
+ ("memory: # c\nz: 2\n", "memory: {provider: sibyl} # c\nz: 2\n"),
+ ("memory: {}\n", "memory: {provider: sibyl}\n"),
+ ("a: 1\r\nmemory:\r\n provider: 'x'\r\n", "a: 1\r\nmemory:\r\n provider: sibyl\r\n"),
+ ("a: 1\r\n", "a: 1\r\nmemory:\r\n provider: sibyl\r\n"),
+])
+def test_hermes_text_edit_cases(text, expected):
+ assert S._hermes_provider_text(text) == expected
+
+
+def test_hermes_scalar_memory_value_goes_through_the_overwrite_gate(tmp_path, monkeypatch):
+ for scalar in ("honcho", "true"):
+ text = f"model: x\nmemory: {scalar}\n"
+ w, cfg = _hermes(tmp_path, monkeypatch, text)
+ out = w.wire()
+ assert out.status == "skipped" and out.overwrite_of, out.message
+ assert cfg.read_text() == text
+ out = w.wire(force=True)
+ assert out.status == "wired"
+ assert cfg.read_text() == "model: x\nmemory: {provider: sibyl}\n"
+
+
+def test_hermes_unprovable_edit_gives_manual_lines_and_leaves_the_file(tmp_path, monkeypatch):
+ text = "memory: {provider: honcho, x: 1} # flow form\nmodel: x\n"
+ w, cfg = _hermes(tmp_path, monkeypatch, text)
+ out = w.wire(force=True)
+ assert out.status == "error"
+ assert out.manual_block == "memory:\n provider: sibyl"
+ assert yaml.safe_load(out.manual_block) == {"memory": {"provider": "sibyl"}}
+ assert out.message.endswith(out.manual_block) and out.handoff[0] == "done"
+ assert cfg.read_text() == text
+
+
+def test_hermes_proof_failure_never_falls_back_to_safe_dump(tmp_path, monkeypatch):
+ w, cfg = _hermes(tmp_path, monkeypatch, HERMES_CFG)
+ real = yaml.safe_load
+ calls = {"n": 0}
+
+ def lying_load(t):
+ calls["n"] += 1
+ got = real(t)
+ if isinstance(got, dict) and isinstance(got.get("memory"), dict) \
+ and got["memory"].get("provider") == "sibyl":
+ got["extra"] = 1 # the proof sees a change it did not ask for
+ return got
+
+ monkeypatch.setattr(yaml, "safe_load", lying_load)
+ monkeypatch.setattr(yaml, "safe_dump", lambda *a, **k: pytest.fail("safe_dump called"))
+ out = w.wire(force=True)
+ assert out.status == "error" and out.manual_block
+ assert cfg.read_bytes() == HERMES_CFG.encode("utf-8")
+
+
+def test_hermes_symlinked_config_is_written_through(tmp_path, monkeypatch):
+ dot = tmp_path / "dotfiles"
+ dot.mkdir()
+ real = dot / "config.yaml"
+ real.write_text("model: x\n")
+ w, cfg = _hermes(tmp_path, monkeypatch, None)
+ cfg.symlink_to(real)
+ assert w.wire().status == "wired"
+ assert cfg.is_symlink() and os.readlink(cfg) == str(real)
+ assert real.read_text() == "model: x\nmemory:\n provider: sibyl\n"
+ assert leftovers(dot) == [] and leftovers(cfg.parent) == []
+
+
+# =========================================================================
+# 2. Codex headers are found structurally
+# =========================================================================
+
+OURS_PATH = None # resolved per test (the isolated fake binary)
+
+FOREIGN_THEN_PROJECTS = """\
+model = "o4"
+
+[mcp_servers.sibyl_memory]
+command = "npx"
+args = ["-y", "other-server"]
+
+[projects."/home/u/repo"]
+trust_level = "trusted"
+
+[projects.'C:\\x\\y']
+trust_level = "trusted"
+
+[mcp_servers."a@b"]
+command = "a-b-mcp"
+"""
+
+
+def test_codex_force_replace_keeps_quoted_project_tables(tmp_path, toml_mode):
+ p = tmp_path / "config.toml"
+ p.write_text(FOREIGN_THEN_PROJECTS)
+ w = CodexWirer(config_path=p)
+ out = w.wire(force=True)
+ assert out.status == "wired", out.message
+ new = p.read_text()
+ for kept in ('[projects."/home/u/repo"]', "[projects.'C:\\x\\y']", '[mcp_servers."a@b"]',
+ 'command = "a-b-mcp"', 'model = "o4"'):
+ assert kept in new, kept
+ doc = _toml(new)
+ assert doc["mcp_servers"]["sibyl_memory"] == {"command": S.mcp_command_path()}
+ assert doc["projects"]["/home/u/repo"] == {"trust_level": "trusted"}
+ assert doc["mcp_servers"]["a@b"] == {"command": "a-b-mcp"}
+
+
+def test_codex_commandless_table_never_takes_the_next_servers_command(tmp_path, toml_mode):
+ text = ('[mcp_servers.sibyl_memory]\nargs = []\n\n'
+ '[mcp_servers."ctx@upstash"]\ncommand = "npx"\nargs = ["-y", "ctx"]\n')
+ p = tmp_path / "config.toml"
+ p.write_text(text)
+ out = CodexWirer(config_path=p).wire()
+ assert out.status == "wired", out.message
+ doc = _toml(p.read_text())
+ assert doc["mcp_servers"]["ctx@upstash"]["command"] == "npx"
+ assert doc["mcp_servers"]["sibyl_memory"]["command"] == S.mcp_command_path()
+
+
+def test_codex_header_inside_a_multiline_string_is_not_ours(tmp_path, toml_mode):
+ text = 'notes = """\n[mcp_servers.sibyl_memory]\ncommand = "/old/sibyl-memory-mcp"\n"""\n'
+ p = tmp_path / "config.toml"
+ p.write_text(text)
+ assert S._codex_scan(text)["headers"] == []
+ w = CodexWirer(config_path=p)
+ for force in (False, True):
+ w.wire(force=force)
+ assert p.read_text() == text
+ assert w.doctor_probe()[0]["entry"] != "present"
+
+
+def test_codex_table_replace_proof_checks_kept_lines_without_a_parser(tmp_path, monkeypatch):
+ monkeypatch.setattr(S, "_tomllib", None)
+ w = CodexWirer(config_path=tmp_path / "config.toml")
+ old = FOREIGN_THEN_PROJECTS
+ good = w._replace_table(old)
+ w._verify_table_replace(old, good)
+ damaged = good.replace('[projects."/home/u/repo"]\ntrust_level = "trusted"\n', "")
+ with pytest.raises(ValueError):
+ w._verify_table_replace(old, damaged)
+
+
+# =========================================================================
+# 3. Codex append path is proven
+# =========================================================================
+
+def test_codex_append_refuses_inline_mcp_servers(tmp_path, toml_mode):
+ text = 'mcp_servers = { github = { command = "gh-mcp" } }\n'
+ p = tmp_path / "config.toml"
+ p.write_text(text)
+ out = CodexWirer(config_path=p).wire()
+ assert out.status == "error" and out.handoff[0] == "done"
+ assert p.read_text() == text and backups_dir("codex").exists() is False
+ entry = "{ " + out.manual_block.split("{", 1)[1]
+ assert out.manual_block.startswith("sibyl_memory = {")
+ assert _toml("x = " + entry)["x"] == {"command": S.mcp_command_path()}
+
+
+def test_codex_append_refuses_a_file_ending_in_an_open_string(tmp_path, toml_mode):
+ text = 'model = "o4"\nnote = """\nnever closed\n'
+ p = tmp_path / "config.toml"
+ p.write_text(text)
+ out = CodexWirer(config_path=p).wire()
+ assert out.status == "error"
+ assert p.read_text() == text
+
+
+def test_codex_append_keeps_crlf(tmp_path, toml_mode):
+ text = 'model = "o4"\r\n[other]\r\nx = 1\r\n'
+ p = tmp_path / "config.toml"
+ p.write_bytes(text.encode())
+ out = CodexWirer(config_path=p).wire()
+ assert out.status == "wired", out.message
+ data = p.read_bytes().decode()
+ assert "\n" not in data.replace("\r\n", "")
+ assert data.startswith(text)
+ _toml(data)
+
+
+def test_codex_doctor_does_not_pass_a_file_codex_cannot_parse(tmp_path, toml_mode):
+ # What an earlier setup appended to an inline mcp_servers table.
+ text = ('mcp_servers = { github = { command = "gh-mcp" } }\n\n'
+ f'[mcp_servers.sibyl_memory]\ncommand = "{S.mcp_command_path()}"\n')
+ p = tmp_path / "config.toml"
+ p.write_text(text)
+ w = CodexWirer(config_path=p)
+ assert w.doctor_probe()[0]["entry"] == "unreadable"
+ assert w.current_state()["wired_with_sibyl"] is False
+ w.wire(force=True)
+ assert p.read_text() == text
+
+
+def test_codex_setup_refuses_a_file_the_parser_rejects(tmp_path):
+ if REAL_TOML is None:
+ pytest.skip("needs a TOML parser")
+ text = 'model = \n'
+ p = tmp_path / "config.toml"
+ p.write_text(text)
+ out = CodexWirer(config_path=p).wire()
+ assert out.status == "error" and "not valid TOML" in out.message
+ assert p.read_text() == text
+
+
+# =========================================================================
+# 4. Hermes installer refusal is honored (unstubbed installer)
+# =========================================================================
+
+def test_hermes_installer_refusal_stops_setup_before_the_config(tmp_path, monkeypatch):
+ h = tmp_path / "hermes-home"
+ (h / "plugins" / "sibyl" / "__pycache__").mkdir(parents=True)
+ cfg = h / "config.yaml"
+ text = "memory:\n provider: honcho\n"
+ cfg.write_text(text)
+ w = HermesWirer(hermes_home=h)
+ with contextlib.redirect_stdout(io.StringIO()):
+ out = w.wire(force=True)
+ assert out.status == "error" and "refused (code 2)" in out.message
+ assert out.handoff[0] == "done" and "install-plugin --force" in out.handoff[1]
+ assert cfg.read_text() == text
+ assert not (h / "plugins" / "sibyl" / "__init__.py").exists()
+
+
+def test_hermes_doctor_repair_reports_the_refusal(tmp_path):
+ h = tmp_path / "hermes-home"
+ (h / "plugins" / "sibyl" / "__pycache__").mkdir(parents=True)
+ (h / "config.yaml").write_text("memory:\n provider: sibyl\n")
+ w = HermesWirer(hermes_home=h)
+ probe = w.doctor_probe()[0]
+ assert probe.get("broken")
+ with contextlib.redirect_stdout(io.StringIO()):
+ out = w.repair_mcp(probe)
+ assert out.status == "error" and "Installed" not in out.message
+
+
+# =========================================================================
+# 5. _write_via_tmp
+# =========================================================================
+
+def test_write_via_tmp_mode_is_set_before_content_and_data_is_synced(tmp_path, monkeypatch):
+ target = tmp_path / "config.toml"
+ target.write_text("old\n")
+ target.chmod(0o600)
+ old_umask = os.umask(0o022)
+ seen = []
+ real_fchmod, real_chmod, real_fsync, real_replace = os.fchmod, os.chmod, os.fsync, os.replace
+
+ def fchmod(fd, mode):
+ seen.append(("fchmod", os.fstat(fd).st_size, mode))
+ return real_fchmod(fd, mode)
+
+ def chmod(path, mode, *a, **k):
+ seen.append(("chmod", os.stat(path).st_size, mode))
+ return real_chmod(path, mode, *a, **k)
+
+ def fsync(fd):
+ seen.append(("fsync",))
+ return real_fsync(fd)
+
+ def replace(src, dst):
+ st = os.stat(src)
+ seen.append(("replace", st.st_size, stat.S_IMODE(st.st_mode)))
+ return real_replace(src, dst)
+
+ monkeypatch.setattr(S.os, "fchmod", fchmod)
+ monkeypatch.setattr(S.os, "chmod", chmod)
+ monkeypatch.setattr(S.os, "fsync", fsync)
+ monkeypatch.setattr(S.os, "replace", replace)
+ try:
+ S._write_via_tmp(target, target.with_suffix(".toml.tmp"), "secret = 1\n")
+ finally:
+ os.umask(old_umask)
+ modes = [e for e in seen if e[0] in ("fchmod", "chmod")]
+ assert modes and all(size == 0 for _k, size, _m in modes), seen
+ rep = [e for e in seen if e[0] == "replace"][0]
+ assert rep[1] > 0 and rep[2] == 0o600
+ assert sum(1 for e in seen if e[0] == "fsync") >= 2 # the file and the directory
+ assert target.read_text() == "secret = 1\n" and stat.S_IMODE(target.stat().st_mode) == 0o600
+
+
+def test_write_via_tmp_never_follows_a_preplaced_fixed_name(tmp_path):
+ victim = tmp_path / "victim.txt"
+ victim.write_text("keep me\n")
+ target = tmp_path / "mcp.json"
+ target.write_text("{}\n")
+ (tmp_path / "mcp.json.tmp").symlink_to(victim)
+ S._write_via_tmp(target, target.with_suffix(".json.tmp"), '{"a": 1}\n')
+ assert victim.read_text() == "keep me\n"
+ assert target.read_text() == '{"a": 1}\n'
+ assert (tmp_path / "mcp.json.tmp").is_symlink() # another file is never removed
+
+
+def test_write_via_tmp_failure_removes_only_its_own_temp(tmp_path, monkeypatch):
+ tmp_path = tmp_path / "harness"
+ tmp_path.mkdir()
+ target = tmp_path / "config.yaml"
+ target.write_text("a: 1\n")
+ other = tmp_path / "config.yaml.tmp"
+ other.write_text("another run\n")
+
+ def boom(src, dst):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(S.os, "replace", boom)
+ with pytest.raises(OSError):
+ S._write_via_tmp(target, target.with_suffix(".yaml.tmp"), "a: 2\n")
+ assert sorted(p.name for p in tmp_path.iterdir()) == ["config.yaml", "config.yaml.tmp"]
+ assert other.read_text() == "another run\n" and target.read_text() == "a: 1\n"
+
+
+def test_write_via_tmp_new_file_follows_umask(tmp_path):
+ old = os.umask(0o077)
+ try:
+ S._write_via_tmp(tmp_path / "new.json", tmp_path / "new.json.tmp", "{}\n")
+ finally:
+ os.umask(old)
+ assert stat.S_IMODE((tmp_path / "new.json").stat().st_mode) == 0o600
+
+
+# =========================================================================
+# 6. CLI bearer host gate
+# =========================================================================
+
+class _Resp:
+ def __init__(self, body: bytes = b'{"ok": true}'):
+ self._b = body
+
+ def read(self):
+ return self._b
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+
+@pytest.fixture
+def urlopen_spy(monkeypatch):
+ calls = []
+
+ def fake(req, timeout=None, context=None):
+ calls.append(req.full_url)
+ return _Resp()
+
+ monkeypatch.setattr(cli.urllib.request, "urlopen", fake)
+ return calls
+
+
+@pytest.mark.parametrize("base", ["http://evil.example", "https://evil.example",
+ "http://api.sibyllabs.org", "ftp://127.0.0.1"])
+def test_bearer_is_not_sent_to_an_untrusted_base(monkeypatch, urlopen_spy, capsys, base):
+ monkeypatch.setattr(cli, "API_BASE", base)
+ for kw in ({"headers": {"Authorization": "Bearer t0k"}},
+ {"headers": {"X-Sibyl-Entitlement": "e"}},
+ {"body": {"account_id": "a", "session_token": "t0k"}}):
+ with pytest.raises(cli.HttpError) as ei:
+ cli.http_request("POST", "/api/plugin/access", **kw)
+ assert ei.value.code == cli.UNTRUSTED_BASE_CODE
+ assert urlopen_spy == []
+ err = capsys.readouterr().err
+ assert "SIBYL_API_BASE" in err and "t0k" not in err
+
+
+@pytest.mark.parametrize("base", ["https://api.sibyllabs.org", "http://127.0.0.1:8787",
+ "http://localhost:9"])
+def test_bearer_goes_to_the_api_or_loopback(monkeypatch, urlopen_spy, base):
+ monkeypatch.setattr(cli, "API_BASE", base)
+ assert cli.http_request("POST", "/x", headers={"Authorization": "Bearer t"}) == {"ok": True}
+ assert urlopen_spy == [f"{base}/x"]
+
+
+def test_unauthenticated_call_is_not_gated(monkeypatch, urlopen_spy):
+ monkeypatch.setattr(cli, "API_BASE", "http://staging.example")
+ cli.http_request("POST", "/api/plugin/session-init", body={"device": "x"})
+ assert urlopen_spy == ["http://staging.example/api/plugin/session-init"]
+
+
+def test_legacy_upgrade_link_never_carries_the_bearer_to_another_host(monkeypatch):
+ monkeypatch.setattr(cli, "UPGRADE_BASE", "http://evil.example/up")
+ assert cli._legacy_upgrade_url("t0k") is None
+ monkeypatch.setattr(cli, "UPGRADE_BASE", "https://sibyllabs.org/plugin/upgrade")
+ assert cli._legacy_upgrade_url("t0k") == "https://sibyllabs.org/plugin/upgrade?session=t0k"
+
+
+# =========================================================================
+# 7. Quoted "command" key
+# =========================================================================
+
+@pytest.mark.parametrize("key", ['"command"', "'command'"])
+def test_codex_quoted_command_key_is_updated_in_place(tmp_path, toml_mode, key):
+ text = f'[mcp_servers.sibyl_memory]\n{key} = "/old/venv/bin/sibyl-memory-mcp"\n'
+ p = tmp_path / "config.toml"
+ p.write_text(text)
+ w = CodexWirer(config_path=p)
+ probe = w.doctor_probe()[0]
+ assert probe["entry"] == "present" and probe["command"] == "/old/venv/bin/sibyl-memory-mcp"
+ out = w.repair_mcp(probe)
+ assert out.status == "wired", out.message
+ new = p.read_text()
+ assert new == f'[mcp_servers.sibyl_memory]\n{key} = "{S.mcp_command_path()}"\n'
+ assert _toml(new)["mcp_servers"]["sibyl_memory"] == {"command": S.mcp_command_path()}
+
+
+def test_codex_missing_command_is_not_fixable_without_a_parser(tmp_path, monkeypatch):
+ p = tmp_path / "config.toml"
+ p.write_text("[mcp_servers.sibyl_memory]\nargs = []\n")
+ w = CodexWirer(config_path=p)
+ if REAL_TOML is not None:
+ assert w.doctor_probe()[0]["fixable"] is True
+ monkeypatch.setattr(S, "_tomllib", None)
+ assert w.doctor_probe()[0]["fixable"] is False
+
+
+# =========================================================================
+# 8. DeepSeek Harness manual fallback
+# =========================================================================
+
+def _dsh_home(tmp_path):
+ home = Path.home() / ".dsh"
+ home.mkdir(parents=True, exist_ok=True)
+ return home
+
+
+def _parse_printed_block(block: str):
+ """Every printed block is YAML. A plain block parses with yaml.safe_load;
+ one that holds DeepSeek Harness's own !!js tag (which safe_load does not
+ construct) must compose with the stock SafeLoader and load with the
+ SafeLoader subclass that only adds that tag."""
+ yaml.compose(block, Loader=yaml.SafeLoader)
+ if "!!js" in block:
+ return S._dsh_yaml_load(block)
+ return yaml.safe_load(block)
+
+
+def test_deepseek_command_fallback_names_the_existing_row(tmp_path, monkeypatch):
+ home = _dsh_home(tmp_path)
+ hp = home / "cordis.patch.yml"
+ old = (FIX / "ours_stale.yml").read_bytes()
+ hp.write_bytes(old)
+ monkeypatch.setattr(DeepSeekWirer, "_plan_text", lambda self, scan, ch: None)
+ w = DeepSeekWirer()
+ out = w.wire()
+ assert out.status == "error"
+ assert "Change the command of the existing sibyl-memory row" in out.message
+ assert "- insert:" not in out.message and "Add this block" not in out.message
+ assert _parse_printed_block(out.manual_block) == {"command": S.mcp_command_path()}
+ assert "do not add a second row" in out.handoff[1]
+ assert hp.read_bytes() == old
+
+
+def test_deepseek_doctor_keeps_the_block_lines(tmp_path, monkeypatch, capsys):
+ home = _dsh_home(tmp_path)
+ hp = home / "cordis.patch.yml"
+ hp.write_bytes((FIX / "ours_stale.yml").read_bytes())
+ monkeypatch.setattr(DeepSeekWirer, "_plan_text", lambda self, scan, ch: None)
+ w = DeepSeekWirer()
+ probe = w.doctor_probe()[0]
+ check = D.check_harness(w, probe, verified={})
+ new, out = D.repair_check(w, probe, check, verified={})
+ assert new.fix_block == out.manual_block and "\n" not in new.fix_message
+ line = D._check_line(new)
+ assert line.endswith("\n" + out.manual_block)
+ assert _parse_printed_block(line.split("\n", 1)[1]) == {"command": S.mcp_command_path()}
+ data = json.loads(json.dumps(D.asdict(new)))
+ assert _parse_printed_block(data["fix_block"]) == {"command": S.mcp_command_path()}
+
+
+@pytest.mark.parametrize("mode", ["add", "command", "replace"])
+def test_every_deepseek_manual_block_is_valid_yaml(tmp_path, mode):
+ w = DeepSeekWirer(dsh_home=_dsh_home(tmp_path))
+ out = w._manual_block_error(Path("/p/cordis.patch.yml"), "lead.", mode=mode,
+ env={"SIBYL_MEMORY_MCP_OUTPUT_TOKENS": "4000"})
+ got = _parse_printed_block(out.manual_block)
+ cmd = S.mcp_command_path()
+ if mode == "command":
+ assert got == {"command": cmd}
+ elif mode == "replace":
+ assert got == [w._expected_row(cmd, {"SIBYL_MEMORY_MCP_OUTPUT_TOKENS": "4000"})]
+ else:
+ assert got == [{"insert": [w._expected_row(cmd, {"SIBYL_MEMORY_MCP_OUTPUT_TOKENS": "4000"})]}]
+ assert out.message.endswith("\n" + out.manual_block)
+
+
+def test_codex_and_hermes_manual_blocks_parse(tmp_path):
+ p = tmp_path / "config.toml"
+ p.write_text("model = 1\n")
+ out = CodexWirer(config_path=p)._manual_table_error("reason.")
+ assert _toml(out.manual_block)["mcp_servers"]["sibyl_memory"] == {"command": S.mcp_command_path()}
+ assert yaml.safe_load("\n".join(S.HERMES_MANUAL_LINES)) == {"memory": {"provider": "sibyl"}}
+
+
+# =========================================================================
+# 10. Claude Code without the claude CLI is not reported as wired
+# =========================================================================
+
+def test_claude_without_cli_is_not_wired_and_hands_over_the_command(tmp_path, monkeypatch, capsys):
+ settings = tmp_path / ".claude" / "settings.json"
+ settings.parent.mkdir()
+ settings.write_text("{}\n")
+ ns = cli.build_parser().parse_args(["setup", "claude-code", "--yes",
+ "--claude-settings", str(settings)])
+ rc = S.cmd_setup(ns)
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert "MCP server is ready" not in out
+ assert "next: claude mcp add --scope user sibyl-memory -- " in out
+ assert "mcpServers" not in json.loads(settings.read_text())
+
+
+# =========================================================================
+# 15. Codex "already wired" needs a command of ours
+# =========================================================================
+
+def test_codex_commandless_table_is_not_already_wired(tmp_path, toml_mode):
+ p = tmp_path / "config.toml"
+ p.write_text("[mcp_servers.sibyl_memory]\nargs = []\n")
+ w = CodexWirer(config_path=p)
+ assert w.current_state()["wired_with_sibyl"] is False
+ out = w.wire()
+ assert out.status == "wired", out.message
+ assert p.read_text() == (f'[mcp_servers.sibyl_memory]\ncommand = "{S.mcp_command_path()}"\n'
+ "args = []\n")
+
+
+def test_codex_foreign_table_is_not_wired_for_other_callers(tmp_path):
+ p = tmp_path / "config.toml"
+ p.write_text('[mcp_servers.sibyl_memory]\ncommand = "npx"\n')
+ assert CodexWirer(config_path=p).current_state()["wired_with_sibyl"] is False
+
+
+# =========================================================================
+# 32. Verification layers that no test fed a failing plan before
+# =========================================================================
+
+def _dsh_patch(fixture: str) -> tuple:
+ home = Path.home() / ".dsh"
+ home.mkdir(parents=True, exist_ok=True)
+ hp = home / "cordis.patch.yml"
+ data = (FIX / fixture).read_bytes()
+ hp.write_bytes(data)
+ return hp, data
+
+
+_REAL_ROW_LINES = DeepSeekWirer._row_lines
+
+
+def _row_with(self_, command, env, **override):
+ rows = _REAL_ROW_LINES(self_, command, env)
+ for i, r in enumerate(rows):
+ for k, v in override.items():
+ if r.lstrip().startswith(k + ":"):
+ rows[i] = r[: len(r) - len(r.lstrip())] + f"{k}: {v}"
+ return rows
+
+
+def test_deepseek_case_d_verification_rejects_a_row_that_parses_differently(monkeypatch):
+ # The row stays a candidate of ours with the right command and a !!js cwd,
+ # so only the "got == old + [insert]" proof can catch the extra arg.
+ hp, old = _dsh_patch("user_patches.yml")
+ monkeypatch.setattr(DeepSeekWirer, "_row_lines",
+ lambda self, c, e: _row_with(self, c, e, args="[--evil]"))
+ out = DeepSeekWirer().wire()
+ assert out.status == "error" and out.manual_block
+ assert hp.read_bytes() == old
+
+
+def test_deepseek_cwd_must_stay_a_js_expression(monkeypatch):
+ # A plain string "process.cwd()" equals the _JsExpr in ==, so only the
+ # type check on cwd catches it.
+ hp, old = _dsh_patch("user_patches.yml")
+ monkeypatch.setattr(DeepSeekWirer, "_row_lines",
+ lambda self, c, e: _row_with(self, c, e, cwd="'process.cwd()'"))
+ out = DeepSeekWirer().wire()
+ assert out.status == "error" and out.manual_block
+ assert hp.read_bytes() == old
+
+
+def test_deepseek_rescan_candidate_count_is_checked(monkeypatch):
+ hp, old = _dsh_patch("ours_stale.yml")
+ real = DeepSeekWirer._scan_text
+ new_cmd = S.mcp_command_path()
+
+ def scan(self, text):
+ out = real(self, text)
+ if new_cmd in text and out.get("candidates"):
+ extra = dict(out["candidates"][0])
+ extra["path"] = ["phantom"]
+ out["candidates"] = out["candidates"] + [extra]
+ return out
+
+ monkeypatch.setattr(DeepSeekWirer, "_scan_text", scan)
+ out = DeepSeekWirer().wire()
+ assert out.status == "error" and "Change the command of the existing" in out.message
+ assert hp.read_bytes() == old
+
+
+def test_atomic_text_refuses_a_symlinked_target(tmp_path):
+ real = tmp_path / "real.md"
+ real.write_text("mine\n")
+ link = tmp_path / "AGENTS.md"
+ link.symlink_to(real)
+ with pytest.raises(ValueError):
+ S._atomic_text(link, "replaced\n")
+ assert link.is_symlink() and real.read_text() == "mine\n"
diff --git a/sibyl-memory-cli/tests/test_path_fallback_2026_11_01.py b/sibyl-memory-cli/tests/test_path_fallback_2026_11_01.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a7457f8c8d016599f9d62d2fe72faecf854c4d9
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_path_fallback_2026_11_01.py
@@ -0,0 +1,126 @@
+"""cli 0.6.1: setup and doctor find sibyl-memory-mcp when ~/.local/bin is not on PATH.
+
+Field report 2026-11-01: on a fresh Grok Bot machine, `sibyl setup grokbot` failed
+with "'sibyl-memory-mcp' not on PATH. Install it" although the installer had just
+put the server in ~/.local/bin. The Bot fixed it by hand. These tests pin the fix:
+the wirers resolve the binary from PATH, then beside the interpreter, then from
+~/.local/bin, and write the absolute path into the client config.
+"""
+from __future__ import annotations
+
+import json
+import os
+import stat
+from pathlib import Path
+
+import pytest
+
+import sibyl_memory_cli.setup as S
+from sibyl_memory_cli import doctor as D
+
+
+@pytest.fixture()
+def fresh_home(tmp_path, monkeypatch):
+ """A HOME whose ~/.local/bin holds the server, with a PATH that does not."""
+ home = tmp_path / "home"
+ bindir = home / ".local" / "bin"
+ bindir.mkdir(parents=True)
+ exe = bindir / "sibyl-memory-mcp"
+ exe.write_text("#!/bin/sh\nexit 0\n")
+ exe.chmod(exe.stat().st_mode | stat.S_IXUSR)
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("PATH", str(tmp_path / "empty"))
+ # the interpreter's own bin dir must not answer for it in these tests
+ monkeypatch.setattr(S.sys, "executable", str(tmp_path / "py" / "bin" / "python"))
+ return home, exe
+
+
+def _no_install(monkeypatch):
+ calls = []
+ monkeypatch.setattr(S, "_install_pkg_or_instruct",
+ lambda pkg: calls.append(pkg) or "should not be called")
+ return calls
+
+
+def test_resolve_finds_user_bin_off_path(fresh_home):
+ _home, exe = fresh_home
+ assert S.resolve_mcp_binary() == str(exe)
+ assert S.mcp_command_path() == str(exe)
+
+
+def test_resolve_prefers_path(fresh_home, tmp_path, monkeypatch):
+ on_path = tmp_path / "onpath"
+ on_path.mkdir()
+ exe2 = on_path / "sibyl-memory-mcp"
+ exe2.write_text("#!/bin/sh\nexit 0\n")
+ exe2.chmod(0o755)
+ monkeypatch.setenv("PATH", str(on_path))
+ assert S.resolve_mcp_binary() == str(exe2)
+
+
+def test_resolve_none_when_not_installed(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path / "h"))
+ monkeypatch.setenv("PATH", str(tmp_path / "empty"))
+ monkeypatch.setattr(S.sys, "executable", str(tmp_path / "py" / "bin" / "python"))
+ assert S.resolve_mcp_binary() is None
+
+
+def test_non_executable_file_is_ignored(fresh_home):
+ _home, exe = fresh_home
+ exe.chmod(0o644)
+ assert S.resolve_mcp_binary() is None
+
+
+@pytest.mark.parametrize("cls", [S.CursorWirer, S.GrokBotWirer])
+def test_cursor_and_grokbot_wire_without_path(fresh_home, monkeypatch, cls):
+ home, exe = fresh_home
+ calls = _no_install(monkeypatch)
+ cfg = home / ".cursor" / "mcp.json"
+ out = cls(config_path=cfg).wire()
+ assert out.status == "wired", out.message
+ assert calls == [] # no reinstall attempt
+ data = json.loads(cfg.read_text())
+ assert data["mcpServers"]["sibyl-memory"]["command"] == str(exe)
+
+
+def test_cursor_rerun_reports_already(fresh_home, monkeypatch):
+ home, _exe = fresh_home
+ _no_install(monkeypatch)
+ cfg = home / ".cursor" / "mcp.json"
+ assert S.CursorWirer(config_path=cfg).wire().status == "wired"
+ assert S.CursorWirer(config_path=cfg).wire().status == "already"
+
+
+def test_cursor_truly_missing_says_not_installed(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path / "h"))
+ monkeypatch.setenv("PATH", str(tmp_path / "empty"))
+ monkeypatch.setattr(S.sys, "executable", str(tmp_path / "py" / "bin" / "python"))
+ monkeypatch.setattr(S, "_install_pkg_or_instruct", lambda pkg: None)
+ out = S.CursorWirer(config_path=tmp_path / "h" / ".cursor" / "mcp.json").wire()
+ assert out.status == "error"
+ assert "is not installed" in out.message
+ assert ".local" in out.message # names where it looked
+ assert "not on PATH" not in out.message
+
+
+def test_cursor_verify_uses_fallback(fresh_home, monkeypatch):
+ _home, exe = fresh_home
+ seen = []
+ monkeypatch.setattr(S, "_verify_mcp_starts", lambda b: seen.append(b) or (True, "ok"))
+ assert S.CursorWirer().verify_mcp_starts() == (True, "ok")
+ assert seen == [str(exe)]
+
+
+def test_codex_command_uses_fallback(fresh_home):
+ _home, exe = fresh_home
+ assert S.CodexWirer()._mcp_command() == str(exe)
+ assert S.CodexWirer()._mcp_binary_found()
+
+
+def test_claude_binary_found_uses_fallback(fresh_home):
+ assert S.ClaudeCodeWirer()._mcp_binary_found()
+
+
+def test_doctor_finds_server_off_path(fresh_home):
+ _home, exe = fresh_home
+ assert D._server_cmd() == [str(exe)]
diff --git a/sibyl-memory-cli/tests/test_platform_gate_2026_09_04.py b/sibyl-memory-cli/tests/test_platform_gate_2026_09_04.py
new file mode 100644
index 0000000000000000000000000000000000000000..b64fb0a4807bda8a429456a33e687546f66201bc
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_platform_gate_2026_09_04.py
@@ -0,0 +1,188 @@
+"""Platform support gate (2026-09-04 operator ruling).
+
+Sibyl Memory runs on Linux, macOS (Apple Silicon and Intel), and Windows
+through WSL2. Native Windows is not supported: `sibyl init` and `sibyl setup`
+refuse it, every other command keeps working so existing native-Windows
+accounts never lose `status`, `upgrade`, `claim`, `devices` or `logout`.
+
+Six cases, and for each of them a pin on `_detect_os_family()`, whose return
+vocabulary telemetry consumers key on and which this change must not move.
+"""
+from __future__ import annotations
+
+import platform as _platform
+
+import pytest
+
+from sibyl_memory_cli import cli
+
+
+def _fake(monkeypatch, *, sys_platform, release="", machine="", mac_ver="", env=None):
+ monkeypatch.setattr(cli.sys, "platform", sys_platform, raising=False)
+ monkeypatch.setattr(_platform, "release", lambda: release)
+ monkeypatch.setattr(_platform, "machine", lambda: machine)
+ monkeypatch.setattr(_platform, "mac_ver", lambda: (mac_ver, ("", "", ""), ""))
+ monkeypatch.delenv("WSL_DISTRO_NAME", raising=False)
+ monkeypatch.delenv(cli.NATIVE_WINDOWS_ESCAPE_ENV, raising=False)
+ for k, v in (env or {}).items():
+ monkeypatch.setenv(k, v)
+
+
+# ---------------------------------------------------------------- supported
+
+def test_linux(monkeypatch, capsys):
+ _fake(monkeypatch, sys_platform="linux", release="6.8.0-40-generic", machine="x86_64")
+ assert cli._platform_info() == ("linux", "Linux (x86_64)", True)
+ assert cli._detect_os_family() == "linux"
+ assert cli._is_wsl() is False
+ assert cli.print_platform_line(gate=True) == 0
+ assert "platform Linux (x86_64) · supported" in capsys.readouterr().out
+
+
+def test_wsl_detected_from_kernel_release(monkeypatch, capsys):
+ _fake(monkeypatch, sys_platform="linux",
+ release="5.15.153.1-microsoft-standard-WSL2", machine="x86_64")
+ assert cli._platform_info() == ("linux", "Linux, WSL2 (x86_64)", True)
+ assert cli._detect_os_family() == "linux"
+ assert cli._is_wsl() is True
+ assert cli.print_platform_line(gate=True) == 0
+ assert "platform Linux, WSL2 (x86_64) · supported" in capsys.readouterr().out
+
+
+def test_wsl_detected_from_env_alone(monkeypatch, capsys):
+ """A WSL kernel that does not carry 'microsoft' in its release string still
+ exports WSL_DISTRO_NAME. Either signal is enough."""
+ _fake(monkeypatch, sys_platform="linux", release="6.6.36.6", machine="aarch64",
+ env={"WSL_DISTRO_NAME": "Ubuntu"})
+ assert cli._platform_info() == ("linux", "Linux, WSL2 (aarch64)", True)
+ assert cli._detect_os_family() == "linux"
+ assert cli._is_wsl() is True
+ assert cli.print_platform_line(gate=True) == 0
+
+
+def test_macos(monkeypatch, capsys):
+ _fake(monkeypatch, sys_platform="darwin", release="24.6.0", machine="arm64",
+ mac_ver="15.6")
+ assert cli._platform_info() == ("macos", "macOS 15.6 (arm64)", True)
+ assert cli._detect_os_family() == "macos"
+ assert cli.print_platform_line(gate=True) == 0
+ assert "platform macOS 15.6 (arm64) · supported" in capsys.readouterr().out
+
+
+# ------------------------------------------------------------ native Windows
+
+def test_native_windows_labels_itself_unsupported(monkeypatch):
+ _fake(monkeypatch, sys_platform="win32", release="11", machine="AMD64")
+ assert cli._platform_info() == ("windows", "Windows 11 native (AMD64)", False)
+ assert cli._detect_os_family() == "windows"
+ assert cli._is_wsl() is False
+
+
+def test_native_windows_warns_and_continues_under_warn_policy(monkeypatch, capsys):
+ _fake(monkeypatch, sys_platform="win32", release="11", machine="AMD64")
+ monkeypatch.setattr(cli, "NATIVE_WINDOWS_POLICY", "warn")
+ assert cli.print_platform_line(gate=True) == 0
+ out = capsys.readouterr().out
+ assert "platform Windows 11 native (AMD64) · not supported" in out
+ assert "Run it inside WSL2" in out
+ assert cli.WSL_DOCS_URL in out
+ assert "Continuing anyway." in out
+
+
+def test_native_windows_blocks_init_and_setup_under_block_policy(monkeypatch, capsys):
+ _fake(monkeypatch, sys_platform="win32", release="11", machine="AMD64")
+ assert cli.NATIVE_WINDOWS_POLICY == "block" # shipped policy
+ assert cli.print_platform_line(gate=True) == 1
+ out = capsys.readouterr().out
+ assert "platform Windows 11 native (AMD64) · not supported" in out
+ assert "Install it inside WSL2" in out
+ assert cli.WSL_DOCS_URL in out
+ assert "status, upgrade, claim, devices and logout keep working." in out
+ assert "SIBYL_ALLOW_NATIVE_WINDOWS=1" in out
+
+
+def test_native_windows_escape_hatch_lets_init_through(monkeypatch, capsys):
+ _fake(monkeypatch, sys_platform="win32", release="11", machine="AMD64",
+ env={"SIBYL_ALLOW_NATIVE_WINDOWS": "1"})
+ assert cli.print_platform_line(gate=True) == 0
+ assert "Continuing anyway." in capsys.readouterr().out
+
+
+def test_native_windows_never_blocks_an_ungated_command(monkeypatch, capsys):
+ """The 76 native-Windows activations keep every command except init/setup."""
+ _fake(monkeypatch, sys_platform="win32", release="11", machine="AMD64")
+ assert cli.print_platform_line(gate=False) == 0
+ assert "Continuing anyway." in capsys.readouterr().out
+
+
+# ------------------------------------------------------------------ unknown
+
+def test_unknown_platform_warns_but_never_blocks(monkeypatch, capsys):
+ _fake(monkeypatch, sys_platform="freebsd14", release="14.1-RELEASE", machine="amd64")
+ assert cli._platform_info() == ("unknown", "freebsd14", False)
+ assert cli._detect_os_family() is None
+ assert cli.print_platform_line(gate=True) == 0
+ out = capsys.readouterr().out
+ assert "platform freebsd14 · not supported" in out
+ assert "built and tested on Linux and macOS" in out
+
+
+# ------------------------------------------- session-init telemetry payload
+
+@pytest.mark.parametrize(
+ "sys_platform,release,machine,expect_family,expect_wsl",
+ [
+ ("linux", "6.8.0-40-generic", "x86_64", "linux", False),
+ ("linux", "5.15.153.1-microsoft-standard-WSL2", "x86_64", "linux", True),
+ ("darwin", "24.6.0", "arm64", "macos", False),
+ ("win32", "11", "AMD64", "windows", False),
+ ],
+)
+def test_session_init_env_keys(monkeypatch, sys_platform, release, machine,
+ expect_family, expect_wsl):
+ """The three new keys the server records (section 6): os_version, arch, wsl."""
+ _fake(monkeypatch, sys_platform=sys_platform, release=release, machine=machine)
+ assert cli._detect_os_family() == expect_family
+ assert _platform.release() == release
+ assert _platform.machine() == machine
+ assert cli._is_wsl() is expect_wsl
+
+
+def test_init_sends_the_new_env_keys(tmp_path, monkeypatch):
+ """End to end: `sibyl init` posts os_version, arch and wsl to session-init."""
+ _fake(monkeypatch, sys_platform="linux",
+ release="5.15.153.1-microsoft-standard-WSL2", machine="x86_64")
+ seen: dict = {}
+
+ def fake_http(method, path, *, body=None, timeout=15.0, headers=None):
+ if path.startswith("/api/plugin/session-init"):
+ seen.update(body["env"])
+ return {"pairing_ttl_seconds": 300}
+ if path.startswith("/api/plugin/check"):
+ return {"bound": True, "credentials": {
+ "account_id": "acct-1", "tier": "free", "bearer_token": "btok",
+ }}
+ raise AssertionError(f"unexpected call {method} {path}")
+
+ monkeypatch.setattr(cli, "http_request", fake_http)
+ monkeypatch.setattr(cli.webbrowser, "open", lambda *a, **k: True)
+ rc = cli.main(["--credentials", str(tmp_path / "credentials.json"), "init"])
+ assert rc == 0
+ assert seen["os_family"] == "linux"
+ assert seen["os_version"] == "5.15.153.1-microsoft-standard-WSL2"
+ assert seen["arch"] == "x86_64"
+ assert seen["wsl"] is True
+
+
+def test_init_refuses_native_windows_before_it_touches_the_network(tmp_path, monkeypatch):
+ _fake(monkeypatch, sys_platform="win32", release="11", machine="AMD64")
+
+ def fake_http(method, path, **kw):
+ raise AssertionError("init must refuse before calling the server")
+
+ monkeypatch.setattr(cli, "http_request", fake_http)
+ monkeypatch.setattr(cli.webbrowser, "open", lambda *a, **k: True)
+ cred = tmp_path / "credentials.json"
+ rc = cli.main(["--credentials", str(cred), "init"])
+ assert rc == 1
+ assert not cred.exists()
diff --git a/sibyl-memory-cli/tests/test_prelaunch_fixes_2026_06_25.py b/sibyl-memory-cli/tests/test_prelaunch_fixes_2026_06_25.py
new file mode 100644
index 0000000000000000000000000000000000000000..46072c8c4c212ffd55e9c0e5c56cb22676ec170b
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_prelaunch_fixes_2026_06_25.py
@@ -0,0 +1,488 @@
+"""Pre-launch fix-pass regression tests (audit 2026-06-25).
+
+One test per audit finding (CLI-1..CLI-16) proving the new, hardened behavior.
+CLI-14 (bearer-in-browser-URL) is deferred — it needs a server-side one-time
+exchange code, out of scope for this client-only pass — so it has no test here.
+
+These exercise the crash-on-malformed-input cluster + durability/atomicity
+hardening that the bounty submitter (D1/D2/D3) and the audit flagged.
+"""
+from __future__ import annotations
+
+import json
+import os
+import stat
+from argparse import Namespace
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import migrate as M
+
+
+# ----------------------------------------------------------------------
+# Helpers
+# ----------------------------------------------------------------------
+
+def _status_args(tmp_path, *, creds="credentials.json", db="memory.db",
+ tier_cache="tier_cache.json") -> Namespace:
+ return Namespace(
+ credentials=str(tmp_path / creds),
+ db=str(tmp_path / db),
+ tier_cache=str(tmp_path / tier_cache),
+ )
+
+
+# ----------------------------------------------------------------------
+# CLI-1 — read_credentials() tolerates a corrupt credentials.json
+# ----------------------------------------------------------------------
+
+def test_cli1_read_credentials_corrupt_returns_none_and_warns(tmp_path, capsys):
+ p = tmp_path / "credentials.json"
+ p.write_text("{ this is not valid json", encoding="utf-8")
+ out = cli.read_credentials(p) # must NOT raise
+ assert out is None
+ msg = capsys.readouterr().out
+ assert "corrupt" in msg.lower()
+ assert "sibyl init --force" in msg
+
+
+# ----------------------------------------------------------------------
+# CLI-2 — write_credentials_atomic uses a unique mkstemp temp (no fixed .tmp)
+# ----------------------------------------------------------------------
+
+def test_cli2_write_credentials_atomic_no_fixed_tmp_and_0600(tmp_path):
+ target = tmp_path / ".sibyl-memory" / "credentials.json"
+ cli.write_credentials_atomic({"account_id": "a", "session_token": "s"}, path=target)
+ assert json.loads(target.read_text())["account_id"] == "a"
+ assert stat.S_IMODE(target.stat().st_mode) == 0o600
+ # No leftover temp files, and specifically NOT the old fixed `.json.tmp` name.
+ leftovers = list(target.parent.glob("*.tmp"))
+ assert leftovers == [], f"temp files left behind: {leftovers}"
+ assert not (target.parent / "credentials.json.tmp").exists()
+
+
+def test_cli2_concurrent_writes_do_not_collide(tmp_path):
+ # Unique-per-call mkstemp means two interleaved writes never fight over one
+ # fixed temp name (the old unlink-then-O_EXCL race). Both must succeed.
+ target = tmp_path / "credentials.json"
+ for i in range(20):
+ cli.write_credentials_atomic({"n": i}, path=target)
+ assert json.loads(target.read_text())["n"] == 19
+ assert list(tmp_path.glob("*.tmp")) == []
+
+
+# ----------------------------------------------------------------------
+# CLI-3 — non-SQLite DB is detected (status label + migrate abort)
+# ----------------------------------------------------------------------
+
+def test_cli3_is_sqlite_db_rejects_garbage_accepts_real(tmp_path):
+ garbage = tmp_path / "garbage.db"
+ garbage.write_bytes(os.urandom(4096))
+ assert cli.is_sqlite_db(garbage) is False
+ empty = tmp_path / "empty.db"
+ empty.write_bytes(b"")
+ assert cli.is_sqlite_db(empty) is True # 0-byte file is a valid empty DB
+ from sibyl_memory_client import MemoryClient
+ real = tmp_path / "real.db"
+ MemoryClient.local(str(real), tenant_id="qa")
+ assert cli.is_sqlite_db(real) is True
+
+
+def test_cli3_status_labels_non_sqlite_db(tmp_path, capsys):
+ creds = tmp_path / "credentials.json"
+ creds.write_text(json.dumps({"account_id": "a"}), encoding="utf-8")
+ db = tmp_path / "memory.db"
+ db.write_bytes(os.urandom(2048)) # not a SQLite file
+ rc = cli.cmd_status(_status_args(tmp_path)) # must NOT raise
+ assert rc == 0
+ out = capsys.readouterr().out
+ assert "not a SQLite database" in out
+
+
+def test_cli3_migrate_aborts_on_unreadable_db(tmp_path):
+ # baseline distinguishes unreadable from 0
+ db = tmp_path / "memory.db"; db.write_bytes(os.urandom(4096))
+ assert M.db_baseline(db) == M.DB_UNREADABLE
+ # orchestrator aborts before verify/debloat with originals intact
+ home = tmp_path / "home"; (home / "myproj").mkdir(parents=True)
+ cm = home / "myproj" / "CLAUDE.md"
+ cm.write_text("# A\n## later\njunk\n", encoding="utf-8")
+ before = cm.read_text()
+ bad_db = home / ".sibyl-memory" / "memory.db"
+ bad_db.parent.mkdir(parents=True)
+ bad_db.write_bytes(os.urandom(4096))
+ rep = M.run_guided_setup(home=home, cwd=home / "myproj", db_path=bad_db,
+ backup_parent=tmp_path / "bk", io=M.GuidedIO(scripted=["y"]),
+ wirers={}, extract_fn=lambda b, d: None)
+ assert rep["ok"] is False
+ assert rep["phases"]["verify"].get("unreadable") is True
+ assert "debloat" not in rep["phases"] # never reached the trim
+ assert cm.read_text() == before # original untouched
+
+
+# ----------------------------------------------------------------------
+# CLI-4 — corrupt tier_cache.json does not crash status
+# ----------------------------------------------------------------------
+
+def test_cli4_status_survives_corrupt_tier_cache(tmp_path, capsys):
+ creds = tmp_path / "credentials.json"
+ creds.write_text(json.dumps({"account_id": "a"}), encoding="utf-8")
+ (tmp_path / "tier_cache.json").write_text("{ broken", encoding="utf-8")
+ rc = cli.cmd_status(_status_args(tmp_path)) # must NOT raise
+ assert rc == 0
+
+
+# ----------------------------------------------------------------------
+# CLI-5 — devices revoke: missing bearer_id bails; negative index rejected
+# ----------------------------------------------------------------------
+
+def _devices_args(tmp_path, idx):
+ return Namespace(
+ credentials=str(tmp_path / "credentials.json"),
+ db=str(tmp_path / "memory.db"),
+ tier_cache=str(tmp_path / "tier_cache.json"),
+ sub="revoke", index=idx,
+ )
+
+
+def test_cli5_revoke_negative_index_rejected(tmp_path, capsys, monkeypatch):
+ (tmp_path / "credentials.json").write_text(
+ json.dumps({"account_id": "a", "session_token": "s"}), encoding="utf-8")
+
+ def _boom(*a, **k):
+ raise AssertionError("must not hit the server for a negative index")
+ monkeypatch.setattr(cli, "http_request", _boom)
+
+ rc = cli.cmd_devices(_devices_args(tmp_path, -1))
+ assert rc == 1
+ assert "invalid index" in capsys.readouterr().out.lower()
+
+
+def test_cli5_revoke_missing_bearer_id_bails_cleanly(tmp_path, capsys, monkeypatch):
+ (tmp_path / "credentials.json").write_text(
+ json.dumps({"account_id": "a", "session_token": "s"}), encoding="utf-8")
+ # Server returns a device record with NO bearer_id (hostile/malformed).
+ monkeypatch.setattr(cli, "http_request",
+ lambda *a, **k: {"devices": [{"device_label": "x"}]})
+ rc = cli.cmd_devices(_devices_args(tmp_path, 0)) # must NOT raise KeyError
+ assert rc == 2
+ assert "bearer_id" in capsys.readouterr().out
+
+
+# ----------------------------------------------------------------------
+# CLI-6 — health expands ~ and wraps provider errors cleanly
+# ----------------------------------------------------------------------
+
+def test_cli6_health_wraps_provider_error(tmp_path, capsys, monkeypatch):
+ import sibyl_memory_hermes
+
+ class _BoomProvider:
+ def __init__(self, *a, **k):
+ raise RuntimeError("db open failed")
+
+ monkeypatch.setattr(sibyl_memory_hermes, "SibylMemoryProvider", _BoomProvider)
+ args = Namespace(db="~/nonexistent/memory.db")
+ rc = cli.cmd_health(args) # must NOT raise
+ assert rc == 1
+ assert "Health check failed" in capsys.readouterr().out
+
+
+# ----------------------------------------------------------------------
+# CLI-7 — memory list/recall tolerate SDK rows missing keys
+# ----------------------------------------------------------------------
+
+def test_cli7_memory_list_tolerates_missing_keys(tmp_path, capsys, monkeypatch):
+ from sibyl_memory_client import MemoryClient
+
+ db = tmp_path / "memory.db"
+ MemoryClient.local(str(db), tenant_id="qa")
+
+ class _FakeClient:
+ @staticmethod
+ def local(*a, **k):
+ return _FakeClient()
+
+ def list_entities(self, **k):
+ return [{"status": "ok"}] # no category/name keys
+
+ monkeypatch.setattr("sibyl_memory_client.MemoryClient", _FakeClient)
+ args = Namespace(db=str(db), mem_cmd="list", category=None, limit=50)
+ rc = cli.cmd_memory(args) # must NOT raise KeyError
+ assert rc == 0
+ assert "?/?" in capsys.readouterr().out
+
+
+# ----------------------------------------------------------------------
+# CLI-13 — _ver_lt orders 1.2 == 1.2.0 and handles rc tags
+# ----------------------------------------------------------------------
+
+def test_cli13_version_compare_normalizes_and_handles_rc():
+ assert cli._ver_lt("1.2", "1.2.0") is False # equal, not "outdated"
+ assert cli._ver_lt("1.2.0", "1.2") is False
+ assert cli._ver_lt("1.2.0", "1.2.1") is True
+ assert cli._ver_lt("0.3.16", "0.3.16") is False
+ # rc precedes the final release
+ assert cli._ver_lt("1.0.0rc1", "1.0.0") is True
+ assert cli._ver_lt("1.0.0", "1.0.0rc1") is False
+
+
+# ----------------------------------------------------------------------
+# CLI-15 — init persists only allowlisted fields, rejects non-dict creds
+# ----------------------------------------------------------------------
+
+def test_cli15_init_allowlists_persisted_fields(tmp_path, monkeypatch):
+ cred_path = tmp_path / "credentials.json"
+ server_creds = {
+ "account_id": "acct-1",
+ "tier": "free",
+ "wallet": "0xabc",
+ "email": "u@example.com",
+ "issued_at": "2026-06-25T00:00:00Z",
+ "bearer_token": "bearer-xyz",
+ # hostile / unexpected extras the server should not be able to plant:
+ "is_admin": True,
+ "__proto__": "x",
+ "arbitrary": {"nested": "junk"},
+ }
+ monkeypatch.setattr(cli, "http_request",
+ lambda *a, **k: {"bound": True, "credentials": dict(server_creds)})
+ # Disable the browser + banner side effects; loop runs once and binds.
+ monkeypatch.setattr(cli.webbrowser, "open", lambda *a, **k: None)
+ args = Namespace(credentials=str(cred_path), force=True)
+ rc = cli.cmd_init(args)
+ assert rc == 0
+ persisted = json.loads(cred_path.read_text())
+ assert persisted["account_id"] == "acct-1"
+ assert persisted["session_token"] == "bearer-xyz" # bearer preferred
+ assert "is_admin" not in persisted
+ assert "__proto__" not in persisted
+ assert "arbitrary" not in persisted
+
+
+def test_cli15_init_rejects_non_dict_credentials(tmp_path, monkeypatch):
+ cred_path = tmp_path / "credentials.json"
+ monkeypatch.setattr(cli, "http_request",
+ lambda *a, **k: {"bound": True, "credentials": "not-a-dict"})
+ monkeypatch.setattr(cli.webbrowser, "open", lambda *a, **k: None)
+ args = Namespace(credentials=str(cred_path), force=True)
+ rc = cli.cmd_init(args) # must NOT raise
+ assert rc == 2
+ assert not cred_path.exists() # nothing persisted from junk
+
+
+# ----------------------------------------------------------------------
+# CLI-16 — cap_bytes formatting tolerates non-int values
+# ----------------------------------------------------------------------
+
+def test_cli16_fmt_cap_bytes_defensive():
+ assert cli._fmt_cap_bytes(None) == "unlimited"
+ assert cli._fmt_cap_bytes(2_097_152) == "2,097,152"
+ assert cli._fmt_cap_bytes("2097152") == "2,097,152" # coerced
+ assert cli._fmt_cap_bytes("lots") == "lots" # uncoercible -> raw, no crash
+ assert cli._fmt_cap_bytes(1048576.0) == "1,048,576"
+
+
+# ----------------------------------------------------------------------
+# CLI-8 — debloat: mkstemp/fsync/atomic + symlink refusal
+# ----------------------------------------------------------------------
+
+def test_cli8_debloat_refuses_symlink_target(tmp_path):
+ real = tmp_path / "real.md"; real.write_text("# real\nsecret\n", encoding="utf-8")
+ link = tmp_path / "CLAUDE.md"; link.symlink_to(real)
+ out = M.debloat_file(link, "lean", backup_exists=True)
+ assert out["written"] is False
+ assert "symlink" in out["error"]
+ assert real.read_text() == "# real\nsecret\n" # target through link untouched
+
+
+def test_cli8_debloat_no_fixed_tmp_left(tmp_path):
+ f = tmp_path / "CLAUDE.md"; f.write_text("# A\n## later\njunk\n" * 50, encoding="utf-8")
+ lean = M.heuristic_lean(f.read_text())
+ out = M.debloat_file(f, lean, backup_exists=True)
+ assert out["written"] and f.read_text() == lean
+ # No leftover temp of any shape, and not the old fixed `.sibyl-tmp` name.
+ assert list(tmp_path.glob("*.sibyl-tmp")) == []
+ assert not (tmp_path / "CLAUDE.md.sibyl-tmp").exists()
+
+
+# ----------------------------------------------------------------------
+# CLI-9 — backup durability + re-verify the specific backup before debloat
+# ----------------------------------------------------------------------
+
+def test_cli9_verify_backup_of_detects_missing_or_truncated(tmp_path):
+ home = tmp_path / "home"; home.mkdir()
+ cm = home / "CLAUDE.md"; cm.write_text("# big\n" * 100, encoding="utf-8")
+ files = M.scan_memory_files(home, cwd=home)
+ bk = M.run_backup(files, tmp_path / "bk")
+ assert bk.ok
+ # backup matches now
+ assert M.verify_backup_of(cm, bk.backup_dir, home=home, cwd=home) is True
+ # truncate the backup copy -> re-verification must FAIL
+ backup_copy = bk.backup_dir / "CLAUDE.md"
+ backup_copy.write_text("x", encoding="utf-8")
+ assert M.verify_backup_of(cm, bk.backup_dir, home=home, cwd=home) is False
+ # delete the backup copy -> re-verification must FAIL
+ backup_copy.unlink()
+ assert M.verify_backup_of(cm, bk.backup_dir, home=home, cwd=home) is False
+
+
+def test_cli9_orchestrator_skips_trim_when_backup_unverifiable(tmp_path):
+ from sibyl_memory_client import MemoryClient
+
+ home = tmp_path / "home"; (home / "proj").mkdir(parents=True)
+ cm = home / "proj" / "CLAUDE.md"
+ cm.write_text("# A\nidentity\n## core\nrule\n## later\n" + "junk line worth trimming\n" * 30, encoding="utf-8")
+ before = cm.read_text()
+ db = home / ".sibyl-memory" / "memory.db"; db.parent.mkdir(parents=True)
+
+ def fake_extract(backup_dir, db_path):
+ c = MemoryClient.local(str(db_path), tenant_id="qa")
+ c.set_entity("facts", "x", {"v": 1})
+
+ # Sabotage the backup AFTER it is made but BEFORE the trim, by intercepting
+ # confirm() to delete the backed-up CLAUDE.md just before debloat runs.
+ class _SabotageIO(M.GuidedIO):
+ def __init__(self, backup_holder):
+ super().__init__(scripted=[])
+ self._holder = backup_holder
+
+ def confirm(self, q, *, default=True):
+ # find + remove the backup copy of CLAUDE.md right before the trim
+ for d in (self._holder["parent"]).glob("sibyl-migration-backup-*"):
+ bc = d / "proj" / "CLAUDE.md"
+ if bc.exists():
+ bc.unlink()
+ return True # say yes to trimming
+
+ holder = {"parent": tmp_path / "bk"}
+ rep = M.run_guided_setup(home=home, cwd=home / "proj", db_path=db,
+ backup_parent=tmp_path / "bk", io=_SabotageIO(holder),
+ wirers={}, extract_fn=fake_extract)
+ # debloat must have refused because the backup could not be re-verified
+ # (2026-09-27: the debloat phase is a list of per-file records)
+ assert [r["written"] for r in rep["phases"]["debloat"]] == [False]
+ assert cm.read_text() == before # original untouched
+
+
+# ----------------------------------------------------------------------
+# CLI-10 — declined Hermes overwrite installs nothing
+# ----------------------------------------------------------------------
+
+def test_cli10_declined_overwrite_installs_nothing(tmp_path, monkeypatch):
+ from sibyl_memory_cli.setup import HermesWirer
+
+ home = tmp_path / "hermes-home"; home.mkdir()
+ (home / "config.yaml").write_text("memory:\n provider: mem0\n", encoding="utf-8")
+
+ installed = {"called": False}
+
+ def _spy_install(self):
+ installed["called"] = True
+ (self.plugin_dir).mkdir(parents=True, exist_ok=True)
+ (self.plugin_dir / "__init__.py").write_text("# stub\n")
+
+ # monkeypatch (not raw assign/del) so the real _install_plugin is restored
+ # cleanly after the test — a manual `del` would remove the method itself.
+ monkeypatch.setattr(HermesWirer, "_install_plugin", _spy_install)
+ w = HermesWirer(hermes_home=home)
+ # prompt declines the overwrite
+ outcome = w.wire(prompt_fn=lambda q, *, default: "n")
+ assert outcome.status == "skipped"
+ assert installed["called"] is False, "plugin must NOT be installed on a declined overwrite"
+ assert not (home / "plugins" / "sibyl" / "__init__.py").exists()
+ # config untouched
+ assert "mem0" in (home / "config.yaml").read_text()
+
+
+# ----------------------------------------------------------------------
+# CLI-11 — pip install respects PEP 668 / pipx (no silent mutation) + surfaces
+# ----------------------------------------------------------------------
+
+def test_cli11_install_helper_respects_pep668(monkeypatch):
+ from sibyl_memory_cli import setup as S
+ import sibyl_memory_cli.cli as _cli
+
+ calls = {"pip": 0}
+ monkeypatch.setattr(_cli, "_detect_install_method", lambda: "pep668")
+ monkeypatch.setattr(S, "_run", lambda *a, **k: calls.__setitem__("pip", calls["pip"] + 1) or (0, "", ""))
+ msg = S._install_pkg_or_instruct("sibyl-memory-mcp")
+ assert calls["pip"] == 0, "must NOT pip install into an externally-managed env"
+ assert msg and "externally-managed" in msg
+ assert "break-system-packages" in msg
+
+
+def test_cli11_install_helper_surfaces_pip_failure(monkeypatch):
+ from sibyl_memory_cli import setup as S
+ import sibyl_memory_cli.cli as _cli
+
+ monkeypatch.setattr(_cli, "_detect_install_method", lambda: "venv")
+ monkeypatch.setattr(S, "_run",
+ lambda *a, **k: (1, "", "ERROR: could not find a version"))
+ msg = S._install_pkg_or_instruct("sibyl-memory-mcp")
+ assert msg and "failed" in msg
+ assert "could not find a version" in msg
+
+
+# ----------------------------------------------------------------------
+# CLI-12 — verify_mcp_starts does not flag a slow-but-alive import as crashed
+# ----------------------------------------------------------------------
+
+def test_cli12_verify_does_not_crash_label_slow_import(monkeypatch):
+ from sibyl_memory_cli.setup import ClaudeCodeWirer
+
+ class _SlowAliveProc:
+ """Simulates a stdio server that is still importing (alive, not exited)
+ for the whole verification window, then blocks on stdin."""
+ def __init__(self):
+ self._polls = 0
+
+ def poll(self):
+ self._polls += 1
+ return None # never exits during the window -> healthy
+
+ def terminate(self):
+ pass
+
+ def wait(self, timeout=None):
+ return 0
+
+ def kill(self):
+ pass
+
+ monkeypatch.setattr("sibyl_memory_cli.setup.shutil.which",
+ lambda name: "/usr/bin/sibyl-memory-mcp")
+ monkeypatch.setattr("subprocess.Popen", lambda *a, **k: _SlowAliveProc())
+ ok, msg = ClaudeCodeWirer().verify_mcp_starts()
+ assert ok is True
+ assert "verified" in msg.lower()
+
+
+def test_cli12_verify_flags_quick_crash(monkeypatch):
+ from sibyl_memory_cli.setup import ClaudeCodeWirer
+
+ class _CrashProc:
+ def __init__(self):
+ import io
+ self.stderr = io.BytesIO(b"ImportError: boom\n")
+
+ def poll(self):
+ return 1 # exited non-zero immediately -> crash
+
+ def terminate(self):
+ pass
+
+ def wait(self, timeout=None):
+ return 1
+
+ def kill(self):
+ pass
+
+ monkeypatch.setattr("sibyl_memory_cli.setup.shutil.which",
+ lambda name: "/usr/bin/sibyl-memory-mcp")
+ monkeypatch.setattr("subprocess.Popen", lambda *a, **k: _CrashProc())
+ ok, msg = ClaudeCodeWirer().verify_mcp_starts()
+ assert ok is False
+ assert "crashed" in msg.lower()
+ assert "ImportError" in msg
diff --git a/sibyl-memory-cli/tests/test_py310_syntax_2026_11_12.py b/sibyl-memory-cli/tests/test_py310_syntax_2026_11_12.py
new file mode 100644
index 0000000000000000000000000000000000000000..a32ecd088df47a8f5b152fdc4a7b0d66ae337fa3
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_py310_syntax_2026_11_12.py
@@ -0,0 +1,88 @@
+"""Every package declares requires-python >=3.10, so no source file may use syntax
+that only parses on 3.12+ (issue #32).
+
+The one form that has shipped is PEP 701 quote reuse: an f-string whose replacement
+field contains a string literal using the f-string's own quote character, e.g.
+f"{x or "-"}". Python 3.12's parser accepts it even with feature_version=(3, 10), so
+this test walks the token stream instead. It needs the 3.12 tokenizer (FSTRING_START
+tokens) and is skipped on older interpreters, where such a file fails to import anyway.
+"""
+
+from __future__ import annotations
+
+import io
+import sys
+import tokenize
+from pathlib import Path
+
+import pytest
+
+pytestmark = pytest.mark.skipif(
+ sys.version_info < (3, 12), reason="needs the 3.12 tokenizer (FSTRING_START tokens)"
+)
+
+_CLI_ROOT = Path(__file__).resolve().parents[1]
+_REPO_ROOT = _CLI_ROOT.parent
+_PACKAGES = (
+ "sibyl-memory-cli",
+ "sibyl-memory-client",
+ "sibyl-memory-mcp",
+ "sibyl-memory-hermes",
+ "sibyl-memory-langgraph",
+)
+
+
+def _source_files() -> list[Path]:
+ files: list[Path] = []
+ for pkg in _PACKAGES:
+ root = _REPO_ROOT / pkg
+ for sub in ("src", "hermes-catalog"):
+ if (root / sub).is_dir():
+ files.extend(sorted((root / sub).rglob("*.py")))
+ return files
+
+
+def _quote_of(token_text: str) -> str:
+ body = token_text.lstrip("rRbBuUfF")
+ return body[:3] if body[:3] in ('"""', "'''") else body[:1]
+
+
+def _quote_reuse(source: str) -> list[int]:
+ """Line numbers where a string inside an f-string reuses an enclosing quote."""
+ hits: list[int] = []
+ enclosing: list[str] = []
+ for tok in tokenize.generate_tokens(io.StringIO(source).readline):
+ if tok.type == tokenize.FSTRING_START:
+ quote = _quote_of(tok.string)
+ if quote in enclosing:
+ hits.append(tok.start[0])
+ enclosing.append(quote)
+ elif tok.type == tokenize.FSTRING_END:
+ enclosing.pop()
+ elif tok.type == tokenize.STRING and enclosing:
+ if _quote_of(tok.string) in enclosing:
+ hits.append(tok.start[0])
+ return hits
+
+
+def test_detector_catches_the_issue_32_line():
+ bad = 'print(f" {a.bold(acct or "x")}")\n'
+ good = "print(f\" {a.bold(acct or 'x')}\")\n"
+ assert _quote_reuse(bad) == [1]
+ assert _quote_reuse(good) == []
+
+
+def test_scan_finds_source_files():
+ files = _source_files()
+ assert any(f.name == "cli.py" for f in files)
+
+
+def test_no_fstring_quote_reuse_in_any_package():
+ offenders = []
+ for path in _source_files():
+ for line in _quote_reuse(path.read_text(encoding="utf-8")):
+ offenders.append(f"{path.relative_to(_REPO_ROOT)}:{line}")
+ assert offenders == [], (
+ "f-string reuses its own quote inside a replacement field (3.12+ only, "
+ "breaks requires-python >=3.10): " + ", ".join(offenders)
+ )
diff --git a/sibyl-memory-cli/tests/test_quality_fixes_2026_06_30.py b/sibyl-memory-cli/tests/test_quality_fixes_2026_06_30.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb0d3b2fafc2f9d81a84b46b43e0440e6be784ae
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_quality_fixes_2026_06_30.py
@@ -0,0 +1,278 @@
+"""Regression tests for the 2026-06-30 quality fix-pass (audit #13, #19, #15).
+
+All LOW severity; these prove the new robustness/diagnostic behavior:
+ - #13 (B001): `status` reports the WAL-inclusive logical DB size (the same
+ measure the cap gate enforces), not the raw `memory.db` file size.
+ - #19 (B001): `migrate` SQLite connections always close, even on query error.
+ - #19 (B005): `migrate._tree_size` skips an un-statable entry instead of
+ aborting.
+ - #19 (B005): `setup` config backups are timestamped and never clobber a
+ prior backup.
+ - #19 (B005): `setup._verify_mcp_starts` is a standalone helper (no cross-class
+ dispatch).
+ - #15: `status` store discovery survives a PermissionError on the profiles dir.
+"""
+from __future__ import annotations
+
+import sqlite3
+import time
+from argparse import Namespace
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import migrate as M
+from sibyl_memory_cli import setup as S
+
+
+def _status_args(tmp_path, *, creds="credentials.json", db="memory.db",
+ tier_cache="tier_cache.json") -> Namespace:
+ return Namespace(
+ credentials=str(tmp_path / creds),
+ db=str(tmp_path / db),
+ tier_cache=str(tmp_path / tier_cache),
+ )
+
+
+# ----------------------------------------------------------------------
+# #13 (B001) — status uses db_size_bytes (WAL-inclusive logical), not st_size
+# ----------------------------------------------------------------------
+
+def test_b001_status_uses_logical_db_size(tmp_path, monkeypatch, capsys):
+ import json
+ from sibyl_memory_client import MemoryClient
+
+ creds = tmp_path / "credentials.json"
+ creds.write_text(json.dumps({"account_id": "a"}), encoding="utf-8")
+ db = tmp_path / "memory.db"
+ MemoryClient.local(str(db), tenant_id="qa") # real SQLite DB
+
+ # Force the cap measure to a sentinel so we can prove status renders THAT
+ # number, not the raw file st_size.
+ sentinel = 1_234_567
+ monkeypatch.setattr(
+ "sibyl_memory_client.storage.db_size_bytes",
+ lambda p: sentinel,
+ )
+ rc = cli.cmd_status(_status_args(tmp_path))
+ assert rc == 0
+ out = capsys.readouterr().out
+ assert f"{sentinel:,}" in out # logical size rendered
+ raw = db.stat().st_size
+ if raw != sentinel:
+ assert f"{raw:,} bytes (" not in out # raw st_size NOT used for the gate label
+
+
+def test_b001_status_size_matches_gate_measure(tmp_path, capsys):
+ """End-to-end (no monkeypatch): the rendered size equals db_size_bytes()."""
+ import json
+ from sibyl_memory_client import MemoryClient
+ from sibyl_memory_client.storage import db_size_bytes
+
+ creds = tmp_path / "credentials.json"
+ creds.write_text(json.dumps({"account_id": "a"}), encoding="utf-8")
+ db = tmp_path / "memory.db"
+ MemoryClient.local(str(db), tenant_id="qa")
+
+ expected = db_size_bytes(db)
+ rc = cli.cmd_status(_status_args(tmp_path))
+ assert rc == 0
+ out = capsys.readouterr().out
+ assert f"{expected:,} bytes (" in out
+
+
+# ----------------------------------------------------------------------
+# #19 (B001) — migrate connections always close, even on query error
+# ----------------------------------------------------------------------
+
+def _make_db(path: Path, *, with_entities: bool) -> None:
+ con = sqlite3.connect(str(path))
+ try:
+ if with_entities:
+ con.execute("CREATE TABLE entities (id INTEGER PRIMARY KEY, category TEXT)")
+ con.execute("INSERT INTO entities (category) VALUES ('people')")
+ con.commit()
+ else:
+ # a real SQLite DB WITHOUT an entities table → COUNT(*) raises
+ con.execute("CREATE TABLE other (id INTEGER PRIMARY KEY)")
+ con.commit()
+ finally:
+ con.close()
+
+
+class _CountingConnection(sqlite3.Connection):
+ """Connection subclass that records every close() into a class-level counter.
+
+ sqlite3.Connection.close is a read-only C attribute (can't be monkeypatched
+ per-instance), so we subclass and pass this as connect(factory=...).
+ """
+
+ closes = 0
+
+ def close(self): # noqa: D401 - thin override
+ type(self).closes += 1
+ return super().close()
+
+
+def _tracking_connect(real_connect):
+ def connect(*a, **k):
+ k.setdefault("factory", _CountingConnection)
+ return real_connect(*a, **k)
+ return connect
+
+
+def test_b001_verify_new_entries_closes_connection_on_error(tmp_path, monkeypatch):
+ db = tmp_path / "memory.db"
+ _make_db(db, with_entities=False) # query path will raise OperationalError
+
+ _CountingConnection.closes = 0
+ monkeypatch.setattr(M.sqlite3, "connect", _tracking_connect(sqlite3.connect))
+ out = M.verify_new_entries(db, baseline_total=0)
+ assert out["ok"] is False
+ assert "error" in out # the missing-table error surfaced
+ # _is_readable_db opens+closes once; the fix ensures the query connection is
+ # ALSO closed despite the error → at least two closes total.
+ assert _CountingConnection.closes >= 2
+
+
+def test_b001_db_baseline_closes_connection_on_error(tmp_path, monkeypatch):
+ db = tmp_path / "memory.db"
+ _make_db(db, with_entities=False)
+
+ _CountingConnection.closes = 0
+ monkeypatch.setattr(M.sqlite3, "connect", _tracking_connect(sqlite3.connect))
+ # readable SQLite, no entities table → baseline 0, not unreadable
+ assert M.db_baseline(db) == 0
+ assert _CountingConnection.closes >= 2
+
+
+def test_verify_new_entries_happy_path_still_works(tmp_path):
+ db = tmp_path / "memory.db"
+ _make_db(db, with_entities=True)
+ out = M.verify_new_entries(db, baseline_total=0)
+ assert out["ok"] is True
+ assert out["new_total"] == 1
+ assert out["by_category"] == {"people": 1}
+
+
+# ----------------------------------------------------------------------
+# #19 (B005) — _tree_size tolerates an unreadable / un-statable entry
+# ----------------------------------------------------------------------
+
+def test_b005_tree_size_skips_unreadable_entry(tmp_path, monkeypatch):
+ root = tmp_path / "tree"
+ root.mkdir()
+ good = root / "good.txt"
+ good.write_bytes(b"hello") # 5 bytes
+ bad = root / "bad.txt"
+ bad.write_bytes(b"xxxxxxxxxx") # would be 10 bytes if statable
+
+ real_stat = Path.stat
+
+ def flaky_stat(self, *a, **k):
+ if self.name == "bad.txt":
+ raise PermissionError("denied")
+ return real_stat(self, *a, **k)
+
+ monkeypatch.setattr(Path, "stat", flaky_stat)
+ # must NOT raise; the bad entry is skipped, only the good one counts
+ assert M._tree_size(root) == 5
+
+
+def test_b005_tree_size_tolerates_broken_symlink(tmp_path):
+ root = tmp_path / "tree"
+ root.mkdir()
+ (root / "real.txt").write_bytes(b"abc") # 3 bytes
+ broken = root / "dangling"
+ try:
+ broken.symlink_to(root / "does-not-exist")
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks not supported on this platform")
+ # is_file()/stat() on a broken symlink must not abort the sum
+ assert M._tree_size(root) == 3
+
+
+# ----------------------------------------------------------------------
+# #19 (B005) — timestamped backups never clobber a prior backup
+# ----------------------------------------------------------------------
+
+def test_b005_timestamped_backup_is_unique(tmp_path, monkeypatch):
+ cfg = tmp_path / "config.yaml"
+ cfg.write_text("v1\n")
+ times = iter(["20260630T010000Z", "20260630T020000Z"])
+ monkeypatch.setattr(
+ S.time, "strftime",
+ lambda fmt, t=None: next(times),
+ )
+ b1 = S._timestamped_backup(cfg)
+ cfg.write_text("v2\n")
+ b2 = S._timestamped_backup(cfg)
+ assert b1 is not None and b2 is not None
+ assert b1 != b2 # distinct backup files
+ assert b1.exists() and b2.exists()
+ assert b1.read_text() == "v1\n" # first backup not overwritten
+ assert b2.read_text() == "v2\n"
+ assert b1.name.endswith(".bak")
+ assert ".20260630T010000Z." in b1.name
+ # original extension preserved in the backup name
+ assert b1.name.startswith("config.yaml.")
+ # cli 0.7.0: backups live under ~/.sibyl-memory/backups// (default
+ # label "other"), never beside the config
+ assert b1.parent == Path.home() / ".sibyl-memory" / "backups" / "other"
+ assert list(tmp_path.glob("config.yaml.*.bak")) == []
+
+
+def test_b005_timestamped_backup_none_when_missing(tmp_path):
+ assert S._timestamped_backup(tmp_path / "nope.yaml") is None
+
+
+# ----------------------------------------------------------------------
+# #19 (B005) — _verify_mcp_starts is a shared standalone helper
+# ----------------------------------------------------------------------
+
+def test_b005_verify_mcp_starts_is_module_helper():
+ assert callable(S._verify_mcp_starts)
+ # binary-not-found short-circuits without spawning anything
+ ok, msg = S._verify_mcp_starts(None)
+ assert ok is False
+ assert "not found" in msg.lower()
+
+
+def test_b005_both_wirers_delegate_to_helper(monkeypatch):
+ calls = []
+ monkeypatch.setattr(S, "_verify_mcp_starts", lambda b: calls.append(b) or (True, "ok"))
+ monkeypatch.setattr(S.shutil, "which", lambda name: "/usr/bin/" + name)
+ claude = S.ClaudeCodeWirer(settings_path=Path("/tmp/x.json"))
+ codex = S.CodexWirer(config_path=Path("/tmp/x.toml"))
+ assert claude.verify_mcp_starts() == (True, "ok")
+ assert codex.verify_mcp_starts() == (True, "ok")
+ # both routed through the shared helper with the resolved binary path
+ assert calls == ["/usr/bin/sibyl-memory-mcp", "/usr/bin/sibyl-memory-mcp"]
+
+
+# ----------------------------------------------------------------------
+# #15 — _discover_stores survives a PermissionError on the profiles dir
+# ----------------------------------------------------------------------
+
+def test_hygiene_discover_stores_survives_restricted_profiles(tmp_path, monkeypatch):
+ primary = tmp_path / ".sibyl-memory" / "memory.db"
+ primary.parent.mkdir(parents=True)
+ primary.write_bytes(b"x" * 10)
+ hermes = tmp_path / ".hermes"
+ profiles = hermes / "sibyl" / "profiles"
+ profiles.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(hermes))
+ monkeypatch.delenv("SIBYL_MEMORY_DB", raising=False)
+
+ real_iterdir = Path.iterdir
+
+ def flaky_iterdir(self):
+ if self == profiles:
+ raise PermissionError("denied")
+ return real_iterdir(self)
+
+ monkeypatch.setattr(Path, "iterdir", flaky_iterdir)
+ # must NOT raise; profiles sweep skipped, default store still discovered
+ stores = cli._discover_stores(primary)
+ assert any(s["label"] == "default (SDK/CLI/MCP)" for s in stores)
diff --git a/sibyl-memory-cli/tests/test_r1_paid_tier_cli_2026_09_29.py b/sibyl-memory-cli/tests/test_r1_paid_tier_cli_2026_09_29.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ea8776365e1d70a591afcb0828a373e88dc13c9
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_r1_paid_tier_cli_2026_09_29.py
@@ -0,0 +1,724 @@
+"""R1 of the paid tier (plan plugin-paid-tier-2026-09-29, sections 2, 3.3, 4, 5.2,
+9.4): CLI side.
+
+* the Claude Code hooks: automatic save by ACTIVE time (a Stop after 61 active
+ minutes with one write continues, with none it does not, a second request
+ inside the same active hour does not, the numbered request and its
+ transcript guard, the `claude -p` heuristic, idle and turn caps, a save made
+ elsewhere restarting the clock), the tier-change and skill lines at start;
+* `sibyl autosave`, `sibyl refresh`, `sibyl skills proposals`;
+* the computer limit: `sibyl init` sends replace on re-activation, prints the
+ computers and the replace prompt (terminal) or the instructions (no
+ terminal) on the recorded 409 / `/check` fixtures of the plan's contract,
+ keeps waiting after a yes; `sibyl devices` and `sibyl status` show the limit;
+ the read-only access row names the computer limit.
+
+On 3e13ca4 every test here fails: `autosave`, `refresh` and `skills proposals`
+are not commands (argparse exits 2), `init --replace` is not an option, the
+hook continued at most once per session (the second-hour and numbered-request
+tests), took no notice of `claude -p` runs, had no `stop_reason`, and init
+treated a 409 on /check as "Unexpected error" and sent no replace.
+"""
+from __future__ import annotations
+
+import builtins
+import json
+import time
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import hooks as H
+from sibyl_memory_client import MemoryClient
+from sibyl_memory_client import skills as SK
+from sibyl_memory_client.lifecycle import state as ST
+from sibyl_memory_client.testing import write_entitlement
+
+FIX = json.loads((Path(__file__).parent / "fixtures" / "device_limit_r1.json").read_text())
+
+
+@pytest.fixture(autouse=True)
+def _quiet(monkeypatch):
+ monkeypatch.setenv("SIBYL_MEMORY_TELEMETRY", "0")
+ monkeypatch.setenv("NO_COLOR", "1")
+
+
+@pytest.fixture(autouse=True)
+def _offline_server(monkeypatch):
+ from sibyl_memory_client import _capcheck
+ monkeypatch.setattr(_capcheck, "_default_check_write_fn",
+ lambda url, payload, timeout=4.0: {"ok": True, "tier": "pro", "cap_bytes": None})
+
+ def offline(*a, **k):
+ raise cli.HttpError(0, {}, "offline")
+ monkeypatch.setattr(cli, "http_request", offline)
+
+
+@pytest.fixture
+def home():
+ return Path.home()
+
+
+@pytest.fixture
+def sm(home):
+ return home / ".sibyl-memory"
+
+
+@pytest.fixture
+def pro(sm, test_signer):
+ write_entitlement(sm, test_signer.mint(tier="pro", cap=None, src="pro"))
+ return sm
+
+
+def _acct(sm: Path) -> list[str]:
+ return ["--credentials", str(sm / "credentials.json"), "--db", str(sm / "memory.db")]
+
+
+def _tenant(sm: Path) -> str:
+ c = json.loads((sm / "credentials.json").read_text())
+ return c.get("tenant_id") or c["account_id"]
+
+
+def _client(sm: Path) -> MemoryClient:
+ return MemoryClient.local(str(sm / "memory.db"), tenant_id=_tenant(sm),
+ credentials_path=sm / "credentials.json")
+
+
+def _hook(event: str, payload: dict, home: Path, now: float) -> str:
+ return H.run_hook(event, json.dumps(payload), home=home, now=now)
+
+
+def _bump(home: Path, tid: str, n: int) -> None:
+ def _u(st):
+ t = ST.tenant(st, tid)
+ t["writes_total"] = int(t.get("writes_total") or 0) + n
+ t["writes_since_save"] = int(t.get("writes_since_save") or 0) + n
+ ST.LifecycleState(home).update(_u)
+
+
+class _Session:
+ """A Claude Code session driven through the hooks: turns of the model
+ (prompt -> stop) with the person's pauses between them."""
+
+ def __init__(self, home: Path, tmp: Path, sid: str, t0: float) -> None:
+ self.home, self.sid, self.t = home, sid, t0
+ self.tr = tmp / f"{sid}.jsonl"
+ self.tr.write_text("{}\n")
+ _hook("session-start", {"session_id": sid, "cwd": str(tmp)}, home, self.t)
+
+ def turn(self, work_min: float, pause_min: float = 1.0) -> str:
+ self.t += pause_min * 60
+ _hook("prompt", {"session_id": self.sid}, self.home, self.t)
+ self.t += work_min * 60
+ return self.stop()
+
+ def stop(self, **extra) -> str:
+ payload = {"session_id": self.sid, "stop_hook_active": False, "transcript_path": str(self.tr)}
+ payload.update(extra)
+ return _hook("stop", payload, self.home, self.t)
+
+ @property
+ def state(self) -> dict:
+ return ST.LifecycleState(self.home).load()["sessions"][ST.session_key(self.sid)]
+
+
+# ----------------------------------------------------------------------
+# Hooks: active-time automatic save (plan 2.2, 2.3, 2.5, 9.4)
+# ----------------------------------------------------------------------
+
+def test_stop_after_61_active_minutes_with_one_write_continues_then_hourly(home, pro, tmp_path):
+ tid = _tenant(pro)
+ s = _Session(home, tmp_path, "h1", time.time() - 6 * 3600)
+ assert s.turn(1) == "" # a first turn
+ _bump(home, tid, 1)
+ assert s.turn(25) == "" and s.turn(25) == ""
+ assert s.state["active_seconds"] < 3600
+ out = s.turn(9) # past 60 active minutes
+ assert json.loads(out) == {"decision": "block", "reason": H.stop_reason(1)}
+ assert "(save 1 of this session). Then stop." in out
+ assert s.turn(20) == "" # same active hour: not again
+ assert s.stop(stop_hook_active=True) == ""
+ assert s.turn(25) == "" and s.turn(10) == ""
+ out = s.turn(6)
+ assert json.loads(out)["reason"] == H.stop_reason(2)
+ st = ST.LifecycleState(home).load()
+ assert st["tenants"][tid]["nudges_today"] == 2 and len(s.state["nudges"]) == 2
+
+
+def test_stop_with_no_writes_never_continues(home, pro, tmp_path):
+ s = _Session(home, tmp_path, "h0", time.time() - 6 * 3600)
+ for _ in range(6):
+ assert s.turn(25) == ""
+ assert s.state["active_seconds"] >= 2 * 3600
+
+
+def test_first_save_rule_still_carries_medium_sessions(home, pro, tmp_path):
+ s = _Session(home, tmp_path, "hm", time.time() - 3600)
+ s.turn(2)
+ _bump(home, _tenant(pro), 5)
+ assert json.loads(s.turn(3))["reason"] == H.stop_reason(1)
+ _bump(home, _tenant(pro), 5)
+ assert s.turn(3) == "" # the first rule is once; the hour rule is next
+
+
+def test_idle_pause_counts_five_minutes_and_a_turn_at_most_thirty(home, pro, tmp_path):
+ s = _Session(home, tmp_path, "hi", time.time() - 12 * 3600)
+ s.turn(1, pause_min=0)
+ a0 = s.state["active_seconds"]
+ s.turn(2, pause_min=180) # three hours away, then a 2-minute turn
+ assert s.state["active_seconds"] - a0 == pytest.approx(5 * 60 + 2 * 60)
+ a1 = s.state["active_seconds"]
+ s.turn(300, pause_min=0) # a turn left waiting for five hours
+ assert s.state["active_seconds"] - a1 == pytest.approx(ST.TURN_CAP_SECONDS)
+
+
+def test_scripted_runs_are_never_continued(home, pro, tmp_path):
+ tid = _tenant(pro)
+ t = time.time() - 4 * 3600
+ _hook("session-start", {"session_id": "p1", "cwd": str(tmp_path)}, home, t)
+ _hook("prompt", {"session_id": "p1"}, home, t + 1) # `claude -p`: one prompt
+ _bump(home, tid, 40)
+ tr = tmp_path / "p1.jsonl"
+ tr.write_text("{}\n")
+ for i in range(1, 5):
+ assert _hook("stop", {"session_id": "p1", "stop_hook_active": False, "transcript_path": str(tr)},
+ home, t + i * 1800) == ""
+ s = _Session(home, tmp_path, "p2", time.time() - 4 * 3600)
+ s.turn(1)
+ s.turn(1)
+ s.t += 3 * 3600
+ assert s.stop(transcript_path="") == "" # no transcript: scripted
+ log = (pro / "lifecycle.log").read_text()
+ assert "hook stop: pass" in log
+
+
+def test_numbered_request_guard_survives_a_rewritten_state(home, pro, tmp_path):
+ tid = _tenant(pro)
+ s = _Session(home, tmp_path, "hg", time.time() - 8 * 3600)
+ s.turn(1)
+ _bump(home, tid, 2)
+ out = ""
+ for _ in range(5):
+ out = s.turn(25)
+ if out:
+ break
+ reason = json.loads(out)["reason"]
+ assert reason == H.stop_reason(1)
+ s.tr.write_text(s.tr.read_text() + json.dumps({"type": "user", "content": reason}) + "\n")
+ for _ in range(3):
+ s.turn(25)
+ second = H.stop_reason(len(s.state["nudges"]) + 1)
+ # Claude Code already recorded that numbered request (the state lost it).
+ s.tr.write_text(s.tr.read_text() + json.dumps({"type": "user", "content": second}) + "\n")
+ assert s.turn(25) == ""
+
+
+def test_a_save_elsewhere_restarts_the_hook_clock(home, pro, tmp_path):
+ tid = _tenant(pro)
+ s = _Session(home, tmp_path, "hs", time.time() - 8 * 3600)
+ s.turn(1)
+ for _ in range(2):
+ s.turn(25)
+ # another agent (Cursor, a terminal) saves: the DB marker is shared
+ c = _client(pro)
+ c.enable_lifecycle_counting(home) # as the MCP server's client does
+ c.set_state("sibyl_save:last_save", {"ts": "2026-09-29T00:00:00Z"})
+ ST.flush_all()
+ _bump(home, tid, 3) # new work after that save
+ assert s.turn(25) == "" # 76 active minutes, but 25 since that save
+ assert s.turn(25) == ""
+ assert json.loads(s.turn(15))["reason"] == H.stop_reason(1)
+
+
+def test_free_stop_and_prompt_never_automate(home, sm, tmp_path):
+ s = _Session(home, tmp_path, "hf", time.time() - 8 * 3600)
+ _bump(home, _tenant(sm), 50)
+ for _ in range(6):
+ assert s.turn(25) == ""
+ assert s.stop() == ""
+
+
+def test_autosave_off_stops_the_hook(home, pro, tmp_path, capsys):
+ assert cli.main(["autosave", "off"]) == 0
+ s = _Session(home, tmp_path, "ho", time.time() - 8 * 3600)
+ s.turn(1)
+ _bump(home, _tenant(pro), 9)
+ for _ in range(5):
+ assert s.turn(25) == ""
+
+
+def test_session_start_tier_change_and_skill_lines(home, sm, test_signer, tmp_path):
+ t = time.time() - 7200
+ _hook("session-start", {"session_id": "t1", "cwd": str(tmp_path)}, home, t) # first sight: free
+ write_entitlement(sm, test_signer.mint(tier="pro", cap=None, src="stake"))
+ c = _client(sm)
+ now = time.time()
+ ev = [{"event_id": str(i), "ts": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(x)), "snippet": "x"}
+ for i, x in enumerate((now - 4 * 86400, now - 2 * 86400, now - 1800))]
+ with c.storage.transaction() as con:
+ for i in range(4):
+ con.execute("INSERT INTO skill_proposals (id, tenant_id, pattern_kind, proposed_slug, "
+ "proposed_title, proposed_body, evidence, confidence, summarizer) VALUES "
+ "(?, ?, 'repeated_action', ?, NULL, 'b', ?, ?, 'local-deterministic')",
+ (f"id{i}", _tenant(sm), f"fix-lockfile-{i}", json.dumps(ev), 0.9 - i / 100))
+ out = json.loads(_hook("session-start", {"session_id": "t2", "cwd": str(tmp_path)}, home, now))
+ ctx = out["hookSpecificOutput"]["additionalContext"]
+ assert "this computer is now on Pro" in ctx
+ assert ("Sibyl Memory: 4 candidate skills from your recent sessions (fix-lockfile-0, fix-lockfile-1, "
+ "fix-lockfile-2 and 1 more). Say /sibyl-save curate to review, or run sibyl skills proposals.") in ctx
+ again = _hook("session-start", {"session_id": "t3", "cwd": str(tmp_path)}, home, now + 60)
+ assert "candidate skill" not in again # 24 h throttle
+
+
+# ----------------------------------------------------------------------
+# sibyl autosave (plan 2.4)
+# ----------------------------------------------------------------------
+
+def test_autosave_status_every_bounds_and_free_copy(home, sm, pro, capsys):
+ assert cli.main(_acct(sm) + ["autosave"]) == 0
+ out = capsys.readouterr().out
+ assert "every 60 min of active work" in out and "at most 8 a session and 12 a day" in out
+ assert cli.main(_acct(sm) + ["autosave", "every", "45"]) == 0
+ assert "every 45 min of active work" in capsys.readouterr().out
+ assert ST.LifecycleState(home).load()["autosave"]["interval_seconds"] == 2700
+ for bad in ("29", "241"):
+ assert cli.main(_acct(sm) + ["autosave", "every", bad]) == 1
+ assert "30 to 240" in capsys.readouterr().out
+ assert cli.main(_acct(sm) + ["autosave", "every"]) == 1
+ assert cli.main(_acct(sm) + ["autosave", "off"]) == 0
+ assert "off · sibyl autosave on" in capsys.readouterr().out
+ assert ST.LifecycleState(home).load()["autosave"]["enabled"] is False
+ assert cli.main(_acct(sm) + ["autosave", "on"]) == 0
+ capsys.readouterr()
+
+
+def test_autosave_on_free_says_pro_and_keeps_the_setting(home, sm, capsys):
+ assert cli.main(_acct(sm) + ["autosave", "every", "90"]) == 0
+ out = capsys.readouterr().out
+ assert "automatic save is on Pro · this setting applies the day you upgrade" in out
+ assert ST.LifecycleState(home).load()["autosave"]["interval_seconds"] == 5400
+
+
+# ----------------------------------------------------------------------
+# sibyl refresh (plan 5.2)
+# ----------------------------------------------------------------------
+
+def test_refresh_without_an_account_exits_0(tmp_path, capsys):
+ assert cli.main(["--credentials", str(tmp_path / "none.json"), "refresh"]) == 0
+ out = capsys.readouterr().out
+ assert "Not activated. Run `sibyl init`." in out
+
+
+def test_refresh_reports_the_upgrade_and_what_it_refreshed(home, sm, test_signer, monkeypatch, capsys):
+ from sibyl_memory_client import _entitlement as E
+ (home / ".claude").mkdir()
+ acct = {"complete": True, "email_verified": True, "email_required": False,
+ "devices": FIX["entitlement_acct_devices_pro"]}
+ monkeypatch.setattr(E, "http_refresh", test_signer.refresh_fn(tier="pro", cap=None, src="stake",
+ acct=acct))
+ assert cli.main(_acct(sm) + ["refresh"]) == 0
+ out = capsys.readouterr().out
+ assert "free -> pro (stake)" in out
+ assert "5 MB -> none" in out
+ assert "computers" in out and "2 of 10" in out
+ assert "procedures" in out and (home / ".claude" / "skills" / "sibyl-save" / "SKILL.md").exists()
+ assert "Hooks and shims are the same on every plan" in out
+ assert "Running agents pick this up on their next call." in out
+ assert "automatic · every 60 min of active work" in out
+ assert "0 skill proposals pending" in out
+ # nothing changed the second time
+ assert cli.main(_acct(sm) + ["refresh"]) == 0
+ assert "no change · pro" in capsys.readouterr().out
+
+
+def test_refresh_offline_exits_2_and_shows_the_last_check_in(sm, monkeypatch, capsys):
+ from sibyl_memory_client import _entitlement as E
+ monkeypatch.setattr(E, "http_refresh", lambda a, t: E.RefreshOutcome("transient", code="offline"))
+ assert cli.main(_acct(sm) + ["refresh"]) == 2
+ assert "could not reach the server" in capsys.readouterr().out
+
+
+# ----------------------------------------------------------------------
+# sibyl init: the computer limit (plan 4.2 / 4.4), recorded fixtures
+# ----------------------------------------------------------------------
+
+ACCT, BEARER = "11111111-2222-4333-8444-555555555555", "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
+
+
+class FakeServer:
+ def __init__(self):
+ self.routes: dict = {}
+ self.calls: list = []
+
+ def on(self, method, prefix, *resps):
+ self.routes[(method, prefix)] = list(resps)
+
+ def __call__(self, method, path, *, body=None, timeout=15.0, headers=None):
+ self.calls.append((method, path, json.loads(json.dumps(body)) if body is not None else None))
+ for (m, prefix), resps in self.routes.items():
+ if m == method and path.startswith(prefix):
+ r = resps.pop(0) if len(resps) > 1 else resps[0]
+ if isinstance(r, cli.HttpError):
+ raise r
+ return json.loads(json.dumps(r))
+ raise cli.HttpError(404, {"error": "not routed"}, f"https://api{path}")
+
+
+def _bound(signer):
+ return {"bound": True, "entitlement": signer.mint(account_id=ACCT, session_token=BEARER),
+ "credentials": {"account_id": ACCT, "tenant_id": ACCT, "tier": "free", "email": "u@example.com",
+ "wallet": None, "issued_at": "2026-09-29T00:00:00Z", "bearer_token": BEARER}}
+
+
+@pytest.fixture
+def server(monkeypatch):
+ s = FakeServer()
+ monkeypatch.setattr(cli, "http_request", s)
+ monkeypatch.setattr(cli.time, "sleep", lambda *_: None)
+ monkeypatch.setattr(cli, "invalidate_tier_cache", lambda *a, **k: None)
+ opened: list = []
+ monkeypatch.setattr(cli.webbrowser, "open", lambda url, *a, **k: opened.append(url) or True)
+ s.opened = opened
+ s.on("POST", "/api/plugin/session-init", {"pairing_ttl_seconds": 300})
+ return s
+
+
+def _init(tmp_path, *extra):
+ cred = tmp_path / "c" / "credentials.json"
+ return cred, cli.main(["--credentials", str(cred), "--db", str(tmp_path / "c" / "m.db"),
+ "init", "--force", "--no-email", *extra])
+
+
+def test_409_at_session_init_without_a_terminal_prints_the_computers_and_what_to_do(
+ tmp_path, server, monkeypatch, capsys):
+ monkeypatch.setattr(cli, "_is_interactive", lambda: False)
+ monkeypatch.setattr(builtins, "input", lambda *a, **k: pytest.fail("no prompt without a terminal"))
+ server.on("POST", "/api/plugin/session-init", cli.HttpError(409, FIX["bind_409_body"], "u"))
+ cred, rc = _init(tmp_path)
+ out = capsys.readouterr().out
+ assert rc == 2 and not cred.exists()
+ assert "This account already has 1 computer signed in; Free is one computer." in out
+ assert "work-laptop" in out and "macos" in out and "last seen 2026-09-28 17:02 UTC" in out
+ assert "https://account.sibyllabs.org/security" in out and "sibyl init" in out
+ assert "Pro works on every computer you use: https://sibyllabs.org/pro" in out # R1B-4: no constant
+ assert "up to 10" not in out
+ assert BEARER not in out and "token" not in out.lower()
+
+
+def test_check_limit_in_a_terminal_asks_to_replace_and_no_is_the_default(tmp_path, server, monkeypatch,
+ capsys, test_signer):
+ monkeypatch.setattr(cli, "_is_interactive", lambda: True)
+ asked: list = []
+ monkeypatch.setattr(builtins, "input", lambda prompt="": asked.append(prompt) or "")
+ server.on("GET", "/api/plugin/check", FIX["check_at_limit"])
+ cred, rc = _init(tmp_path)
+ assert rc == 2 and not cred.exists()
+ assert asked == ["Open the account page to sign work-laptop out? [y/N]: "]
+ assert server.opened[-1].startswith("https://auth") or server.opened[-1].startswith("http")
+ assert "https://account.sibyllabs.org/security" not in server.opened
+
+
+def test_check_limit_yes_opens_the_security_page_and_keeps_waiting(tmp_path, server, monkeypatch,
+ capsys, test_signer):
+ monkeypatch.setattr(cli, "_is_interactive", lambda: True)
+ monkeypatch.setattr(builtins, "input", lambda prompt="": "y")
+ server.on("GET", "/api/plugin/check", FIX["check_at_limit"], FIX["check_at_limit"], _bound(test_signer))
+ cred, rc = _init(tmp_path)
+ out = capsys.readouterr().out
+ assert rc == 0 and cred.exists()
+ assert "https://account.sibyllabs.org/security" in server.opened
+ assert out.count("already has 1 computer signed in") == 1 # shown once
+ assert "This terminal keeps waiting." in out and "Activated." in out
+
+
+def test_a_409_on_check_is_the_limit_not_an_unexpected_error(tmp_path, server, monkeypatch, capsys):
+ monkeypatch.setattr(cli, "_is_interactive", lambda: False)
+ server.on("GET", "/api/plugin/check", cli.HttpError(409, FIX["bind_409_body"], "u"))
+ _cred, rc = _init(tmp_path)
+ out = capsys.readouterr().out
+ assert rc == 2 and "Unexpected error" not in out and "work-laptop" in out
+
+
+def test_reactivation_sends_replace_with_the_sign_in_this_computer_holds(tmp_path, server, test_signer,
+ monkeypatch):
+ monkeypatch.setattr(builtins, "input", lambda *a, **k: "")
+ server.on("GET", "/api/plugin/check", _bound(test_signer))
+ cred = tmp_path / "c" / "credentials.json"
+ cred.parent.mkdir(parents=True)
+ cred.write_text(json.dumps({"account_id": ACCT, "tenant_id": ACCT, "tier": "free",
+ "session_token": "old-bearer-0000"}))
+ _cred, rc = _init(tmp_path, "--replace")
+ assert rc == 0
+ body = [b for m, p, b in server.calls if p == "/api/plugin/session-init"][0]
+ assert body["replace"] == {"session_token": "old-bearer-0000"}
+ # a first activation sends no replace
+ server.calls.clear()
+ other = tmp_path / "fresh"
+ assert cli.main(["--credentials", str(other / "credentials.json"), "--db", str(other / "m.db"),
+ "init", "--no-email"]) == 0
+ body = [b for m, p, b in server.calls if p == "/api/plugin/session-init"][0]
+ assert "replace" not in body
+
+
+def test_an_old_api_without_the_limit_is_unchanged(tmp_path, server, test_signer, monkeypatch, capsys):
+ monkeypatch.setattr(builtins, "input", lambda *a, **k: "")
+ server.on("GET", "/api/plugin/check", {"bound": False}, {"bound": False, "limit": 3}, _bound(test_signer))
+ _cred, rc = _init(tmp_path)
+ assert rc == 0 and "computer signed in" not in capsys.readouterr().out
+
+
+# ----------------------------------------------------------------------
+# devices, status, the read-only row
+# ----------------------------------------------------------------------
+
+def _with_devices(sm, signer, devices, monkeypatch, **kw):
+ """The entitlement on disk and every refresh (sibyl status refreshes) carry
+ acct.devices, as the api does once it counts computers."""
+ from sibyl_memory_client import _entitlement as E
+ acct = {"complete": True, "email_verified": True, "email_required": False, "devices": devices}
+ write_entitlement(sm, signer.mint(acct=acct, **kw))
+ monkeypatch.setattr(E, "http_refresh", signer.refresh_fn(acct=acct, **kw))
+
+
+def test_devices_and_status_show_the_limit(sm, test_signer, monkeypatch, capsys):
+ _with_devices(sm, test_signer, FIX["entitlement_acct_devices_ok"], monkeypatch)
+ monkeypatch.setattr(cli, "_security_request", lambda *a, **k: {"devices": [
+ {"device_label": "this-one", "is_this_device": True, "install_method": "cli",
+ "last_seen_at": "2026-09-29T10:00:00Z", "bearer_id": "b1"}]})
+ assert cli.main(_acct(sm) + ["devices"]) == 0
+ out = capsys.readouterr().out
+ assert "1 active" in out and "1 of 1 (Free) · Pro: up to 10" in out
+ assert cli.main(_acct(sm) + ["status"]) == 0
+ out = capsys.readouterr().out
+ assert "Computers" in out and "1 of 1 (Free) · Pro: up to 10" in out
+
+
+def test_over_the_limit_reads_as_read_only_for_that_reason(sm, test_signer, monkeypatch, capsys):
+ _with_devices(sm, test_signer, FIX["entitlement_acct_devices_over"], monkeypatch, mem="read_only")
+ assert cli.main(_acct(sm) + ["status"]) == 0
+ out = capsys.readouterr().out
+ assert "read only on this computer · more computers signed in than the plan allows" in out
+ assert "confirm your email" not in out
+ assert "3 of 1 (Free)" in out and "over the limit" in out
+
+
+# ----------------------------------------------------------------------
+# sibyl skills proposals (plan 3.3)
+# ----------------------------------------------------------------------
+
+def test_proposals_without_an_account_and_on_free(tmp_path, sm, capsys):
+ assert cli.main(["--credentials", str(tmp_path / "none.json"), "skills", "proposals"]) == 0
+ assert "Not activated" in capsys.readouterr().out
+ assert cli.main(_acct(sm) + ["skills", "proposals"]) == 0
+ out = capsys.readouterr().out
+ assert "on Pro" in out and "candidate" not in out
+
+
+def _seed(sm: Path, verb: str = "deploy preview check") -> MemoryClient:
+ c = _client(sm)
+ start = time.time() - 3 * 86400
+ for i in range(4):
+ c.write_event(acted={"kind": verb},
+ ts=time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(start + i * 20 * 3600)))
+ c.learn()
+ return c
+
+
+def test_proposals_list_show_accept_writes_valid_skills_per_harness(home, pro, capsys):
+ assert cli.main(_acct(pro) + ["skills", "proposals"]) == 0
+ out = capsys.readouterr().out
+ assert "pending" in out and "none" in out
+ for d in (".claude", ".codex", ".hermes"):
+ (home / d).mkdir(exist_ok=True)
+ c = _seed(pro)
+ p = [x for x in c.learner().list_proposals() if x.pattern_kind == "repeated_action"][0]
+ assert cli.main(_acct(pro) + ["skills", "proposals"]) == 0
+ out = capsys.readouterr().out
+ assert p.id[:8] in out and "repeated_action" in out and "confidence" in out
+ assert cli.main(_acct(pro) + ["skills", "proposals", "show", p.id[:8]]) == 0
+ assert p.proposed_body.splitlines()[0] in capsys.readouterr().out
+ assert cli.main(_acct(pro) + ["skills", "proposals", "accept", p.id[:8]]) == 0
+ out = capsys.readouterr().out
+ name = SK.skill_name(p.proposed_slug)
+ for d in (home / ".claude" / "skills", home / ".codex" / "skills", home / ".hermes" / "skills"):
+ f = d / name / "SKILL.md"
+ assert f.exists(), f
+ assert SK.validate_skill_text(f.read_text(), name) == []
+ assert f"reference copy in memory as skill/{p.proposed_slug}" in out
+ assert c.learner().get_proposal(p.id).status == "accepted"
+ # accepting again rewrites nothing and says so
+ assert cli.main(_acct(pro) + ["skills", "proposals", "accept", p.id]) == 0
+ assert "already there" in capsys.readouterr().out
+
+
+def test_proposals_accept_to_a_folder_and_reject_mute_unmute(home, pro, tmp_path, capsys):
+ c = _seed(pro, "rotate the logs")
+ ps = [x for x in c.learner().list_proposals()]
+ assert len(ps) >= 2
+ dest = tmp_path / "skills-out"
+ assert cli.main(_acct(pro) + ["skills", "proposals", "accept", ps[0].id, "--to", str(dest)]) == 0
+ assert (dest / SK.skill_name(ps[0].proposed_slug) / "SKILL.md").exists()
+ capsys.readouterr()
+ assert cli.main(_acct(pro) + ["skills", "proposals", "reject", ps[1].id, "--note", "noise"]) == 0
+ out = capsys.readouterr().out
+ assert "not proposed again for 30 days" in out
+ assert c.learner().get_proposal(ps[1].id).review_note == "noise"
+ assert cli.main(_acct(pro) + ["skills", "proposals", "reject", ps[1].id]) == 1
+ assert cli.main(_acct(pro) + ["skills", "proposals", "mute", "co_occurrence", "--days", "7"]) == 0
+ st = ST.LifecycleState(home).load()
+ assert st["skills"]["muted_kinds"]["co_occurrence"] > time.time() + 6 * 86400
+ assert cli.main(_acct(pro) + ["skills", "proposals", "mute", "nonsense"]) == 1
+ assert cli.main(_acct(pro) + ["skills", "proposals", "unmute", "co_occurrence"]) == 0
+ assert "co_occurrence" not in ST.LifecycleState(home).load()["skills"]["muted_kinds"]
+ assert cli.main(_acct(pro) + ["skills", "proposals", "unmute", ps[1].proposed_slug]) == 0
+ assert ps[1].proposed_slug in ST.LifecycleState(home).load()["skills"]["unmuted"]
+ assert cli.main(_acct(pro) + ["skills", "proposals", "show", "zz"]) == 1
+
+
+def test_no_new_environment_switch_and_no_token_in_outputs(home, pro, tmp_path, capsys):
+ import re
+ for mod in ("lifecycle_cli.py", "hooks.py"):
+ src = (Path(cli.__file__).parent / mod).read_text()
+ assert not re.search(r"SIBYL_[A-Z_]*(AUTO|SAVE|SKILL|DEVICE)", src)
+ tok = json.loads((pro / "entitlement.json").read_text())["token"]
+ s = _Session(home, tmp_path, "tk", time.time() - 3 * 3600)
+ s.turn(1)
+ _bump(home, _tenant(pro), 6)
+ outs = [s.turn(25) for _ in range(4)]
+ cli.main(_acct(pro) + ["autosave"])
+ cli.main(_acct(pro) + ["skills", "proposals"])
+ text = "".join(outs) + capsys.readouterr().out + (pro / "lifecycle.log").read_text() \
+ + (pro / "lifecycle.json").read_text()
+ assert tok not in text and "session_token" not in text
+
+
+# ----------------------------------------------------------------------
+# R1B-4 (independent check of a7084df). On a7084df these fail: the status row
+# said "the most recently used computer" (F5); the prompt offered "Sign out
+# and use this computer instead?" and the upgrade line always said
+# "up to 10" (F8); a Stop request suppressed by the transcript guard was
+# still recorded (caps, interval) (F10a); one session's compaction made
+# another session due (F10b).
+# ----------------------------------------------------------------------
+
+def test_r1b4_status_over_the_limit_names_the_newest_sign_in(sm, test_signer, monkeypatch, capsys):
+ _with_devices(sm, test_signer, FIX["entitlement_acct_devices_over"], monkeypatch, mem="read_only")
+ assert cli.main(_acct(sm) + ["status"]) == 0
+ out = capsys.readouterr().out
+ assert "over the limit: new memories save only on the computer that signed in most recently" in out
+ assert "recently used" not in out
+
+
+def test_r1b4_the_prompt_says_the_terminal_cannot_sign_out_and_asks_to_open_the_page(
+ tmp_path, server, monkeypatch, capsys):
+ monkeypatch.setattr(cli, "_is_interactive", lambda: True)
+ seen: list = []
+
+ def ask(prompt=""):
+ seen.append((capsys.readouterr().out, prompt))
+ return ""
+ monkeypatch.setattr(builtins, "input", ask)
+ server.on("GET", "/api/plugin/check", FIX["check_at_limit"])
+ _cred, rc = _init(tmp_path)
+ assert rc == 2
+ before, prompt = seen[0]
+ assert "This terminal cannot sign another computer out; that is done on the account page." in before
+ assert prompt == "Open the account page to sign work-laptop out? [y/N]: "
+ assert "use this computer instead" not in prompt
+
+
+def test_r1b4_yes_opens_the_page_and_says_what_to_do_next(tmp_path, server, monkeypatch, capsys, test_signer):
+ monkeypatch.setattr(cli, "_is_interactive", lambda: True)
+ monkeypatch.setattr(builtins, "input", lambda prompt="": "y")
+ server.on("GET", "/api/plugin/check", FIX["check_at_limit"], _bound(test_signer))
+ _cred, rc = _init(tmp_path)
+ out = " ".join(capsys.readouterr().out.split())
+ assert rc == 0 and "https://account.sibyllabs.org/security" in server.opened
+ assert ("Next: choose Sign out next to work-laptop there, then finish the sign-in on the activation "
+ "page in your browser. This terminal keeps waiting.") in out
+
+
+def test_r1b4_upgrade_line_uses_the_server_pro_limit_when_sent(tmp_path, server, monkeypatch, capsys):
+ monkeypatch.setattr(cli, "_is_interactive", lambda: False)
+ server.on("POST", "/api/plugin/session-init", cli.HttpError(409, FIX["bind_409_body_with_pro_limit"], "u"))
+ _cred, rc = _init(tmp_path)
+ out = capsys.readouterr().out
+ assert rc == 2 and "Pro works on every computer you use (up to 10): https://sibyllabs.org/pro" in out
+ for bad in (True, "10", -1, 0):
+ server.on("POST", "/api/plugin/session-init",
+ cli.HttpError(409, dict(FIX["bind_409_body"], pro_limit=bad), "u"))
+ _init(tmp_path)
+ out = capsys.readouterr().out
+ assert "Pro works on every computer you use: https://sibyllabs.org/pro" in out, bad
+
+
+def test_r1b4_a_paid_account_at_its_limit_gets_no_upgrade_line(tmp_path, server, monkeypatch, capsys):
+ monkeypatch.setattr(cli, "_is_interactive", lambda: False)
+ body = dict(FIX["bind_409_body"], tier="pro", limit=10)
+ server.on("POST", "/api/plugin/session-init", cli.HttpError(409, body, "u"))
+ _cred, rc = _init(tmp_path)
+ out = capsys.readouterr().out
+ assert rc == 2 and "its plan allows 10" in out and "Pro works" not in out
+
+
+def test_r1b4_a_request_suppressed_by_the_transcript_guard_costs_nothing(home, pro, tmp_path):
+ tid = _tenant(pro)
+ s = _Session(home, tmp_path, "hx", time.time() - 8 * 3600)
+ s.turn(1)
+ _bump(home, tid, 2)
+ for _ in range(2):
+ assert s.turn(25) == ""
+ # The state lost request 1, which the transcript already holds.
+ s.tr.write_text(s.tr.read_text() + json.dumps({"type": "user", "content": H.stop_reason(1)}) + "\n")
+ assert s.turn(15) == "" # due, but suppressed
+ st = ST.LifecycleState(home).load()
+ assert s.state["nudges"] == [] and s.state["last_nudge_active"] is None
+ assert ST.nudges_today(st["tenants"][tid], s.t) == 0 and s.state["seq_floor"] == 1
+ assert "already in the transcript" in (pro / "lifecycle.log").read_text()
+ out = s.turn(1) # still due: the next request, numbered past it
+ assert json.loads(out)["reason"] == H.stop_reason(2)
+ st = ST.LifecycleState(home).load()
+ assert len(s.state["nudges"]) == 1 and ST.nudges_today(st["tenants"][tid], s.t) == 1
+
+
+def test_r1b4_suppressed_requests_do_not_eat_the_daily_cap(home, pro, tmp_path):
+ tid = _tenant(pro)
+ s = _Session(home, tmp_path, "hd", time.time() - 8 * 3600)
+ s.turn(1)
+ _bump(home, tid, 2)
+ ST.LifecycleState(home).update(lambda st: ST.tenant(st, tid).update(
+ nudges_day=time.strftime("%Y-%m-%d", time.localtime(s.t)), nudges_today=11))
+ s.turn(25)
+ s.turn(25)
+ s.tr.write_text(s.tr.read_text() + json.dumps({"type": "user", "content": H.stop_reason(1)}) + "\n")
+ assert s.turn(15) == ""
+ assert json.loads(s.turn(1))["reason"] == H.stop_reason(2) # the 12th of the day is still available
+ assert s.turn(1) == "" # and then the cap holds
+
+
+def test_r1b4_one_sessions_compaction_does_not_make_another_due(home, pro, tmp_path):
+ tid = _tenant(pro)
+ t0 = time.time() - 4 * 3600
+ a = _Session(home, tmp_path, "ca", t0)
+ b = _Session(home, tmp_path, "cb", t0)
+ for x in (a, b):
+ x.turn(1)
+ _bump(home, tid, 1)
+ _hook("pre-compact", {"session_id": "ca", "trigger": "auto"}, home, a.t + 30)
+ assert b.turn(2) == "" # B was not compacted
+ a.t += 60
+ assert json.loads(a.turn(2))["reason"] == H.stop_reason(1)
+ assert b.state["compaction_seen"] is False and a.state["compaction_seen"] is True
+
+
+def test_r1b4_free_compaction_reminder_stays_in_its_session(home, sm, tmp_path):
+ tid = _tenant(sm)
+ now = time.time()
+ _hook("session-start", {"session_id": "fa", "cwd": str(tmp_path)}, home, now)
+ _hook("session-start", {"session_id": "fb", "cwd": str(tmp_path)}, home, now)
+ _bump(home, tid, 1)
+ _hook("pre-compact", {"session_id": "fa", "trigger": "auto"}, home, now + 5)
+ assert _hook("prompt", {"session_id": "fb"}, home, now + 10) == ""
+ out = json.loads(_hook("prompt", {"session_id": "fa"}, home, now + 20))
+ assert out["hookSpecificOutput"]["additionalContext"].startswith("Sibyl Memory: 1 writes since the last save.")
diff --git a/sibyl-memory-cli/tests/test_release_fixes_2026_09_27.py b/sibyl-memory-cli/tests/test_release_fixes_2026_09_27.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd7aea37a265a21de5f3efbc8e1d7d53c05233bf
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_release_fixes_2026_09_27.py
@@ -0,0 +1,150 @@
+"""Release fix batch (GATE-15): the CLI's session calls and the setup copy.
+
+`_bearer_headers` (used by /access, /email-verify/*, /upgrade-nonce,
+/stripe-claim) refreshes first when this computer holds no usable token (the
+same ensure-fresh path the security calls use). When the api answers 403
+client_too_old and this CLI still holds no token, the plugin is not too old:
+setup is not finished, so the line says to connect once, not to update.
+"""
+from __future__ import annotations
+
+import json
+import time
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import _account_gate as G
+from sibyl_memory_client import _entitlement as E
+from sibyl_memory_client.testing import write_entitlement
+
+from test_account_gate_2026_09_27 import ( # noqa: F401 (fixtures)
+ ACCESS,
+ BEARER,
+ _fast,
+ err,
+ mint,
+ refresh,
+ run,
+ server,
+ write_creds,
+)
+
+CS = "cs_test_" + "a" * 40
+
+
+def _setup(tmp_path, monkeypatch, *, token=None, past=False, signer=None):
+ cred = write_creds(tmp_path / "credentials.json")
+ monkeypatch.setattr(cli, "_ENT_CRED_PATH", cred)
+ if token == "past":
+ t = time.time() - 20 * 86400
+ write_entitlement(tmp_path, mint(signer, now=t), received_at=t)
+ elif token == "fresh":
+ write_entitlement(tmp_path, mint(signer))
+ return cred
+
+
+# ---- refresh first -----------------------------------------------------
+
+def test_bearer_headers_refresh_first_when_the_token_is_past_grace(tmp_path, monkeypatch, test_signer, refresh) -> None:
+ cred = _setup(tmp_path, monkeypatch, token="past", signer=test_signer)
+ fresh = mint(test_signer)
+ refresh["outcome"] = E.RefreshOutcome("ok", token=fresh)
+ h = cli._bearer_headers(json.loads(cred.read_text()))
+ assert refresh["calls"] == 1
+ assert h["X-Sibyl-Entitlement"] == fresh and h["Authorization"] == f"Bearer {BEARER}"
+
+
+def test_bearer_headers_refresh_first_when_there_is_no_token(tmp_path, monkeypatch, test_signer, refresh) -> None:
+ cred = _setup(tmp_path, monkeypatch)
+ fresh = mint(test_signer)
+ refresh["outcome"] = E.RefreshOutcome("ok", token=fresh)
+ h = cli._bearer_headers(json.loads(cred.read_text()))
+ assert refresh["calls"] == 1 and h["X-Sibyl-Entitlement"] == fresh
+
+
+def test_bearer_headers_do_not_refresh_a_usable_token(tmp_path, monkeypatch, test_signer, refresh) -> None:
+ cred = _setup(tmp_path, monkeypatch, token="fresh", signer=test_signer)
+ h = cli._bearer_headers(json.loads(cred.read_text()))
+ assert refresh["calls"] == 0 and "X-Sibyl-Entitlement" in h
+
+
+def test_bearer_headers_refresh_failure_sends_no_token(tmp_path, monkeypatch, test_signer, refresh) -> None:
+ cred = _setup(tmp_path, monkeypatch, token="past", signer=test_signer)
+ refresh["outcome"] = E.RefreshOutcome("transient", code="offline")
+ h = cli._bearer_headers(json.loads(cred.read_text()))
+ assert refresh["calls"] == 1
+ assert "X-Sibyl-Entitlement" not in h and h["Authorization"] == f"Bearer {BEARER}"
+
+
+@pytest.mark.parametrize("which", ["access", "email_request", "email_confirm", "upgrade_nonce", "stripe_claim"])
+def test_every_bearer_call_carries_the_refreshed_token(which, tmp_path, monkeypatch, server, test_signer, refresh) -> None:
+ cred = _setup(tmp_path, monkeypatch, token="past", signer=test_signer)
+ fresh = mint(test_signer)
+ refresh["outcome"] = E.RefreshOutcome("ok", token=fresh)
+ creds = json.loads(cred.read_text())
+ server.on("POST", "/api/plugin/access", ACCESS)
+ server.on("POST", "/api/plugin/email-verify/request", {"ok": True, "sent": True})
+ server.on("POST", "/api/plugin/email-verify/confirm", {"ok": True})
+ server.on("POST", "/api/plugin/upgrade-nonce", {"exchange_url": "https://account.sibyllabs.org/x"})
+ server.on("POST", "/api/plugin/stripe-claim", {"ok": True})
+ path = {
+ "access": ("/api/plugin/access", lambda: cli._fetch_access_ex(creds)),
+ "email_request": ("/api/plugin/email-verify/request", lambda: cli._email_request(creds, None)),
+ "email_confirm": ("/api/plugin/email-verify/confirm",
+ lambda: cli._email_confirm_once_h(creds, "123456", cred)[:2]),
+ "upgrade_nonce": ("/api/plugin/upgrade-nonce",
+ lambda: cli._upgrade_exchange_url(creds, creds["account_id"])),
+ "stripe_claim": ("/api/plugin/stripe-claim", lambda: run(["claim", CS], cred, tmp_path)),
+ }[which]
+ path[1]()
+ call = server.calls_to(path[0])[0]
+ assert call["headers"].get("X-Sibyl-Entitlement") == fresh
+
+
+# ---- client_too_old without a token = setup not finished ------------------
+
+def test_client_too_old_without_a_token_prints_the_setup_line(tmp_path, monkeypatch, server, refresh, capsys) -> None:
+ cred = _setup(tmp_path, monkeypatch)
+ refresh["outcome"] = E.RefreshOutcome("transient", code="offline")
+ server.on("POST", "/api/plugin/email-verify/confirm", err(403, {"code": "client_too_old", "error": "x"}))
+ run(["email", "confirm", "123456"], cred, tmp_path)
+ out = capsys.readouterr().out
+ assert "connect to the internet once to finish setup" in out
+ assert "pip install -U" not in out and "update the plugin" not in out
+
+
+def test_client_too_old_with_a_token_still_says_update(tmp_path, monkeypatch, server, test_signer, capsys) -> None:
+ cred = _setup(tmp_path, monkeypatch, token="fresh", signer=test_signer)
+ server.on("POST", "/api/plugin/email-verify/confirm", err(403, {"code": "client_too_old", "error": "x"}))
+ run(["email", "confirm", "123456"], cred, tmp_path)
+ out = capsys.readouterr().out
+ assert "pip install -U" in out and "finish setup" not in out
+
+
+@pytest.mark.parametrize("surface", ["devices", "claim", "upgrade_nonce"])
+def test_setup_line_on_every_gate_surface(surface, tmp_path, monkeypatch, server, refresh, capsys) -> None:
+ cred = _setup(tmp_path, monkeypatch)
+ refresh["outcome"] = E.RefreshOutcome("transient", code="offline")
+ too_old = err(403, {"code": "client_too_old", "error": "x"})
+ server.on("GET", "/api/plugin/devices", too_old)
+ server.on("POST", "/api/plugin/stripe-claim", too_old)
+ server.on("POST", "/api/plugin/upgrade-nonce", too_old)
+ if surface == "devices":
+ run(["devices"], cred, tmp_path)
+ elif surface == "claim":
+ run(["claim", CS], cred, tmp_path)
+ else:
+ cli._upgrade_exchange_url(json.loads(cred.read_text()), "x")
+ out = capsys.readouterr().out
+ assert "connect to the internet once to finish setup" in out and "pip install -U" not in out
+
+
+def test_gate_http_line_contract(tmp_path, test_signer) -> None:
+ cred = write_creds(tmp_path / "credentials.json")
+ assert G.gate_http_line(403, "client_too_old") == G.CLIENT_TOO_OLD_LINE
+ assert G.gate_http_line(403, "client_too_old", cred_path=cred) == G.SETUP_INCOMPLETE_LINE
+ write_entitlement(tmp_path, mint(test_signer))
+ assert G.gate_http_line(403, "client_too_old", cred_path=cred) == G.CLIENT_TOO_OLD_LINE
+ assert "connect to the internet once to finish setup" in G.SETUP_INCOMPLETE_LINE
+ assert G.gate_http_line(403, "entitlement_invalid", cred_path=cred) == G.ENTITLEMENT_INVALID_LINE
diff --git a/sibyl-memory-cli/tests/test_sd_final_cli_2026_09_27.py b/sibyl-memory-cli/tests/test_sd_final_cli_2026_09_27.py
new file mode 100644
index 0000000000000000000000000000000000000000..02cf1ab1fb998f247a528fd6f79c502433dda0ca
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_sd_final_cli_2026_09_27.py
@@ -0,0 +1,148 @@
+"""Final fixes on the save/debloat build, CLI side (SD-11.., 2026-09-27).
+
+C `--root` given through a symlink names the real files (one authorisation,
+ one backup slot); a stow-style ``~/.claude`` symlink is trimmed by an
+ interactive free apply;
+D `sibyl debloat undo` without a file undoes the exact file the last apply
+ trimmed (matched on its path identity), never the same NAME elsewhere.
+
+Each test fails on 4abce3a (the docstring says how).
+"""
+from __future__ import annotations
+
+import json
+import os
+import time
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_client.lifecycle import apply as A
+from sibyl_memory_client.lifecycle import policy as P
+from sibyl_memory_client.lifecycle import state as ST
+
+CURRENT = "# Agent rules\n\n" + "".join(f"- rule {i} stays current\n" for i in range(10)) + "\n"
+HIST = "## History\n" + "".join(f"- an old decision number {i} that is history now\n" for i in range(12))
+
+
+@pytest.fixture(autouse=True)
+def _quiet(monkeypatch):
+ monkeypatch.setenv("SIBYL_MEMORY_TELEMETRY", "0")
+ monkeypatch.setenv("NO_COLOR", "1")
+
+
+@pytest.fixture(autouse=True)
+def _offline_server(monkeypatch):
+ from sibyl_memory_client import _capcheck
+ monkeypatch.setattr(_capcheck, "_default_check_write_fn",
+ lambda url, payload, timeout=4.0: {"ok": True, "tier": "free", "cap_bytes": 5242880})
+
+ def offline(*a, **k):
+ raise cli.HttpError(0, {}, "offline")
+ monkeypatch.setattr(cli, "http_request", offline)
+
+
+@pytest.fixture
+def home():
+ return Path.home()
+
+
+@pytest.fixture
+def sm(home):
+ return home / ".sibyl-memory"
+
+
+def _write(p: Path, text: str) -> Path:
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text)
+ t = time.time() - 3600
+ os.utime(p, (t, t))
+ return p
+
+
+def _acct(sm: Path) -> list[str]:
+ return ["--credentials", str(sm / "credentials.json"), "--db", str(sm / "memory.db")]
+
+
+def test_c_root_through_a_symlink_trims_the_real_file(tmp_path, sm, home, capsys, monkeypatch):
+ """4abce3a refused every file under a `--root` reached through a symlink."""
+ f = _write(tmp_path / "real" / "proj" / "AGENTS.md", CURRENT + HIST)
+ link = tmp_path / "link"
+ link.symlink_to(tmp_path / "real", target_is_directory=True)
+ monkeypatch.chdir(tmp_path)
+ assert cli.main(_acct(sm) + ["debloat", "apply", "AGENTS.md", "--yes", "--root",
+ str(link / "proj")]) == 0, capsys.readouterr().out
+ assert "old decision number 3" not in f.read_text() and link.is_symlink()
+ assert (tmp_path / "real" / "proj" / "AGENTS-history.md").is_file()
+ rec = ST.LifecycleState(home).load()["debloat"]["last_apply"]["results"][0]
+ assert rec["id"] == f.as_posix() and rec["applied"]
+ # The same file from the real root: one backup slot, undo finds it.
+ assert cli.main(_acct(sm) + ["debloat", "undo", "AGENTS.md", "--yes", "--root",
+ str(tmp_path / "real" / "proj")]) == 0
+ assert "old decision number 3" in f.read_text()
+
+
+def test_c_auto_through_a_symlinked_root_stores_the_real_path(tmp_path, sm, home, capsys, monkeypatch):
+ f = _write(tmp_path / "real" / "proj" / "AGENTS.md", CURRENT + HIST)
+ link = tmp_path / "link"
+ link.symlink_to(tmp_path / "real", target_is_directory=True)
+ monkeypatch.chdir(tmp_path)
+ assert cli.main(_acct(sm) + ["debloat", "auto", "AGENTS.md", "--yes", "--root",
+ str(link / "proj")]) == 0
+ assert P.load(home)["auto_files"] == [f.as_posix()]
+ assert cli.main(_acct(sm) + ["debloat", "manual", str(link / "proj" / "AGENTS.md"),
+ "--root", str(tmp_path)]) == 0
+ assert P.load(home)["auto_files"] == []
+
+
+def test_c_stow_dot_claude_is_trimmed_by_a_free_interactive_apply(tmp_path, sm, home, capsys, monkeypatch):
+ """4abce3a: 'refused: ~/.claude is a symlink' for every stow user."""
+ f = _write(home / "dotfiles" / "claude" / "CLAUDE.md", CURRENT + HIST)
+ (home / ".claude").symlink_to(home / "dotfiles" / "claude", target_is_directory=True)
+ proj = tmp_path / "proj"
+ proj.mkdir()
+ monkeypatch.chdir(proj)
+ assert cli.main(_acct(sm) + ["debloat", "apply", "~/.claude/CLAUDE.md", "--yes"]) == 0, \
+ capsys.readouterr().out
+ assert "old decision number 3" not in f.read_text() and (home / ".claude").is_symlink()
+ assert (home / "dotfiles" / "claude" / "CLAUDE-history.md").is_file()
+
+
+def test_d_bare_undo_never_restores_the_same_name_in_another_project(tmp_path, sm, home, capsys,
+ monkeypatch):
+ """4abce3a matched the last apply on its bare label: after trimming
+ repo-a/AGENTS.md, a bare `sibyl debloat undo` in repo-b restored
+ repo-b's AGENTS.md from repo-b's own backup."""
+ a = _write(tmp_path / "repo-a" / "AGENTS.md", CURRENT + HIST)
+ b = _write(tmp_path / "repo-b" / "AGENTS.md", CURRENT + HIST)
+ a_orig = a.read_bytes()
+ monkeypatch.chdir(b.parent)
+ assert cli.main(_acct(sm) + ["debloat", "apply", "AGENTS.md", "--yes"]) == 0
+ b_trimmed = b.read_bytes()
+ monkeypatch.chdir(a.parent)
+ assert cli.main(_acct(sm) + ["debloat", "apply", "AGENTS.md", "--yes"]) == 0
+ capsys.readouterr()
+ monkeypatch.chdir(b.parent)
+ assert cli.main(_acct(sm) + ["debloat", "undo", "--yes"]) == 1
+ out = capsys.readouterr().out
+ assert a.as_posix() in out and "run `sibyl debloat undo ` where it lives" in out
+ assert b.read_bytes() == b_trimmed
+ monkeypatch.chdir(a.parent)
+ assert cli.main(_acct(sm) + ["debloat", "undo", "--yes"]) == 0
+ assert a.read_bytes() == a_orig and b.read_bytes() == b_trimmed
+
+
+def test_d_a_record_without_an_id_asks_for_the_file(tmp_path, sm, home, capsys, monkeypatch):
+ f = _write(tmp_path / "proj" / "AGENTS.md", CURRENT + HIST)
+ monkeypatch.chdir(f.parent)
+ assert cli.main(_acct(sm) + ["debloat", "apply", "AGENTS.md", "--yes"]) == 0
+ trimmed = f.read_bytes()
+
+ def strip(st):
+ for r in st["debloat"]["last_apply"]["results"]:
+ r.pop("id", None)
+ ST.LifecycleState(home).update(strip)
+ capsys.readouterr()
+ assert cli.main(_acct(sm) + ["debloat", "undo", "--yes"]) == 1
+ assert "name the file" in capsys.readouterr().out and f.read_bytes() == trimmed
diff --git a/sibyl-memory-cli/tests/test_sd_fixes_cli_2026_09_27.py b/sibyl-memory-cli/tests/test_sd_fixes_cli_2026_09_27.py
new file mode 100644
index 0000000000000000000000000000000000000000..79d6469c51d29885fb5276a184f8cdf906ba8f07
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_sd_fixes_cli_2026_09_27.py
@@ -0,0 +1,463 @@
+"""Independent-check fixes on the save/debloat build, CLI side (SD-7.., 2026-09-27).
+
+Each test fails on a6338cc (the docstring says how when it is behavioural).
+"""
+from __future__ import annotations
+
+import builtins
+import json
+import os
+import time
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import lifecycle_cli as LC
+from sibyl_memory_client.lifecycle import apply as A
+from sibyl_memory_client.lifecycle import policy as P
+from sibyl_memory_client.testing import write_entitlement
+
+CURRENT = "# Agent rules\n\n" + "".join(f"- rule {i} stays current\n" for i in range(10)) + "\n"
+HIST = "## History\n" + "".join(f"- an old decision number {i} that is history now\n" for i in range(12))
+
+
+@pytest.fixture(autouse=True)
+def _quiet(monkeypatch):
+ monkeypatch.setenv("SIBYL_MEMORY_TELEMETRY", "0")
+ monkeypatch.setenv("NO_COLOR", "1")
+
+
+@pytest.fixture(autouse=True)
+def _offline_server(monkeypatch):
+ from sibyl_memory_client import _capcheck
+ monkeypatch.setattr(_capcheck, "_default_check_write_fn",
+ lambda url, payload, timeout=4.0: {"ok": True, "tier": "pro", "cap_bytes": None})
+
+ def offline(*a, **k):
+ raise cli.HttpError(0, {}, "offline")
+ monkeypatch.setattr(cli, "http_request", offline)
+
+
+@pytest.fixture
+def home():
+ return Path.home()
+
+
+@pytest.fixture
+def sm(home):
+ return home / ".sibyl-memory"
+
+
+@pytest.fixture
+def pro(sm, test_signer):
+ write_entitlement(sm, test_signer.mint(tier="pro", cap=None, src="pro"))
+ return sm
+
+
+def _write(p: Path, text: str) -> Path:
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text)
+ t = time.time() - 3600
+ os.utime(p, (t, t))
+ return p
+
+
+def _acct(sm: Path) -> list[str]:
+ return ["--credentials", str(sm / "credentials.json"), "--db", str(sm / "memory.db")]
+
+
+# ----------------------------------------------------------------------
+# F1
+# ----------------------------------------------------------------------
+
+def test_f1_auto_names_this_file_at_its_path_and_manual_takes_it_back(tmp_path, pro, home, capsys,
+ monkeypatch):
+ """a6338cc stored the bare name 'AGENTS.md' and said 'Automatic context
+ trim for AGENTS.md', which then matched AGENTS.md in every project."""
+ a = _write(tmp_path / "repo-a" / "AGENTS.md", CURRENT + HIST)
+ b = _write(tmp_path / "repo-b" / "AGENTS.md", CURRENT + HIST)
+ monkeypatch.chdir(a.parent)
+ asked: list[str] = []
+ monkeypatch.setattr(LC.sys.stdin, "isatty", lambda: True, raising=False)
+ monkeypatch.setattr(builtins, "input", lambda q="": asked.append(q) or "y")
+ assert cli.main(_acct(pro) + ["debloat", "auto", "AGENTS.md"]) == 0
+ out = capsys.readouterr().out
+ fid_a = P.auth_id(a, home)
+ assert f"Automatic context trim for this file at {fid_a} means:" in out
+ assert "a file with the same name in another project" in out
+ assert asked == [f"Let Sibyl trim this file at {fid_a} automatically? [y/N]: "]
+ assert P.load(home)["auto_files"] == [fid_a]
+ # `manual AGENTS.md` in repo-b removes nothing: that file was never on auto.
+ monkeypatch.chdir(b.parent)
+ assert cli.main(_acct(pro) + ["debloat", "manual", "AGENTS.md"]) == 0
+ assert "was not on automatic; nothing changed" in capsys.readouterr().out
+ assert P.load(home)["auto_files"] == [fid_a]
+ # By path, from anywhere.
+ assert cli.main(_acct(pro) + ["debloat", "manual", fid_a]) == 0
+ assert P.load(home)["auto_files"] == [] and P.load(home)["mode"] == "propose"
+
+
+def test_f1_cli_shows_the_one_time_notice_for_name_only_entries(tmp_path, sm, home, capsys, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ (sm / "debloat.json").write_text(json.dumps({"mode": "auto", "auto_files": ["AGENTS.md"]}))
+ cli.main(_acct(sm) + ["debloat", "plan"])
+ out = capsys.readouterr().out
+ assert "AGENTS.md was set by name only and is back to manual" in out
+ cli.main(_acct(sm) + ["debloat", "plan"])
+ assert "set by name only" not in capsys.readouterr().out
+ assert json.loads((sm / "debloat.json").read_text())["auto_files"] == []
+
+
+# ----------------------------------------------------------------------
+# F4
+# ----------------------------------------------------------------------
+
+def test_f4_undo_restores_the_backup_the_last_apply_recorded(tmp_path, sm, home, capsys, monkeypatch):
+ """a6338cc restored the newest backup; after an interrupted later attempt
+ that copy equals the trimmed file, so undo 'restored' nothing."""
+ f = _write(tmp_path / "proj" / "AGENTS.md", CURRENT + HIST)
+ original = f.read_bytes()
+ monkeypatch.chdir(f.parent)
+ assert cli.main(_acct(sm) + ["debloat", "apply", "AGENTS.md", "--yes"]) == 0
+ trimmed = f.read_bytes()
+ assert trimmed != original
+ A.backup(f, trimmed, home=home, cwd=f.parent, now=time.time() + 60) # the interrupted attempt
+ capsys.readouterr()
+ assert cli.main(_acct(sm) + ["debloat", "undo", "AGENTS.md", "--yes"]) == 0
+ assert f.read_bytes() == original
+ # Undoing again: the recorded backup now equals the file; refused, clearly.
+ assert cli.main(_acct(sm) + ["debloat", "undo", "AGENTS.md", "--yes"]) == 1
+ assert "nothing to undo" in capsys.readouterr().out and f.read_bytes() == original
+
+
+# ----------------------------------------------------------------------
+# F5: the Claude Code hook path is bounded and never touches the network
+# ----------------------------------------------------------------------
+
+from sibyl_memory_cli import hooks as H # noqa: E402
+from sibyl_memory_client.lifecycle import state as ST # noqa: E402
+
+
+def _hook(event, payload, home, **kw):
+ return H.run_hook(event, payload if isinstance(payload, str) else json.dumps(payload), home=home, **kw)
+
+
+def _warm_tier_cache(sm: Path) -> None:
+ from sibyl_memory_client._capcheck import TierCache, TierCacheEntry
+ acct = json.loads((sm / "credentials.json").read_text())["account_id"]
+ TierCache(sm / "tier_cache.json").store(TierCacheEntry(account_id=acct, tier="pro",
+ checked_at=time.time(), cap_bytes=None))
+
+
+@pytest.fixture
+def slow_net(monkeypatch):
+ """/check-write that would take 3 s (then fail), counted."""
+ from sibyl_memory_client import _capcheck
+ calls = []
+
+ def slow(url, payload, timeout=4.0):
+ calls.append(url)
+ time.sleep(3)
+ raise _capcheck.TierVerificationError("unreachable")
+ monkeypatch.setattr(_capcheck, "_default_check_write_fn", slow)
+ return calls
+
+
+def test_f5_pro_start_without_a_tier_cache_plans_only_and_calls_no_network(tmp_path, pro, home, slow_net):
+ """a6338cc applied through the gated client, whose /check-write (4 s
+ timeout, two retries) outlived Claude Code's 5 s hook timeout."""
+ f = _write(tmp_path / "p" / "AGENTS.md", CURRENT + HIST)
+ before = f.read_bytes()
+ P.set_auto(P.auth_id(f, home), True, home)
+ t = time.monotonic()
+ out = _hook("session-start", {"session_id": "s", "cwd": str(f.parent)}, home)
+ assert time.monotonic() - t < 1.5 and slow_net == []
+ line = json.loads(out)["hookSpecificOutput"]["additionalContext"]
+ assert "AGENTS.md is set to automatic; it is trimmed at a later start" in line
+ assert f.read_bytes() == before
+ assert not A.backups_root(home).exists() or list(A.backups_root(home).iterdir()) == []
+ assert "plan only: no fresh tier cache" in (pro / "lifecycle.log").read_text()
+ # With a fresh tier cache (what any MCP write leaves) the next start applies.
+ _warm_tier_cache(pro)
+ ST.LifecycleState(home).update(lambda st: st["debloat"].clear())
+ out = _hook("session-start", {"session_id": "s2", "cwd": str(f.parent)}, home)
+ assert "history stored to memory as debloat/AGENTS.md/" in out and slow_net == []
+
+
+def test_f5_capsules_wait_for_a_tier_cache_and_the_write_budget(tmp_path, pro, home, slow_net, monkeypatch):
+ """a6338cc wrote the capsule through /check-write inside the hook."""
+ _hook("session-start", {"session_id": "c", "cwd": str(tmp_path)}, home)
+ t = time.monotonic()
+ _hook("pre-compact", {"session_id": "c"}, home)
+ assert time.monotonic() - t < 1.5 and slow_net == []
+ log = (pro / "lifecycle.log").read_text()
+ assert "capsule not written (no fresh tier cache" in log
+ from sibyl_memory_client import MemoryClient
+ reader = MemoryClient.local(str(pro / "memory.db"), tenant_id=json.loads(
+ (pro / "credentials.json").read_text())["tenant_id"], credentials_path=pro / "credentials.json")
+ _warm_tier_cache(pro)
+ monkeypatch.setattr(H, "WRITE_BUDGET_SECONDS", 0.0)
+ _hook("pre-compact", {"session_id": "c"}, home)
+ assert "capsule not written (out of time)" in (pro / "lifecycle.log").read_text()
+ monkeypatch.setattr(H, "WRITE_BUDGET_SECONDS", 2.5)
+ _hook("session-end", {"session_id": "c"}, home)
+ kinds = [e["acted"]["kind"] for e in reader.read_events(limit=10)]
+ assert kinds == ["session_capsule"] and slow_net == []
+
+
+def test_f5_the_hook_client_never_refreshes_and_sends_no_heartbeat(pro, home):
+ """a6338cc's hook client refreshed the entitlement in a background thread
+ and flushed the usage heartbeat (4 s timeout) at process exit."""
+ from sibyl_memory_client._heartbeat import _NullHeartbeat
+ creds = json.loads((pro / "credentials.json").read_text())
+ c = H._pro_client(pro / "memory.db", pro / "credentials.json", creds, creds["tenant_id"])
+ assert isinstance(c._heartbeat, _NullHeartbeat)
+ assert c.entitlement_gate._allow_refresh is False
+
+
+def test_f5_a_start_that_used_up_its_budget_only_plans(tmp_path, pro, home, monkeypatch):
+ f = _write(tmp_path / "p" / "AGENTS.md", CURRENT + HIST)
+ before = f.read_bytes()
+ P.set_auto(P.auth_id(f, home), True, home)
+ _warm_tier_cache(pro)
+ out = _hook("session-start", {"session_id": "b", "cwd": str(f.parent)}, home,
+ started=time.monotonic() - 10)
+ assert "is set to automatic; it is trimmed at a later start" in out and f.read_bytes() == before
+
+
+# ----------------------------------------------------------------------
+# F11: free hooks return before the client, the verification and the DB
+# ----------------------------------------------------------------------
+
+def test_f11_paid_tier_literal_matches_the_client():
+ # The hooks mirror is the client's ONE paid set (tier convention 2026-10-05).
+ from sibyl_memory_client.tiers import PAID_TIERS
+ from sibyl_memory_client.lifecycle.entitled import PAID_TIERS as ENTITLED
+ assert H.PAID_TIERS == PAID_TIERS == ENTITLED
+
+
+def test_f11_claims_paid_for_elite_any_case_and_not_for_an_unknown_label(sm, test_signer):
+ for label, want in (("elite", True), (" Elite ", True), ("gold", False)):
+ write_entitlement(sm, test_signer.mint(tier=label))
+ assert H.claims_paid(sm / "credentials.json") is want, label
+
+
+def test_f11_claims_paid_reads_the_unverified_claim_and_a_forged_claim_unlocks_nothing(
+ tmp_path, sm, home, test_signer):
+ assert H.claims_paid(sm / "credentials.json") is False # the free test home
+ # A hand-edited claim of "pro" with a bad signature: the fast path sends it
+ # to the verified check, which refuses it.
+ tok = test_signer.mint(tier="free")
+ head, seg, sig = tok.split(".")
+ import base64
+ claim = json.loads(base64.urlsafe_b64decode(seg + "=" * (-len(seg) % 4)))
+ claim["tier"] = "pro"
+ forged = ".".join([head, base64.urlsafe_b64encode(json.dumps(claim).encode()).decode().rstrip("="), sig])
+ write_entitlement(sm, forged)
+ assert H.claims_paid(sm / "credentials.json") is True
+ tid = json.loads((sm / "credentials.json").read_text())["tenant_id"]
+ _hook("session-start", {"session_id": "x", "cwd": str(tmp_path)}, home)
+ ST.LifecycleState(home).update(lambda st: ST.tenant(st, tid).update(writes_total=50))
+ assert _hook("stop", {"session_id": "x", "stop_hook_active": False}, home) == ""
+
+
+def test_f11_free_pre_compact_and_session_end_skip_verification_and_the_db(tmp_path, sm, home, monkeypatch):
+ """a6338cc verified the entitlement and opened memory.db on every free
+ PreCompact / SessionEnd."""
+ from sibyl_memory_client.lifecycle import entitled as EN
+ seen = []
+ monkeypatch.setattr(EN, "automation_allowed_for_credentials", lambda *a, **k: seen.append("verify") or (False, "free"))
+ monkeypatch.setattr(ST, "read_save_marker", lambda *a, **k: seen.append("db") or None)
+ _hook("pre-compact", {"session_id": "f", "trigger": "auto"}, home)
+ _hook("session-end", {"session_id": "f", "reason": "other"}, home)
+ _hook("stop", {"session_id": "f", "stop_hook_active": False}, home)
+ assert seen == []
+ tid = json.loads((sm / "credentials.json").read_text())["tenant_id"]
+ st = ST.LifecycleState(home).load()
+ assert st["sessions"][ST.session_key("f")]["compaction_seen"] is True # R1B-4: per session
+ assert "compaction_seen" not in st["tenants"][tid]
+ assert st["sessions"][ST.session_key("f")]["ended_at"]
+
+
+def _run_entry(home: Path, event: str, payload: dict, probe: str) -> str:
+ import subprocess
+ import sys
+ code = ("import sys, json; from sibyl_memory_cli._entry import main; rc = main(['hook', %r]); "
+ "print('RC', rc); print('MODS', json.dumps(sorted(%s)))" % (event, probe))
+ env = dict(os.environ, HOME=str(home), SIBYL_MEMORY_TELEMETRY="0")
+ env.pop("SIBYL_MEMORY_DB", None)
+ p = subprocess.run([sys.executable, "-c", code], input=json.dumps(payload), text=True,
+ capture_output=True, env=env, timeout=60)
+ assert p.returncode == 0, p.stderr
+ return p.stdout
+
+
+def test_f11_the_installed_entry_runs_a_free_stop_with_the_standard_library_only(tmp_path, sm, home):
+ """a6338cc's `sibyl` script imported the whole CLI, the client, the
+ entitlement verifier and SQLite for every Stop (about 150 ms)."""
+ out = _run_entry(home, "stop", {"session_id": "e", "stop_hook_active": False},
+ "m for m in sys.modules if m.startswith(('sibyl_memory_client', 'cryptography', "
+ "'sqlite3', 'sibyl_memory_cli.cli', 'urllib.request'))")
+ assert "RC 0" in out
+ assert json.loads(out.split("MODS ", 1)[1]) == []
+
+
+def test_f11_entry_sends_every_other_command_to_the_cli(monkeypatch):
+ from sibyl_memory_cli import _entry
+ from sibyl_memory_cli import cli as C
+ got = []
+ monkeypatch.setattr(C, "main", lambda argv=None: got.append(argv) or 7)
+ assert _entry.main(["status"]) == 7 and got == [["status"]]
+ assert _entry.main(["hook", "nonsense"]) == 7 # argparse reports it, as before
+ import sibyl_memory_cli
+ assert sibyl_memory_cli.main is C.main and isinstance(sibyl_memory_cli.__version__, str)
+
+
+# ----------------------------------------------------------------------
+# F8: a hook whose package is gone exits 0 silently
+# ----------------------------------------------------------------------
+
+import shutil as _shutil # noqa: E402
+import subprocess as _subprocess # noqa: E402
+
+from sibyl_memory_cli import setup as SU # noqa: E402
+
+
+@pytest.mark.skipif(_shutil.which("bash") is None, reason="bash not available")
+def test_f8_the_hook_command_exits_0_silently_when_the_binary_is_gone(tmp_path):
+ """a6338cc wrote `/sibyl hook `: after `pip uninstall` every
+ session start, prompt and turn end ran a missing command (exit 127)."""
+ fake = tmp_path / "venv bin" / "sibyl"
+ fake.parent.mkdir()
+ fake.write_text('#!/bin/sh\necho "ran $1 $2"; cat >/dev/null\n')
+ fake.chmod(0o755)
+ cmd = SU.hook_command(str(fake), "stop")
+ assert SU.is_our_hook({"type": "command", "command": cmd})
+ run = lambda: _subprocess.run(["bash", "-c", cmd], input="{}", text=True, # noqa: E731
+ capture_output=True, timeout=20)
+ p = run()
+ assert p.returncode == 0 and p.stdout == "ran hook stop\n"
+ fake.unlink()
+ p = run()
+ assert p.returncode == 0 and p.stdout == "" and p.stderr == ""
+
+
+def test_f8_setup_replaces_entries_of_the_earlier_shape_and_uninstall_removes_both(tmp_path, monkeypatch):
+ p = tmp_path / ".claude" / "settings.json"
+ p.parent.mkdir()
+ old = {"hooks": {ev: [{"hooks": [{"type": "command", "command": f"/old/bin/sibyl hook {arg}",
+ "timeout": 5}]}] for ev, arg in SU.HOOK_EVENTS}}
+ p.write_text(json.dumps(old))
+ monkeypatch.setattr(SU, "sibyl_binary", lambda: "/new/bin/sibyl")
+ w = SU.ClaudeCodeWirer(settings_path=p)
+ w.wire_hooks()
+ cfg = json.loads(p.read_text())
+ assert SU.count_our_hooks(cfg) == 5 and "/old/bin" not in json.dumps(cfg)
+ assert cfg["hooks"]["Stop"] == [{"hooks": [{"type": "command", "timeout": 5, "command":
+ "[ -x /new/bin/sibyl ] && exec /new/bin/sibyl hook stop; exit 0"}]}]
+ w.unwire_hooks()
+ assert "hooks" not in json.loads(p.read_text())
+
+
+def test_f8_uninstall_help_says_to_run_it_before_pip_uninstall(capsys):
+ with pytest.raises(SystemExit):
+ cli.main(["skills", "uninstall", "--help"])
+ out = " ".join(capsys.readouterr().out.split())
+ assert "before `pip uninstall sibyl-memory-cli`" in out and "hooks" in out
+
+
+# ----------------------------------------------------------------------
+# Codex skills shim (Codex CLI 0.135.0 discovers $CODEX_HOME/skills)
+# ----------------------------------------------------------------------
+
+def _codex_quick_validate(skill_dir: Path) -> tuple[bool, str]:
+ """The rules of the skill validator bundled in the installed Codex CLI
+ 0.135.0 (skill-creator/scripts/quick_validate.py, read from the binary)."""
+ import re as _re
+ import yaml
+ content = (skill_dir / "SKILL.md").read_text()
+ if not content.startswith("---"):
+ return False, "No YAML frontmatter found"
+ m = _re.match(r"^---\n(.*?)\n---", content, _re.DOTALL)
+ if not m:
+ return False, "Invalid frontmatter format"
+ fm = yaml.safe_load(m.group(1))
+ if not isinstance(fm, dict):
+ return False, "Frontmatter must be a YAML dictionary"
+ if set(fm) - {"name", "description", "license", "allowed-tools", "metadata"}:
+ return False, "unexpected keys"
+ name, desc = str(fm.get("name", "")).strip(), str(fm.get("description", "")).strip()
+ if not name or not _re.match(r"^[a-z0-9-]+$", name) or name.startswith("-") or "--" in name \
+ or len(name) > 64:
+ return False, "bad name"
+ if not desc or "<" in desc or ">" in desc or len(desc) > 1024:
+ return False, "bad description"
+ return True, "Skill is valid!"
+
+
+def test_codex_skill_shims_install_validate_and_uninstall(tmp_path, home, capsys):
+ """a6338cc wrote no Codex skill (the AGENTS.md block only)."""
+ from sibyl_memory_client import skills as SK
+ cfg = tmp_path / ".codex" / "config.toml"
+ cfg.parent.mkdir()
+ w = SU.CodexWirer(config_path=cfg)
+ w.wire_lifecycle()
+ for name, shim in SK.SHIM_NAMES.items():
+ d = cfg.parent / "skills" / shim
+ assert _codex_quick_validate(d) == (True, "Skill is valid!")
+ t = (d / "SKILL.md").read_text()
+ assert f"Read `~/.sibyl-memory/skills/{name}` and follow it exactly" in t
+ st = SK.status(home)["shims"]
+ assert {v["harness"] for k, v in st.items() if "/.codex/skills/" in k} == {"codex"}
+ # An edited shim is kept on refresh and on uninstall; an unedited one goes.
+ edited = cfg.parent / "skills" / "sibyl-debloat" / "SKILL.md"
+ edited.write_text(edited.read_text() + "\nmy note\n")
+ assert "user_modified" in " ".join(w.wire_lifecycle())
+ assert edited.read_text().endswith("my note\n")
+ out = SK.uninstall(home)
+ assert out[str(cfg.parent / "skills" / "sibyl-save" / "SKILL.md")] == "removed"
+ assert out[str(edited)] != "removed" and edited.exists()
+ assert not (cfg.parent / "skills" / "sibyl-save" / "SKILL.md").exists()
+
+
+# ----------------------------------------------------------------------
+# Copy: migrate pointer (C6-9), automatic save timing (F7), uninstall (F8)
+# ----------------------------------------------------------------------
+
+def test_c6_9_migrate_pointer_claims_only_what_is_true(tmp_path):
+ """a6338cc: 'the history that was here ... was extracted into Sibyl
+ Memory' (the extraction stores entries, not necessarily this text)."""
+ from sibyl_memory_cli import migrate as M
+ text = "# Rules\n\n" + "".join(f"- rule {i}\n" for i in range(20)) + "\n## History\n" + \
+ "".join(f"- 2025-01-0{i % 9 + 1} old thing {i}\n" for i in range(30))
+ lean = M.lean_text_for(text, "AGENTS.md", tmp_path / "bk")
+ assert lean is not None
+ assert f"a full copy of this file is in the backup at {tmp_path / 'bk'}; the migrate extraction " \
+ "stored entries in Sibyl Memory" in lean
+ assert "was extracted into Sibyl Memory" not in lean
+ lean2 = M.heuristic_lean("# A\n\n## one\nx\n## two\n" + "y\n" * 50)
+ assert "the migrate extraction stored entries in Sibyl Memory" in lean2
+ assert "accumulated memory now lives in Sibyl Memory" not in lean2
+
+
+_REPO = Path(__file__).resolve().parents[2]
+_READMES = ["README.md", "sibyl-memory-cli/README.md", "sibyl-memory-client/README.md",
+ "sibyl-memory-hermes/README.md", "sibyl-memory-mcp/README.md", "sibyl-memory-langgraph/README.md"]
+
+
+def test_f7_f8_every_readme_says_when_automatic_save_runs_and_how_to_uninstall():
+ """a6338cc: 'Automatic save (the Claude Code Stop hook, session capsules)'
+ read as a save at session end; no README said to remove the hooks first."""
+ for rel in _READMES:
+ t = " ".join((_REPO / rel).read_text().split())
+ assert "sibyl skills uninstall" in t and "before `pip uninstall" in t or \
+ "run `sibyl skills uninstall` first" in t, rel
+ if rel != "sibyl-memory-langgraph/README.md":
+ # R1 (2026-09-29): the cadence is by active time now; the "one nudge per
+ # session" copy is gone from every README.
+ assert ("once early (after 5 memory writes or a compaction), then about every 60 minutes "
+ "of active work") in t, rel
+ assert "one nudge per session" not in t, rel
+ assert "Automatic save (the Claude Code Stop hook, session capsules)" not in t, rel
+ assert "\u2014" not in (_REPO / rel).read_text().split("## Save and debloat", 1)[1]
diff --git a/sibyl-memory-cli/tests/test_setup.py b/sibyl-memory-cli/tests/test_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c3bdcaa2acc9816c820a68be60451a643f7dcc2
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_setup.py
@@ -0,0 +1,396 @@
+"""Tests for the v0.1.4 `sibyl setup` command.
+
+Covers:
+- Hermes wirer: fresh, existing-no-memory, existing-sibyl, existing-other-provider,
+ force-overwrite, dry-run, plugin-install side-effect.
+- Claude Code wirer: fresh-no-file, fresh-with-other-mcps, existing-sibyl,
+ existing-sibyl-mismatch, force-overwrite, dry-run.
+- Detection: is_present logic for both wirers.
+- Outcomes: WireOutcome status field correctness.
+- Atomic writes + backup files land at the expected paths.
+"""
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
+
+from sibyl_memory_cli.setup import ( # noqa: E402
+ ALL_WIRERS,
+ HOOK_EVENTS,
+ ClaudeCodeWirer,
+ HermesWirer,
+ WireOutcome,
+ _accept_defaults_prompt,
+ _interactive_prompt,
+ count_our_hooks,
+)
+
+
+# ----------------------------------------------------------------------
+# Helpers
+# ----------------------------------------------------------------------
+
+
+def _backups(harness: str) -> Path:
+ """cli 0.7.0: where a wirer's config backups land (under the test HOME)."""
+ return Path.home() / ".sibyl-memory" / "backups" / harness
+
+
+def _stub_install_plugin(hermes_home: str):
+ """Replacement for sibyl_memory_hermes.install_plugin.install: drops a fake
+ adapter file so the wirer sees plugin_installed=True afterwards."""
+ plugin_dir = Path(hermes_home) / "plugins" / "sibyl"
+ plugin_dir.mkdir(parents=True, exist_ok=True)
+ (plugin_dir / "__init__.py").write_text("# stub plugin\n")
+
+
+# ----------------------------------------------------------------------
+# WireOutcome basics
+# ----------------------------------------------------------------------
+
+def test_outcome_dataclass_basic():
+ o = WireOutcome("hermes", "wired", "test")
+ assert o.name == "hermes" and o.status == "wired" and o.backup_path is None
+ o2 = WireOutcome("claude-code", "skipped", "no", backup_path=Path("/tmp/x.bak"))
+ assert o2.backup_path == Path("/tmp/x.bak")
+
+
+# ----------------------------------------------------------------------
+# Prompt helpers
+# ----------------------------------------------------------------------
+
+def test_interactive_prompt_default_y_empty_input(monkeypatch):
+ monkeypatch.setattr("builtins.input", lambda _: "")
+ assert _interactive_prompt("Q?", default="Y") == "y"
+
+
+def test_interactive_prompt_default_n_empty_input(monkeypatch):
+ monkeypatch.setattr("builtins.input", lambda _: "")
+ assert _interactive_prompt("Q?", default="N") == "n"
+
+
+def test_interactive_prompt_explicit_y(monkeypatch):
+ monkeypatch.setattr("builtins.input", lambda _: "y")
+ assert _interactive_prompt("Q?", default="N") == "y"
+
+
+def test_interactive_prompt_explicit_n(monkeypatch):
+ monkeypatch.setattr("builtins.input", lambda _: "no")
+ assert _interactive_prompt("Q?", default="Y") == "n"
+
+
+def test_accept_defaults_prompt_returns_default():
+ assert _accept_defaults_prompt("Q?", default="Y") == "y"
+ assert _accept_defaults_prompt("Q?", default="N") == "n"
+
+
+# ----------------------------------------------------------------------
+# HermesWirer
+# ----------------------------------------------------------------------
+
+def test_hermes_wirer_auto_home_env(monkeypatch, tmp_path):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "custom-hermes"))
+ w = HermesWirer()
+ assert w.hermes_home == tmp_path / "custom-hermes"
+
+
+def test_hermes_wirer_auto_home_default(monkeypatch):
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+ w = HermesWirer()
+ assert w.hermes_home == Path.home() / ".hermes"
+
+
+def test_hermes_is_present_false_when_no_dir_no_bin(monkeypatch, tmp_path):
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+ w = HermesWirer(hermes_home=tmp_path / "nope")
+ with patch("sibyl_memory_cli.setup.shutil.which", return_value=None):
+ assert not w.is_present()
+
+
+def test_hermes_is_present_true_when_dir_exists(tmp_path):
+ (tmp_path / "hermes-home").mkdir()
+ w = HermesWirer(hermes_home=tmp_path / "hermes-home")
+ assert w.is_present()
+
+
+def test_hermes_state_fresh(tmp_path):
+ w = HermesWirer(hermes_home=tmp_path / "hermes-home")
+ st = w.current_state()
+ assert st["config_exists"] is False
+ assert st["plugin_installed"] is False
+ assert st["memory_provider"] is None
+ assert st["wired_with_sibyl"] is False
+
+
+def test_hermes_state_existing_sibyl(tmp_path):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text("memory:\n provider: sibyl\n")
+ w = HermesWirer(hermes_home=home)
+ st = w.current_state()
+ assert st["memory_provider"] == "sibyl"
+ assert st["wired_with_sibyl"] is True
+
+
+def test_hermes_state_existing_other_provider(tmp_path):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text("memory:\n provider: mem0\nother: thing\n")
+ w = HermesWirer(hermes_home=home)
+ st = w.current_state()
+ assert st["memory_provider"] == "mem0"
+ assert st["wired_with_sibyl"] is False
+
+
+def test_hermes_wire_fresh_creates_config_and_installs_plugin(tmp_path, monkeypatch):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ w = HermesWirer(hermes_home=home)
+ # Stub the install_plugin import via the wirer's _install_plugin override
+ monkeypatch.setattr(
+ HermesWirer, "_install_plugin",
+ lambda self: _stub_install_plugin(str(self.hermes_home)),
+ )
+ outcome = w.wire()
+ assert outcome.status == "wired"
+ # Config now has memory.provider: sibyl
+ import yaml
+ cfg = yaml.safe_load((home / "config.yaml").read_text())
+ assert cfg == {"memory": {"provider": "sibyl"}}
+ # Plugin "installed" (stub created the file)
+ assert (home / "plugins" / "sibyl" / "__init__.py").exists()
+
+
+def test_hermes_wire_existing_sibyl_is_noop(tmp_path, monkeypatch):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text("memory:\n provider: sibyl\n")
+ # Also pre-install the plugin so the noop path is true end-to-end
+ (home / "plugins" / "sibyl").mkdir(parents=True)
+ (home / "plugins" / "sibyl" / "__init__.py").write_text("# stub\n")
+ w = HermesWirer(hermes_home=home)
+ outcome = w.wire()
+ assert outcome.status == "already"
+
+
+def test_hermes_wire_existing_other_provider_refused_without_force(tmp_path, monkeypatch):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text("memory:\n provider: mem0\n")
+ monkeypatch.setattr(
+ HermesWirer, "_install_plugin",
+ lambda self: _stub_install_plugin(str(self.hermes_home)),
+ )
+ w = HermesWirer(hermes_home=home)
+ # No prompt_fn means non-interactive refusal
+ outcome = w.wire()
+ assert outcome.status == "skipped"
+ # Config UNCHANGED
+ assert "mem0" in (home / "config.yaml").read_text()
+
+
+def test_hermes_wire_existing_other_provider_with_force(tmp_path, monkeypatch):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text("memory:\n provider: mem0\n")
+ monkeypatch.setattr(
+ HermesWirer, "_install_plugin",
+ lambda self: _stub_install_plugin(str(self.hermes_home)),
+ )
+ w = HermesWirer(hermes_home=home)
+ outcome = w.wire(force=True)
+ assert outcome.status == "wired"
+ import yaml
+ cfg = yaml.safe_load((home / "config.yaml").read_text())
+ assert cfg["memory"]["provider"] == "sibyl"
+ # Backup landed (audit #19: timestamped suffix, not a fixed .bak). cli 0.7.0:
+ # backups live under ~/.sibyl-memory/backups//, never beside the config.
+ assert list(home.glob("config.yaml.*.bak")) == []
+ backups = list((Path.home() / ".sibyl-memory" / "backups" / "hermes").glob("config.yaml.*.bak"))
+ assert len(backups) == 1
+ assert "mem0" in backups[0].read_text()
+
+
+def test_hermes_wire_existing_other_provider_prompt_y_accepts(tmp_path, monkeypatch):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text("memory:\n provider: mem0\n")
+ monkeypatch.setattr(
+ HermesWirer, "_install_plugin",
+ lambda self: _stub_install_plugin(str(self.hermes_home)),
+ )
+ w = HermesWirer(hermes_home=home)
+ outcome = w.wire(prompt_fn=lambda q, *, default: "y")
+ assert outcome.status == "wired"
+
+
+def test_hermes_wire_dry_run_no_writes(tmp_path):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ w = HermesWirer(hermes_home=home)
+ outcome = w.wire(dry_run=True)
+ assert outcome.status == "dry-run"
+ assert not (home / "config.yaml").exists()
+ assert not (home / "plugins" / "sibyl" / "__init__.py").exists()
+
+
+def test_hermes_wire_preserves_other_top_level_keys(tmp_path, monkeypatch):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text(
+ "model:\n name: gpt-4\ntools:\n - search\n - file\n"
+ )
+ monkeypatch.setattr(
+ HermesWirer, "_install_plugin",
+ lambda self: _stub_install_plugin(str(self.hermes_home)),
+ )
+ w = HermesWirer(hermes_home=home)
+ w.wire()
+ import yaml
+ cfg = yaml.safe_load((home / "config.yaml").read_text())
+ assert cfg["model"]["name"] == "gpt-4"
+ assert cfg["tools"] == ["search", "file"]
+ assert cfg["memory"]["provider"] == "sibyl"
+
+
+# ----------------------------------------------------------------------
+# ClaudeCodeWirer
+# ----------------------------------------------------------------------
+
+def test_claude_is_present_false_when_no_settings_no_bin(monkeypatch, tmp_path):
+ w = ClaudeCodeWirer(settings_path=tmp_path / "no.json")
+ with patch("sibyl_memory_cli.setup.shutil.which", return_value=None):
+ assert not w.is_present()
+
+
+def test_claude_is_present_true_when_settings_exists(tmp_path):
+ p = tmp_path / "settings.json"
+ p.write_text("{}")
+ w = ClaudeCodeWirer(settings_path=p)
+ assert w.is_present()
+
+
+def test_claude_state_fresh(tmp_path):
+ w = ClaudeCodeWirer(settings_path=tmp_path / "settings.json")
+ st = w.current_state()
+ assert st["settings_exists"] is False
+ assert st["mcp_servers_count"] == 0
+ assert st["sibyl_mcp"] is None
+ assert st["wired_with_sibyl"] is False
+
+
+def test_claude_state_existing_sibyl(tmp_path):
+ # Panel fix 10 (2026-11-14): without the claude CLI an mcpServers entry in
+ # settings.json is not a registration Claude Code reads, so it is never
+ # reported as wired.
+ p = tmp_path / "settings.json"
+ p.write_text(json.dumps({"mcpServers": {"sibyl-memory": {"command": "sibyl-memory-mcp"}}}))
+ w = ClaudeCodeWirer(settings_path=p)
+ st = w.current_state()
+ assert st["wired_with_sibyl"] is False and st["cli_registered"] is None
+
+
+def test_claude_state_existing_other_mcps_no_sibyl(tmp_path):
+ p = tmp_path / "settings.json"
+ p.write_text(json.dumps({
+ "mcpServers": {"github": {"command": "gh-mcp"}, "filesystem": {"command": "fs-mcp"}}
+ }))
+ w = ClaudeCodeWirer(settings_path=p)
+ st = w.current_state()
+ assert st["mcp_servers_count"] == 2
+ assert st["sibyl_mcp"] is None
+ assert st["wired_with_sibyl"] is False
+
+
+def _assert_not_registered_outcome(outcome):
+ assert outcome.status == "skipped"
+ assert "not registered" in outcome.message
+ nxt = outcome.handoff[0]
+ assert nxt.startswith("claude mcp add --scope user sibyl-memory -- ")
+ assert nxt in outcome.message
+
+
+def test_claude_wire_without_cli_writes_no_mcp_entry(tmp_path):
+ p = tmp_path / "subdir" / "settings.json" # parent doesn't exist yet
+ w = ClaudeCodeWirer(settings_path=p)
+ outcome = w.wire()
+ _assert_not_registered_outcome(outcome)
+ cfg = json.loads(p.read_text()) # the hooks were still written
+ assert "mcpServers" not in cfg
+ assert count_our_hooks(cfg) == len(HOOK_EVENTS)
+
+
+def test_claude_wire_without_cli_preserves_other_mcps(tmp_path):
+ p = tmp_path / "settings.json"
+ p.write_text(json.dumps({
+ "mcpServers": {"github": {"command": "gh-mcp"}},
+ "theme": "dark",
+ }))
+ w = ClaudeCodeWirer(settings_path=p)
+ outcome = w.wire()
+ _assert_not_registered_outcome(outcome)
+ cfg = json.loads(p.read_text())
+ assert cfg["mcpServers"] == {"github": {"command": "gh-mcp"}}
+ assert cfg["theme"] == "dark"
+ # cli 0.7.0: backups under ~/.sibyl-memory/backups/claude-code/, nothing
+ # beside the config; one backup, before the lifecycle hooks write.
+ assert list(tmp_path.glob("settings.json.*.bak")) == []
+ assert len(list(_backups("claude-code").glob("settings.json.*.bak"))) == 1
+
+
+def test_claude_wire_existing_settings_entry_is_not_already(tmp_path):
+ p = tmp_path / "settings.json"
+ p.write_text(json.dumps({"mcpServers": {"sibyl-memory": {"command": "sibyl-memory-mcp"}}}))
+ w = ClaudeCodeWirer(settings_path=p)
+ _assert_not_registered_outcome(w.wire())
+ first = list(_backups("claude-code").glob("settings.json.*.bak"))
+ # The second run changes nothing and writes no further backup.
+ _assert_not_registered_outcome(w.wire())
+ assert list(_backups("claude-code").glob("settings.json.*.bak")) == first
+ assert json.loads(p.read_text())["mcpServers"] == {
+ "sibyl-memory": {"command": "sibyl-memory-mcp"}}
+
+
+def test_claude_wire_mismatched_sibyl_untouched_even_with_force(tmp_path):
+ p = tmp_path / "settings.json"
+ p.write_text(json.dumps({"mcpServers": {"sibyl-memory": {"command": "/some/other/path"}}}))
+ w = ClaudeCodeWirer(settings_path=p)
+ for force in (False, True):
+ _assert_not_registered_outcome(w.wire(force=force))
+ assert json.loads(p.read_text())["mcpServers"]["sibyl-memory"]["command"] == "/some/other/path"
+
+
+def test_claude_wire_dry_run_no_writes(tmp_path):
+ p = tmp_path / "settings.json"
+ w = ClaudeCodeWirer(settings_path=p)
+ outcome = w.wire(dry_run=True)
+ assert outcome.status == "dry-run"
+ assert not p.exists()
+
+
+def test_claude_wire_dry_run_without_cli_names_the_command(tmp_path):
+ p = tmp_path / "settings.json"
+ p.write_text(json.dumps({"mcpServers": {"sibyl-memory": {"command": "/old"}}}))
+ w = ClaudeCodeWirer(settings_path=p, )
+ outcome = w.wire(dry_run=True, force=True)
+ assert outcome.status == "dry-run"
+ assert "claude mcp add --scope user sibyl-memory" in outcome.message
+ # Still no write
+ assert "/old" in p.read_text()
+
+
+# ----------------------------------------------------------------------
+# Registry
+# ----------------------------------------------------------------------
+
+def test_registry_has_all_wirers():
+ assert set(ALL_WIRERS) == {"hermes", "claude-code", "codex", "cursor", "deepseek"}
+ assert ALL_WIRERS["hermes"] is HermesWirer
+ assert ALL_WIRERS["claude-code"] is ClaudeCodeWirer
diff --git a/sibyl-memory-cli/tests/test_signin_display_fixes_2026_10_10.py b/sibyl-memory-cli/tests/test_signin_display_fixes_2026_10_10.py
new file mode 100644
index 0000000000000000000000000000000000000000..760648a364e490ef321ff5404a47a62878680a7d
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_signin_display_fixes_2026_10_10.py
@@ -0,0 +1,292 @@
+"""Plugin fixes (2026-10-10).
+
+F-1 (contract C1): the api's 401 ``signed_out_on_claim`` is named on every
+surface that used to say only "signed out . run sibyl init".
+`sibyl setup --dry-run` says "already in" for skills, shims,
+hooks and the Codex block that are already installed.
+times shown to people carry a zone (`2026-10-09 19:08 UTC`).
+`sibyl --version` names every installed Sibyl package.
+the USDC-from-a-mobile-wallet path is offered only when the api minted
+a USDC-send bind for the session.
+
+Nothing here reaches the network: `cli.http_request` / `_security_request` are
+fakes and the gate's refresh transport is scripted.
+"""
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import _account_gate as G
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import setup as S
+from sibyl_memory_cli._timefmt import utc_hm, utc_minute
+from sibyl_memory_client import _entitlement as E
+from sibyl_memory_client.testing import write_entitlement
+
+from conftest import handoff
+
+CLAIM_BODY = {
+ "error": "this computer was signed out when the email was confirmed on the account page. "
+ "run sibyl init --force and approve it there.",
+ "code": "signed_out_on_claim",
+ "signed_out_at": "2026-10-08T18:34:05.123Z",
+}
+CLAIM_LINE = ("signed out: this computer was signed out when your email was confirmed on the account "
+ "page (2026-10-08 18:34 UTC). run: sibyl init --force")
+
+
+@pytest.fixture(autouse=True)
+def _quiet(monkeypatch):
+ monkeypatch.setenv("SIBYL_MEMORY_TELEMETRY", "0")
+ monkeypatch.setenv("NO_COLOR", "1")
+
+
+@pytest.fixture
+def sm() -> Path:
+ return Path.home() / ".sibyl-memory"
+
+
+def _acct(sm: Path) -> list[str]:
+ return ["--credentials", str(sm / "credentials.json"), "--db", str(sm / "memory.db"),
+ "--tier-cache", str(sm / "tier_cache.json")]
+
+
+def _claim_err() -> cli.HttpError:
+ return cli.HttpError(401, dict(CLAIM_BODY), "https://api/x")
+
+
+# ---- F-1 (C1) ---------------------------------------------------------------
+
+def test_access_row_names_the_claim_and_init_force() -> None:
+ info = {"state": "locked", "code": "signed_out", "cause": "signed_out_on_claim",
+ "signed_out_at": "2026-10-08T18:34:05.123Z"}
+ assert G.access_row(info) == CLAIM_LINE
+ assert G.access_handoff(info) == ("sibyl init --force", None)
+
+
+def test_access_row_plain_signed_out_is_unchanged() -> None:
+ info = {"state": "locked", "code": "signed_out"}
+ assert G.access_row(info) == "signed out · run sibyl init"
+ assert G.access_handoff(info)[0] == "sibyl init"
+
+
+def test_claim_line_without_a_time_has_no_parenthesis() -> None:
+ assert G.signed_out_on_claim_line(None) == (
+ "signed out: this computer was signed out when your email was confirmed on the account "
+ "page. run: sibyl init --force")
+
+
+def test_gate_http_line_401_signed_out_on_claim() -> None:
+ assert G.gate_http_line(401, "signed_out_on_claim", body=CLAIM_BODY) == CLAIM_LINE
+ assert G.gate_http_handoff(401, "signed_out_on_claim", body=CLAIM_BODY) == ("sibyl init --force", None)
+ assert G.gate_http_line(401, None, body={"error": "session not found"}) is None
+
+
+def test_status_names_the_claim_after_the_refresh_is_refused(sm, test_signer, monkeypatch, capsys):
+ write_entitlement(sm, test_signer.mint())
+ monkeypatch.setattr(E, "http_refresh", lambda account_id, session_token: E.classify_denial(401, CLAIM_BODY))
+
+ def server(method, path, **kw):
+ raise _claim_err()
+ monkeypatch.setattr(cli, "http_request", server)
+ cli.main(_acct(sm) + ["status"])
+ out = capsys.readouterr().out
+ assert CLAIM_LINE in out
+ assert "signed out · run sibyl init" not in out
+ assert "server error: 401" not in out
+ assert handoff(out)["next"] == "sibyl init --force"
+
+
+def test_devices_names_the_claim(sm, monkeypatch, capsys):
+ def boom(*a, **k):
+ raise _claim_err()
+ monkeypatch.setattr(cli, "_security_request", boom)
+ assert cli.main(_acct(sm) + ["devices"]) == 2
+ out = capsys.readouterr().out
+ assert CLAIM_LINE in out and "Session expired." not in out
+ assert handoff(out)["next"] == "sibyl init --force"
+
+
+def test_email_show_names_the_claim(sm, monkeypatch, capsys):
+ def server(method, path, **kw):
+ raise _claim_err()
+ monkeypatch.setattr(cli, "http_request", server)
+ assert cli.main(_acct(sm) + ["email"]) == 1
+ out = capsys.readouterr().out
+ assert CLAIM_LINE in out and "session expired" not in out
+ assert handoff(out)["next"] == "sibyl init --force"
+
+
+def test_email_verify_error_names_the_claim():
+ assert cli._email_error_message(_claim_err()) == CLAIM_LINE
+ assert cli._email_error_handoff(_claim_err()) == ("sibyl init --force", None)
+ plain = cli.HttpError(401, {"error": "session not found"}, "https://api/x")
+ assert cli._email_error_message(plain) == "session expired. re-run sibyl init."
+
+
+# ---- times carry a zone --------------------------------------------
+
+@pytest.mark.parametrize("value,expect", [
+ ("2026-10-09T19:08:12.345Z", "2026-10-09 19:08 UTC"),
+ ("2026-10-09T21:08:12+02:00", "2026-10-09 19:08 UTC"),
+ ("2026-10-09 19:08:12", "2026-10-09 19:08 UTC"),
+ (1791572892, "2026-10-09 19:08 UTC"),
+ ("yesterday", None),
+ (None, None),
+ (True, None),
+])
+def test_utc_minute(value, expect):
+ assert utc_minute(value) == expect
+
+
+def test_utc_hm():
+ assert utc_hm(1791572892) == "19:08 UTC"
+
+
+def test_devices_last_seen_has_a_zone(sm, test_signer, monkeypatch, capsys):
+ monkeypatch.setattr(cli, "_security_request", lambda *a, **k: {"devices": [
+ {"device_label": "this-one", "is_this_device": True, "install_method": "cli",
+ "last_seen_at": "2026-10-09T19:08:12.345Z", "bearer_id": "b1"}]})
+ assert cli.main(_acct(sm) + ["devices"]) == 0
+ out = capsys.readouterr().out
+ assert "last seen 2026-10-09 19:08 UTC" in out
+ assert "19:08:12" not in out
+
+
+def test_lifecycle_timestamps_have_a_zone():
+ from sibyl_memory_cli import lifecycle_cli
+ assert lifecycle_cli._fmt_ts(1791572892) == "2026-10-09 19:08 UTC"
+ assert lifecycle_cli._fmt_ts(None) == "never"
+
+
+# ---- --version -------------------------------------------------------
+
+def test_version_names_every_installed_package(monkeypatch, capsys):
+ vers = {"sibyl-memory-client": "0.9.0+dev.5", "sibyl-memory-mcp": "0.3.0+dev.5"}
+ monkeypatch.setattr(cli, "_client_version", lambda: "0.5.0+dev.5")
+ monkeypatch.setattr(cli, "_installed_version", lambda pkg: vers.get(pkg))
+ with pytest.raises(SystemExit) as ei:
+ cli.main(["--version"])
+ assert ei.value.code == 0
+ assert capsys.readouterr().out == "sibyl cli 0.5.0+dev.5 · client 0.9.0+dev.5 · mcp 0.3.0+dev.5\n"
+
+
+def test_version_includes_hermes_and_langgraph_when_installed(monkeypatch, capsys):
+ vers = {"sibyl-memory-client": "0.9.0", "sibyl-memory-mcp": "0.3.0",
+ "sibyl-memory-hermes": "0.5.0", "sibyl-memory-langgraph": "0.3.0"}
+ monkeypatch.setattr(cli, "_client_version", lambda: "0.5.0")
+ monkeypatch.setattr(cli, "_installed_version", lambda pkg: vers.get(pkg))
+ with pytest.raises(SystemExit):
+ cli.main(["--version"])
+ assert capsys.readouterr().out == (
+ "sibyl cli 0.5.0 · client 0.9.0 · mcp 0.3.0 · hermes 0.5.0 · langgraph 0.3.0\n")
+
+
+# ---- USDC path only when the api minted it ---------------------------
+
+class _InitServer:
+ def __init__(self, init_resp):
+ self.init_resp = init_resp
+
+ def __call__(self, method, path, *, body=None, timeout=15.0, headers=None):
+ if path.startswith("/api/plugin/session-init"):
+ return json.loads(json.dumps(self.init_resp))
+ if path.startswith("/api/plugin/check"):
+ return {"bound": True, "credentials": {
+ "account_id": "11111111-2222-4333-8444-555555555555",
+ "tenant_id": "11111111-2222-4333-8444-555555555555", "tier": "free",
+ "email": None, "wallet": "0x1234567890abcdef1234567890abcdef12345678",
+ "issued_at": "2026-10-10T00:00:00Z",
+ "bearer_token": "22222222-3333-4444-8555-666666666666"}}
+ raise cli.HttpError(404, {"error": "not routed"}, f"https://api{path}")
+
+
+def _init(tmp_path, monkeypatch, init_resp):
+ monkeypatch.setattr(cli, "http_request", _InitServer(init_resp))
+ monkeypatch.setattr(cli.webbrowser, "open", lambda *a, **k: True)
+ monkeypatch.setattr(cli.time, "sleep", lambda *_: None)
+ monkeypatch.setattr(cli, "invalidate_tier_cache", lambda *a, **k: None)
+ return cli.main(["--credentials", str(tmp_path / "c.json"), "init", "--force"])
+
+
+def test_init_offers_no_usdc_path_while_usdc_sign_in_is_off(tmp_path, monkeypatch, capsys):
+ _init(tmp_path, monkeypatch, {"pairing_ttl_seconds": 60, "bind_amount_micros": None,
+ "bind_bus_wallet": None})
+ out = capsys.readouterr().out
+ assert "USDC" not in out and "mobile wallet" not in out
+ assert "two paths" in out
+ ask = next(ln for ln in out.splitlines() if ln.startswith("ask your human: "))
+ assert ask.endswith("with a desktop wallet or with email plus the code "
+ + re.search(r"(\d{3} \d{3})", ask).group(1) + "; I pick it up here")
+
+
+def test_init_offers_the_usdc_path_when_the_api_minted_it(tmp_path, monkeypatch, capsys):
+ _init(tmp_path, monkeypatch, {"pairing_ttl_seconds": 60, "bind_amount_micros": 123456,
+ "bind_bus_wallet": "0x5ab927893db6f35083a82bd69c2c091fbe488f32"})
+ out = capsys.readouterr().out
+ assert "or send USDC from any mobile wallet" in out and "three paths" in out
+
+
+def test_usdc_bind_offered_shape():
+ assert cli._usdc_bind_offered({"bind_amount_micros": 1, "bind_bus_wallet": "0xabc"})
+ for bad in ({}, None, {"bind_amount_micros": True, "bind_bus_wallet": "0xabc"},
+ {"bind_amount_micros": 0, "bind_bus_wallet": "0xabc"},
+ {"bind_amount_micros": 5, "bind_bus_wallet": " "}):
+ assert not cli._usdc_bind_offered(bad)
+
+
+# ---- setup --dry-run compares with what is installed ----------------
+
+def _claude(tmp_path, monkeypatch):
+ w = S.ClaudeCodeWirer(settings_path=tmp_path / ".claude" / "settings.json")
+ monkeypatch.setattr(w, "_ensure_mcp_binary", lambda *a, **k: True)
+ return w
+
+
+def test_claude_dry_run_after_setup_says_already_in(tmp_path, monkeypatch):
+ w = _claude(tmp_path, monkeypatch)
+ # Panel fix 10: with no claude CLI the server is not registered (skipped),
+ # but skills, shims and hooks are installed, and a dry run says so.
+ assert w.wire().status == "skipped"
+ before = (tmp_path / ".claude" / "settings.json").read_text()
+ out = w.wire(dry_run=True)
+ assert out.status == "dry-run"
+ lines = out.lifecycle
+ assert any(re.match(r"skills v\S+: SAVE\.md, DEBLOAT\.md already in ", ln) for ln in lines), lines
+ assert sum(1 for ln in lines if ln.startswith("shim ") and ln.endswith(": already in")) == 2, lines
+ assert any(ln.startswith("hooks: 5 already in ") for ln in lines), lines
+ assert not any(ln.startswith("would") for ln in lines), lines
+ assert (tmp_path / ".claude" / "settings.json").read_text() == before
+
+
+def test_claude_dry_run_on_a_fresh_computer_says_would(tmp_path, monkeypatch):
+ w = _claude(tmp_path, monkeypatch)
+ out = w.wire(dry_run=True)
+ assert out.status == "dry-run"
+ assert any("would install" in ln for ln in out.lifecycle)
+ assert any(ln.startswith("would write shim ") for ln in out.lifecycle)
+ assert any(ln.startswith("would add hook ") for ln in out.lifecycle)
+ assert not any("already in" in ln for ln in out.lifecycle)
+ assert not (tmp_path / ".claude" / "settings.json").exists()
+
+
+def test_dry_run_after_one_skill_was_removed_mixes_states(tmp_path, monkeypatch):
+ w = _claude(tmp_path, monkeypatch)
+ w.wire()
+ (Path.home() / ".sibyl-memory" / "skills" / "DEBLOAT.md").unlink()
+ lines = w.wire(dry_run=True).lifecycle
+ assert any(ln.startswith("skills: SAVE.md already in ") for ln in lines), lines
+ assert any("would install" in ln and "DEBLOAT.md" in ln for ln in lines), lines
+
+
+def test_codex_dry_run_after_setup_says_block_already_in(tmp_path, monkeypatch):
+ w = S.CodexWirer(config_path=tmp_path / ".codex" / "config.toml")
+ monkeypatch.setattr(w, "_ensure_mcp_binary", lambda *a, **k: True)
+ assert w.wire().status == "wired"
+ lines = w.wire(dry_run=True).lifecycle
+ assert any(ln.startswith("block: already in ") for ln in lines), lines
+ assert sum(1 for ln in lines if ln.endswith(": already in")) == 2, lines
diff --git a/sibyl-memory-cli/tests/test_skills_signals_cli_2026_09_29.py b/sibyl-memory-cli/tests/test_skills_signals_cli_2026_09_29.py
new file mode 100644
index 0000000000000000000000000000000000000000..891381d32d8ac3658abb49191230863b257e49fb
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_skills_signals_cli_2026_09_29.py
@@ -0,0 +1,203 @@
+"""R2 `sibyl skills signals status|clear|off|on` and the two new kinds in
+`sibyl skills proposals` (spec plugin-paid-tier-r2 1.3, 1.5, 1.6).
+
+* status prints counts, size and dates, never an entry (a canary tool name and
+ argument key are not printed); free tier and a locked device print "Skill
+ signals are on Pro.";
+* clear deletes the file; off stops recording; on starts it again from now; on
+ the free tier `on` changes nothing;
+* `mute tool_sequence` / `mute correction_loop` are accepted kinds; a
+ tool_sequence proposal is listed, shown, accepted (a valid SKILL.md and the
+ reference copy) and rejected through the CLI.
+
+On b591aa1 these fail: `skills signals` is not a command (argparse exits 2)
+and `mute tool_sequence` answers "Unknown kind".
+"""
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_client import MemoryClient
+from sibyl_memory_client import skills as SK
+from sibyl_memory_client.lifecycle import signals as SG
+from sibyl_memory_client.lifecycle import state as ST
+from sibyl_memory_client.testing import write_entitlement
+
+CANARY_TOOL = "mcp__canarysrv__canary_tool_4d4d"
+CANARY_KEY = "canary_key_9b2c"
+
+
+@pytest.fixture(autouse=True)
+def _quiet(monkeypatch):
+ monkeypatch.setenv("SIBYL_MEMORY_TELEMETRY", "0")
+ monkeypatch.setenv("NO_COLOR", "1")
+ from sibyl_memory_client import _capcheck
+ monkeypatch.setattr(_capcheck, "_default_check_write_fn",
+ lambda url, payload, timeout=4.0: {"ok": True, "tier": "pro", "cap_bytes": None})
+
+ def offline(*a, **k):
+ raise cli.HttpError(0, {}, "offline")
+ monkeypatch.setattr(cli, "http_request", offline)
+ yield
+ with SG._registry_lock:
+ for b in SG._BUFFERS.values():
+ b.discard()
+ SG._BUFFERS.clear()
+
+
+@pytest.fixture
+def home():
+ return Path.home()
+
+
+@pytest.fixture
+def sm(home):
+ return home / ".sibyl-memory"
+
+
+@pytest.fixture
+def pro(sm, test_signer):
+ write_entitlement(sm, test_signer.mint(tier="pro", cap=None, src="pro"))
+ return sm
+
+
+def _acct(sm: Path) -> list[str]:
+ return ["--credentials", str(sm / "credentials.json"), "--db", str(sm / "memory.db")]
+
+
+def _tenant(sm: Path) -> str:
+ c = json.loads((sm / "credentials.json").read_text())
+ return c.get("tenant_id") or c["account_id"]
+
+
+def _client(sm: Path) -> MemoryClient:
+ return MemoryClient.local(str(sm / "memory.db"), tenant_id=_tenant(sm),
+ credentials_path=sm / "credentials.json")
+
+
+def _record(home: Path, names=("Read", "Edit", CANARY_TOOL), times=3, t0=None) -> None:
+ t0 = time.time() - 7200 if t0 is None else t0
+ sig = SG.load_unlocked(home)
+ t = t0
+ for i in range(times):
+ evs = [(n, SG.arg_shape({CANARY_KEY: 1}), t + 300 * j) for j, n in enumerate(names)]
+ evs.append((f"Sep{i}", SG.arg_shape({}), t + 300 * len(names)))
+ SG.apply_tool_events(sig, "aaaaaaaa", evs, time.time())
+ t += 300 * (len(names) + 1)
+ SG.save_unlocked(home, sig)
+
+
+# ----------------------------------------------------------------------
+# sibyl skills signals
+# ----------------------------------------------------------------------
+
+def test_status_prints_counts_never_entries(home, pro, capsys):
+ _record(home)
+ assert cli.main(_acct(pro) + ["skills", "signals"]) == 0
+ out = capsys.readouterr().out
+ assert "recording" in out and "on" in out and "sequences" in out and "KB" in out
+ assert CANARY_TOOL not in out and "canary" not in out.lower() and CANARY_KEY not in out
+ assert "Read" not in out and "Edit" not in out
+ assert cli.main(_acct(pro) + ["skills", "signals", "status"]) == 0
+ assert "sequences" in capsys.readouterr().out
+
+
+def test_status_on_free_and_on_a_locked_device_says_pro(home, sm, test_signer, capsys):
+ assert cli.main(_acct(sm) + ["skills", "signals", "status"]) == 0
+ assert "Skill signals are on Pro." in capsys.readouterr().out
+ write_entitlement(sm, test_signer.sign_payload(test_signer.payload(
+ now=time.time() - 40 * 86400, tier="pro", cap=None, src="pro")))
+ assert cli.main(_acct(sm) + ["skills", "signals", "status"]) == 0
+ assert "Skill signals are on Pro." in capsys.readouterr().out
+ assert not SG.path_of(home).exists()
+
+
+def test_on_on_free_changes_nothing_off_and_clear_work_everywhere(home, sm, capsys):
+ ST.LifecycleState(home).update(lambda st: st.setdefault("skills", ST.default_skills())
+ .update(signals=False))
+ assert cli.main(_acct(sm) + ["skills", "signals", "on"]) == 0
+ assert "Skill signals are on Pro." in capsys.readouterr().out
+ assert SG.enabled(home) is False
+ _record(home) # a file left from an earlier Pro period
+ assert cli.main(_acct(sm) + ["skills", "signals", "status"]) == 0
+ assert "earlier Pro period" in capsys.readouterr().out
+ assert cli.main(_acct(sm) + ["skills", "signals", "clear"]) == 0
+ assert not SG.path_of(home).exists()
+ assert cli.main(_acct(sm) + ["skills", "signals", "off"]) == 0
+ assert SG.enabled(home) is False
+
+
+def test_clear_off_on_on_pro(home, pro, capsys):
+ _record(home)
+ assert cli.main(_acct(pro) + ["skills", "signals", "clear"]) == 0
+ out = capsys.readouterr().out
+ assert "signals.json deleted" in out
+ assert not SG.path_of(home).exists()
+ assert cli.main(_acct(pro) + ["skills", "signals", "clear"]) == 0
+ assert "nothing was recorded" in capsys.readouterr().out
+ assert cli.main(_acct(pro) + ["skills", "signals", "off"]) == 0
+ assert SG.enabled(home) is False
+ assert cli.main(_acct(pro) + ["skills", "signals"]) == 0
+ assert "off (sibyl skills signals on)" in capsys.readouterr().out
+ before = time.time()
+ assert cli.main(_acct(pro) + ["skills", "signals", "on"]) == 0
+ st = ST.LifecycleState(home).load()["skills"]
+ assert st["signals"] is True and st["signals_since"] >= before
+
+
+def test_save_fact_counts_as_an_entity_write_on_pro(home, pro, capsys):
+ assert cli.main(_acct(pro) + ["save", "--fact", "the deploy key rotates monthly"]) == 0
+ SG.flush_all()
+ sig = SG.load(home)
+ assert len(sig["entity_writes"]) == 1
+ assert b"deploy key" not in SG.path_of(home).read_bytes()
+
+
+# ----------------------------------------------------------------------
+# sibyl skills proposals with the two new kinds
+# ----------------------------------------------------------------------
+
+def test_mute_accepts_the_new_kinds(home, sm, capsys):
+ for k in ("tool_sequence", "correction_loop"):
+ assert cli.main(_acct(sm) + ["skills", "proposals", "mute", k]) == 0
+ assert set(ST.LifecycleState(home).load()["skills"]["muted_kinds"]) == {"tool_sequence", "correction_loop"}
+ capsys.readouterr()
+ assert cli.main(_acct(sm) + ["skills", "proposals", "mute", "nonsense"]) == 1
+ assert "tool_sequence" in capsys.readouterr().out
+
+
+def test_tool_sequence_proposal_list_show_accept_reject(home, pro, tmp_path, capsys):
+ from sibyl_memory_client.lifecycle import proposals as PR
+ _record(home, names=("Read", "Edit", "Bash"))
+ c = _client(pro)
+ rep = PR.run_learner(c, home=home)
+ assert rep is not None and rep.proposals_made == 1
+ p = c.learner().get_proposal(rep.proposal_ids[0])
+ assert p.pattern_kind == "tool_sequence"
+ assert cli.main(_acct(pro) + ["skills", "proposals"]) == 0
+ out = capsys.readouterr().out
+ assert "tool_sequence" in out and p.id[:8] in out
+ assert cli.main(_acct(pro) + ["skills", "proposals", "show", p.id[:8]]) == 0
+ assert "Recurring tool sequence: `Read -> Edit -> Bash`" in capsys.readouterr().out
+ dest = tmp_path / "skills-out"
+ assert cli.main(_acct(pro) + ["skills", "proposals", "accept", p.id, "--to", str(dest)]) == 0
+ name = SK.skill_name(p.proposed_slug)
+ text = (dest / name / "SKILL.md").read_text()
+ assert SK.validate_skill_text(text, name) == []
+ assert c.get_reference(f"skill/{p.proposed_slug}") is not None
+ # mute tool_sequence: the next run proposes no tool sequence
+ assert cli.main(_acct(pro) + ["skills", "proposals", "mute", "tool_sequence"]) == 0
+ _record(home, names=("Grep", "Write", "Bash"), t0=time.time() - 3600)
+ assert PR.run_learner(c, home=home).proposals_made == 0
+ assert cli.main(_acct(pro) + ["skills", "proposals", "unmute", "tool_sequence"]) == 0
+ rep2 = PR.run_learner(c, home=home)
+ assert rep2.proposals_made == 1
+ p2 = c.learner().get_proposal(rep2.proposal_ids[0])
+ assert cli.main(_acct(pro) + ["skills", "proposals", "reject", p2.id]) == 0
+ assert "not proposed again for 30 days" in capsys.readouterr().out
+ assert PR.run_learner(c, home=home).proposals_made == 0
diff --git a/sibyl-memory-cli/tests/test_status_stores_2026_06_11.py b/sibyl-memory-cli/tests/test_status_stores_2026_06_11.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d3295e454a02be702747f1009bc0ae7427cfc1d
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_status_stores_2026_06_11.py
@@ -0,0 +1,70 @@
+"""PKG-2/3 regression: `sibyl status` discovers + lists every memory store and
+warns on split-brain divergence (beta report 2026-06-11).
+
+Read-only: discovery never creates or moves a DB.
+"""
+import os
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+
+
+@pytest.fixture
+def sandbox(monkeypatch):
+ d = Path(tempfile.mkdtemp())
+ primary = d / ".sibyl-memory" / "memory.db"
+ primary.parent.mkdir(parents=True)
+ hermes = d / ".hermes"
+ (hermes / "sibyl").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(hermes))
+ monkeypatch.delenv("SIBYL_MEMORY_DB", raising=False)
+ return d, primary, hermes
+
+
+def test_discovers_default_hermes_and_profiles(sandbox):
+ d, primary, hermes = sandbox
+ primary.write_bytes(b"x" * 100)
+ (hermes / "sibyl" / "memory.db").write_bytes(b"y" * 200)
+ prof = hermes / "sibyl" / "profiles" / "alpha"
+ prof.mkdir(parents=True)
+ (prof / "memory.db").write_bytes(b"z" * 50)
+
+ stores = cli._discover_stores(primary)
+ labels = {s["label"] for s in stores}
+ assert "default (SDK/CLI/MCP)" in labels
+ assert "hermes adapter" in labels
+ assert any(l.startswith("hermes profile") for l in labels)
+ assert {s["size"] for s in stores} == {100, 200, 50}
+
+
+def test_skips_nonexistent_and_dedups(sandbox):
+ d, primary, hermes = sandbox
+ primary.write_bytes(b"x" * 10)
+ # hermes adapter db does not exist → excluded
+ stores = cli._discover_stores(primary)
+ assert [s["label"] for s in stores] == ["default (SDK/CLI/MCP)"]
+
+
+def test_mcp_override_included(sandbox, monkeypatch):
+ d, primary, hermes = sandbox
+ primary.write_bytes(b"x" * 10)
+ shadow = d / "shadow.db"
+ shadow.write_bytes(b"s" * 5)
+ monkeypatch.setenv("SIBYL_MEMORY_DB", str(shadow))
+ stores = cli._discover_stores(primary)
+ assert any(s["label"] == "MCP SIBYL_MEMORY_DB" for s in stores)
+
+
+def test_status_warns_on_divergence(sandbox, capsys):
+ d, primary, hermes = sandbox
+ primary.write_bytes(b"x" * 100)
+ (hermes / "sibyl" / "memory.db").write_bytes(b"y" * 200)
+
+ # Build the minimal args cmd_status reads. No credentials → early-return
+ # path, so drive discovery directly to assert the warning copy instead.
+ stores = cli._discover_stores(primary)
+ with_data = [s for s in stores if s["size"] > 0]
+ assert len(with_data) > 1 # divergence condition that triggers the warning
diff --git a/sibyl-memory-cli/tests/test_superpatch_2026_07_05.py b/sibyl-memory-cli/tests/test_superpatch_2026_07_05.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f0116595e10f78092742bb2195445aede83c925
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_superpatch_2026_07_05.py
@@ -0,0 +1,138 @@
+"""Regression tests for the 2026-07-05 super-patch (Unit CLI).
+
+ Real #4 `sibyl logout` must best-effort REVOKE this device's server bearer
+ before unlinking local credentials (the bearer has no server-side
+ expiry), reusing the same /api/plugin/devices endpoint + Bearer
+ auth as `sibyl devices revoke`. A network failure is swallowed but
+ REPORTED as an offline caveat.
+ Contract T `sibyl init` must PERSIST the server-issued tenant_id into
+ credentials.json (it was dropped from the _CRED_FIELDS allowlist),
+ so every surface resolves the same tenant.
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from sibyl_memory_cli import cli
+
+
+# ----------------------------------------------------------------------
+# Real #4 — logout revokes this device's server bearer
+# ----------------------------------------------------------------------
+
+def _write_creds(path: Path, **extra) -> None:
+ creds = {"account_id": "acct-1", "session_token": "tok-abc", "tier": "paid"}
+ creds.update(extra)
+ path.write_text(json.dumps(creds))
+
+
+def test_logout_issues_revoke_when_online(tmp_path, monkeypatch, capsys):
+ cred = tmp_path / "credentials.json"
+ tc = tmp_path / "tier_cache.json"
+ _write_creds(cred)
+ tc.write_text("{}")
+
+ calls: list[tuple] = []
+
+ def fake_http(method, path, *, body=None, timeout=15.0, headers=None):
+ calls.append((method, path, body, headers))
+ if method == "GET" and path.startswith("/api/plugin/devices"):
+ return {"devices": [
+ {"is_this_device": False, "bearer_id": "other", "device_label": "phone"},
+ {"is_this_device": True, "bearer_id": "bid-9", "device_label": "thislaptop"},
+ ]}
+ if method == "POST" and path == "/api/plugin/devices":
+ return {"revoked": True}
+ raise AssertionError(f"unexpected call {method} {path}")
+
+ monkeypatch.setattr(cli, "http_request", fake_http)
+
+ rc = cli.main(["--credentials", str(cred), "--tier-cache", str(tc), "logout"])
+ assert rc == 0
+
+ # A POST revoke was issued for THIS device's bearer_id, with the bearer auth
+ # shape reused from `sibyl devices revoke`.
+ posts = [c for c in calls if c[0] == "POST" and c[1] == "/api/plugin/devices"]
+ assert posts, "logout did not issue the server-side revoke POST"
+ assert posts[0][2] == {"bearer_id": "bid-9"}
+ assert posts[0][3].get("Authorization") == "Bearer tok-abc"
+
+ # Local logout still happened; no offline caveat on the happy path.
+ out = capsys.readouterr().out
+ assert not cred.exists()
+ assert "remote session may still be active" not in out
+
+
+def test_logout_prints_offline_caveat_on_network_failure(tmp_path, monkeypatch, capsys):
+ cred = tmp_path / "credentials.json"
+ tc = tmp_path / "tier_cache.json"
+ _write_creds(cred)
+
+ def fake_http_fail(method, path, *, body=None, timeout=15.0, headers=None):
+ # Simulate the CLI's network-failure envelope (URLError -> HttpError 0).
+ raise cli.HttpError(0, {"error": "network unreachable"}, f"http://x{path}")
+
+ monkeypatch.setattr(cli, "http_request", fake_http_fail)
+
+ rc = cli.main(["--credentials", str(cred), "--tier-cache", str(tc), "logout"])
+ out = capsys.readouterr().out
+
+ # Failure is swallowed (logout succeeds locally) but the caveat is reported.
+ assert rc == 0
+ assert not cred.exists()
+ assert "remote session may still be active" in out
+ assert "sibyl devices revoke" in out
+
+
+def test_logout_without_bearer_id_reports_caveat(tmp_path, monkeypatch, capsys):
+ """Server lists devices but can't identify this one -> can't confirm revoke."""
+ cred = tmp_path / "credentials.json"
+ tc = tmp_path / "tier_cache.json"
+ _write_creds(cred)
+
+ def fake_http(method, path, *, body=None, timeout=15.0, headers=None):
+ if method == "GET" and path.startswith("/api/plugin/devices"):
+ return {"devices": [{"is_this_device": False, "bearer_id": "other"}]}
+ raise AssertionError(f"unexpected call {method} {path}")
+
+ monkeypatch.setattr(cli, "http_request", fake_http)
+
+ rc = cli.main(["--credentials", str(cred), "--tier-cache", str(tc), "logout"])
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert not cred.exists()
+ assert "remote session may still be active" in out
+
+
+# ----------------------------------------------------------------------
+# Contract T — init persists the server-issued tenant_id
+# ----------------------------------------------------------------------
+
+def test_init_persists_server_tenant_id(tmp_path, monkeypatch):
+ cred = tmp_path / "credentials.json" # absent -> fresh activation
+
+ def fake_http(method, path, *, body=None, timeout=15.0, headers=None):
+ if path.startswith("/api/plugin/session-init"):
+ return {"pairing_ttl_seconds": 300}
+ if path.startswith("/api/plugin/check"):
+ return {"bound": True, "credentials": {
+ "account_id": "acct-1",
+ "tenant_id": "tid-server-issued",
+ "tier": "paid",
+ "bearer_token": "btok-123",
+ }}
+ raise AssertionError(f"unexpected call {method} {path}")
+
+ monkeypatch.setattr(cli, "http_request", fake_http)
+ # Don't spawn a browser in CI.
+ monkeypatch.setattr(cli.webbrowser, "open", lambda *a, **k: True)
+
+ rc = cli.main(["--credentials", str(cred), "init"])
+ assert rc == 0
+
+ persisted = json.loads(cred.read_text())
+ # THE regression: tenant_id must survive activation (was dropped pre-fix).
+ assert persisted.get("tenant_id") == "tid-server-issued"
+ assert persisted.get("account_id") == "acct-1"
+ assert persisted.get("session_token") == "btok-123" # bearer persisted
diff --git a/sibyl-memory-cli/tests/test_telemetry_default_2026_10_28.py b/sibyl-memory-cli/tests/test_telemetry_default_2026_10_28.py
new file mode 100644
index 0000000000000000000000000000000000000000..052cce06cb91db5f654713fa1fc1bbd9672d4bc3
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_telemetry_default_2026_10_28.py
@@ -0,0 +1,27 @@
+"""cli 0.6.0: the agent-equivalent client the CLI builds (`sibyl save --fact`)
+keeps the usage-count opt-out default (Hermes turned its own off in 0.6.0)."""
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+
+from sibyl_memory_cli import lifecycle_cli as L
+from sibyl_memory_client._heartbeat import HeartbeatReporter
+
+
+def _args(tmp_path):
+ return argparse.Namespace(credentials=str(Path.home() / ".sibyl-memory" / "credentials.json"),
+ db=str(tmp_path / "m.db"))
+
+
+def test_cli_client_reports_by_default(monkeypatch, tmp_path) -> None:
+ monkeypatch.delenv("SIBYL_MEMORY_TELEMETRY", raising=False)
+ hb = L._client(_args(tmp_path))._heartbeat
+ assert isinstance(hb, HeartbeatReporter)
+ assert hb._enabled is bool(hb._account_id)
+
+
+def test_cli_client_opt_out(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("SIBYL_MEMORY_TELEMETRY", "0")
+ hb = L._client(_args(tmp_path))._heartbeat
+ assert isinstance(hb, HeartbeatReporter) and hb._enabled is False
diff --git a/sibyl-memory-cli/tests/test_tier_plan_2026_10_08.py b/sibyl-memory-cli/tests/test_tier_plan_2026_10_08.py
new file mode 100644
index 0000000000000000000000000000000000000000..e205e41361323050f594f28667971f037a470638
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_tier_plan_2026_10_08.py
@@ -0,0 +1,270 @@
+"""QA findings F1 and F2 (2026-10-08).
+
+F1: every user-facing tier line shows the tier of the current verified pass
+(the saved credentials tier only without a valid pass), and a refresh or a
+background re-check rewrites the saved tier so every reader agrees. One tier
+per screen.
+
+F2: `sibyl status` shows the billing date from the pass's acct.plan
+(`Plan Pro · ends 8 Oct 2027` / `Pro · renews 8 Oct 2027`), and the access
+row says `re-checks in Xh` (the pass re-check), never `renews in`.
+
+`cli.http_request` is a routing fake and the gate's refresh transport is
+scripted per test; nothing reaches the network (the conftest refuses it).
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+import stat
+import time
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import _account_gate as G
+from sibyl_memory_client import _entitlement as E
+from sibyl_memory_client.testing import write_entitlement
+
+ACCT = "11111111-2222-4333-8444-555555555555"
+BEARER = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
+PRO_ACCESS = {"ok": True, "tier": "pro", "source": "subscription", "cap_bytes": None}
+FREE_ACCESS = {"ok": True, "tier": "free", "source": "free", "cap_bytes": 5242880}
+ACCT_BASE = {"complete": True, "email_verified": True, "email_required": False,
+ "grace_until": None, "enforced": False, "purchase_blocked": False}
+
+
+class FakeServer:
+ def __init__(self):
+ self.routes: dict = {}
+
+ def on(self, method, prefix, resp):
+ self.routes[(method, prefix)] = resp
+ return self
+
+ def __call__(self, method, path, *, body=None, timeout=15.0, headers=None):
+ for (m, prefix), resp in self.routes.items():
+ if m == method and path.startswith(prefix):
+ if isinstance(resp, cli.HttpError):
+ raise resp
+ return json.loads(json.dumps(resp))
+ raise cli.HttpError(404, {"error": "not routed"}, f"https://api{path}")
+
+
+@pytest.fixture()
+def server(monkeypatch):
+ s = FakeServer()
+ monkeypatch.setattr(cli, "http_request", s)
+ return s
+
+
+@pytest.fixture()
+def refresh(monkeypatch):
+ state = {"outcome": E.RefreshOutcome("transient", code="offline"), "calls": 0}
+
+ def fn(account_id, session_token):
+ state["calls"] += 1
+ out = state["outcome"]
+ return out(account_id, session_token) if callable(out) else out
+ monkeypatch.setattr(E, "http_refresh", fn)
+ return state
+
+
+def write_creds(path: Path, mode: int = 0o600, **over) -> Path:
+ c = {"account_id": ACCT, "tenant_id": ACCT, "tier": "free", "email": "u@example.com",
+ "wallet": None, "issued_at": "2026-09-27T00:00:00Z", "schema_version": 3,
+ "session_token": BEARER, "bearer_token": BEARER}
+ c.update(over)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(c))
+ os.chmod(path, mode)
+ return path
+
+
+def mint(signer, **kw):
+ return signer.mint(account_id=ACCT, session_token=BEARER, **kw)
+
+
+def pro_token(signer, plan=None, **kw):
+ acct = dict(ACCT_BASE, plan=dict({"tier": "pro", "src": "card"}, **(plan or {})))
+ return mint(signer, tier="pro", cap=None, src="subscription", acct=acct, **kw)
+
+
+def free_token(signer, **kw):
+ acct = dict(ACCT_BASE, plan={"tier": "free", "src": "none"})
+ return mint(signer, tier="free", acct=acct, **kw)
+
+
+def run(tail, tmp_path):
+ return cli.main(["--credentials", str(tmp_path / "credentials.json"), "--db", str(tmp_path / "memory.db"),
+ "--tier-cache", str(tmp_path / "tier_cache.json")] + tail)
+
+
+def status(tmp_path, server, capsys, access):
+ server.on("POST", "/api/plugin/access", access)
+ rc = run(["status"], tmp_path)
+ return rc, capsys.readouterr().out
+
+
+def tier_rows(out: str) -> list[str]:
+ return [m.group(1) for m in re.finditer(r"^\s+Tier\s{2,}(\S+)", out, re.M)]
+
+
+def saved(tmp_path) -> dict:
+ return json.loads((tmp_path / "credentials.json").read_text())
+
+
+# ---- F1: status after a pass with a different tier than the saved one ------
+
+def test_signed_in_free_then_bought_pro_status_shows_pro_everywhere(tmp_path, server, test_signer,
+ refresh, capsys) -> None:
+ write_creds(tmp_path / "credentials.json", tier="free", signature="sig", signed_at="2026-09-27")
+ refresh["outcome"] = lambda a, s: E.RefreshOutcome("ok", token=pro_token(test_signer))
+ rc, out = status(tmp_path, server, capsys, PRO_ACCESS)
+ assert rc == 0
+ assert tier_rows(out) == ["Pro", "Pro"], out # LOCAL and SERVER agree
+ assert "differs from server tier" not in out
+ assert "uncapped" in out or "not created" in out # cap follows the shown tier
+ c = saved(tmp_path)
+ assert c["tier"] == "pro" # the refresh rewrote the saved tier
+ assert "signature" not in c and "signed_at" not in c # a signed field never changes under an old signature
+ assert c["session_token"] == BEARER and c["email"] == "u@example.com"
+
+
+def test_pro_ended_status_shows_free_even_offline(tmp_path, server, test_signer, refresh, capsys) -> None:
+ # saved Pro, the last verified pass says Free, this check-in fails (offline)
+ write_creds(tmp_path / "credentials.json", tier="pro")
+ write_entitlement(tmp_path, free_token(test_signer))
+ rc, out = status(tmp_path, server, capsys, FREE_ACCESS)
+ assert tier_rows(out) == ["Free", "Free"], out
+ assert saved(tmp_path)["tier"] == "pro" # no check-in happened: nothing rewritten
+ assert "differs from server tier" not in out
+
+
+def test_no_valid_pass_falls_back_to_the_saved_tier(tmp_path, server, refresh, capsys) -> None:
+ write_creds(tmp_path / "credentials.json", tier="pro") # no entitlement, refresh fails
+ rc, out = status(tmp_path, server, capsys, PRO_ACCESS)
+ assert tier_rows(out)[0] == "Pro"
+ assert saved(tmp_path)["tier"] == "pro"
+
+
+def test_stale_tier_cache_is_not_shown_as_a_second_tier(tmp_path, server, test_signer, refresh, capsys) -> None:
+ write_creds(tmp_path / "credentials.json", tier="pro")
+ write_entitlement(tmp_path, pro_token(test_signer))
+ (tmp_path / "tier_cache.json").write_text(json.dumps({"tier": "free", "checked_at": time.time()}))
+ rc, out = status(tmp_path, server, capsys, PRO_ACCESS)
+ line = [ln for ln in out.splitlines() if "Tier cache" in ln][0]
+ assert "superseded by the access pass" in line and "free" not in line
+
+
+def test_refresh_rewrites_the_saved_tier_atomically_keeping_the_mode(tmp_path, server, test_signer,
+ refresh, capsys) -> None:
+ cred = write_creds(tmp_path / "credentials.json", mode=0o640, tier="free")
+ ino_before = os.stat(cred).st_ino
+ (tmp_path / "tier_cache.json").write_text(json.dumps({"tier": "free", "checked_at": time.time()}))
+ refresh["outcome"] = lambda a, s: E.RefreshOutcome("ok", token=pro_token(test_signer))
+ assert run(["refresh"], tmp_path) == 0
+ out = capsys.readouterr().out
+ assert "-> pro" in out
+ assert saved(tmp_path)["tier"] == "pro"
+ assert stat.S_IMODE(os.stat(cred).st_mode) == 0o640 # same file mode
+ assert os.stat(cred).st_ino != ino_before # replaced, not edited in place
+ assert not list(tmp_path.glob("credentials.json.*.tmp")) # no temp left behind
+ assert not (tmp_path / "tier_cache.json").exists() # the old cached answer goes with it
+ # and back to Free when the plan ends
+ refresh["outcome"] = lambda a, s: E.RefreshOutcome("ok", token=free_token(test_signer))
+ assert run(["refresh"], tmp_path) == 0
+ capsys.readouterr()
+ assert saved(tmp_path)["tier"] == "free"
+
+
+def test_whoami_and_init_already_activated_show_the_pass_tier(tmp_path, test_signer, capsys) -> None:
+ write_creds(tmp_path / "credentials.json", tier="free")
+ write_entitlement(tmp_path, pro_token(test_signer))
+ assert run(["whoami"], tmp_path) == 0
+ assert "PRO" in capsys.readouterr().out
+ assert run(["init"], tmp_path) == 0
+ out = capsys.readouterr().out
+ assert re.search(r"Tier\s+PRO", out), out
+
+
+def test_init_already_activated_without_a_pass_shows_the_saved_tier(tmp_path, capsys) -> None:
+ write_creds(tmp_path / "credentials.json", tier="pro")
+ assert run(["init"], tmp_path) == 0
+ assert re.search(r"Tier\s+PRO", capsys.readouterr().out)
+ assert not (tmp_path / "entitlement.json").exists() # looking left no file behind
+
+
+def test_display_tier_rules() -> None:
+ assert G.display_tier(None, "pro") == "pro"
+ assert G.display_tier({"state": "locked", "tier": "pro"}, "free") == "free"
+ assert G.display_tier({"state": "fresh", "tier": "pro", "tier_effective": "pro"}, "free") == "pro"
+ assert G.display_tier({"state": "stale", "tier": "free", "tier_effective": "free"}, "pro") == "free"
+ # an unrecognised label is shown as it is enforced: Free
+ assert G.display_tier({"state": "fresh", "tier": "platinum", "tier_effective": "free"}, "pro") == "free"
+
+
+# ---- F2: Plan row and the re-check label ----------------------------------
+
+def test_status_plan_ends_on_a_scheduled_cancel(tmp_path, server, test_signer, refresh, capsys,
+ monkeypatch) -> None:
+ monkeypatch.setenv("TZ", "UTC")
+ time.tzset()
+ try:
+ write_creds(tmp_path / "credentials.json", tier="pro")
+ refresh["outcome"] = lambda a, s: E.RefreshOutcome("ok", token=pro_token(
+ test_signer, plan={"ends_at": "2027-10-08T12:00:00.000Z"}))
+ rc, out = status(tmp_path, server, capsys, PRO_ACCESS)
+ assert re.search(r"^\s+Plan\s+Pro · ends 8 Oct 2027$", out, re.M), out
+ assert "renews 8 Oct" not in out
+ assert "active · re-checks in" in out and "renews in" not in out
+ plan_line = [ln for ln in out.splitlines() if re.match(r"^\s+Plan\s", ln)][0]
+ assert "\u2014" not in plan_line # no em dash
+ finally:
+ monkeypatch.delenv("TZ")
+ time.tzset()
+
+
+def test_status_plan_renews_for_a_renewing_card_plan(tmp_path, server, test_signer, refresh, capsys,
+ monkeypatch) -> None:
+ monkeypatch.setenv("TZ", "UTC")
+ time.tzset()
+ try:
+ write_creds(tmp_path / "credentials.json", tier="pro")
+ refresh["outcome"] = lambda a, s: E.RefreshOutcome("ok", token=pro_token(
+ test_signer, plan={"renews_at": "2027-10-08T12:00:00Z"}))
+ rc, out = status(tmp_path, server, capsys, PRO_ACCESS)
+ assert re.search(r"^\s+Plan\s+Pro · renews 8 Oct 2027$", out, re.M), out
+ finally:
+ monkeypatch.delenv("TZ")
+ time.tzset()
+
+
+def test_status_has_no_plan_row_without_a_date(tmp_path, server, test_signer, refresh, capsys) -> None:
+ write_creds(tmp_path / "credentials.json", tier="pro")
+ refresh["outcome"] = lambda a, s: E.RefreshOutcome("ok", token=pro_token(test_signer))
+ rc, out = status(tmp_path, server, capsys, PRO_ACCESS)
+ assert not re.search(r"^\s+Plan\s", out, re.M)
+
+
+def test_plan_row_rules() -> None:
+ fresh = {"state": "fresh", "tier": "pro", "tier_effective": "pro"}
+ assert G.plan_row(None) is None
+ assert G.plan_row(dict(fresh)) is None
+ assert G.plan_row(dict(fresh, plan={"tier": "pro", "src": "card"})) is None
+ assert G.plan_row(dict(fresh, plan={"tier": "pro", "src": "card", "ends_at": "garbage"})) is None
+ assert G.plan_row({"state": "locked", "plan": {"ends_at": "2027-10-08T12:00:00Z"}}) is None
+ row = G.plan_row(dict(fresh, plan={"tier": "pro", "src": "card", "ends_at": "2027-10-08T12:00:00Z"}))
+ assert row.startswith("Pro · ends ") and "Oct 2027" in row
+ # the tier word is the shown tier, never a second label from the plan
+ row = G.plan_row(dict(fresh, plan={"tier": "elite", "src": "comp", "ends_at": "2027-10-08T12:00:00Z"}))
+ assert row.startswith("Pro ")
+
+
+def test_access_row_says_re_checks_not_renews() -> None:
+ assert G.access_row({"state": "fresh", "tier_known": True, "renews_in_seconds": 7200}) == \
+ "active · re-checks in 2h"
+ ro = G.access_row({"state": "fresh", "tier_known": True, "renews_in_seconds": 3600, "mem": "read_only"})
+ assert ro.endswith("re-checks in 1h") and "renews" not in ro
diff --git a/sibyl-memory-cli/tests/test_tiers_cli_2026_10_05.py b/sibyl-memory-cli/tests/test_tiers_cli_2026_10_05.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c65870c15c122ecaf5487927977c298ba7f8088
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_tiers_cli_2026_10_05.py
@@ -0,0 +1,202 @@
+"""Tier convention, CLI side (spec tier-convention-spec-2026-10-05, 5.2 and 5.4).
+
+`sibyl status` prints Free / Pro / Elite; an unrecognised signed label prints
+the `tier_unknown` access row; a 503 `tier_unknown` from the server keeps the
+token and prints the renewal-paused row. The hooks keep a stdlib-only literal
+mirror of the client's paid set; the source guard at the bottom is the CLI's
+grep gate.
+"""
+from __future__ import annotations
+
+import ast
+import builtins
+import json
+import re
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_cli import hooks as H
+from sibyl_memory_client import _entitlement as E
+from sibyl_memory_client import tiers
+from sibyl_memory_client.testing import write_entitlement
+
+ACCT = "11111111-2222-4333-8444-555555555555"
+BEARER = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
+ACCT_OBJ = {"complete": True, "email_verified": True, "email_required": False,
+ "grace_until": None, "enforced": False, "purchase_blocked": False}
+
+
+@pytest.fixture(autouse=True)
+def _quiet(monkeypatch):
+ monkeypatch.setenv("SIBYL_MEMORY_TELEMETRY", "0")
+ monkeypatch.setenv("NO_COLOR", "1")
+ monkeypatch.setattr(cli.time, "sleep", lambda *_: None)
+ monkeypatch.setattr(cli, "invalidate_tier_cache", lambda *a, **k: None)
+ monkeypatch.setattr(builtins, "input", lambda *a, **k: "")
+
+
+@pytest.fixture()
+def access(monkeypatch):
+ """Route `/api/plugin/access` (the status server view); everything else 404."""
+ state = {"body": {"ok": True, "tier": "free", "source": "free", "cap_bytes": 5242880}}
+
+ def fake(method, path, *, body=None, timeout=15.0, headers=None):
+ if method == "POST" and path.startswith("/api/plugin/access"):
+ return json.loads(json.dumps(state["body"]))
+ raise cli.HttpError(404, {"error": "not routed"}, f"https://api{path}")
+ monkeypatch.setattr(cli, "http_request", fake)
+ return state
+
+
+@pytest.fixture()
+def refresh(monkeypatch):
+ state = {"outcome": E.RefreshOutcome("transient", code="offline")}
+
+ def fn(account_id, session_token):
+ out = state["outcome"]
+ return out(account_id, session_token) if callable(out) else out
+ monkeypatch.setattr(E, "http_refresh", fn)
+ return state
+
+
+def _creds(path: Path, tier: str) -> Path:
+ c = {"account_id": ACCT, "tenant_id": ACCT, "tier": tier, "email": "u@example.com",
+ "wallet": None, "issued_at": "2026-10-05T00:00:00Z", "schema_version": 3,
+ "session_token": BEARER, "bearer_token": BEARER}
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(c))
+ return path
+
+
+def _mint(signer, **kw):
+ return signer.mint(account_id=ACCT, session_token=BEARER, **kw)
+
+
+def _status(tmp_path, capsys) -> tuple[int, str]:
+ rc = cli.main(["--credentials", str(tmp_path / "credentials.json"),
+ "--db", str(tmp_path / "memory.db"),
+ "--tier-cache", str(tmp_path / "tier_cache.json"), "status"])
+ return rc, capsys.readouterr().out
+
+
+# ---- hooks mirror ---------------------------------------------------------
+
+def test_hooks_mirror_includes_elite():
+ assert H.PAID_TIERS == tiers.PAID_TIERS
+ assert "elite" in H.PAID_TIERS and "free" not in H.PAID_TIERS
+
+
+def _claim_file(sm: Path, signer, tier: str) -> Path:
+ write_entitlement(sm, signer.mint(tier=tier))
+ return sm / "credentials.json"
+
+
+@pytest.mark.parametrize("label,paid", [("elite", True), (" Elite ", True), ("PRO", True),
+ ("stake", True), ("gold", False), ("free", False)])
+def test_claims_paid_normalises_the_claim(entitled_home, test_signer, label, paid):
+ cred = _claim_file(entitled_home, test_signer, label)
+ assert H.claims_paid(cred) is paid
+ assert H.claim_label(cred) == label.strip().lower()
+
+
+def test_hook_logs_tier_unknown_for_an_unrecognised_label(tmp_path, entitled_home, test_signer):
+ home = entitled_home.parent
+ _claim_file(entitled_home, test_signer, "gold")
+ H.run_hook("session-start", json.dumps({"session_id": "s1", "cwd": str(tmp_path)}), home=home)
+ logs = list((home / ".sibyl-memory").rglob("lifecycle.log"))
+ assert logs, "no lifecycle.log written"
+ text = "".join(p.read_text() for p in logs)
+ assert "hook session-start: tier_unknown" in text
+
+
+def test_hook_logs_nothing_for_a_free_label(tmp_path, entitled_home, test_signer):
+ home = entitled_home.parent
+ _claim_file(entitled_home, test_signer, "free")
+ H.run_hook("session-start", json.dumps({"session_id": "s1", "cwd": str(tmp_path)}), home=home)
+ text = "".join(p.read_text() for p in (home / ".sibyl-memory").rglob("lifecycle.log"))
+ assert "tier_unknown" not in text
+
+
+# ---- sibyl status ---------------------------------------------------------
+
+def test_status_prints_elite(tmp_path, access, refresh, test_signer, capsys):
+ _creds(tmp_path / "credentials.json", "elite")
+ acct = dict(ACCT_OBJ, plan={"tier": "elite", "src": "comp"},
+ devices={"n": 1, "limit": 10, "over": False})
+ refresh["outcome"] = lambda a, s: E.RefreshOutcome(
+ "ok", token=_mint(test_signer, tier="elite", cap=None, src="subscription", acct=acct))
+ access["body"] = {"ok": True, "tier": "elite", "source": "subscription", "cap_bytes": None}
+ rc, out = _status(tmp_path, capsys)
+ assert rc == 0
+ assert len(re.findall(r"Tier\s+Elite\b", out)) == 2 # local and server view
+ assert "ELITE" not in out
+ assert "1 of 10 (Elite)" in out and "Pro: up to" not in out
+ assert "active · re-checks in" in out
+ assert "differs from server tier" not in out
+
+
+def test_status_legacy_local_label_is_not_drift(tmp_path, access, refresh, test_signer, capsys):
+ _creds(tmp_path / "credentials.json", "stake")
+ refresh["outcome"] = lambda a, s: E.RefreshOutcome(
+ "ok", token=_mint(test_signer, tier="pro", cap=None, src="staker"))
+ access["body"] = {"ok": True, "tier": "pro", "source": "staker", "cap_bytes": None}
+ rc, out = _status(tmp_path, capsys)
+ assert rc == 0
+ assert len(re.findall(r"Tier\s+Pro\b", out)) == 2
+ assert "STAKE" not in out and "differs from server tier" not in out
+
+
+def test_status_unknown_label_prints_the_tier_unknown_row(tmp_path, access, refresh, test_signer, capsys):
+ _creds(tmp_path / "credentials.json", "gold")
+ refresh["outcome"] = lambda a, s: E.RefreshOutcome(
+ "ok", token=_mint(test_signer, tier="gold", cap=None, src="subscription"))
+ rc, out = _status(tmp_path, capsys)
+ assert rc == 0
+ assert ('active · access label "gold" is not recognised by this version, treated as Free '
+ "(tier_unknown) · run sibyl update") in out
+ assert re.search(r"Tier\s+Free\b", out)
+ assert "% of free cap" in out or "not created" in out
+
+
+def test_status_server_503_tier_unknown_keeps_the_token(tmp_path, access, refresh, test_signer, capsys):
+ _creds(tmp_path / "credentials.json", "pro")
+ tok = _mint(test_signer, tier="pro", cap=None, src="subscription")
+ write_entitlement(tmp_path, tok)
+ refresh["outcome"] = E.RefreshOutcome("transient", code="tier_unknown")
+ rc, out = _status(tmp_path, capsys)
+ assert rc == 0
+ assert ("renewal paused · access label check (tier_unknown) · keep working; "
+ "it retries on its own") in out
+ assert json.loads((tmp_path / "entitlement.json").read_text())["token"] == tok
+
+
+def test_unknown_rows_do_not_hide_locked_states():
+ from sibyl_memory_cli import _account_gate as G
+ assert G.access_row({"state": "locked", "code": "signed_out", "tier_known": False,
+ "refresh_code": "tier_unknown"}) == "signed out · run sibyl init"
+ assert "re-checks in" in G.access_row({"state": "fresh", "tier_known": True, "renews_in_seconds": 3600})
+
+
+# ---- source guard (the CLI's grep gate) -------------------------------------
+
+def test_no_legacy_tier_literal_outside_the_hooks_mirror():
+ """No legacy tier name is spelled in the CLI package except the single
+ hooks.py mirror line, and that line parses to the client's paid set."""
+ pkg = Path(cli.__file__).parent
+ legacy = re.compile(r'"(sync|team|lifetime|stake|enterprise)"')
+ paid_set = re.compile(r'frozenset\(\{\s*"pro"')
+ hits, mirror = [], []
+ for p in sorted(pkg.rglob("*.py")):
+ for n, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1):
+ if p.name == "hooks.py" and line.startswith("PAID_TIERS = frozenset("):
+ mirror.append(line)
+ continue
+ if legacy.search(line) or paid_set.search(line):
+ hits.append(f"{p.relative_to(pkg)}:{n}: {line.strip()}")
+ assert hits == []
+ assert len(mirror) == 1
+ literal = ast.literal_eval(mirror[0].split("frozenset(", 1)[1].rsplit(")", 1)[0])
+ assert frozenset(literal) == tiers.PAID_TIERS
+
diff --git a/sibyl-memory-cli/tests/test_trust_context_2026_08_25.py b/sibyl-memory-cli/tests/test_trust_context_2026_08_25.py
new file mode 100644
index 0000000000000000000000000000000000000000..1be5c637efeed43f7a026020f231122e7939f56b
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_trust_context_2026_08_25.py
@@ -0,0 +1,78 @@
+"""Darwin trust-store fix (2026-08-25), CLI leg: `sibyl init` on the macOS
+python.org framework build failed every server call with
+`Warning: session-init failed (0)` (CERTIFICATE_VERIFY_FAILED surfacing as
+HttpError status 0). Both CLI network paths, http_request (all
+api.sibyllabs.org calls) and _pypi_latest (update check), now pass the shared
+certifi-backed context from sibyl_memory_client._trust, with a stdlib-default
+fallback when the client package is absent. These tests pin the wiring at both
+call sites and the graceful fallback."""
+from __future__ import annotations
+
+import ssl
+import sys
+import urllib.request
+
+from sibyl_memory_cli import cli
+
+
+class _Resp:
+ def __init__(self, body: bytes = b"{}"):
+ self._body = body
+ def read(self):
+ return self._body
+ def __enter__(self):
+ return self
+ def __exit__(self, *a):
+ return False
+
+
+def _shared_context():
+ from sibyl_memory_client import _trust
+ return _trust.https_context()
+
+
+def test_http_request_passes_trust_context(monkeypatch):
+ captured = {}
+
+ def fake_urlopen(req, timeout=None, context=None):
+ captured["context"] = context
+ return _Resp(b"{\"ok\": true}")
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+ out = cli.http_request("GET", "/api/plugin/whoami")
+ assert out == {"ok": True}
+ assert captured["context"] is _shared_context()
+
+
+def test_pypi_latest_passes_trust_context(monkeypatch):
+ captured = {}
+
+ def fake_urlopen(req, timeout=None, context=None):
+ captured["context"] = context
+ return _Resp(b"{\"info\": {\"version\": \"9.9.9\"}}")
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+ assert cli._pypi_latest("sibyl-memory-cli") == "9.9.9"
+ assert captured["context"] is _shared_context()
+
+
+def test_fallback_without_client_package(monkeypatch):
+ # sys.modules[name] = None makes the from-import raise ImportError.
+ monkeypatch.setitem(sys.modules, "sibyl_memory_client._trust", None)
+ ctx = cli._https_context() # must not raise
+ assert isinstance(ctx, ssl.SSLContext)
+ assert ctx.check_hostname is True
+ assert ctx.verify_mode == ssl.CERT_REQUIRED
+
+
+def test_fallback_still_serves_http_request(monkeypatch):
+ monkeypatch.setitem(sys.modules, "sibyl_memory_client._trust", None)
+ captured = {}
+
+ def fake_urlopen(req, timeout=None, context=None):
+ captured["context"] = context
+ return _Resp()
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+ assert cli.http_request("GET", "/api/plugin/whoami") == {}
+ assert isinstance(captured["context"], ssl.SSLContext)
diff --git a/sibyl-memory-cli/tests/test_update_installed_pkgs_2026_10_09.py b/sibyl-memory-cli/tests/test_update_installed_pkgs_2026_10_09.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a83d53ce26e3484214f9486df04681c0ebc29f6
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_update_installed_pkgs_2026_10_09.py
@@ -0,0 +1,179 @@
+"""`sibyl update` covers every INSTALLED Sibyl package (2026-10-09).
+
+The installer installs `sibyl-memory-cli[mcp]`, so the MCP server is on every standard install;
+`sibyl update --apply` used to leave it on the old version. Now cli, hermes, client, mcp and
+langgraph are each checked and upgraded when installed, and a package that is not installed is
+neither shown nor installed by --apply.
+
+PyPI (`_pypi_latest`), importlib.metadata (`_installed_version`), the install-method probe and
+`subprocess.call` are stubbed; nothing reaches the network.
+"""
+from __future__ import annotations
+
+import json
+import subprocess
+
+import pytest
+
+from sibyl_memory_cli import cli
+
+ALL = ("sibyl-memory-cli", "sibyl-memory-hermes", "sibyl-memory-client",
+ "sibyl-memory-mcp", "sibyl-memory-langgraph")
+
+
+def _stub(monkeypatch, installed: dict, latest: dict, method: str = "venv"):
+ asked = []
+
+ def pypi(pkg, timeout=4.0):
+ asked.append(pkg)
+ return latest.get(pkg)
+
+ monkeypatch.setattr(cli, "_installed_version", lambda pkg: installed.get(pkg))
+ monkeypatch.setattr(cli, "_pypi_latest", pypi)
+ monkeypatch.setattr(cli, "_detect_install_method", lambda: method)
+ return asked
+
+
+# The production install: cli[mcp] pulls client + hermes + mcp. No langgraph.
+STD = {"sibyl-memory-cli": "0.5.0", "sibyl-memory-hermes": "0.5.0",
+ "sibyl-memory-client": "0.9.0", "sibyl-memory-mcp": "0.3.0"}
+CURRENT = {"sibyl-memory-cli": "0.5.0", "sibyl-memory-hermes": "0.5.0",
+ "sibyl-memory-client": "0.9.0", "sibyl-memory-mcp": "0.3.0",
+ "sibyl-memory-langgraph": "0.3.0"}
+
+
+def _pip_calls(monkeypatch, rc=0):
+ calls = []
+
+ def call(args, *a, **k):
+ calls.append(list(args))
+ return rc
+ monkeypatch.setattr(subprocess, "call", call)
+ return calls
+
+
+def test_update_packages_lists_all_five():
+ assert cli.UPDATE_PACKAGES == ALL
+
+
+def test_mcp_outdated_is_listed_and_in_the_pip_call(monkeypatch, capsys):
+ asked = _stub(monkeypatch, STD, {**CURRENT, "sibyl-memory-mcp": "0.4.0"})
+ calls = _pip_calls(monkeypatch)
+ rc = cli.main(["update", "--apply"])
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert "sibyl-memory-mcp" in out and "0.4.0" in out
+ pip = calls[0]
+ assert pip[1:5] == ["-m", "pip", "install", "-U"]
+ assert pip[5:] == ["sibyl-memory-mcp"]
+ # langgraph is not installed: never asked of PyPI, never shown.
+ assert "sibyl-memory-langgraph" not in asked
+ assert "sibyl-memory-langgraph" not in out
+
+
+def test_cli_and_mcp_upgrade_in_one_pip_call(monkeypatch, capsys):
+ _stub(monkeypatch, STD, {**CURRENT, "sibyl-memory-cli": "0.6.0", "sibyl-memory-mcp": "0.4.0"})
+ calls = _pip_calls(monkeypatch)
+ assert cli.main(["update", "--apply"]) == 0
+ capsys.readouterr()
+ pip_calls = [c for c in calls if "pip" in c]
+ assert len(pip_calls) == 1
+ assert pip_calls[0][5:] == ["sibyl-memory-cli", "sibyl-memory-mcp"]
+
+
+def test_langgraph_not_installed_absent_from_rows_and_pip_args(monkeypatch, capsys):
+ out_of_date = {p: "9.9.9" for p in ALL}
+ _stub(monkeypatch, STD, out_of_date)
+ calls = _pip_calls(monkeypatch)
+ cli.main(["update", "--apply"])
+ out = capsys.readouterr().out
+ assert "langgraph" not in out
+ assert "sibyl-memory-langgraph" not in calls[0]
+ assert calls[0][5:] == ["sibyl-memory-cli", "sibyl-memory-hermes",
+ "sibyl-memory-client", "sibyl-memory-mcp"]
+
+
+def test_langgraph_installed_is_included(monkeypatch, capsys):
+ installed = {**STD, "sibyl-memory-langgraph": "0.3.0"}
+ _stub(monkeypatch, installed, {**CURRENT, "sibyl-memory-langgraph": "0.4.0"})
+ calls = _pip_calls(monkeypatch)
+ assert cli.main(["update", "--apply"]) == 0
+ out = capsys.readouterr().out
+ assert "sibyl-memory-langgraph" in out
+ assert calls[0][5:] == ["sibyl-memory-langgraph"]
+
+
+def test_langgraph_installed_and_current_shows_as_a_row(monkeypatch, capsys):
+ installed = {**STD, "sibyl-memory-langgraph": "0.3.0"}
+ _stub(monkeypatch, installed, CURRENT)
+ assert cli.main(["update"]) == 0
+ out = capsys.readouterr().out
+ assert "All packages current." in out
+ for p in ALL:
+ assert p in out
+ assert "(not installed)" not in out
+
+
+def test_json_shape_unchanged_except_rows(monkeypatch, capsys):
+ _stub(monkeypatch, STD, {**CURRENT, "sibyl-memory-mcp": "0.4.0"})
+ rc = cli.main(["update", "--json"])
+ doc = json.loads(capsys.readouterr().out)
+ assert rc == 2
+ assert doc["any_outdated"] is True
+ assert doc["next"] == "sibyl update --apply"
+ pkgs = [r["pkg"] for r in doc["packages"]]
+ assert pkgs == ["sibyl-memory-cli", "sibyl-memory-hermes",
+ "sibyl-memory-client", "sibyl-memory-mcp"]
+ for r in doc["packages"]:
+ assert set(r) == {"pkg", "installed", "latest", "outdated"}
+ assert r["installed"] is not None
+ mcp = doc["packages"][3]
+ assert mcp == {"pkg": "sibyl-memory-mcp", "installed": "0.3.0",
+ "latest": "0.4.0", "outdated": True}
+
+
+def test_json_with_langgraph_installed_has_five_rows(monkeypatch, capsys):
+ _stub(monkeypatch, {**STD, "sibyl-memory-langgraph": "0.3.0"}, CURRENT)
+ assert cli.main(["update", "--json"]) == 0
+ doc = json.loads(capsys.readouterr().out)
+ assert [r["pkg"] for r in doc["packages"]] == list(ALL)
+ assert doc["any_outdated"] is False and doc["next"] == "done"
+
+
+@pytest.mark.parametrize("argv", [["update"], ["update", "--apply"]])
+def test_pipx_hint_lists_mcp_when_outdated(monkeypatch, capsys, argv):
+ _stub(monkeypatch, STD, {**CURRENT, "sibyl-memory-cli": "0.6.0", "sibyl-memory-mcp": "0.4.0"},
+ method="pipx")
+ calls = _pip_calls(monkeypatch)
+ rc = cli.main(argv)
+ out = capsys.readouterr().out
+ assert rc == 2
+ assert "pipx upgrade sibyl-memory-cli sibyl-memory-mcp" in out
+ assert not calls # pipx is never driven through pip
+
+
+def test_pipx_json_next_lists_mcp(monkeypatch, capsys):
+ _stub(monkeypatch, STD, {**CURRENT, "sibyl-memory-mcp": "0.4.0"}, method="pipx")
+ cli.main(["update", "--json"])
+ doc = json.loads(capsys.readouterr().out)
+ assert doc["next"] == "pipx upgrade sibyl-memory-mcp"
+
+
+def test_pep440_compare_kept_for_mcp(monkeypatch, capsys):
+ # 0.3.0 vs 0.3 is equal, 0.3.0 vs 0.3.1rc1 is older.
+ _stub(monkeypatch, STD, {**CURRENT, "sibyl-memory-mcp": "0.3"})
+ assert cli.main(["update", "--json"]) == 0
+ capsys.readouterr()
+ _stub(monkeypatch, STD, {**CURRENT, "sibyl-memory-mcp": "0.3.1rc1"})
+ assert cli.main(["update", "--json"]) == 2
+ doc = json.loads(capsys.readouterr().out)
+ assert [r["pkg"] for r in doc["packages"] if r["outdated"]] == ["sibyl-memory-mcp"]
+
+
+def test_mcp_pypi_unreachable_is_retry(monkeypatch, capsys):
+ latest = dict(CURRENT)
+ latest["sibyl-memory-mcp"] = None
+ _stub(monkeypatch, STD, latest)
+ assert cli.main(["update", "--json"]) == 0
+ doc = json.loads(capsys.readouterr().out)
+ assert doc["next"] == "retry"
diff --git a/sibyl-memory-cli/tests/test_verdict_contract_2026_08_31.py b/sibyl-memory-cli/tests/test_verdict_contract_2026_08_31.py
new file mode 100644
index 0000000000000000000000000000000000000000..85657257edabbd38438a8bc280eda736eb0c4f9f
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_verdict_contract_2026_08_31.py
@@ -0,0 +1,126 @@
+"""The verdict contract in the terminal (stage 3, 2026-08-31).
+
+`sibyl memory search` used to print "(no matches for 'x')" and stop. That is the
+terminal-shaped version of the defect this stage closes: a zero that cannot
+explain itself, and in the CLI's case the person reading it is a new user
+deciding whether the product works. "No matches" against an EMPTY store is the
+single most misleading thing this command could say, and it was what it said.
+
+These tests pin that every zero prints a cause in plain language, that the cause
+is the canonical one from `sibyl_memory_client.verdicts` rather than a
+CLI-local string, and that nothing about a successful search changed.
+"""
+from __future__ import annotations
+
+import ast
+import inspect
+from pathlib import Path
+
+from sibyl_memory_client import MemoryClient
+from sibyl_memory_client.verdicts import GateCause, VerdictCode
+from sibyl_memory_cli import cli
+
+
+def _store(tmp_path: Path) -> Path:
+ d = tmp_path / "memory.db"
+ c = MemoryClient.local(path=d)
+ c.set_entity("partner", "Blocktronics",
+ {"stage": "active", "note": "token forensics suite"})
+ c.set_entity("partner", "Reppo", {"stage": "negotiation"})
+ return d
+
+
+def _empty_store(tmp_path: Path) -> Path:
+ d = tmp_path / "empty.db"
+ MemoryClient.local(path=d)
+ return d
+
+
+def test_a_zero_result_prints_a_cause_not_just_no_matches(tmp_path, capsys):
+ d = _store(tmp_path)
+ rc = cli.main(["--db", str(d), "memory", "search", "qwzjvxzzyplm"])
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert "(no matches" in out
+ assert f"cause: {VerdictCode.NO_MATCH.value}" in out
+ assert "genuine miss" in out
+
+
+def test_an_empty_store_says_so_instead_of_blaming_the_query(tmp_path, capsys):
+ """The one that matters most to a new user: this is a fixable state, and
+ 'no matches' hid that behind what looks like a failed search."""
+ d = _empty_store(tmp_path)
+ rc = cli.main(["--db", str(d), "memory", "search", "anything at all"])
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert f"cause: {VerdictCode.EMPTY_STORE.value}" in out
+ assert "no rows yet" in out
+
+
+def test_the_cause_is_plain_language_a_human_can_act_on(tmp_path, capsys):
+ d = _empty_store(tmp_path)
+ cli.main(["--db", str(d), "memory", "search", "anything at all"])
+ out = capsys.readouterr().out
+ # a sentence, not an enum dump
+ assert "Nothing was returned" in out
+
+
+def test_a_successful_search_is_unchanged(tmp_path, capsys):
+ d = _store(tmp_path)
+ rc = cli.main(["--db", str(d), "memory", "search", "forensics"])
+ out = capsys.readouterr().out
+ assert rc == 0 and "Blocktronics" in out
+ assert "cause:" not in out # no noise on the success path
+
+# --------------------------------------------------------------------------
+# one vocabulary
+# --------------------------------------------------------------------------
+def _code_only(text: str) -> str:
+ """Strip docstrings and comments, leaving code.
+
+ Parsed, not split on `\"\"\"`. The first version of this helper did
+ `text.replace('\"\"\"', chr(0)).split(chr(0))[0::2]`, which silently INVERTS
+ which half it scans when the marker count is odd — the test would then check
+ the prose and skip the code, and still pass.
+ """
+ try:
+ tree = ast.parse(text)
+ except SyntaxError: # pragma: no cover
+ return text
+ spans = []
+ for node in ast.walk(tree):
+ body = getattr(node, "body", None)
+ if not isinstance(body, list): # ast.IfExp.body is an expr
+ continue
+ for child in body:
+ if (isinstance(child, ast.Expr)
+ and isinstance(child.value, ast.Constant)
+ and isinstance(child.value.value, str)):
+ spans.append((child.lineno, child.end_lineno))
+ drop = {i for a, b in spans for i in range(a, b + 1)}
+ return "\n".join(ln.split("#", 1)[0]
+ for i, ln in enumerate(text.splitlines(), 1) if i not in drop)
+
+
+#: Derived from the enums, so renaming a cause updates the guard automatically.
+CAUSE_LITERALS = tuple([c.value for c in VerdictCode if c is not VerdictCode.OK]
+ + [g.value for g in GateCause])
+
+
+def _assert_declares_no_vocabulary(*modules):
+ """BOTH quote styles. These tests originally checked only double quotes, and
+ an adversarial review slipped `_LOCAL_CAUSE_COPY = 'abstained_on'` into the
+ MCP server past a green suite — exactly the drift the guard exists to stop."""
+ offenders = []
+ for mod in modules:
+ code = _code_only(inspect.getsource(mod))
+ for lit in CAUSE_LITERALS:
+ if f'"{lit}"' in code or f"'{lit}'" in code:
+ offenders.append((mod.__name__, lit))
+ assert offenders == [], f"cause strings re-declared outside verdicts.py: {offenders}"
+
+
+def test_the_cli_imports_the_vocabulary_and_declares_none():
+ """One vocabulary, one module. The CLI prints causes; it does not own them."""
+ assert "from sibyl_memory_client.verdicts import refine_zero" in inspect.getsource(cli)
+ _assert_declares_no_vocabulary(cli)
diff --git a/sibyl-memory-cli/tests/test_version_2026_10_08.py b/sibyl-memory-cli/tests/test_version_2026_10_08.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a3dffe621bfe0b7919a7274213f49ea85e9d44b
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_version_2026_10_08.py
@@ -0,0 +1,135 @@
+"""Version row (2026-10-08): `sibyl --version` and the `Version` row of `sibyl status`.
+
+`sibyl --version` prints `sibyl ` and exits 0 without touching ~/.sibyl-memory (argparse's
+version action runs before the required-subcommand check). `sibyl status` prints a `plugin` eyebrow
+with one `Version cli · client ` row first, in both branches: not activated, and activated.
+
+`cli.http_request` is a routing fake and the gate's refresh transport is scripted; nothing reaches
+the network (the conftest refuses it).
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import cli
+from sibyl_memory_client import _entitlement as E
+
+ACCT = "11111111-2222-4333-8444-555555555555"
+BEARER = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
+FREE_ACCESS = {"ok": True, "tier": "free", "source": "free", "cap_bytes": 5242880}
+VERSION_ROW = re.compile(r"^\s+Version\s{2,}cli (\S+) · client (\S+(?: \S+)?)\s*$", re.M)
+
+
+class FakeServer:
+ def __init__(self):
+ self.routes: dict = {}
+
+ def on(self, method, prefix, resp):
+ self.routes[(method, prefix)] = resp
+ return self
+
+ def __call__(self, method, path, *, body=None, timeout=15.0, headers=None):
+ for (m, prefix), resp in self.routes.items():
+ if m == method and path.startswith(prefix):
+ return json.loads(json.dumps(resp))
+ raise cli.HttpError(404, {"error": "not routed"}, f"https://api{path}")
+
+
+@pytest.fixture()
+def server(monkeypatch):
+ s = FakeServer()
+ monkeypatch.setattr(cli, "http_request", s)
+ return s
+
+
+@pytest.fixture()
+def offline_refresh(monkeypatch):
+ monkeypatch.setattr(E, "http_refresh", lambda account_id, session_token: E.RefreshOutcome("transient", code="offline"))
+
+
+def run(tail, tmp_path):
+ return cli.main(["--credentials", str(tmp_path / "credentials.json"), "--db", str(tmp_path / "memory.db"),
+ "--tier-cache", str(tmp_path / "tier_cache.json")] + tail)
+
+
+# ---- sibyl --version ---------------------------------------------------------
+
+def test_version_flag_prints_one_line_and_exits_zero(capsys) -> None:
+ with pytest.raises(SystemExit) as ei:
+ cli.main(["--version"])
+ assert ei.value.code == 0
+ out = capsys.readouterr().out
+ # one line, every installed Sibyl package, the CLI first.
+ assert re.fullmatch(r"sibyl cli \S+( \u00b7 [a-z]+ \S+)*\n", out), out
+ assert out.startswith(f"sibyl cli {cli._client_version()}")
+
+
+def test_version_flag_needs_no_subcommand_and_no_credentials_file(tmp_path, capsys) -> None:
+ with pytest.raises(SystemExit) as ei:
+ run(["--version"], tmp_path)
+ assert ei.value.code == 0
+ assert not (tmp_path / "credentials.json").exists()
+
+
+def test_version_flag_never_touches_the_sibyl_memory_dir(tmp_path, monkeypatch, capsys) -> None:
+ home = tmp_path / "fresh-home"
+ home.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ default_dir = Path(cli.DEFAULT_CRED_PATH).parent
+ before_default = default_dir.exists()
+ with pytest.raises(SystemExit) as ei:
+ cli.main(["--version"])
+ assert ei.value.code == 0
+ assert not (home / ".sibyl-memory").exists()
+ assert list(home.iterdir()) == []
+ assert default_dir.exists() == before_default
+
+
+# ---- sibyl status: Version row ----------------------------------------------
+
+def test_status_not_activated_prints_the_version_row_first(tmp_path, server, capsys) -> None:
+ rc = run(["status"], tmp_path)
+ out = capsys.readouterr().out
+ assert rc == 0
+ rows = VERSION_ROW.findall(out)
+ assert len(rows) == 1, out
+ assert rows[0][0] == cli._client_version()
+ assert out.index("Version") < out.index("Not activated.")
+ assert not (tmp_path / "credentials.json").exists()
+
+
+def test_status_activated_prints_the_version_row_once_above_local(tmp_path, server, offline_refresh,
+ capsys) -> None:
+ c = {"account_id": ACCT, "tenant_id": ACCT, "tier": "free", "email": "u@example.com",
+ "wallet": None, "issued_at": "2026-09-27T00:00:00Z", "schema_version": 3,
+ "session_token": BEARER, "bearer_token": BEARER}
+ p = tmp_path / "credentials.json"
+ p.write_text(json.dumps(c))
+ os.chmod(p, 0o600)
+ server.on("POST", "/api/plugin/access", FREE_ACCESS)
+ rc = run(["status"], tmp_path)
+ out = capsys.readouterr().out
+ assert rc == 0
+ rows = VERSION_ROW.findall(out)
+ assert len(rows) == 1, out
+ cli_v, client_v = rows[0]
+ assert cli_v == cli._client_version()
+ assert client_v == (cli._installed_version("sibyl-memory-client") or "not installed")
+ assert out.index("Version") < out.index("Credentials")
+
+
+def test_status_version_row_says_not_installed_without_the_client(tmp_path, server, monkeypatch,
+ capsys) -> None:
+ real = cli._installed_version
+ monkeypatch.setattr(cli, "_installed_version",
+ lambda pkg: None if pkg == "sibyl-memory-client" else real(pkg))
+ run(["status"], tmp_path)
+ out = capsys.readouterr().out
+ rows = VERSION_ROW.findall(out)
+ assert len(rows) == 1 and rows[0][1] == "not installed", out
diff --git a/sibyl-memory-cli/tests/test_wiring_fix.py b/sibyl-memory-cli/tests/test_wiring_fix.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c5778933625a895cf1f583cdd5157badebc6490
--- /dev/null
+++ b/sibyl-memory-cli/tests/test_wiring_fix.py
@@ -0,0 +1,186 @@
+"""Tests for the bug fix: Claude Code MCP registration via `claude mcp add` (not the
+stale settings.json), and Codex auto-wiring its config.toml. The Claude CLI is fully
+MOCKED here — no test ever runs the real `claude mcp` against this machine's config."""
+import sys
+from pathlib import Path
+
+import pytest
+
+from sibyl_memory_cli import setup as S
+from sibyl_memory_cli.setup import ClaudeCodeWirer, CodexWirer, ALL_WIRERS
+
+
+def _with_cli(monkeypatch):
+ monkeypatch.setattr(ClaudeCodeWirer, "_claude_cli", staticmethod(lambda: "/usr/bin/claude"))
+
+
+def _mock_run(monkeypatch, *, get_rc=1, add_rc=0, add_err="boom"):
+ calls = []
+ state = {"added": False}
+ def fake(cmd, *, timeout=20.0):
+ calls.append(cmd)
+ if cmd[:3] == ["claude", "mcp", "get"]:
+ # Model real CLI state: once a successful `add` has run the server is
+ # registered, so the post-wire verification `get` succeeds. Before that
+ # it returns get_rc (1 = not yet registered).
+ return (0, "", "") if state["added"] else (get_rc, "", "")
+ if cmd[:3] == ["claude", "mcp", "add"]:
+ if add_rc == 0:
+ state["added"] = True
+ return (add_rc, "", "" if add_rc == 0 else add_err)
+ if cmd[:3] == ["claude", "mcp", "remove"]:
+ state["added"] = False
+ return (0, "", "")
+ return (0, "", "")
+ monkeypatch.setattr(S, "_run", fake)
+ return calls
+
+
+# ---------------------------------------------------------------- Claude CLI path
+
+def test_claude_wire_uses_mcp_add_user_scope(monkeypatch):
+ _with_cli(monkeypatch)
+ monkeypatch.setattr(ClaudeCodeWirer, "_ensure_mcp_binary", lambda self, **k: True)
+ calls = _mock_run(monkeypatch, get_rc=1, add_rc=0) # not registered -> add
+ out = ClaudeCodeWirer().wire()
+ assert out.status == "wired"
+ add = [c for c in calls if c[:3] == ["claude", "mcp", "add"]]
+ assert len(add) == 1
+ c = add[0]
+ assert c[:6] == ["claude", "mcp", "add", "--scope", "user", "sibyl-memory"]
+ assert c[6] == "--" and c[7].endswith("sibyl-memory-mcp") # resolved abspath or bare
+
+
+def test_claude_wire_already_registered_is_noop(monkeypatch):
+ _with_cli(monkeypatch)
+ monkeypatch.setattr(ClaudeCodeWirer, "_ensure_mcp_binary", lambda self, **k: True)
+ calls = _mock_run(monkeypatch, get_rc=0) # get -> registered
+ out = ClaudeCodeWirer().wire()
+ assert out.status == "already"
+ assert not [c for c in calls if c[:3] == ["claude", "mcp", "add"]]
+
+
+def test_claude_wire_force_reregisters(monkeypatch):
+ _with_cli(monkeypatch)
+ monkeypatch.setattr(ClaudeCodeWirer, "_ensure_mcp_binary", lambda self, **k: True)
+ calls = _mock_run(monkeypatch, get_rc=0, add_rc=0)
+ out = ClaudeCodeWirer().wire(force=True)
+ assert out.status == "wired"
+ assert any(c[:3] == ["claude", "mcp", "remove"] for c in calls)
+ assert any(c[:3] == ["claude", "mcp", "add"] for c in calls)
+
+
+def test_claude_wire_add_failure_is_error(monkeypatch):
+ _with_cli(monkeypatch)
+ monkeypatch.setattr(ClaudeCodeWirer, "_ensure_mcp_binary", lambda self, **k: True)
+ _mock_run(monkeypatch, get_rc=1, add_rc=2, add_err="permission denied")
+ out = ClaudeCodeWirer().wire()
+ assert out.status == "error" and "permission denied" in out.message
+
+
+def test_claude_wire_dry_run_does_not_add(monkeypatch):
+ _with_cli(monkeypatch)
+ monkeypatch.setattr(ClaudeCodeWirer, "_ensure_mcp_binary", lambda self, **k: True)
+ calls = _mock_run(monkeypatch, get_rc=1)
+ out = ClaudeCodeWirer().wire(dry_run=True)
+ assert out.status == "dry-run" and "claude mcp add" in out.message
+ assert not [c for c in calls if c[:3] == ["claude", "mcp", "add"]]
+
+
+def test_claude_wire_binary_missing_errors(monkeypatch):
+ _with_cli(monkeypatch)
+ monkeypatch.setattr(ClaudeCodeWirer, "_ensure_mcp_binary", lambda self, **k: False)
+ _mock_run(monkeypatch, get_rc=1)
+ out = ClaudeCodeWirer().wire()
+ assert out.status == "error" and "is not installed" in out.message
+
+
+def test_claude_current_state_reflects_cli(monkeypatch):
+ _with_cli(monkeypatch)
+ monkeypatch.setattr(ClaudeCodeWirer, "_mcp_binary_found", lambda self: True)
+ _mock_run(monkeypatch, get_rc=0)
+ st = ClaudeCodeWirer().current_state()
+ assert st["claude_cli"] is True and st["cli_registered"] is True and st["wired_with_sibyl"] is True
+ _mock_run(monkeypatch, get_rc=1)
+ assert ClaudeCodeWirer().current_state()["wired_with_sibyl"] is False
+
+
+def test_claude_no_cli_registers_nothing_and_says_so(tmp_path):
+ # autouse conftest forces no-CLI. Panel fix 10 (2026-11-14): settings.json
+ # is not where Claude Code reads MCP servers, so nothing is written for
+ # the server and the outcome names the command instead of "wired".
+ p = tmp_path / "settings.json"
+ out = ClaudeCodeWirer(settings_path=p).wire()
+ assert out.status in ("skipped", "error") # error only if the binary is missing
+ if out.status == "skipped":
+ import json
+ assert "mcpServers" not in json.loads(p.read_text())
+ assert out.handoff[0].startswith("claude mcp add --scope user sibyl-memory -- ")
+
+
+# ---------------------------------------------------------------- Codex auto-wire
+
+def test_codex_in_registry():
+ assert "codex" in ALL_WIRERS and ALL_WIRERS["codex"] is CodexWirer
+
+
+def test_codex_wire_fresh_creates_config(tmp_path):
+ cfg = tmp_path / ".codex" / "config.toml"
+ out = CodexWirer(config_path=cfg).wire()
+ assert out.status == "wired" and out.backup_path is None
+ txt = cfg.read_text()
+ assert "[mcp_servers.sibyl_memory]" in txt
+ # command is the RESOLVED absolute path (or bare name fallback) — matches
+ # codex's own `mcp add` behavior; never connect-fails on spawn PATH.
+ cmd_line = [l for l in txt.splitlines() if l.startswith("command = ")][0]
+ assert cmd_line.rstrip().endswith('sibyl-memory-mcp"')
+
+
+def test_codex_wire_appends_and_preserves(tmp_path):
+ cfg = tmp_path / "config.toml"
+ cfg.write_text('model = "o4"\n[other]\nx = 1\n')
+ out = CodexWirer(config_path=cfg).wire()
+ assert out.status == "wired" and out.backup_path is not None
+ txt = cfg.read_text()
+ assert 'model = "o4"' in txt and "[other]" in txt # preserved
+ assert "[mcp_servers.sibyl_memory]" in txt # appended
+ # audit #19: timestamped backup suffix, not a fixed .bak; cli 0.7.0: the
+ # backup lives under ~/.sibyl-memory/backups/codex/, nothing beside the config
+ assert list(tmp_path.glob("config.toml.*.bak")) == []
+ bdir = Path.home() / ".sibyl-memory" / "backups" / "codex"
+ assert len(list(bdir.glob("config.toml.*.bak"))) == 1
+
+
+def test_codex_wire_idempotent(tmp_path):
+ cfg = tmp_path / "config.toml"; cfg.write_text('model = "o4"\n')
+ CodexWirer(config_path=cfg).wire()
+ after_first = cfg.read_text()
+ out2 = CodexWirer(config_path=cfg).wire()
+ assert out2.status == "already" and cfg.read_text() == after_first # no double-append
+
+
+def test_codex_wire_dry_run_untouched(tmp_path):
+ cfg = tmp_path / "config.toml"; cfg.write_text('model = "o4"\n')
+ out = CodexWirer(config_path=cfg).wire(dry_run=True)
+ assert out.status == "dry-run" and "[mcp_servers.sibyl_memory]" not in cfg.read_text()
+
+
+def test_codex_result_is_valid_toml(tmp_path):
+ cfg = tmp_path / "config.toml"; cfg.write_text('model = "o4"\nfoo = "bar"\n')
+ CodexWirer(config_path=cfg).wire()
+ try:
+ import tomllib
+ parsed = tomllib.loads(cfg.read_text())
+ assert parsed["mcp_servers"]["sibyl_memory"]["command"].endswith("sibyl-memory-mcp")
+ assert parsed["model"] == "o4"
+ except ModuleNotFoundError:
+ pytest.skip("tomllib not available (<3.11)")
+
+
+def test_codex_binary_missing_errors(tmp_path, monkeypatch):
+ cfg = tmp_path / "config.toml"; cfg.write_text("model='o4'\n")
+ monkeypatch.setattr(CodexWirer, "_mcp_binary_found", lambda self: False)
+ monkeypatch.setattr(S.subprocess, "check_call", lambda *a, **k: None) # pip install no-op
+ out = CodexWirer(config_path=cfg).wire()
+ assert out.status == "error" and "is not installed" in out.message
+ assert "[mcp_servers.sibyl_memory]" not in cfg.read_text() # not written on error
diff --git a/sibyl-memory-client/CHANGELOG.md b/sibyl-memory-client/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..c4fdba0c6896ff164101378abfa861347bd35af1
--- /dev/null
+++ b/sibyl-memory-client/CHANGELOG.md
@@ -0,0 +1,2856 @@
+# Changelog
+
+All notable changes to `sibyl-memory-client` are recorded here. Format
+follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning
+follows [SemVer](https://semver.org/).
+
+## [0.10.0] - 2026-10-31
+
+One release: the paid tier R2 line, the shipped 0.9.0 family fixes it was built beside, the graph line (tiered retrieval and relations) and the release merge items below.
+
+### Release summary
+- Typed links between entities, reference documents and state (`link`, `unlink`, `neighbors`,
+ `links_of`; schema v6 `memory_links`). Existing `entity_relations` rows are copied once, on first
+ open, in one transaction; nothing existing is rewritten, and a 0.9.0 client still opens the store.
+- Reference documents: paged read, list and delete. Tier-aware search with a token output budget.
+- `doc_neighborhood`: a document's owning hubs and small-hub siblings (used by MCP `memory_recall`).
+- Pro: skill signals (tool names and hashes only, local) feed workflow proposals.
+- `MemoryClient(telemetry=False)` turns the usage count off for one client.
+
+### Release merge (2026-10-28)
+- Recall neighborhood (from the hopfix line): `MemoryClient.doc_neighborhood`, `_links.owners_of`,
+ `hub_members`, `doc_neighborhood`; `output_budget` drops `owners_total` in its counts-only stage.
+- Two retrieval flags, both default OFF (they reproduce the agent-bench harness configuration):
+ `SIBYL_MEMORY_RANKED_FALLBACK=1` (a short multi-record result is filled with ranked candidates,
+ `match: "ranked"`, verdict `ranked_appended`, code `ranked_fallback` when no gated row existed;
+ tuning `SIBYL_MEMORY_RANKED_MIN_TOKENS`, `SIBYL_MEMORY_RANKED_EXCLUDE_CATEGORIES`) and
+ `SIBYL_MEMORY_HOP_OWNERS=1` (a document's link sample lists its owning hubs first, `owners_total`).
+ Unset, the verdict envelope keeps its 19 keys. Documented in the README.
+- `telemetry: bool | None = None` on `MemoryClient.__init__` and `MemoryClient.local`: False selects
+ the null heartbeat; None or True follow `SIBYL_MEMORY_TELEMETRY` (on unless "0").
+- Known limit, large stores: `count_touching` scans a tenant's edges per entity insert (felt near
+ 111k edges) and the search shadow triggers scan at about 680k rows. Not fixed in this release.
+- Tests: `test_hopfix_neighborhood_2026_10_28.py` (8), `test_hopfix_flags_2026_10_28.py` (8),
+ `test_upgrade_0_9_0_store_2026_10_28.py` (4: the 0.9.0 fixture and a store the 0.9.0 client
+ creates; base tables hashed before and after, second open a no-op, the 0.9.0 client reads and
+ searches the upgraded file, a crash inside the copy rolls back), `test_telemetry_param_2026_10_28.py` (5).
+
+### Paid tier R2: skill signals (built 2026-09-29)
+
+Spec plugin-paid-tier-r2-spec-2026-09-29 section 1 (skill signals). Follow-up release to 0.9.0;
+minor, no break. BYOK drafting (spec section 2) is not in this release (operator 2026-09-29):
+proposals stay fully local with the deterministic draft.
+
+### Changed (tier convention, 2026-10-05; carried from 0.9.0)
+- The shared `tiers` module (free / pro / elite, legacy labels as input aliases, an unrecognised
+ label is Free with reason `tier_unknown`) is carried from 0.9.0 / 0.5.0 unchanged (cherry-picked
+ onto this line; no conflict in the client). See the 0.9.0 entry. Suite 866 + 11 skipped ->
+ 903 + 11 skipped.
+
+### Added
+- `lifecycle.signals`: the Pro skill-signal recorder and its file `~/.sibyl-memory/signals.json`
+ (0600, atomic, symlink-refusing, read bounded at 64 KB, a damaged file is empty, written under
+ `lifecycle.lock`). Tool events keep the tool name (64 characters of `[A-Za-z0-9_.:-]`) and
+ `arg_shape`, the first 12 hex of sha256 over the sorted TOP-LEVEL argument key names; never a
+ value, a nested key, a key name in plain text, a result, a path or a prompt. Entity writes
+ (`set_entity`, `delete_entity`, `archive_entity`) keep only `sha256(tenant:category:name)[:16]`.
+ N-grams of 3 to 5 tool calls with day buckets, per-session counts and recent timestamps.
+ Bounds on every write and load: 200 n-grams (lowest count, then oldest, evicted), 14-day
+ drop under 3 hits, 30-day drop for everything and 30 days after a proposal, 7 day buckets,
+ 200 entity keys of 32 writes, 7-day write retention, 64 KB file cap.
+- Recording is armed only on a verified paid entitlement (`automation_allowed`); free and locked
+ devices create no buffer and no file. `lifecycle.json` `skills.signals` turns it off;
+ `skills.signals_since` is a floor moved by `on` and `clear`, so a running process can never
+ write back what was cleared and a transcript is never read back over the time it was off.
+- `SignalBuffer` (one per home and process): cheap `note_tool` / `note_entity_write`, flushed at
+ most every 30 s or 20 events and at exit. `record_transcript` / `read_slice`: the Claude Code
+ Stop hook's incremental transcript slice (stored byte offset and a hash of the path in the
+ session's `lifecycle.json` entry, at most 4 MiB per call, complete lines only, offset reset on
+ a changed or truncated transcript, sidechain entries skipped).
+- The client's write path (`_note_lifecycle_write`, only for clients a plugin surface enabled)
+ records entity writes; writes inside `suppressed()` (capsules, trims, the Hermes journal, the
+ learner) are not recorded.
+- Learner: `Learner.run(signals=)` runs two new detectors, also when the journal has nothing new.
+ `tool_sequence`: 3 times in one session, or 5 times in 7 days across 2 sessions; all-identical
+ names and memory-read-only sequences excluded; the longest gram wins over a contained gram seen
+ no more often, and the windows of one loop are one pattern; confidence 0.60 + 0.05 per hit
+ over 3, +0.05 across sessions, cap 0.85; slug `seq---` (`mcp__x__y` -> `x-y`), plus
+ 4 hex of the shapes when two sequences share names but not shapes. `correction_loop`: 3
+ rewrites of one entity in one session spanning at least 10 minutes, or a delete/archive then a
+ write within 24 h; confidence 0.65, 0.75 across sessions; slug `fix--` when the
+ hash resolves against the entities in `memory.db` at run time (one bounded SELECT), else
+ `fix-