Merge origin/develop into feat/benchmark-multilingual
Resolve conflicts: - backends/chroma.py: keep both new except handlers in get_collection (CollectionNotInitializedError from develop + EF-mismatch helper from this branch), ordered _ChromaNotFoundError before ValueError to match the create-branch handler order. - uv.lock: regenerated from merged pyproject.toml. Fix lint: ruff format mempalace/embedding.py + tests/test_embeddinggemma.py (CI now pins ruff==0.15.9 via develop's workflow update). Full suite: 1923 passed, 1 skipped.
This commit is contained in:
@@ -6,7 +6,8 @@
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/mempal-stop-hook.sh\""
|
||||
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/mempal-stop-hook.sh\"",
|
||||
"timeout": 30
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -16,7 +17,8 @@
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/mempal-precompact-hook.sh\""
|
||||
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/mempal-precompact-hook.sh\"",
|
||||
"timeout": 90
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -50,6 +50,9 @@ jobs:
|
||||
with:
|
||||
python-version: "3.11"
|
||||
cache: 'pip'
|
||||
- run: pip install "ruff>=0.4.0,<0.5"
|
||||
# Keep this pin identical to the `ruff==` pin in pyproject.toml
|
||||
# ([project.optional-dependencies].dev and [dependency-groups].dev)
|
||||
# so CI and `pip install -e ".[dev]"` format/lint identically.
|
||||
- run: pip install "ruff==0.15.9"
|
||||
- run: ruff check .
|
||||
- run: ruff format --check .
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
# Keep in lock-step with the ruff version pinned in .github/workflows/ci.yml
|
||||
# (>=0.4.0,<0.5). Using a newer rev here produces a different formatter
|
||||
# output than CI and breaks `ruff format --check` in the lint job.
|
||||
rev: v0.4.10
|
||||
# Keep this rev in lock-step with the exact ruff pin in pyproject.toml
|
||||
# ([project.optional-dependencies].dev / [dependency-groups].dev) and
|
||||
# .github/workflows/ci.yml. A different ruff here produces different
|
||||
# formatter output than CI and breaks `ruff format --check` in lint.
|
||||
rev: v0.15.9
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix]
|
||||
|
||||
@@ -8,8 +8,12 @@
|
||||
# context about what was discussed. This hook forces one final save of
|
||||
# EVERYTHING before that happens.
|
||||
#
|
||||
# Unlike the save hook (which triggers every N exchanges), this ALWAYS
|
||||
# blocks — because compaction is always worth saving before.
|
||||
# Unlike the save hook (which gates on a message-count threshold and on
|
||||
# MEMPAL_VERBOSE), this runs the mine synchronously on every PreCompact
|
||||
# event — compaction is always worth saving before. The hook itself
|
||||
# returns ``{}`` so it does not emit a ``decision: block`` to Claude
|
||||
# Code; the "always run" semantics live in the mine call, not in the
|
||||
# Stop-hook block protocol.
|
||||
#
|
||||
# === INSTALL ===
|
||||
# Add to .claude/settings.local.json:
|
||||
@@ -35,10 +39,15 @@
|
||||
# === HOW IT WORKS ===
|
||||
#
|
||||
# Claude Code sends JSON on stdin with:
|
||||
# session_id — unique session identifier
|
||||
# session_id — unique session identifier
|
||||
# transcript_path — path to the JSONL transcript file
|
||||
#
|
||||
# We always return decision: "block" with a reason telling the AI
|
||||
# to save everything. After the AI saves, compaction proceeds normally.
|
||||
# The hook runs the transcript mine synchronously (the foreground
|
||||
# ``mempalace mine`` call below blocks until it returns), then prints
|
||||
# ``{}`` to stdout so Claude Code proceeds with the compaction. We do
|
||||
# not emit a ``decision: block`` to the hook protocol — the
|
||||
# "always save before compaction" guarantee is provided by the
|
||||
# synchronous mine, not by the Stop-hook block contract.
|
||||
#
|
||||
# === MEMPALACE CLI ===
|
||||
# The hook ALWAYS mines the active conversation transcript synchronously
|
||||
@@ -66,20 +75,71 @@ fi
|
||||
INPUT=$(cat)
|
||||
|
||||
# Parse session_id and transcript_path in one call. Sanitize both, then
|
||||
# read sanitized values from one-per-line stdout into shell variables —
|
||||
# avoids ``eval`` on generated code (#1231 review). Same contract as
|
||||
# mempal_save_hook.sh.
|
||||
mapfile -t _mempal_parsed < <(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c "
|
||||
# read sanitized values from one-per-line stdout into shell variables
|
||||
# (avoids ``eval`` on generated code, #1231 review). Uses ``sed -n 'Np'``
|
||||
# rather than the bash 4-only ``mapfile`` so the script also runs on
|
||||
# macOS /bin/bash 3.2.57 (Apple GPLv3 freeze, 2006), where ``mapfile``
|
||||
# silently caused every parsed value to fall back to its default (#1440).
|
||||
#
|
||||
# The leading ``__MEMPAL_PARSE_OK__`` sentinel lets the defense-in-depth
|
||||
# guard below distinguish "Python parsed cleanly" from "Python crashed
|
||||
# and printed nothing". Same parsing contract as mempal_save_hook.sh.
|
||||
# Python stderr is captured to last_python_err.log so the guard below can
|
||||
# distinguish "bad user input" from "broken interpreter / future regression
|
||||
# in this inline script". Same diagnostic contract as mempal_save_hook.sh.
|
||||
#
|
||||
# ``umask 077`` inside the command-substitution subshell makes the
|
||||
# ``2>$STATE_DIR/last_python_err.log`` redirect create the file at mode
|
||||
# 0600 atomically, closing the TOCTOU window between creation at
|
||||
# umask-default and the ``chmod 600`` below. ``printf '%s'`` replaces
|
||||
# ``echo`` so payloads beginning with ``-n``/``-e``/``-E`` or containing
|
||||
# backslashes are not mangled by echo flag parsing.
|
||||
_mempal_parsed=$(
|
||||
umask 077
|
||||
printf '%s' "$INPUT" | "$MEMPAL_PYTHON_BIN" -c "
|
||||
import sys, json, re
|
||||
data = json.load(sys.stdin)
|
||||
sid = data.get('session_id', 'unknown')
|
||||
sid = data.get('session_id', '')
|
||||
tp = data.get('transcript_path', '')
|
||||
safe = lambda s: re.sub(r'[^a-zA-Z0-9_/.\-~]', '', str(s))
|
||||
print('__MEMPAL_PARSE_OK__')
|
||||
print(safe(sid))
|
||||
print(safe(tp))
|
||||
" 2>/dev/null)
|
||||
SESSION_ID="${_mempal_parsed[0]:-unknown}"
|
||||
TRANSCRIPT_PATH="${_mempal_parsed[1]:-}"
|
||||
" 2>"$STATE_DIR/last_python_err.log"
|
||||
)
|
||||
# Drop the empty file on success; chmod 600 on failure to mirror
|
||||
# last_input.log's privacy contract.
|
||||
if [ -s "$STATE_DIR/last_python_err.log" ]; then
|
||||
chmod 600 "$STATE_DIR/last_python_err.log" 2>/dev/null
|
||||
else
|
||||
rm -f "$STATE_DIR/last_python_err.log"
|
||||
fi
|
||||
_MEMPAL_PARSE_MARKER=$(printf '%s\n' "$_mempal_parsed" | sed -n '1p')
|
||||
SESSION_ID=$(printf '%s\n' "$_mempal_parsed" | sed -n '2p')
|
||||
TRANSCRIPT_PATH=$(printf '%s\n' "$_mempal_parsed" | sed -n '3p')
|
||||
SESSION_ID="${SESSION_ID:-unknown}"
|
||||
TRANSCRIPT_PATH="${TRANSCRIPT_PATH:-}"
|
||||
|
||||
# Defense-in-depth: if INPUT was non-empty but Python never reached the
|
||||
# print() calls (sentinel missing), parsing silently failed. Surface the
|
||||
# raw payload so the next debugger does not lose a day to hook.log lines
|
||||
# that say "Session unknown". Bounded to 4 KB and overwritten on each
|
||||
# failure (not appended) to keep ~/.mempalace/hook_state/ from growing
|
||||
# unbounded under a repeating misconfiguration. chmod 600 so the dump,
|
||||
# which mirrors the Claude Code PreCompact payload (includes
|
||||
# transcript_path revealing the user's home + project layout), is not
|
||||
# world-readable.
|
||||
if [ -n "$INPUT" ] && [ "$_MEMPAL_PARSE_MARKER" != "__MEMPAL_PARSE_OK__" ]; then
|
||||
echo "[$(date '+%H:%M:%S')] WARN: input parse failed (sentinel missing); see $STATE_DIR/last_input.log and $STATE_DIR/last_python_err.log" >> "$STATE_DIR/hook.log"
|
||||
# ``head -c 4096`` is a byte cap, locale-independent; ``${INPUT:0:4096}``
|
||||
# would count characters under UTF-8 and slip a multibyte payload past
|
||||
# the bound. ``set -o pipefail`` is not enabled in this script so the
|
||||
# natural SIGPIPE-on-printf from ``head`` closing stdin is absorbed.
|
||||
# ``umask 077`` in the subshell creates last_input.log at mode 0600
|
||||
# atomically — the ``chmod 600`` below stays as belt-and-suspenders.
|
||||
( umask 077 && printf '%s' "$INPUT" | head -c 4096 > "$STATE_DIR/last_input.log" )
|
||||
chmod 600 "$STATE_DIR/last_input.log" 2>/dev/null
|
||||
fi
|
||||
|
||||
# Expand ~ in path
|
||||
TRANSCRIPT_PATH="${TRANSCRIPT_PATH/#\~/$HOME}"
|
||||
|
||||
+87
-11
@@ -83,27 +83,103 @@ fi
|
||||
INPUT=$(cat)
|
||||
|
||||
# Parse all fields in a single Python call (3x faster than separate invocations)
|
||||
# without invoking ``eval`` on generated code: Python prints one sanitized
|
||||
# value per line, the shell reads them via ``mapfile`` and does plain
|
||||
# variable assignment — same data, smaller blast radius if the sanitizer
|
||||
# is ever bypassed (#1231 review).
|
||||
mapfile -t _mempal_parsed < <(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c "
|
||||
# without invoking ``eval`` on generated code: Python prints a parse-success
|
||||
# sentinel followed by one sanitized value per line, the shell reads each
|
||||
# line via ``sed -n 'Np'`` and does plain variable assignment. Same data,
|
||||
# smaller blast radius if the sanitizer is ever bypassed (#1231 review).
|
||||
#
|
||||
# Why ``sed -n 'Np'`` and not ``mapfile`` / ``readarray``: macOS ships
|
||||
# GNU bash 3.2.57 (frozen at Apple's GPLv3 cutoff in 2006), and both
|
||||
# array-read builtins only landed in bash 4.0 (2009). On a stock macOS
|
||||
# the previous ``mapfile`` form errored, every value fell back to its
|
||||
# default, and the hook silently produced zero saves (#1440).
|
||||
#
|
||||
# The leading ``__MEMPAL_PARSE_OK__`` sentinel lets the defense-in-depth
|
||||
# guard below distinguish "Python parsed cleanly, user set session_id to
|
||||
# the literal string 'unknown'" or "session_id was non-ASCII and got
|
||||
# sanitized to empty" from the actual failure mode ("Python crashed,
|
||||
# nothing was printed"). Without the sentinel the guard false-fires
|
||||
# every Stop hook for users on i18n harnesses or unusual harness configs.
|
||||
# Python stderr is captured to last_python_err.log so the guard below can
|
||||
# distinguish "bad user input" (JSONDecodeError) from "broken interpreter
|
||||
# / future regression in this inline script" (ImportError, SyntaxError,
|
||||
# ModuleNotFoundError). Without the stderr capture, last_input.log shows
|
||||
# a valid payload while the actual root cause stays hidden.
|
||||
#
|
||||
# Two extra hardenings inside the command-substitution subshell:
|
||||
#
|
||||
# * ``umask 077`` so the ``2>$STATE_DIR/last_python_err.log`` redirect
|
||||
# creates the file at mode 0600 atomically. Without it, the file
|
||||
# appeared briefly at the parent process's umask (often 0644) before
|
||||
# the explicit ``chmod 600`` below closed it — a small TOCTOU window
|
||||
# where another local user on a shared box could read the traceback,
|
||||
# which can echo back the user's home + project layout.
|
||||
#
|
||||
# * ``printf '%s'`` in place of ``echo``. ``echo`` is unreliable for
|
||||
# arbitrary payloads: it interprets ``-n``/``-e``/``-E`` as flags,
|
||||
# handles backslashes inconsistently across builtin vs /bin/echo,
|
||||
# and depends on the ``xpg_echo`` shopt on bash. JSON typically
|
||||
# starts with ``{`` so the failure mode is latent, but flipping to
|
||||
# ``printf '%s'`` removes the class of bug entirely.
|
||||
_mempal_parsed=$(
|
||||
umask 077
|
||||
printf '%s' "$INPUT" | "$MEMPAL_PYTHON_BIN" -c "
|
||||
import sys, json, re
|
||||
data = json.load(sys.stdin)
|
||||
sid = data.get('session_id', 'unknown')
|
||||
sid = data.get('session_id', '')
|
||||
sha_raw = data.get('stop_hook_active', False)
|
||||
tp = data.get('transcript_path', '')
|
||||
# Shell-safe output — only allow alphanumeric, underscore, hyphen, slash, dot, tilde
|
||||
# Shell-safe output: only allow alphanumeric, underscore, hyphen, slash, dot, tilde
|
||||
safe = lambda s: re.sub(r'[^a-zA-Z0-9_/.\-~]', '', str(s))
|
||||
# Coerce stop_hook_active to strict boolean string
|
||||
sha = 'True' if sha_raw is True or str(sha_raw).lower() in ('true', '1', 'yes') else 'False'
|
||||
print('__MEMPAL_PARSE_OK__')
|
||||
print(safe(sid))
|
||||
print(sha)
|
||||
print(safe(tp))
|
||||
" 2>/dev/null)
|
||||
SESSION_ID="${_mempal_parsed[0]:-unknown}"
|
||||
STOP_HOOK_ACTIVE="${_mempal_parsed[1]:-False}"
|
||||
TRANSCRIPT_PATH="${_mempal_parsed[2]:-}"
|
||||
" 2>"$STATE_DIR/last_python_err.log"
|
||||
)
|
||||
# The 2> redirect creates the file even when stderr is empty (success).
|
||||
# Remove the empty file so the state directory stays clean on the happy
|
||||
# path; on failure, lock the file's permissions to 600 to mirror
|
||||
# last_input.log's privacy contract (the traceback can reveal absolute
|
||||
# paths inside the user's home).
|
||||
if [ -s "$STATE_DIR/last_python_err.log" ]; then
|
||||
chmod 600 "$STATE_DIR/last_python_err.log" 2>/dev/null
|
||||
else
|
||||
rm -f "$STATE_DIR/last_python_err.log"
|
||||
fi
|
||||
_MEMPAL_PARSE_MARKER=$(printf '%s\n' "$_mempal_parsed" | sed -n '1p')
|
||||
SESSION_ID=$(printf '%s\n' "$_mempal_parsed" | sed -n '2p')
|
||||
STOP_HOOK_ACTIVE=$(printf '%s\n' "$_mempal_parsed" | sed -n '3p')
|
||||
TRANSCRIPT_PATH=$(printf '%s\n' "$_mempal_parsed" | sed -n '4p')
|
||||
SESSION_ID="${SESSION_ID:-unknown}"
|
||||
STOP_HOOK_ACTIVE="${STOP_HOOK_ACTIVE:-False}"
|
||||
TRANSCRIPT_PATH="${TRANSCRIPT_PATH:-}"
|
||||
|
||||
# Defense-in-depth: if INPUT was non-empty but Python never reached the
|
||||
# print() calls (sentinel missing), parsing silently failed. Surface the
|
||||
# raw payload so the next debugger does not lose a day to hook.log lines
|
||||
# that say "Session unknown". Bounded to 4 KB and overwritten on each
|
||||
# failure (not appended) to keep ~/.mempalace/hook_state/ from growing
|
||||
# unbounded under a repeating misconfiguration. chmod 600 so the dump,
|
||||
# which mirrors the Claude Code Stop payload (includes transcript_path
|
||||
# revealing the user's home + project layout), is not world-readable.
|
||||
if [ -n "$INPUT" ] && [ "$_MEMPAL_PARSE_MARKER" != "__MEMPAL_PARSE_OK__" ]; then
|
||||
echo "[$(date '+%H:%M:%S')] WARN: input parse failed (sentinel missing); see $STATE_DIR/last_input.log and $STATE_DIR/last_python_err.log" >> "$STATE_DIR/hook.log"
|
||||
# ``head -c 4096`` caps at exactly 4096 BYTES regardless of locale.
|
||||
# Bash's ``${INPUT:0:4096}`` would count characters under a UTF-8
|
||||
# locale, letting a CJK/emoji payload silently exceed the cap by up
|
||||
# to 4x. ``set -o pipefail`` is not enabled in this script, so the
|
||||
# natural ``head``-closes-stdin / SIGPIPE-on-printf interaction is
|
||||
# silently absorbed by bash (the canonical way to read N bytes from
|
||||
# a string in shell). The ``umask 077`` subshell creates
|
||||
# last_input.log at mode 0600 atomically — the ``chmod 600`` below
|
||||
# stays as a belt-and-suspenders guard if a future edit drops the
|
||||
# umask line.
|
||||
( umask 077 && printf '%s' "$INPUT" | head -c 4096 > "$STATE_DIR/last_input.log" )
|
||||
chmod 600 "$STATE_DIR/last_input.log" 2>/dev/null
|
||||
fi
|
||||
|
||||
# Expand ~ in path
|
||||
TRANSCRIPT_PATH="${TRANSCRIPT_PATH/#\~/$HOME}"
|
||||
|
||||
@@ -1,6 +1,39 @@
|
||||
"""MemPalace — Give your AI a memory. No API key required."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def _strip_leaked_pythonpath_from_sys_path() -> None:
|
||||
# Venvs inherit PYTHONPATH; on multi-Python systems it can cause
|
||||
# transitive imports to load compiled extensions (pydantic_core,
|
||||
# chromadb_rust_bindings) from the wrong ABI. Remove sys.path entries
|
||||
# the interpreter populated from PYTHONPATH so this process imports
|
||||
# only the venv's own packages. Comparison normalizes case + separators
|
||||
# so Windows paths and trailing-separator quirks do not slip through
|
||||
# string equality. The empty-string CWD marker on sys.path is preserved
|
||||
# regardless, so PYTHONPATH=. does not collapse the implicit current
|
||||
# directory.
|
||||
#
|
||||
# os.environ is intentionally NOT modified here. CLI entry points
|
||||
# (mempalace.cli:main, mempalace.mcp_server:main) drop PYTHONPATH from
|
||||
# the env themselves so any subprocess they spawn starts clean. Host
|
||||
# applications that embed mempalace as a library (e.g. import
|
||||
# mempalace.searcher) keep their PYTHONPATH intact for their own
|
||||
# unrelated subprocesses.
|
||||
leaked = os.environ.get("PYTHONPATH", None)
|
||||
if not leaked:
|
||||
return
|
||||
|
||||
def _norm(path: str) -> str:
|
||||
return os.path.normcase(os.path.normpath(path))
|
||||
|
||||
leaked_entries = {_norm(p) for p in leaked.split(os.pathsep) if p}
|
||||
sys.path[:] = [p for p in sys.path if not p or _norm(p) not in leaked_entries]
|
||||
|
||||
|
||||
_strip_leaked_pythonpath_from_sys_path()
|
||||
|
||||
from .version import __version__ # noqa: E402
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ from .base import (
|
||||
BackendError,
|
||||
BaseBackend,
|
||||
BaseCollection,
|
||||
CollectionNotInitializedError,
|
||||
DimensionMismatchError,
|
||||
EmbedderIdentityMismatchError,
|
||||
GetResult,
|
||||
@@ -46,6 +47,7 @@ __all__ = [
|
||||
"BaseCollection",
|
||||
"ChromaBackend",
|
||||
"ChromaCollection",
|
||||
"CollectionNotInitializedError",
|
||||
"DimensionMismatchError",
|
||||
"EmbedderIdentityMismatchError",
|
||||
"GetResult",
|
||||
|
||||
@@ -35,6 +35,18 @@ class PalaceNotFoundError(BackendError, FileNotFoundError):
|
||||
"""
|
||||
|
||||
|
||||
class CollectionNotInitializedError(PalaceNotFoundError):
|
||||
"""Raised when the palace exists on disk but the requested collection has
|
||||
never been created (e.g. ``init`` ran but ``mine`` has not).
|
||||
|
||||
Distinct from :class:`PalaceNotFoundError`: the palace dir and DB are
|
||||
present and valid, only the collection has not been bootstrapped yet.
|
||||
Subclass of :class:`PalaceNotFoundError` (and therefore
|
||||
:class:`FileNotFoundError`) so legacy callers catching either parent
|
||||
keep working unchanged.
|
||||
"""
|
||||
|
||||
|
||||
class BackendClosedError(BackendError):
|
||||
"""Raised when a backend method is called after ``close()``."""
|
||||
|
||||
|
||||
+116
-12
@@ -16,6 +16,7 @@ from chromadb.errors import NotFoundError as _ChromaNotFoundError
|
||||
from .base import (
|
||||
BaseBackend,
|
||||
BaseCollection,
|
||||
CollectionNotInitializedError,
|
||||
GetResult,
|
||||
HealthStatus,
|
||||
PalaceNotFoundError,
|
||||
@@ -70,8 +71,34 @@ def _hnsw_link_to_data_ratio(seg_dir: str) -> Optional[float]:
|
||||
return link_size / data_size
|
||||
|
||||
|
||||
def _hnsw_link_lists_is_usable_for_payload(seg_dir: str) -> bool:
|
||||
"""Return False when a non-trivial HNSW payload lacks usable link lists.
|
||||
|
||||
A missing or empty link_lists.bin is acceptable only for a fresh/empty
|
||||
segment. Once data_level0.bin has real payload, a zero-byte link_lists.bin
|
||||
is not a harmless async-flush shape: ChromaDB can later hand the broken
|
||||
graph to hnswlib and crash in native code.
|
||||
"""
|
||||
data_path = os.path.join(seg_dir, "data_level0.bin")
|
||||
link_path = os.path.join(seg_dir, "link_lists.bin")
|
||||
|
||||
try:
|
||||
if not os.path.isfile(data_path):
|
||||
return True
|
||||
|
||||
data_size = os.path.getsize(data_path)
|
||||
if data_size <= _HNSW_MISSING_METADATA_DATA_FLOOR:
|
||||
return True
|
||||
|
||||
return os.path.isfile(link_path) and os.path.getsize(link_path) > 0
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _hnsw_payload_appears_sane(seg_dir: str) -> bool:
|
||||
"""Return False when HNSW payload files are structurally implausible."""
|
||||
if not _hnsw_link_lists_is_usable_for_payload(seg_dir):
|
||||
return False
|
||||
|
||||
ratio = _hnsw_link_to_data_ratio(seg_dir)
|
||||
return ratio is None or ratio <= _HNSW_LINK_TO_DATA_MAX_RATIO
|
||||
@@ -644,20 +671,59 @@ def _valid_dimensionality(value: object) -> bool:
|
||||
return isinstance(value, Integral) and not isinstance(value, bool) and int(value) > 0
|
||||
|
||||
|
||||
def _persisted_metadata_fields(obj: object) -> tuple[object, object]:
|
||||
def _persisted_metadata_value(obj: object, name: str) -> object:
|
||||
if isinstance(obj, dict):
|
||||
return obj.get("dimensionality"), obj.get("id_to_label")
|
||||
return getattr(obj, "dimensionality", None), getattr(obj, "id_to_label", None)
|
||||
return obj.get(name)
|
||||
return getattr(obj, name, None)
|
||||
|
||||
|
||||
def _persisted_metadata_fields(obj: object) -> tuple[object, object]:
|
||||
return _persisted_metadata_value(obj, "dimensionality"), _persisted_metadata_value(
|
||||
obj, "id_to_label"
|
||||
)
|
||||
|
||||
|
||||
def _missing_dimensionality_appears_recoverable(
|
||||
persisted: object, id_to_label: dict, seg_dir: str
|
||||
) -> bool:
|
||||
total = _persisted_metadata_value(persisted, "total_elements_added")
|
||||
label_to_id = _persisted_metadata_value(persisted, "label_to_id")
|
||||
data_path = os.path.join(seg_dir, "data_level0.bin")
|
||||
link_path = os.path.join(seg_dir, "link_lists.bin")
|
||||
|
||||
if not isinstance(total, Integral) or isinstance(total, bool):
|
||||
return False
|
||||
if not isinstance(label_to_id, dict):
|
||||
return False
|
||||
try:
|
||||
if not (
|
||||
os.path.isfile(data_path)
|
||||
and os.path.isfile(link_path)
|
||||
and os.path.getsize(data_path) > _HNSW_MISSING_METADATA_DATA_FLOOR
|
||||
):
|
||||
return False
|
||||
except OSError:
|
||||
return False
|
||||
if not _hnsw_payload_appears_sane(seg_dir):
|
||||
return False
|
||||
|
||||
label_count = len(id_to_label)
|
||||
if int(total) != label_count or len(label_to_id) != label_count:
|
||||
return False
|
||||
try:
|
||||
return all(label_to_id.get(label) == item_id for item_id, label in id_to_label.items())
|
||||
except TypeError:
|
||||
return False
|
||||
|
||||
|
||||
def quarantine_invalid_hnsw_metadata(palace_path: str) -> list[str]:
|
||||
"""Quarantine segment dirs whose ``index_metadata.pickle`` is unreadable or invalid.
|
||||
|
||||
Chroma's persisted HNSW metadata is untrusted disk state. If a segment has
|
||||
labels but no valid positive dimensionality, current Chroma versions can
|
||||
accept the pickle and crash later in the Rust loader. We rename the entire
|
||||
segment out of the way before ``PersistentClient`` opens so Chroma can
|
||||
rebuild cleanly instead of touching known-bad metadata.
|
||||
labels but invalid or partial metadata, current Chroma versions can accept
|
||||
the pickle and crash later in the Rust loader. We rename the entire segment
|
||||
out of the way before ``PersistentClient`` opens so Chroma can rebuild
|
||||
cleanly instead of touching known-bad metadata.
|
||||
"""
|
||||
try:
|
||||
entries = os.listdir(palace_path)
|
||||
@@ -708,7 +774,22 @@ def quarantine_invalid_hnsw_metadata(palace_path: str) -> list[str]:
|
||||
reason = f"invalid id_to_label type {type(id_to_label).__name__}"
|
||||
else:
|
||||
has_labels = bool(id_to_label)
|
||||
if has_labels and not _valid_dimensionality(dimensionality):
|
||||
if (
|
||||
has_labels
|
||||
and dimensionality is None
|
||||
and not _missing_dimensionality_appears_recoverable(
|
||||
persisted, id_to_label, seg_dir
|
||||
)
|
||||
):
|
||||
reason = (
|
||||
"labels present but dimensionality is missing or invalid "
|
||||
f"({dimensionality!r})"
|
||||
)
|
||||
elif (
|
||||
has_labels
|
||||
and dimensionality is not None
|
||||
and not _valid_dimensionality(dimensionality)
|
||||
):
|
||||
reason = (
|
||||
"labels present but dimensionality is missing or invalid "
|
||||
f"({dimensionality!r})"
|
||||
@@ -873,10 +954,30 @@ class ChromaCollection(BaseCollection):
|
||||
# Writes
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _sanitize_metadatas_for_chromadb(metadatas):
|
||||
"""chromadb 1.5.x rejects None and empty-dict entries in the metadatas
|
||||
list (ValueError: Expected metadata to be a non-empty dict, got 0
|
||||
metadata attributes in add). Coerce any such entry to a sentinel so
|
||||
the write succeeds. Operators can later locate coerced drawers via
|
||||
``where={"_repaired_empty_meta": True}``.
|
||||
|
||||
This is the chokepoint catch-all: even if a caller's own sanitizer
|
||||
misses a case (or skips for performance), reaching the chromadb
|
||||
client always goes through here first.
|
||||
"""
|
||||
if metadatas is None:
|
||||
return None
|
||||
return [
|
||||
m if (isinstance(m, dict) and len(m) > 0) else {"_repaired_empty_meta": True}
|
||||
for m in metadatas
|
||||
]
|
||||
|
||||
def add(self, *, documents, ids, metadatas=None, embeddings=None):
|
||||
kwargs: dict[str, Any] = {"documents": documents, "ids": ids}
|
||||
if metadatas is not None:
|
||||
kwargs["metadatas"] = metadatas
|
||||
sanitized = self._sanitize_metadatas_for_chromadb(metadatas)
|
||||
if sanitized is not None:
|
||||
kwargs["metadatas"] = sanitized
|
||||
if embeddings is not None:
|
||||
kwargs["embeddings"] = embeddings
|
||||
with self._write_lock():
|
||||
@@ -884,8 +985,9 @@ class ChromaCollection(BaseCollection):
|
||||
|
||||
def upsert(self, *, documents, ids, metadatas=None, embeddings=None):
|
||||
kwargs: dict[str, Any] = {"documents": documents, "ids": ids}
|
||||
if metadatas is not None:
|
||||
kwargs["metadatas"] = metadatas
|
||||
sanitized = self._sanitize_metadatas_for_chromadb(metadatas)
|
||||
if sanitized is not None:
|
||||
kwargs["metadatas"] = sanitized
|
||||
if embeddings is not None:
|
||||
kwargs["embeddings"] = embeddings
|
||||
with self._write_lock():
|
||||
@@ -1372,6 +1474,8 @@ class ChromaBackend(BaseBackend):
|
||||
else:
|
||||
try:
|
||||
collection = client.get_collection(collection_name, **ef_kwargs)
|
||||
except _ChromaNotFoundError as e:
|
||||
raise CollectionNotInitializedError(palace_path) from e
|
||||
except ValueError as e:
|
||||
explanation = self._explain_ef_mismatch(e, palace_path)
|
||||
if explanation:
|
||||
|
||||
+31
-9
@@ -590,6 +590,10 @@ def cmd_sync(args):
|
||||
if not os.path.isdir(palace_path):
|
||||
print(f"\n No palace found at {palace_path}")
|
||||
return
|
||||
if not os.path.isfile(os.path.join(palace_path, "chroma.sqlite3")):
|
||||
print(f"\n Palace dir at {palace_path} exists but has no chroma.sqlite3 yet.")
|
||||
print(" Run: mempalace mine <dir>")
|
||||
return
|
||||
|
||||
project_dirs = []
|
||||
if args.dir:
|
||||
@@ -988,8 +992,8 @@ def cmd_mcp(args):
|
||||
|
||||
def cmd_compress(args):
|
||||
"""Compress drawers in a wing using AAAK Dialect."""
|
||||
from .backends.chroma import ChromaBackend
|
||||
from .dialect import Dialect
|
||||
from .palace import get_closets_collection
|
||||
|
||||
palace_path = os.path.expanduser(args.palace) if args.palace else MempalaceConfig().palace_path
|
||||
|
||||
@@ -1007,13 +1011,13 @@ def cmd_compress(args):
|
||||
else:
|
||||
dialect = Dialect()
|
||||
|
||||
# Connect to palace
|
||||
backend = ChromaBackend()
|
||||
try:
|
||||
col = backend.get_collection(palace_path, "mempalace_drawers")
|
||||
except Exception:
|
||||
print(f"\n No palace found at {palace_path}")
|
||||
print(" Run: mempalace init <dir> then mempalace mine <dir>")
|
||||
# State-aware open: distinguish "no palace" from "initialized but empty"
|
||||
# from "corrupt" via the shared helper (#1498). MCP and library callers
|
||||
# catch the backend exceptions directly; CLI gets the friendly print.
|
||||
from .palace import _open_collection_or_explain
|
||||
|
||||
col = _open_collection_or_explain(palace_path, collection_name="mempalace_drawers")
|
||||
if col is None:
|
||||
sys.exit(1)
|
||||
|
||||
# Query drawers in batches to avoid SQLite variable limit (~999)
|
||||
@@ -1085,7 +1089,10 @@ def cmd_compress(args):
|
||||
# Store compressed versions (unless dry-run)
|
||||
if not args.dry_run:
|
||||
try:
|
||||
comp_col = backend.get_or_create_collection(palace_path, "mempalace_closets")
|
||||
# Route through palace.get_closets_collection so the shared
|
||||
# _DEFAULT_BACKEND is reused (avoids a redundant ChromaBackend
|
||||
# instance and its potential WAL-lock contention on Windows).
|
||||
comp_col = get_closets_collection(palace_path, create=True)
|
||||
for doc_id, compressed, meta, stats in compressed_entries:
|
||||
comp_meta = dict(meta)
|
||||
comp_meta["compression_ratio"] = round(stats["size_ratio"], 1)
|
||||
@@ -1129,6 +1136,21 @@ def _reconfigure_stdio_utf8_on_windows():
|
||||
|
||||
|
||||
def main():
|
||||
"""CLI entry point for the ``mempalace`` console script.
|
||||
|
||||
Side effect: pops ``PYTHONPATH`` from ``os.environ`` (see #1423) so
|
||||
any subprocess this CLI spawns inherits a clean env. Host applications
|
||||
that call ``main()`` programmatically should be aware that the parent
|
||||
process loses ``PYTHONPATH`` as well. Library imports
|
||||
(``import mempalace.searcher`` from a host app) do NOT trigger this
|
||||
side effect; only the CLI/MCP entry points pop the env var.
|
||||
"""
|
||||
# Drop leaked PYTHONPATH so any subprocess the CLI spawns (mine workers,
|
||||
# repair tooling) starts with a clean env. The sys.path filter in
|
||||
# mempalace/__init__.py already protects this process from the same
|
||||
# ABI mismatch; here we extend the protection to children.
|
||||
os.environ.pop("PYTHONPATH", None)
|
||||
|
||||
_reconfigure_stdio_utf8_on_windows()
|
||||
|
||||
version_label = f"MemPalace {__version__}"
|
||||
|
||||
@@ -189,6 +189,15 @@ def get_configured_collection_name() -> str:
|
||||
return MempalaceConfig().collection_name
|
||||
|
||||
|
||||
# Single source of truth for chunking defaults. ``mempalace.miner``
|
||||
# imports these so the legacy module-level ``CHUNK_SIZE`` /
|
||||
# ``CHUNK_OVERLAP`` / ``MIN_CHUNK_SIZE`` constants stay in sync with
|
||||
# ``MempalaceConfig.chunk_*``. Putting them here (not in miner.py) keeps
|
||||
# the config layer self-contained and avoids circular imports.
|
||||
DEFAULT_CHUNK_SIZE = 800
|
||||
DEFAULT_CHUNK_OVERLAP = 100
|
||||
DEFAULT_MIN_CHUNK_SIZE = 50
|
||||
|
||||
DEFAULT_TOPIC_WINGS = [
|
||||
"emotions",
|
||||
"consciousness",
|
||||
@@ -304,6 +313,113 @@ class MempalaceConfig:
|
||||
"""Mapping of hall names to keyword lists."""
|
||||
return self._file_config.get("hall_keywords", DEFAULT_HALL_KEYWORDS)
|
||||
|
||||
@staticmethod
|
||||
def _try_coerce_int(value, minimum=None):
|
||||
"""Coerce a raw config value to int, or ``None`` if it cannot be a
|
||||
valid setting.
|
||||
|
||||
bool, empty/garbage string, non-numeric, and below-``minimum``
|
||||
values all return ``None``. Shared by ``_coerce_config_int``
|
||||
(which substitutes a documented default) and
|
||||
``min_chunk_size_explicit`` (which must distinguish "unusable"
|
||||
from "explicitly set" without crashing the convo path).
|
||||
"""
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
try:
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
if not value:
|
||||
return None
|
||||
value = int(value)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
# OverflowError: JSON ``1e1000`` parses to float('inf'), and
|
||||
# ``int(inf)`` raises it — still just garbage config, not a crash.
|
||||
return None
|
||||
if minimum is not None and value < minimum:
|
||||
return None
|
||||
return value
|
||||
|
||||
def _coerce_config_int(self, key: str, default: int, minimum=None) -> int:
|
||||
"""Read an int config value, falling back to ``default`` on bad input.
|
||||
|
||||
Hand-edited ``config.json`` is the most common source of garbage:
|
||||
a string, a bool, a negative number, or a JSON null. None of those
|
||||
should crash mining or hang ``chunk_text()`` — fall back silently
|
||||
to the documented default rather than letting a typo break ingest.
|
||||
"""
|
||||
coerced = self._try_coerce_int(self._file_config.get(key, default), minimum)
|
||||
return default if coerced is None else coerced
|
||||
|
||||
def _validated_chunk_config(self):
|
||||
"""Return ``(chunk_size, chunk_overlap, min_chunk_size)`` post-validation.
|
||||
|
||||
Enforces the invariants the miner relies on:
|
||||
* ``chunk_size >= 1``
|
||||
* ``0 <= chunk_overlap < chunk_size`` — equality would loop forever
|
||||
* ``min_chunk_size <= chunk_size`` — otherwise no chunk is ever
|
||||
large enough to file, and ingest silently produces 0 drawers
|
||||
|
||||
Repairs (rather than raises) on violation so a single bad
|
||||
config.json key doesn't take ingest down.
|
||||
"""
|
||||
chunk_size = self._coerce_config_int("chunk_size", DEFAULT_CHUNK_SIZE, minimum=1)
|
||||
chunk_overlap = self._coerce_config_int("chunk_overlap", DEFAULT_CHUNK_OVERLAP, minimum=0)
|
||||
min_chunk_size = self._coerce_config_int(
|
||||
"min_chunk_size", DEFAULT_MIN_CHUNK_SIZE, minimum=0
|
||||
)
|
||||
|
||||
if chunk_overlap >= chunk_size:
|
||||
chunk_overlap = (
|
||||
DEFAULT_CHUNK_OVERLAP
|
||||
if DEFAULT_CHUNK_OVERLAP < chunk_size
|
||||
else max(0, chunk_size - 1)
|
||||
)
|
||||
|
||||
if min_chunk_size > chunk_size:
|
||||
min_chunk_size = (
|
||||
DEFAULT_MIN_CHUNK_SIZE if DEFAULT_MIN_CHUNK_SIZE <= chunk_size else chunk_size
|
||||
)
|
||||
|
||||
return chunk_size, chunk_overlap, min_chunk_size
|
||||
|
||||
@property
|
||||
def chunk_size(self) -> int:
|
||||
"""Characters per drawer chunk (validated, ``>= 1``)."""
|
||||
return self._validated_chunk_config()[0]
|
||||
|
||||
@property
|
||||
def chunk_overlap(self) -> int:
|
||||
"""Overlap between adjacent chunks (validated, ``< chunk_size``)."""
|
||||
return self._validated_chunk_config()[1]
|
||||
|
||||
@property
|
||||
def min_chunk_size(self) -> int:
|
||||
"""Minimum chunk size — skip smaller chunks (validated, ``<= chunk_size``)."""
|
||||
return self._validated_chunk_config()[2]
|
||||
|
||||
@property
|
||||
def min_chunk_size_explicit(self):
|
||||
"""Validated ``min_chunk_size`` iff the user explicitly set it.
|
||||
|
||||
Returns the coerced int when ``config.json`` defines a usable
|
||||
``min_chunk_size`` (``>= 0`` and ``<= chunk_size``); ``None`` when
|
||||
the key is absent/null or the value is unusable. ``convo_miner``
|
||||
relies on the ``None`` sentinel to keep its lower 30-char floor
|
||||
(more permissive than the 50-char project default, so short
|
||||
exchanges are not dropped) for untuned users while still honoring
|
||||
an explicit override —
|
||||
replacing the raw, unvalidated ``_file_config`` reach that crashed
|
||||
convo ingest on a bad key (#1024 review).
|
||||
"""
|
||||
raw = self._file_config.get("min_chunk_size")
|
||||
if raw is None:
|
||||
return None
|
||||
coerced = self._try_coerce_int(raw, minimum=0)
|
||||
if coerced is None or coerced > self.chunk_size:
|
||||
return None
|
||||
return coerced
|
||||
|
||||
@property
|
||||
def entity_languages(self):
|
||||
"""Languages whose entity-detection patterns should be applied.
|
||||
@@ -454,6 +570,14 @@ class MempalaceConfig:
|
||||
except (OSError, NotImplementedError):
|
||||
pass # Windows doesn't support Unix permissions
|
||||
if not self._config_file.exists():
|
||||
# Chunking parameters (chunk_size, chunk_overlap, min_chunk_size)
|
||||
# are intentionally NOT written here — convo_miner.py distinguishes
|
||||
# "user has tuned this" from "user is on defaults" by checking
|
||||
# ``_file_config.get("min_chunk_size") is None``. Writing the
|
||||
# miner.py defaults (50) into config.json breaks that detection
|
||||
# and silently overrides convo_miner's stricter 30-char floor,
|
||||
# dropping legitimate short conversation exchanges. Module-level
|
||||
# defaults already apply correctly when these keys are absent.
|
||||
default_config = {
|
||||
"palace_path": DEFAULT_PALACE_PATH,
|
||||
"collection_name": DEFAULT_COLLECTION_NAME,
|
||||
|
||||
+135
-31
@@ -20,9 +20,11 @@ from .normalize import normalize
|
||||
from .palace import (
|
||||
NORMALIZE_VERSION,
|
||||
SKIP_DIRS,
|
||||
_metadata_matches_extract_mode,
|
||||
file_already_mined,
|
||||
get_collection,
|
||||
mine_lock,
|
||||
prefetch_mined_set,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("mempalace_mcp")
|
||||
@@ -69,14 +71,15 @@ MAX_FILE_SIZE = 500 * 1024 * 1024 # 500 MB — skip files larger than this.
|
||||
# use also scales with source size.
|
||||
|
||||
|
||||
def _register_file(collection, source_file: str, wing: str, agent: str):
|
||||
def _register_file(collection, source_file: str, wing: str, agent: str, extract_mode: str):
|
||||
"""Write a sentinel so file_already_mined() returns True for 0-chunk files.
|
||||
|
||||
Without this, files that normalize to nothing or produce zero chunks are
|
||||
re-read and re-processed on every mine run because nothing was written to
|
||||
ChromaDB on the first pass.
|
||||
"""
|
||||
sentinel_id = f"_reg_{hashlib.sha256(source_file.encode()).hexdigest()[:24]}"
|
||||
sentinel_key = f"{source_file}:{extract_mode}"
|
||||
sentinel_id = f"_reg_{hashlib.sha256(sentinel_key.encode()).hexdigest()[:24]}"
|
||||
collection.upsert(
|
||||
documents=[f"[registry] {source_file}"],
|
||||
ids=[sentinel_id],
|
||||
@@ -88,36 +91,86 @@ def _register_file(collection, source_file: str, wing: str, agent: str):
|
||||
"added_by": agent,
|
||||
"filed_at": datetime.now().isoformat(),
|
||||
"ingest_mode": "registry",
|
||||
"extract_mode": extract_mode,
|
||||
"normalize_version": NORMALIZE_VERSION,
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _source_file_delete_ids(collection, source_file: str, extract_mode: str) -> list[str]:
|
||||
"""Collect drawer IDs for one source file and extraction mode.
|
||||
|
||||
Legacy conversation drawers did not carry extract_mode; treat those as
|
||||
exchange-mode rows so schema rebuilds can still clean them up without
|
||||
deleting newer general-mode drawers for the same transcript.
|
||||
"""
|
||||
ids: list[str] = []
|
||||
offset = 0
|
||||
while True:
|
||||
batch = collection.get(
|
||||
where={"source_file": source_file},
|
||||
limit=1000,
|
||||
offset=offset,
|
||||
include=["metadatas"],
|
||||
)
|
||||
batch_ids = batch.get("ids") or []
|
||||
metadatas = batch.get("metadatas") or []
|
||||
for drawer_id, meta in zip(batch_ids, metadatas):
|
||||
if _metadata_matches_extract_mode(meta or {}, extract_mode):
|
||||
ids.append(drawer_id)
|
||||
if not batch_ids:
|
||||
break
|
||||
offset += len(batch_ids)
|
||||
return ids
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# CHUNKING — exchange pairs for conversations
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def chunk_exchanges(content: str) -> list:
|
||||
def chunk_exchanges(
|
||||
content: str,
|
||||
chunk_size: int = None,
|
||||
min_chunk_size: int = None,
|
||||
) -> list:
|
||||
"""
|
||||
Chunk by exchange pair: one > turn + AI response = one unit.
|
||||
Falls back to paragraph chunking if no > markers.
|
||||
|
||||
Optional params override module-level defaults when provided.
|
||||
|
||||
Raises ``ValueError`` if ``chunk_size`` is not a positive integer or
|
||||
``min_chunk_size`` is negative. A non-positive ``chunk_size`` would
|
||||
cause ``_chunk_by_exchange`` below to loop forever — ``content[:0]``
|
||||
is empty, ``content[0:]`` is the whole string, and the remainder
|
||||
never shrinks.
|
||||
"""
|
||||
if chunk_size is None:
|
||||
chunk_size = CHUNK_SIZE
|
||||
if min_chunk_size is None:
|
||||
min_chunk_size = MIN_CHUNK_SIZE
|
||||
|
||||
if chunk_size <= 0:
|
||||
raise ValueError(f"chunk_size must be > 0, got {chunk_size}")
|
||||
if min_chunk_size < 0:
|
||||
raise ValueError(f"min_chunk_size must be >= 0, got {min_chunk_size}")
|
||||
|
||||
lines = content.split("\n")
|
||||
quote_lines = sum(1 for line in lines if line.strip().startswith(">"))
|
||||
|
||||
if quote_lines >= 3:
|
||||
return _chunk_by_exchange(lines)
|
||||
return _chunk_by_exchange(lines, chunk_size, min_chunk_size)
|
||||
else:
|
||||
return _chunk_by_paragraph(content)
|
||||
return _chunk_by_paragraph(content, min_chunk_size)
|
||||
|
||||
|
||||
def _chunk_by_exchange(lines: list) -> list:
|
||||
def _chunk_by_exchange(lines: list, chunk_size: int, min_chunk_size: int) -> list:
|
||||
"""One user turn (>) + the AI response that follows = one or more chunks.
|
||||
|
||||
The full AI response is preserved verbatim. When the combined
|
||||
user-turn + response exceeds CHUNK_SIZE the response is split across
|
||||
user-turn + response exceeds chunk_size the response is split across
|
||||
consecutive drawers so nothing is silently discarded.
|
||||
"""
|
||||
chunks = []
|
||||
@@ -141,20 +194,20 @@ def _chunk_by_exchange(lines: list) -> list:
|
||||
ai_response = " ".join(ai_lines)
|
||||
content = f"{user_turn}\n{ai_response}" if ai_response else user_turn
|
||||
|
||||
# Split into multiple drawers when the exchange exceeds CHUNK_SIZE
|
||||
if len(content) > CHUNK_SIZE:
|
||||
# Split into multiple drawers when the exchange exceeds chunk_size
|
||||
if len(content) > chunk_size:
|
||||
# First chunk: user turn + as much response as fits
|
||||
first_part = content[:CHUNK_SIZE]
|
||||
if len(first_part.strip()) > MIN_CHUNK_SIZE:
|
||||
first_part = content[:chunk_size]
|
||||
if len(first_part.strip()) > min_chunk_size:
|
||||
chunks.append({"content": first_part, "chunk_index": len(chunks)})
|
||||
# Remaining response in CHUNK_SIZE-sized continuation drawers
|
||||
remainder = content[CHUNK_SIZE:]
|
||||
# Remaining response in chunk_size-sized continuation drawers
|
||||
remainder = content[chunk_size:]
|
||||
while remainder:
|
||||
part = remainder[:CHUNK_SIZE]
|
||||
remainder = remainder[CHUNK_SIZE:]
|
||||
if len(part.strip()) > MIN_CHUNK_SIZE:
|
||||
part = remainder[:chunk_size]
|
||||
remainder = remainder[chunk_size:]
|
||||
if len(part.strip()) > min_chunk_size:
|
||||
chunks.append({"content": part, "chunk_index": len(chunks)})
|
||||
elif len(content.strip()) > MIN_CHUNK_SIZE:
|
||||
elif len(content.strip()) > min_chunk_size:
|
||||
chunks.append(
|
||||
{
|
||||
"content": content,
|
||||
@@ -167,7 +220,7 @@ def _chunk_by_exchange(lines: list) -> list:
|
||||
return chunks
|
||||
|
||||
|
||||
def _chunk_by_paragraph(content: str) -> list:
|
||||
def _chunk_by_paragraph(content: str, min_chunk_size: int) -> list:
|
||||
"""Fallback: chunk by paragraph breaks."""
|
||||
chunks = []
|
||||
paragraphs = [p.strip() for p in content.split("\n\n") if p.strip()]
|
||||
@@ -177,12 +230,12 @@ def _chunk_by_paragraph(content: str) -> list:
|
||||
lines = content.split("\n")
|
||||
for i in range(0, len(lines), 25):
|
||||
group = "\n".join(lines[i : i + 25]).strip()
|
||||
if len(group) > MIN_CHUNK_SIZE:
|
||||
if len(group) > min_chunk_size:
|
||||
chunks.append({"content": group, "chunk_index": len(chunks)})
|
||||
return chunks
|
||||
|
||||
for para in paragraphs:
|
||||
if len(para) > MIN_CHUNK_SIZE:
|
||||
if len(para) > min_chunk_size:
|
||||
chunks.append({"content": para, "chunk_index": len(chunks)})
|
||||
|
||||
return chunks
|
||||
@@ -283,7 +336,12 @@ def detect_convo_room(content: str) -> str:
|
||||
|
||||
|
||||
def scan_convos(convo_dir: str) -> list:
|
||||
"""Find all potential conversation files."""
|
||||
"""Find all potential conversation files.
|
||||
|
||||
Skips symlinks and oversized files. Each skipped symlink is logged to
|
||||
``sys.stderr`` with a `` SKIP: <relative-path> (symlink)`` line so the
|
||||
caller can tell why an apparent conversation directory yielded no files.
|
||||
"""
|
||||
convo_path = Path(convo_dir).expanduser().resolve()
|
||||
files = []
|
||||
for root, dirs, filenames in os.walk(convo_path):
|
||||
@@ -295,6 +353,11 @@ def scan_convos(convo_dir: str) -> list:
|
||||
if filepath.suffix.lower() in CONVO_EXTENSIONS:
|
||||
# Skip symlinks and oversized files
|
||||
if filepath.is_symlink():
|
||||
rel = filepath.relative_to(convo_path).as_posix()
|
||||
try:
|
||||
print(f" SKIP: {rel} (symlink)", file=sys.stderr)
|
||||
except OSError:
|
||||
pass
|
||||
continue
|
||||
try:
|
||||
if filepath.stat().st_size > MAX_FILE_SIZE:
|
||||
@@ -325,14 +388,16 @@ def _file_chunks_locked(collection, source_file, chunks, wing, room, agent, extr
|
||||
# Re-check after lock — another agent may have just finished this file
|
||||
# at the current schema. A stale-version hit here returns False, so we
|
||||
# still fall through to the purge+rebuild path below.
|
||||
if file_already_mined(collection, source_file):
|
||||
if file_already_mined(collection, source_file, extract_mode=extract_mode):
|
||||
return 0, room_counts_delta, True
|
||||
|
||||
# Purge stale drawers first. When the normalize schema bumps,
|
||||
# file_already_mined() returned False for pre-v2 drawers — clean
|
||||
# them out so the source doesn't end up with mixed old/new drawers.
|
||||
try:
|
||||
collection.delete(where={"source_file": source_file})
|
||||
delete_ids = _source_file_delete_ids(collection, source_file, extract_mode)
|
||||
if delete_ids:
|
||||
collection.delete(ids=delete_ids)
|
||||
except Exception:
|
||||
logger.debug("Stale-drawer purge failed for %s", source_file, exc_info=True)
|
||||
|
||||
@@ -349,7 +414,11 @@ def _file_chunks_locked(collection, source_file, chunks, wing, room, agent, extr
|
||||
chunk_room = chunk.get("memory_type", room) if extract_mode == "general" else room
|
||||
if extract_mode == "general":
|
||||
room_counts_delta[chunk_room] += 1
|
||||
drawer_id = f"drawer_{wing}_{chunk_room}_{hashlib.sha256((source_file + str(chunk['chunk_index'])).encode()).hexdigest()[:24]}"
|
||||
drawer_key = f"{source_file}:{extract_mode}:{chunk['chunk_index']}"
|
||||
drawer_id = (
|
||||
f"drawer_{wing}_{chunk_room}_"
|
||||
f"{hashlib.sha256(drawer_key.encode()).hexdigest()[:24]}"
|
||||
)
|
||||
batch_docs.append(chunk["content"])
|
||||
batch_ids.append(drawer_id)
|
||||
batch_metas.append(
|
||||
@@ -393,7 +462,29 @@ def mine_convos(
|
||||
extract_mode:
|
||||
"exchange" — default exchange-pair chunking (Q+A = one unit)
|
||||
"general" — general extractor: decisions, preferences, milestones, problems, emotions
|
||||
|
||||
Chunking parameters (chunk_size, min_chunk_size) are read from
|
||||
MempalaceConfig so `config.json` governs both this path and the
|
||||
project-file miner in `miner.py`. `min_chunk_size` preserves
|
||||
convo_miner's lower default (30 — more permissive than the 50-char
|
||||
project default, so short conversation exchanges are not dropped)
|
||||
when not explicitly set in config.json, so a user who never touches
|
||||
chunking keeps the existing behavior.
|
||||
"""
|
||||
from .config import MempalaceConfig
|
||||
|
||||
palace_config = MempalaceConfig()
|
||||
cfg_chunk_size = palace_config.chunk_size
|
||||
# Only override convo_miner's MIN_CHUNK_SIZE when the user has set
|
||||
# min_chunk_size explicitly. min_chunk_size_explicit returns the
|
||||
# validated value or None — None keeps convo's lower 30-char floor
|
||||
# (more permissive than the 50-char project default, so short
|
||||
# exchanges aren't dropped). Using the validated accessor (not raw
|
||||
# _file_config) means a
|
||||
# garbage/negative/bool config value can't TypeError the length gate
|
||||
# below or ValueError out of chunk_exchanges and abort convo ingest.
|
||||
explicit_min = palace_config.min_chunk_size_explicit
|
||||
cfg_min_chunk_size = explicit_min if explicit_min is not None else MIN_CHUNK_SIZE
|
||||
|
||||
convo_path = Path(convo_dir).expanduser().resolve()
|
||||
if not wing:
|
||||
@@ -418,6 +509,15 @@ def mine_convos(
|
||||
|
||||
collection = get_collection(palace_path) if not dry_run else None
|
||||
|
||||
# Bulk pre-fetch already-mined set in one paginated pass instead of
|
||||
# `len(files)` separate WHERE-source_file queries. On a 150k-drawer
|
||||
# palace each per-file query costs ~2s, so a 2000-file sweep used to
|
||||
# spend >1h just deciding to skip. prefetch_mined_set() does the same
|
||||
# decisions in a single scan; loop body becomes an O(1) set check.
|
||||
mined_set: set[str] = (
|
||||
prefetch_mined_set(collection, extract_mode=extract_mode) if not dry_run else set()
|
||||
)
|
||||
|
||||
total_drawers = 0
|
||||
files_skipped = 0
|
||||
room_counts = defaultdict(int)
|
||||
@@ -425,8 +525,8 @@ def mine_convos(
|
||||
for i, filepath in enumerate(files, 1):
|
||||
source_file = str(filepath)
|
||||
|
||||
# Skip if already filed
|
||||
if not dry_run and file_already_mined(collection, source_file):
|
||||
# Skip if already filed at current NORMALIZE_VERSION
|
||||
if not dry_run and source_file in mined_set:
|
||||
files_skipped += 1
|
||||
continue
|
||||
|
||||
@@ -435,12 +535,12 @@ def mine_convos(
|
||||
content = normalize(str(filepath))
|
||||
except (OSError, ValueError):
|
||||
if not dry_run:
|
||||
_register_file(collection, source_file, wing, agent)
|
||||
_register_file(collection, source_file, wing, agent, extract_mode)
|
||||
continue
|
||||
|
||||
if not content or len(content.strip()) < MIN_CHUNK_SIZE:
|
||||
if not content or len(content.strip()) < cfg_min_chunk_size:
|
||||
if not dry_run:
|
||||
_register_file(collection, source_file, wing, agent)
|
||||
_register_file(collection, source_file, wing, agent, extract_mode)
|
||||
continue
|
||||
|
||||
# Chunk — either exchange pairs or general extraction
|
||||
@@ -450,11 +550,15 @@ def mine_convos(
|
||||
chunks = extract_memories(content)
|
||||
# Each chunk already has memory_type; use it as the room name
|
||||
else:
|
||||
chunks = chunk_exchanges(content)
|
||||
chunks = chunk_exchanges(
|
||||
content,
|
||||
chunk_size=cfg_chunk_size,
|
||||
min_chunk_size=cfg_min_chunk_size,
|
||||
)
|
||||
|
||||
if not chunks:
|
||||
if not dry_run:
|
||||
_register_file(collection, source_file, wing, agent)
|
||||
_register_file(collection, source_file, wing, agent, extract_mode)
|
||||
continue
|
||||
|
||||
# Detect room from content (general mode uses memory_type instead)
|
||||
|
||||
+23
-6
@@ -159,7 +159,9 @@ class EmbeddinggemmaONNX:
|
||||
return "embeddinggemma_300m"
|
||||
|
||||
def __init__(self, preferred_providers=None):
|
||||
self._providers = list(preferred_providers) if preferred_providers else ["CPUExecutionProvider"]
|
||||
self._providers = (
|
||||
list(preferred_providers) if preferred_providers else ["CPUExecutionProvider"]
|
||||
)
|
||||
self._session = None
|
||||
self._tokenizer = None
|
||||
self._np = None
|
||||
@@ -181,15 +183,23 @@ class EmbeddinggemmaONNX:
|
||||
"Reinstall with: pip install --upgrade --force-reinstall mempalace"
|
||||
) from e
|
||||
|
||||
logger.info("Downloading %s/%s (cached after first run)…", _EMBEDDINGGEMMA_REPO, _EMBEDDINGGEMMA_ONNX)
|
||||
model_path = hf_hub_download(_EMBEDDINGGEMMA_REPO, subfolder="onnx", filename=_EMBEDDINGGEMMA_ONNX)
|
||||
logger.info(
|
||||
"Downloading %s/%s (cached after first run)…",
|
||||
_EMBEDDINGGEMMA_REPO,
|
||||
_EMBEDDINGGEMMA_ONNX,
|
||||
)
|
||||
model_path = hf_hub_download(
|
||||
_EMBEDDINGGEMMA_REPO, subfolder="onnx", filename=_EMBEDDINGGEMMA_ONNX
|
||||
)
|
||||
tok_path = hf_hub_download(_EMBEDDINGGEMMA_REPO, filename="tokenizer.json")
|
||||
|
||||
self._session = ort.InferenceSession(model_path, providers=self._providers)
|
||||
out_names = [o.name for o in self._session.get_outputs()]
|
||||
# Model card: sentence_embedding is the pooled output (last_hidden_state
|
||||
# is the per-token output we don't want).
|
||||
self._output_idx = out_names.index("sentence_embedding") if "sentence_embedding" in out_names else 1
|
||||
self._output_idx = (
|
||||
out_names.index("sentence_embedding") if "sentence_embedding" in out_names else 1
|
||||
)
|
||||
|
||||
tokenizer = Tokenizer.from_file(tok_path)
|
||||
tokenizer.enable_padding()
|
||||
@@ -204,7 +214,9 @@ class EmbeddinggemmaONNX:
|
||||
encs = self._tokenizer.encode_batch(texts)
|
||||
input_ids = np.asarray([e.ids for e in encs], dtype=np.int64)
|
||||
attention_mask = np.asarray([e.attention_mask for e in encs], dtype=np.int64)
|
||||
outputs = self._session.run(None, {"input_ids": input_ids, "attention_mask": attention_mask})
|
||||
outputs = self._session.run(
|
||||
None, {"input_ids": input_ids, "attention_mask": attention_mask}
|
||||
)
|
||||
sent_emb = outputs[self._output_idx][:, :_EMBEDDINGGEMMA_DIM]
|
||||
# L2-normalize so cosine similarity == dot product (matches what the
|
||||
# MTEB methodology assumes; ChromaDB's distance is configured for it).
|
||||
@@ -243,7 +255,12 @@ def get_embedding_function(device: Optional[str] = None, model: Optional[str] =
|
||||
ef = ef_cls(preferred_providers=providers)
|
||||
|
||||
_EF_CACHE[cache_key] = ef
|
||||
logger.info("Embedding function initialized (model=%s device=%s providers=%s)", model, effective, providers)
|
||||
logger.info(
|
||||
"Embedding function initialized (model=%s device=%s providers=%s)",
|
||||
model,
|
||||
effective,
|
||||
providers,
|
||||
)
|
||||
return ef
|
||||
|
||||
|
||||
|
||||
@@ -327,15 +327,26 @@ class EntityRegistry:
|
||||
# instead of a half-written file or an empty file from the truncate.
|
||||
payload = json.dumps(self._data, indent=2)
|
||||
tmp_path = self._path.with_name(self._path.name + ".tmp")
|
||||
with open(tmp_path, "w", encoding="utf-8") as f:
|
||||
f.write(payload)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
try:
|
||||
tmp_path.chmod(0o600)
|
||||
except (OSError, NotImplementedError):
|
||||
pass
|
||||
os.replace(tmp_path, self._path)
|
||||
with open(tmp_path, "w", encoding="utf-8") as f:
|
||||
f.write(payload)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
try:
|
||||
tmp_path.chmod(0o600)
|
||||
except (OSError, NotImplementedError):
|
||||
pass
|
||||
os.replace(tmp_path, self._path)
|
||||
except BaseException:
|
||||
# Disk full, perms flip, broken FUSE mount, IO error, KeyboardInterrupt
|
||||
# mid-write — unlink the .tmp sidecar so it does not litter the palace
|
||||
# directory or confuse diagnostics. The previous registry is intact
|
||||
# because os.replace is atomic on POSIX/NTFS.
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
# On ext4 (and similar) the rename's durability across power loss
|
||||
# requires an additional fsync on the parent directory. Without it,
|
||||
# the kernel can ack the rename and a crash reverts to the state
|
||||
|
||||
+104
-16
@@ -670,36 +670,124 @@ def _parse_harness_input(data: dict, harness: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
# Common parent-dir tokens stripped from the encoded folder when no
|
||||
# explicit ``-Projects-`` segment is present. Order matters: only the
|
||||
# first match strips. These cover the bulk of Unix layouts; cwd-from-JSONL
|
||||
# (the primary path) handles the long tail correctly without heuristics.
|
||||
_ENCODED_PARENT_PREFIXES = (
|
||||
"git-",
|
||||
"dev-",
|
||||
"projects-",
|
||||
"Projects-",
|
||||
"src-",
|
||||
"code-",
|
||||
"work-",
|
||||
"Documents-",
|
||||
)
|
||||
|
||||
|
||||
def _wing_from_jsonl_cwd(transcript_path: str) -> Optional[str]:
|
||||
"""Read ``cwd`` from the first JSONL line that records it.
|
||||
|
||||
Claude Code stores the absolute working directory on most message
|
||||
types (tool_use, tool_result, user/assistant turns), but not all
|
||||
(e.g. queue-operation lines lack it). Scan up to 200 lines to find
|
||||
the first record that includes a non-empty cwd, then derive the
|
||||
wing from its leaf path segment. Returns ``None`` if the file is
|
||||
unreadable, empty, or contains no cwd.
|
||||
"""
|
||||
try:
|
||||
path = Path(transcript_path).expanduser()
|
||||
if not path.is_file():
|
||||
return None
|
||||
with path.open("r", encoding="utf-8", errors="replace") as f:
|
||||
for i, line in enumerate(f):
|
||||
if i >= 200:
|
||||
break
|
||||
line = line.strip()
|
||||
if not line or '"cwd"' not in line:
|
||||
continue
|
||||
try:
|
||||
data = json.loads(line)
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
continue
|
||||
cwd = data.get("cwd")
|
||||
if not cwd or not isinstance(cwd, str):
|
||||
continue
|
||||
cwd_norm = cwd.replace("\\", "/").rstrip("/")
|
||||
if not cwd_norm:
|
||||
continue
|
||||
project = cwd_norm.rsplit("/", 1)[-1]
|
||||
if project:
|
||||
slug = project.lower().replace(" ", "_").replace("-", "_")
|
||||
return f"wing_{slug}"
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _wing_from_transcript_path(transcript_path: str) -> str:
|
||||
"""Derive a project wing name from a Claude Code transcript path.
|
||||
|
||||
Claude Code encodes the project's source directory by replacing path
|
||||
separators with dashes, producing folders like:
|
||||
~/.claude/projects/-home-<user>-Projects-<project>/session.jsonl
|
||||
~/.claude/projects/-home-<user>-dev-<parent>-<project>/session.jsonl
|
||||
~/.claude/projects/-Users-<user>-<folder>-<project>/session.jsonl
|
||||
Strategy (in priority order):
|
||||
|
||||
The project directory name is the final dash-separated token of the
|
||||
encoded folder. Returns ``wing_<project>`` (lowercased, spaces → ``_``).
|
||||
Falls back to ``wing_sessions`` if the path does not match a Claude Code
|
||||
project-folder layout.
|
||||
1. PRIMARY — Read ``cwd`` from the JSONL transcript. Claude Code records
|
||||
the absolute working directory on most message types, so the project
|
||||
name is whatever the leaf path segment of cwd is. This is the
|
||||
canonical answer when present.
|
||||
|
||||
2. FALLBACK — Decode the encoded folder under ``.claude/projects/``.
|
||||
Claude Code flattens path separators to dashes (``/Users/me/code/foo``
|
||||
→ ``-Users-me-code-foo``), so the original directory boundaries are
|
||||
lost. We strip the platform user-home prefix (``Users-<user>-`` or
|
||||
``home-<user>-``) and one common parent-dir token (``git-``, ``dev-``,
|
||||
``projects-``, etc.), then convert the remaining dashes to
|
||||
underscores. Unlike the previous "last token only" heuristic, this
|
||||
never silently truncates a hyphenated project folder name like
|
||||
``claude-code``, ``react-native``, or ``customer-portal``.
|
||||
|
||||
3. LEGACY — Match an explicit ``-Projects-<name>`` segment for
|
||||
transcripts not under the standard Claude Code projects dir.
|
||||
|
||||
4. DEFAULT — ``wing_sessions``.
|
||||
|
||||
Closes #1410.
|
||||
"""
|
||||
# 1. Primary — cwd from JSONL is the canonical source of truth
|
||||
cwd_wing = _wing_from_jsonl_cwd(transcript_path)
|
||||
if cwd_wing:
|
||||
return cwd_wing
|
||||
|
||||
# Normalize path separators for cross-platform (Windows backslashes)
|
||||
normalized = transcript_path.replace("\\", "/")
|
||||
# Primary: pull the encoded project folder out of ``.claude/projects/``
|
||||
# and take its last dash-separated token.
|
||||
|
||||
# 2. Fallback — encoded project folder under .claude/projects/
|
||||
match = re.search(r"/\.claude/projects/-([^/]+)", normalized)
|
||||
if match:
|
||||
encoded = match.group(1)
|
||||
project = encoded.rsplit("-", 1)[-1]
|
||||
# Strip platform user-home prefix so the wing isn't dominated by
|
||||
# /Users/<user>/ or /home/<user>/.
|
||||
m = re.match(r"(?:Users|home)-[^-]+-(.+)", encoded)
|
||||
if m:
|
||||
encoded = m.group(1)
|
||||
# Strip one common parent-dir token if present, keeping the rest as
|
||||
# the project path. Hyphens become underscores to preserve
|
||||
# uniqueness for hyphenated project folder names.
|
||||
for prefix in _ENCODED_PARENT_PREFIXES:
|
||||
if encoded.startswith(prefix):
|
||||
encoded = encoded[len(prefix) :]
|
||||
break
|
||||
project = encoded.lower().replace(" ", "_").replace("-", "_")
|
||||
if project:
|
||||
return f"wing_{project.lower().replace(' ', '_')}"
|
||||
# Legacy fallback: explicit ``-Projects-<name>`` segment, useful for
|
||||
# transcripts not under the standard Claude Code projects dir.
|
||||
return f"wing_{project}"
|
||||
|
||||
# 3. Legacy — explicit -Projects-<name> segment
|
||||
match = re.search(r"-Projects-([^/]+?)(?:/|$)", normalized)
|
||||
if match:
|
||||
project = match.group(1).lower().replace(" ", "_")
|
||||
project = match.group(1).lower().replace(" ", "_").replace("-", "_")
|
||||
return f"wing_{project}"
|
||||
|
||||
# 4. Default
|
||||
return "wing_sessions"
|
||||
|
||||
|
||||
|
||||
+377
-26
@@ -45,6 +45,7 @@ sys.stdout = sys.stderr
|
||||
import argparse # noqa: E402 (deferred until after stdio protection above)
|
||||
import json # noqa: E402
|
||||
import logging # noqa: E402
|
||||
import re # noqa: E402
|
||||
import hashlib # noqa: E402
|
||||
import sqlite3 # noqa: E402
|
||||
import threading # noqa: E402
|
||||
@@ -84,7 +85,70 @@ from .palace_graph import ( # noqa: E402
|
||||
|
||||
from .knowledge_graph import KnowledgeGraph, DEFAULT_KG_PATH # noqa: E402
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stderr)
|
||||
|
||||
def _init_logging() -> None:
|
||||
"""Root-logger init: always stderr, optionally append to ``MEMPALACE_LOG_FILE``.
|
||||
|
||||
Stderr-only is the default. When ``MEMPALACE_LOG_FILE`` is set, a
|
||||
``FileHandler`` is attached so MCP-client failures that the client
|
||||
does not surface (e.g. the ``-32000`` cold-load timeout in #1495)
|
||||
remain diagnosable from the file.
|
||||
|
||||
Failure modes:
|
||||
|
||||
* Invalid path (missing directory, no perms, Windows NUL byte) →
|
||||
stderr-only with a warning. The env var must not become a new
|
||||
server-start failure surface — that would defeat the diagnostic
|
||||
goal. ``ValueError`` is included in the catch because Windows
|
||||
raises it for paths with embedded NUL bytes, not ``OSError``.
|
||||
* Root logger already configured (host app embedding the server,
|
||||
transitive imports touching ``logging``) → ``force=True`` resets
|
||||
the handlers so MEMPALACE_LOG_FILE's contract holds regardless
|
||||
of what touched root logging first. Without ``force=True``,
|
||||
``basicConfig`` is a no-op when handlers exist and the env var
|
||||
silently does nothing — exactly the diagnostic black hole #1495
|
||||
exists to close.
|
||||
* Concurrent writers (multiple ``mempalace-mcp`` processes pointing
|
||||
at the same path) interleave at the line level. The handler uses
|
||||
append mode so nothing is overwritten, but operators running
|
||||
Claude Code + Claude Desktop simultaneously should give each
|
||||
process its own log path.
|
||||
|
||||
``delay=True`` is intentionally NOT set: deferring the open means an
|
||||
invalid path raises at ``emit()`` time (unhandled), defeating the
|
||||
fail-soft contract. With eager open the same error surfaces inside
|
||||
``FileHandler.__init__`` and lands in our ``except`` below.
|
||||
|
||||
Module-level invocation: this function runs at import time, preserving
|
||||
the side effect of the previous module-level ``logging.basicConfig``
|
||||
call. Callers that import ``mempalace.mcp_server`` for introspection
|
||||
(``TOOLS`` dict, handler functions) inherit the reset; this matches
|
||||
pre-PR behaviour and is intentional for an MCP entry-point module.
|
||||
"""
|
||||
handlers: list[logging.Handler] = [logging.StreamHandler(sys.stderr)]
|
||||
# MEMPALACE_LOG_FILE is operator-supplied and opt-in; this is a
|
||||
# local-first server (CLAUDE.md design principle), so no path
|
||||
# sanitization — the operator's process UID is the trust boundary.
|
||||
log_file = os.environ.get("MEMPALACE_LOG_FILE", "").strip()
|
||||
file_handler_error: Exception | None = None
|
||||
if log_file:
|
||||
try:
|
||||
handlers.append(logging.FileHandler(log_file, mode="a", encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
# Fail-soft: see "Invalid path" failure mode above. Broad on
|
||||
# (OSError, ValueError) because Windows raises ValueError for
|
||||
# NUL-byte paths while POSIX uses OSError for missing-dir / EPERM.
|
||||
file_handler_error = exc
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s", handlers=handlers, force=True)
|
||||
if file_handler_error is not None:
|
||||
logging.getLogger("mempalace_mcp").warning(
|
||||
"MEMPALACE_LOG_FILE=%r could not be opened (%s); using stderr only",
|
||||
log_file,
|
||||
file_handler_error,
|
||||
)
|
||||
|
||||
|
||||
_init_logging()
|
||||
logger = logging.getLogger("mempalace_mcp")
|
||||
|
||||
|
||||
@@ -119,8 +183,35 @@ def _resolve_kg_path() -> str:
|
||||
return DEFAULT_KG_PATH
|
||||
|
||||
|
||||
def _get_kg() -> KnowledgeGraph:
|
||||
path = os.path.abspath(_resolve_kg_path())
|
||||
def _canonicalize_kg_path(path: str) -> str:
|
||||
"""Canonicalize a KG cache key so aliases collapse onto one entry.
|
||||
|
||||
``realpath`` resolves symlinks: two tenants pointing at the same
|
||||
SQLite file via different layouts (``/srv/A`` and
|
||||
``/srv/link-to-A``) hit a single cached ``KnowledgeGraph`` rather
|
||||
than opening duplicate connections. ``normcase`` normalizes Windows
|
||||
drive-letter casing (``C:\\palace`` vs ``c:\\palace``) and
|
||||
path-separator style; on POSIX it returns the input unchanged.
|
||||
"""
|
||||
return os.path.normcase(os.path.realpath(path))
|
||||
|
||||
|
||||
def _get_kg(canonical_path=None) -> KnowledgeGraph:
|
||||
"""Return the cached ``KnowledgeGraph`` for the resolved palace.
|
||||
|
||||
When ``canonical_path`` is ``None`` (default), the path is resolved
|
||||
from module state and canonicalized. Callers like :func:`_call_kg`
|
||||
that have already captured a canonical key before entering a retry
|
||||
loop should pass it through here so the dict insertion uses the same
|
||||
key the caller will later use for eviction. Recomputing the key
|
||||
inside this function would let ``MEMPALACE_PALACE_PATH`` rotation,
|
||||
a symlink remap, or a mount remap between the captured value and
|
||||
this call drift the insert and evict keys apart, stranding a closed
|
||||
handle under one key while the lookup probes another.
|
||||
"""
|
||||
path = (
|
||||
canonical_path if canonical_path is not None else _canonicalize_kg_path(_resolve_kg_path())
|
||||
)
|
||||
kg = _kg_by_path.get(path)
|
||||
if kg is not None:
|
||||
return kg
|
||||
@@ -149,14 +240,24 @@ def _call_kg(op):
|
||||
KG. Beyond one retry give up: a second close means we're losing a
|
||||
sustained race we won't win in this loop, and a hung loop is worse
|
||||
than a clear failure surface.
|
||||
|
||||
The canonical path is captured once at the top and threaded through
|
||||
every ``_get_kg`` call plus the eviction lookup. Doing canonicalize
|
||||
only here means an ``OSError`` from ``realpath`` (transient Windows
|
||||
junction loss, broken mount) surfaces cleanly before any handler
|
||||
runs instead of masking a ``sqlite3.ProgrammingError`` mid-retry.
|
||||
Passing the captured key through to ``_get_kg`` also locks the
|
||||
insert key to the evict key even if FS or env state mutates between
|
||||
attempts, preventing a closed handle from leaking under a stale
|
||||
key the lookup no longer matches.
|
||||
"""
|
||||
path = _canonicalize_kg_path(_resolve_kg_path())
|
||||
for attempt in range(2):
|
||||
kg = _get_kg()
|
||||
kg = _get_kg(path)
|
||||
try:
|
||||
return op(kg)
|
||||
except sqlite3.ProgrammingError:
|
||||
if attempt == 0:
|
||||
path = os.path.abspath(_resolve_kg_path())
|
||||
with _kg_cache_lock:
|
||||
if _kg_by_path.get(path) is kg:
|
||||
_kg_by_path.pop(path, None)
|
||||
@@ -467,6 +568,28 @@ def _no_palace():
|
||||
# ==================== HELPERS ====================
|
||||
|
||||
|
||||
def _safe_meta(meta):
|
||||
"""Coerce a Chroma metadata value to a dict.
|
||||
|
||||
ChromaDB's ``col.get()`` / ``col.query()`` can return ``None`` for the
|
||||
metadata cell of a partially-flushed row (or any row written without
|
||||
metadata in older formats). Indexing the result then yields ``None``,
|
||||
and downstream ``.get(...)`` calls raise::
|
||||
|
||||
AttributeError: 'NoneType' object has no attribute 'get'
|
||||
|
||||
This bug bricked the embeddings_queue cleanup path in issue #1426 —
|
||||
the handler crashed before reaching the ``DELETE FROM embeddings_queue``
|
||||
step, so the queue grew without bound while writes kept appearing
|
||||
successful.
|
||||
|
||||
Centralizing the coercion through this helper makes the contract
|
||||
explicit and keeps the fix self-documenting at every call site:
|
||||
*metadata is always a dict by the time it leaves the boundary*.
|
||||
"""
|
||||
return meta if isinstance(meta, dict) else {}
|
||||
|
||||
|
||||
def _fetch_all_metadata(col, where=None):
|
||||
"""Paginate col.get() to avoid the 10K silent truncation limit."""
|
||||
total = col.count()
|
||||
@@ -833,7 +956,7 @@ def tool_check_duplicate(content: str, threshold: float = 0.9):
|
||||
if similarity >= threshold:
|
||||
# Chroma 1.5.x can return None for partially-flushed rows;
|
||||
# coerce to empty sentinels so downstream .get() is safe.
|
||||
meta = results["metadatas"][0][i] or {}
|
||||
meta = _safe_meta(results["metadatas"][0][i])
|
||||
doc = results["documents"][0][i] or ""
|
||||
duplicates.append(
|
||||
{
|
||||
@@ -903,22 +1026,27 @@ def tool_create_tunnel(
|
||||
Example: an API design discussion in project_api connects to the
|
||||
database schema in project_database.
|
||||
"""
|
||||
# sanitize_name and create_tunnel both raise ValueError for invalid or
|
||||
# missing endpoints (empty/non-string names, and create_tunnel's
|
||||
# room-existence checks). Catch both so the real reason is surfaced
|
||||
# instead of escaping and being wrapped as the opaque "Internal tool
|
||||
# error" (#1473), mirroring sibling tools.
|
||||
try:
|
||||
source_wing = sanitize_name(source_wing, "source_wing")
|
||||
source_room = sanitize_name(source_room, "source_room")
|
||||
target_wing = sanitize_name(target_wing, "target_wing")
|
||||
target_room = sanitize_name(target_room, "target_room")
|
||||
return create_tunnel(
|
||||
source_wing,
|
||||
source_room,
|
||||
target_wing,
|
||||
target_room,
|
||||
label=label,
|
||||
source_drawer_id=source_drawer_id,
|
||||
target_drawer_id=target_drawer_id,
|
||||
)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
return create_tunnel(
|
||||
source_wing,
|
||||
source_room,
|
||||
target_wing,
|
||||
target_room,
|
||||
label=label,
|
||||
source_drawer_id=source_drawer_id,
|
||||
target_drawer_id=target_drawer_id,
|
||||
)
|
||||
|
||||
|
||||
def tool_list_tunnels(wing: str = None):
|
||||
@@ -1031,7 +1159,9 @@ def tool_delete_drawer(drawer_id: str):
|
||||
|
||||
# Log the deletion with the content being removed for audit trail
|
||||
deleted_content = existing.get("documents", [""])[0] if existing.get("documents") else ""
|
||||
deleted_meta = existing.get("metadatas", [{}])[0] if existing.get("metadatas") else {}
|
||||
deleted_meta = _safe_meta(
|
||||
existing.get("metadatas", [{}])[0] if existing.get("metadatas") else {}
|
||||
)
|
||||
_wal_log(
|
||||
"delete_drawer",
|
||||
{
|
||||
@@ -1093,7 +1223,7 @@ def tool_get_drawer(drawer_id: str):
|
||||
result = col.get(ids=[drawer_id], include=["documents", "metadatas"])
|
||||
if not result["ids"]:
|
||||
return {"error": f"Drawer not found: {drawer_id}"}
|
||||
meta = result["metadatas"][0]
|
||||
meta = _safe_meta(result["metadatas"][0])
|
||||
doc = result["documents"][0]
|
||||
# source_file is the absolute filesystem path written by the
|
||||
# miners. Reduce to its basename before handing it to the MCP
|
||||
@@ -1153,7 +1283,7 @@ def tool_list_drawers(wing: str = None, room: str = None, limit: int = 20, offse
|
||||
|
||||
drawers = []
|
||||
for i, did in enumerate(result["ids"]):
|
||||
meta = result["metadatas"][i]
|
||||
meta = _safe_meta(result["metadatas"][i])
|
||||
doc = result["documents"][i]
|
||||
drawers.append(
|
||||
{
|
||||
@@ -1189,7 +1319,7 @@ def tool_update_drawer(drawer_id: str, content: str = None, wing: str = None, ro
|
||||
if not existing["ids"]:
|
||||
return {"success": False, "error": f"Drawer not found: {drawer_id}"}
|
||||
|
||||
old_meta = existing["metadatas"][0]
|
||||
old_meta = _safe_meta(existing["metadatas"][0])
|
||||
old_doc = existing["documents"][0]
|
||||
|
||||
new_doc = old_doc
|
||||
@@ -1499,6 +1629,7 @@ def tool_diary_read(agent_name: str, last_n: int = 10, wing: str = ""):
|
||||
# Combine and sort by timestamp
|
||||
entries = []
|
||||
for doc, meta in zip(results["documents"], results["metadatas"]):
|
||||
meta = _safe_meta(meta)
|
||||
entries.append(
|
||||
{
|
||||
"date": meta.get("date", ""),
|
||||
@@ -2155,6 +2286,15 @@ SUPPORTED_PROTOCOL_VERSIONS = [
|
||||
]
|
||||
|
||||
|
||||
def _internal_tool_error(req_id, tool_name: str) -> dict:
|
||||
logger.exception(f"Tool error in {tool_name}")
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {"code": -32000, "message": "Internal tool error"},
|
||||
}
|
||||
|
||||
|
||||
def handle_request(request):
|
||||
if not isinstance(request, dict):
|
||||
return {
|
||||
@@ -2232,6 +2372,26 @@ def handle_request(request):
|
||||
except (ValueError, TypeError):
|
||||
accepts_var_keyword = False
|
||||
if not accepts_var_keyword:
|
||||
# An unknown kwarg here is almost always a wrong parameter *name*
|
||||
# (e.g. text= instead of content=). Silently dropping it makes the
|
||||
# cause surface only indirectly as a later "Missing required 'X'",
|
||||
# so name it explicitly — symmetric with the missing-required path
|
||||
# below. wait_for_previous is an internal transport kwarg in no
|
||||
# tool schema; it is popped before dispatch further down, so it
|
||||
# must not be reported as unknown here.
|
||||
unknown = [k for k in tool_args if k not in schema_props and k != "wait_for_previous"]
|
||||
if unknown:
|
||||
quoted = ", ".join(f"'{k}'" for k in unknown)
|
||||
word = "parameter" if len(unknown) == 1 else "parameters"
|
||||
logger.debug("Tool %s: unknown %s %s", tool_name, word, quoted)
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {
|
||||
"code": -32602,
|
||||
"message": f"Unknown {word} {quoted} for tool {tool_name}",
|
||||
},
|
||||
}
|
||||
tool_args = {k: v for k, v in tool_args.items() if k in schema_props}
|
||||
# Coerce argument types based on input_schema.
|
||||
# MCP JSON transport may deliver integers as floats or strings;
|
||||
@@ -2250,8 +2410,8 @@ def handle_request(request):
|
||||
"id": req_id,
|
||||
"error": {"code": -32602, "message": f"Invalid value for parameter '{key}'"},
|
||||
}
|
||||
tool_args.pop("wait_for_previous", None)
|
||||
try:
|
||||
tool_args.pop("wait_for_previous", None)
|
||||
result = TOOLS[tool_name]["handler"](**tool_args)
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
@@ -2262,13 +2422,36 @@ def handle_request(request):
|
||||
]
|
||||
},
|
||||
}
|
||||
except TypeError as e:
|
||||
# Qualname match prevents leaking internal helper/param names raised
|
||||
# inside the handler body — see test_handler_internal_signature_shape_stays_generic.
|
||||
msg = str(e)
|
||||
handler = TOOLS[tool_name]["handler"]
|
||||
handler_qn = getattr(handler, "__qualname__", None) or getattr(handler, "__name__", "")
|
||||
# Qualname can include "<locals>" for nested defs and "<lambda>"
|
||||
# for lambdas — accept Python's TypeError emit verbatim.
|
||||
m_missing = re.match(
|
||||
r"^([\w\.<>]+)\(\) missing \d+ required "
|
||||
r"(?:positional |keyword-only )?arguments?: (.+)$",
|
||||
msg,
|
||||
)
|
||||
if m_missing and m_missing.group(1) == handler_qn:
|
||||
names = re.findall(r"'(\w+)'", m_missing.group(2))
|
||||
if names:
|
||||
quoted = ", ".join(f"'{n}'" for n in names)
|
||||
word = "parameter" if len(names) == 1 else "parameters"
|
||||
logger.debug("Tool %s: missing required %s %s", tool_name, word, quoted)
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {
|
||||
"code": -32602,
|
||||
"message": f"Missing required {word} {quoted} for tool {tool_name}",
|
||||
},
|
||||
}
|
||||
return _internal_tool_error(req_id, tool_name)
|
||||
except Exception:
|
||||
logger.exception(f"Tool error in {tool_name}")
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {"code": -32000, "message": "Internal tool error"},
|
||||
}
|
||||
return _internal_tool_error(req_id, tool_name)
|
||||
|
||||
# Notifications (missing id) must never get a response
|
||||
if req_id is None:
|
||||
@@ -2293,7 +2476,171 @@ def _restore_stdout():
|
||||
sys.stdout = _REAL_STDOUT
|
||||
|
||||
|
||||
_WARMUP_TRUTHY = {"1", "true", "yes", "on"}
|
||||
_WARMUP_FALSY = {"", "0", "false", "no", "off"}
|
||||
# Sentinel text for the warmup query. Distinctive so it cannot semantically
|
||||
# match real drawer content (e.g. a palace containing notes about "warmup"
|
||||
# routines) and is greppable in chromadb debug logs if the team ever adds
|
||||
# request instrumentation. Single non-empty string is enough to trigger
|
||||
# ChromaDB's ONNXMiniLM_L6_V2.__call__ → _download_model_if_not_exists +
|
||||
# InferenceSession.
|
||||
_WARMUP_PROBE_TEXT = "__mempalace_warmup_probe__"
|
||||
|
||||
|
||||
def _describe_device_safe() -> str:
|
||||
"""Return ``embedding.describe_device()`` value or ``"unknown"`` on failure.
|
||||
|
||||
Used only inside warmup-failure log lines; the import is deferred so
|
||||
that an embedding-stack import error cannot itself crash the warmup
|
||||
diagnostic path.
|
||||
"""
|
||||
try:
|
||||
from .embedding import describe_device
|
||||
|
||||
return describe_device()
|
||||
except Exception: # fail-soft: see docstring — log-message helper must not crash
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _maybe_eager_warmup_embedder() -> None:
|
||||
"""Pre-load embedder + HNSW segment at startup when ``MEMPALACE_EAGER_WARMUP`` is truthy.
|
||||
|
||||
The first MCP tool call that touches chromadb (``diary_write``,
|
||||
``add_drawer``, ``search``) otherwise pays two compounding cold-load
|
||||
costs that together can exceed the MCP client timeout and surface as
|
||||
``-32000`` "Internal tool error" with no recoverable trace on the
|
||||
agent side (#1495):
|
||||
|
||||
1. ONNX/CoreML embedder init in :func:`mempalace.embedding.get_embedding_function`
|
||||
(5–30s on first inference; ChromaDB's ``ONNXMiniLM_L6_V2.__call__``
|
||||
triggers ``_download_model_if_not_exists`` + ``InferenceSession``).
|
||||
2. HNSW segment cold-load (reading ``data_level0.bin`` into RAM on
|
||||
first collection operation; seconds on palaces of 50k+ drawers).
|
||||
|
||||
Warming via :func:`_get_collection`'s collection-then-query path
|
||||
covers BOTH in a single startup-phase call — mirroring the reporter's
|
||||
proposal in #1495 — so users with large existing palaces see the
|
||||
same benefit as users on the embedder-only cost path.
|
||||
|
||||
Truthy parsing accepts ``1/true/yes/on`` (case-insensitive); falsy
|
||||
set ``0/false/no/off`` and empty/whitespace are silently off; any
|
||||
other value logs a warning and stays off so typos like ``tru`` do
|
||||
not silently disable the feature.
|
||||
|
||||
Fresh-install guard (pre-check, NOT a catch): ``_get_collection``'s
|
||||
retry layer absorbs ``_ChromaNotFoundError`` and returns ``None`` while
|
||||
also materialising ``chroma.sqlite3`` on disk via the chromadb client
|
||||
constructor. To preserve the documented "no palace yet → nothing to
|
||||
warm" contract WITHOUT writing palace scaffolding before
|
||||
``mempalace init`` (which would violate CLAUDE.md "Incremental only"),
|
||||
we test for ``chroma.sqlite3`` ourselves before touching the chromadb
|
||||
client. Operators who set ``MEMPALACE_EAGER_WARMUP=1`` in their MCP
|
||||
config and launch the server before running ``mempalace init`` get a
|
||||
single INFO line and no on-disk side effect.
|
||||
|
||||
Fail-soft beyond the fresh-install pre-check:
|
||||
|
||||
* **Backend open failure** (palace path misconfigured, file locked,
|
||||
corrupted HNSW that ``quarantine_stale_hnsw`` cannot recover) →
|
||||
log exception with device + palace context and return. The next
|
||||
embedding-requiring call sees the same fail mode it would have
|
||||
without warmup.
|
||||
* **`_get_collection` retried and returned None** → palace exists
|
||||
but chromadb cannot open the collection (rare; usually a stale
|
||||
sqlite + segment-files mismatch surfaced by `_get_client` rebuild).
|
||||
A warning suffices because the retry layer already wrote two
|
||||
tracebacks with the underlying chromadb error class.
|
||||
* **Query failure** (network failure during ONNX model download,
|
||||
provider init crash, runtime decoder error) → log exception with
|
||||
device + palace context and return. Same fail-mode preservation.
|
||||
|
||||
Note: on an existing palace with an empty collection (created via
|
||||
``mempalace init`` but never written to), ``col.query`` succeeds but
|
||||
returns ``{'ids': [[]]}`` without reading any HNSW segment — the
|
||||
embedder warms but there is no HNSW segment to load. The success log
|
||||
still says ``embedder + HNSW ready`` because the no-HNSW-segment case
|
||||
has zero cold-load cost; nothing was skipped that the first real tool
|
||||
call would have paid.
|
||||
"""
|
||||
raw = os.environ.get("MEMPALACE_EAGER_WARMUP", "").strip().lower()
|
||||
if raw in _WARMUP_FALSY:
|
||||
return
|
||||
if raw not in _WARMUP_TRUTHY:
|
||||
logger.warning(
|
||||
"MEMPALACE_EAGER_WARMUP=%r is not recognized (use one of %s); warmup disabled",
|
||||
raw,
|
||||
sorted(_WARMUP_TRUTHY | (_WARMUP_FALSY - {""})),
|
||||
)
|
||||
return
|
||||
palace_path = _config.palace_path
|
||||
db_path = os.path.join(palace_path, "chroma.sqlite3")
|
||||
if not os.path.isfile(db_path):
|
||||
# Pre-check (NOT a try/except on _ChromaNotFoundError, which never
|
||||
# propagates out of _get_collection — see docstring). No palace
|
||||
# file means nothing to warm AND avoids the chromadb-client
|
||||
# side effect of materialising the palace dir.
|
||||
logger.info(
|
||||
"MEMPALACE_EAGER_WARMUP=%s: no palace at %s — nothing to warm",
|
||||
raw,
|
||||
palace_path,
|
||||
)
|
||||
return
|
||||
# Cache device once: _describe_device_safe re-imports embedding stack
|
||||
# each call, which is wasteful inside a function that already paid
|
||||
# that cost via the warmup query below.
|
||||
device = _describe_device_safe()
|
||||
try:
|
||||
col = _get_collection(create=False)
|
||||
except Exception as exc: # fail-soft per docstring — broad on purpose
|
||||
logger.exception(
|
||||
"MEMPALACE_EAGER_WARMUP=%s: collection open failed (palace=%s, device=%s, error=%s)",
|
||||
raw,
|
||||
palace_path,
|
||||
device,
|
||||
type(exc).__name__,
|
||||
)
|
||||
return
|
||||
if col is None:
|
||||
logger.warning(
|
||||
"MEMPALACE_EAGER_WARMUP=%s: _get_collection returned None for palace=%s — see prior log lines",
|
||||
raw,
|
||||
palace_path,
|
||||
)
|
||||
return
|
||||
try:
|
||||
col.query(query_texts=[_WARMUP_PROBE_TEXT], n_results=1)
|
||||
except Exception as exc: # fail-soft per docstring — broad on purpose
|
||||
logger.exception(
|
||||
"MEMPALACE_EAGER_WARMUP=%s: warmup query failed (palace=%s, device=%s, error=%s)",
|
||||
raw,
|
||||
palace_path,
|
||||
device,
|
||||
type(exc).__name__,
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"MEMPALACE_EAGER_WARMUP=%s: embedder + HNSW ready (palace=%s, device=%s)",
|
||||
raw,
|
||||
palace_path,
|
||||
device,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""MCP server entry point for the ``mempalace-mcp`` console script.
|
||||
|
||||
Side effect: pops ``PYTHONPATH`` from ``os.environ`` (see #1423) so
|
||||
any subprocess this server spawns inherits a clean env. Host
|
||||
applications that call ``main()`` programmatically should be aware
|
||||
that the parent process loses ``PYTHONPATH`` as well. Library imports
|
||||
(``import mempalace.searcher`` from a host app) do NOT trigger this
|
||||
side effect; only the CLI/MCP entry points pop the env var.
|
||||
"""
|
||||
# Drop leaked PYTHONPATH so any subprocess this server spawns starts
|
||||
# with a clean env. The sys.path filter in mempalace/__init__.py
|
||||
# already protects this process from the same ABI mismatch; here we
|
||||
# extend the protection to children.
|
||||
os.environ.pop("PYTHONPATH", None)
|
||||
_restore_stdout()
|
||||
# Force UTF-8 on stdio. MCP JSON-RPC is UTF-8, but Python on Windows
|
||||
# defaults stdin/stdout to the system codepage (e.g. cp1251), which
|
||||
@@ -2310,6 +2657,10 @@ def main():
|
||||
# is visible at startup rather than on first use (#1222). Pure
|
||||
# filesystem read; never opens a chromadb client.
|
||||
_refresh_vector_disabled_flag()
|
||||
# Opt-in: pre-load the embedder so the first chromadb-write tool call
|
||||
# does not pay the ONNX/CoreML cold-load tax under the MCP client
|
||||
# timeout (#1495). Default off — preserves current startup latency.
|
||||
_maybe_eager_warmup_embedder()
|
||||
while True:
|
||||
try:
|
||||
line = sys.stdin.readline()
|
||||
|
||||
+108
-92
@@ -22,8 +22,10 @@ import errno
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from contextlib import closing
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
@@ -52,61 +54,65 @@ def extract_drawers_from_sqlite(db_path: str) -> list:
|
||||
|
||||
Works regardless of which ChromaDB version created the database.
|
||||
Returns list of dicts with 'id', 'document', and 'metadata' keys.
|
||||
|
||||
The connection is wrapped in ``contextlib.closing`` so an exception
|
||||
during extraction does not leak the SQLite handle. On Windows that
|
||||
would leave a file lock on ``chroma.sqlite3`` and prevent the rest
|
||||
of the migration from touching the palace directory.
|
||||
"""
|
||||
conn = sqlite3.connect(db_path)
|
||||
conn.row_factory = sqlite3.Row
|
||||
with closing(sqlite3.connect(db_path)) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
|
||||
# Get all embedding IDs and their documents
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT e.embedding_id,
|
||||
MAX(CASE WHEN em.key = 'chroma:document' THEN em.string_value END) as document
|
||||
FROM embeddings e
|
||||
JOIN embedding_metadata em ON em.id = e.id
|
||||
GROUP BY e.embedding_id
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
drawers = []
|
||||
for row in rows:
|
||||
embedding_id = row["embedding_id"]
|
||||
document = row["document"]
|
||||
if not document:
|
||||
continue
|
||||
|
||||
# Get metadata for this embedding
|
||||
meta_rows = conn.execute(
|
||||
# Get all embedding IDs and their documents
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT em.key, em.string_value, em.int_value, em.float_value, em.bool_value
|
||||
FROM embedding_metadata em
|
||||
JOIN embeddings e ON e.id = em.id
|
||||
WHERE e.embedding_id = ?
|
||||
AND em.key NOT LIKE 'chroma:%'
|
||||
""",
|
||||
(embedding_id,),
|
||||
SELECT e.embedding_id,
|
||||
MAX(CASE WHEN em.key = 'chroma:document' THEN em.string_value END) as document
|
||||
FROM embeddings e
|
||||
JOIN embedding_metadata em ON em.id = e.id
|
||||
GROUP BY e.embedding_id
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
metadata = {}
|
||||
for mr in meta_rows:
|
||||
key = mr["key"]
|
||||
if mr["string_value"] is not None:
|
||||
metadata[key] = mr["string_value"]
|
||||
elif mr["int_value"] is not None:
|
||||
metadata[key] = mr["int_value"]
|
||||
elif mr["float_value"] is not None:
|
||||
metadata[key] = mr["float_value"]
|
||||
elif mr["bool_value"] is not None:
|
||||
metadata[key] = bool(mr["bool_value"])
|
||||
drawers = []
|
||||
for row in rows:
|
||||
embedding_id = row["embedding_id"]
|
||||
document = row["document"]
|
||||
if not document:
|
||||
continue
|
||||
|
||||
drawers.append(
|
||||
{
|
||||
"id": embedding_id,
|
||||
"document": document,
|
||||
"metadata": metadata,
|
||||
}
|
||||
)
|
||||
# Get metadata for this embedding
|
||||
meta_rows = conn.execute(
|
||||
"""
|
||||
SELECT em.key, em.string_value, em.int_value, em.float_value, em.bool_value
|
||||
FROM embedding_metadata em
|
||||
JOIN embeddings e ON e.id = em.id
|
||||
WHERE e.embedding_id = ?
|
||||
AND em.key NOT LIKE 'chroma:%'
|
||||
""",
|
||||
(embedding_id,),
|
||||
).fetchall()
|
||||
|
||||
metadata = {}
|
||||
for mr in meta_rows:
|
||||
key = mr["key"]
|
||||
if mr["string_value"] is not None:
|
||||
metadata[key] = mr["string_value"]
|
||||
elif mr["int_value"] is not None:
|
||||
metadata[key] = mr["int_value"]
|
||||
elif mr["float_value"] is not None:
|
||||
metadata[key] = mr["float_value"]
|
||||
elif mr["bool_value"] is not None:
|
||||
metadata[key] = bool(mr["bool_value"])
|
||||
|
||||
drawers.append(
|
||||
{
|
||||
"id": embedding_id,
|
||||
"document": document,
|
||||
"metadata": metadata,
|
||||
}
|
||||
)
|
||||
|
||||
conn.close()
|
||||
return drawers
|
||||
|
||||
|
||||
@@ -287,53 +293,63 @@ def migrate(palace_path: str, dry_run: bool = False, confirm: bool = False):
|
||||
print(f"\n Backing up to {backup_path}...")
|
||||
shutil.copytree(palace_path, backup_path)
|
||||
|
||||
# Build fresh palace in a temp directory (avoids chromadb reading old state)
|
||||
import tempfile
|
||||
|
||||
# Build fresh palace in a temp directory (avoids chromadb reading old state).
|
||||
# Wrap the whole import-and-swap dance in try/finally so the temp dir is
|
||||
# cleaned up if any of the chromadb writes, the verify count, or the
|
||||
# rename fails — without try/finally a crashed migration leaves a partial
|
||||
# palace dir under the system temp root that the user has to find by hand.
|
||||
temp_palace = tempfile.mkdtemp(prefix="mempalace_migrate_")
|
||||
print(f" Creating fresh palace in {temp_palace}...")
|
||||
fresh_backend = ChromaBackend()
|
||||
col = fresh_backend.get_or_create_collection(temp_palace, "mempalace_drawers")
|
||||
|
||||
# Re-import in batches
|
||||
batch_size = 500
|
||||
imported = 0
|
||||
for i in range(0, len(drawers), batch_size):
|
||||
batch = drawers[i : i + batch_size]
|
||||
col.add(
|
||||
ids=[d["id"] for d in batch],
|
||||
documents=[d["document"] for d in batch],
|
||||
metadatas=[d["metadata"] for d in batch],
|
||||
)
|
||||
imported += len(batch)
|
||||
print(f" Imported {imported}/{len(drawers)} drawers...")
|
||||
|
||||
# Verify before swapping
|
||||
final_count = col.count()
|
||||
del col
|
||||
del fresh_backend
|
||||
|
||||
# Swap: rename old palace aside, then move new one into place.
|
||||
# This avoids a window where both old and new are missing.
|
||||
print(" Swapping old palace for migrated version...")
|
||||
stale_path = palace_path + ".old"
|
||||
if os.path.exists(stale_path):
|
||||
shutil.rmtree(stale_path)
|
||||
os.replace(palace_path, stale_path)
|
||||
try:
|
||||
os.replace(temp_palace, palace_path)
|
||||
except OSError as e:
|
||||
# EXDEV = temp lives on a different filesystem; fall back to copy+delete.
|
||||
# Anything else is a real error — don't mask it with shutil.move.
|
||||
if getattr(e, "errno", None) != errno.EXDEV:
|
||||
_restore_stale_palace(palace_path, stale_path)
|
||||
raise
|
||||
print(f" Creating fresh palace in {temp_palace}...")
|
||||
fresh_backend = ChromaBackend()
|
||||
col = fresh_backend.get_or_create_collection(temp_palace, "mempalace_drawers")
|
||||
|
||||
# Re-import in batches
|
||||
batch_size = 500
|
||||
imported = 0
|
||||
for i in range(0, len(drawers), batch_size):
|
||||
batch = drawers[i : i + batch_size]
|
||||
col.add(
|
||||
ids=[d["id"] for d in batch],
|
||||
documents=[d["document"] for d in batch],
|
||||
metadatas=[d["metadata"] for d in batch],
|
||||
)
|
||||
imported += len(batch)
|
||||
print(f" Imported {imported}/{len(drawers)} drawers...")
|
||||
|
||||
# Verify before swapping
|
||||
final_count = col.count()
|
||||
del col
|
||||
del fresh_backend
|
||||
|
||||
# Swap: rename old palace aside, then move new one into place.
|
||||
# This avoids a window where both old and new are missing.
|
||||
print(" Swapping old palace for migrated version...")
|
||||
stale_path = palace_path + ".old"
|
||||
if os.path.exists(stale_path):
|
||||
shutil.rmtree(stale_path)
|
||||
os.replace(palace_path, stale_path)
|
||||
try:
|
||||
shutil.move(temp_palace, palace_path)
|
||||
except Exception:
|
||||
_restore_stale_palace(palace_path, stale_path)
|
||||
raise
|
||||
shutil.rmtree(stale_path, ignore_errors=True)
|
||||
os.replace(temp_palace, palace_path)
|
||||
except OSError as e:
|
||||
# EXDEV = temp lives on a different filesystem; fall back to copy+delete.
|
||||
# Anything else is a real error — don't mask it with shutil.move.
|
||||
if getattr(e, "errno", None) != errno.EXDEV:
|
||||
_restore_stale_palace(palace_path, stale_path)
|
||||
raise
|
||||
try:
|
||||
shutil.move(temp_palace, palace_path)
|
||||
except Exception:
|
||||
_restore_stale_palace(palace_path, stale_path)
|
||||
raise
|
||||
shutil.rmtree(stale_path, ignore_errors=True)
|
||||
finally:
|
||||
# On the happy path os.replace/shutil.move consumed temp_palace, so
|
||||
# the directory no longer exists at the temp location — the existence
|
||||
# guard makes this a no-op then. On any failure path it actually
|
||||
# removes the orphan.
|
||||
if os.path.exists(temp_palace):
|
||||
shutil.rmtree(temp_palace, ignore_errors=True)
|
||||
|
||||
print("\n Migration complete.")
|
||||
print(f" Drawers migrated: {final_count}")
|
||||
|
||||
+88
-18
@@ -22,6 +22,7 @@ from typing import Optional
|
||||
from .palace import (
|
||||
NORMALIZE_VERSION,
|
||||
SKIP_DIRS,
|
||||
_open_collection_or_explain,
|
||||
build_closet_lines,
|
||||
file_already_mined,
|
||||
get_closets_collection,
|
||||
@@ -70,9 +71,16 @@ SKIP_FILENAMES = {
|
||||
"yarn.lock",
|
||||
}
|
||||
|
||||
CHUNK_SIZE = 800 # chars per drawer
|
||||
CHUNK_OVERLAP = 100 # overlap between chunks
|
||||
MIN_CHUNK_SIZE = 50 # skip tiny chunks
|
||||
# Re-export the shared defaults from ``config`` so legacy callers that
|
||||
# import ``CHUNK_SIZE`` / ``CHUNK_OVERLAP`` / ``MIN_CHUNK_SIZE`` from
|
||||
# ``mempalace.miner`` keep working unchanged. Single source of truth
|
||||
# lives in ``config.DEFAULT_CHUNK_*``.
|
||||
from .config import ( # noqa: E402 (kept here for the legacy alias)
|
||||
DEFAULT_CHUNK_SIZE as CHUNK_SIZE,
|
||||
DEFAULT_CHUNK_OVERLAP as CHUNK_OVERLAP,
|
||||
DEFAULT_MIN_CHUNK_SIZE as MIN_CHUNK_SIZE,
|
||||
)
|
||||
|
||||
DRAWER_UPSERT_BATCH_SIZE = 1000
|
||||
MAX_FILE_SIZE = 500 * 1024 * 1024 # 500 MB — skip files larger than this.
|
||||
# A single file producing more chunks than this is almost always a generated
|
||||
@@ -402,12 +410,48 @@ def detect_room(filepath: Path, content: str, rooms: list, project_path: Path) -
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def chunk_text(content: str, source_file: str) -> list:
|
||||
def chunk_text(
|
||||
content: str,
|
||||
source_file: str,
|
||||
chunk_size: int = None,
|
||||
chunk_overlap: int = None,
|
||||
min_chunk_size: int = None,
|
||||
) -> list:
|
||||
"""
|
||||
Split content into drawer-sized chunks.
|
||||
Tries to split on paragraph/line boundaries.
|
||||
Returns list of {"content": str, "chunk_index": int}
|
||||
|
||||
Optional params override module-level defaults when provided.
|
||||
"""
|
||||
if chunk_size is None:
|
||||
chunk_size = CHUNK_SIZE
|
||||
if chunk_overlap is None:
|
||||
chunk_overlap = CHUNK_OVERLAP
|
||||
if min_chunk_size is None:
|
||||
min_chunk_size = MIN_CHUNK_SIZE
|
||||
|
||||
# Defensive invariant guard. ``MempalaceConfig.chunk_*`` already
|
||||
# enforces these and falls back to defaults on bad config.json
|
||||
# values, but ``chunk_text`` is a public function — direct callers
|
||||
# (tests, library users, future caller paths) might still pass
|
||||
# values that would loop forever. Fail fast and loud rather than
|
||||
# hang. See review feedback on #1024.
|
||||
if not isinstance(chunk_size, int) or chunk_size <= 0:
|
||||
raise ValueError(f"chunk_size must be a positive int, got {chunk_size!r}")
|
||||
if not isinstance(chunk_overlap, int) or chunk_overlap < 0:
|
||||
raise ValueError(f"chunk_overlap must be a non-negative int, got {chunk_overlap!r}")
|
||||
if chunk_overlap >= chunk_size:
|
||||
# ``start = end - chunk_overlap`` would not advance (or would go
|
||||
# backward) when overlap >= size, producing an infinite loop on
|
||||
# any non-empty input.
|
||||
raise ValueError(
|
||||
f"chunk_overlap ({chunk_overlap}) must be less than chunk_size "
|
||||
f"({chunk_size}); equality or greater would loop forever"
|
||||
)
|
||||
if not isinstance(min_chunk_size, int) or min_chunk_size < 0:
|
||||
raise ValueError(f"min_chunk_size must be a non-negative int, got {min_chunk_size!r}")
|
||||
|
||||
# Clean up
|
||||
content = content.strip()
|
||||
if not content:
|
||||
@@ -418,20 +462,20 @@ def chunk_text(content: str, source_file: str) -> list:
|
||||
chunk_index = 0
|
||||
|
||||
while start < len(content):
|
||||
end = min(start + CHUNK_SIZE, len(content))
|
||||
end = min(start + chunk_size, len(content))
|
||||
|
||||
# Try to break at paragraph boundary
|
||||
if end < len(content):
|
||||
newline_pos = content.rfind("\n\n", start, end)
|
||||
if newline_pos > start + CHUNK_SIZE // 2:
|
||||
if newline_pos > start + chunk_size // 2:
|
||||
end = newline_pos
|
||||
else:
|
||||
newline_pos = content.rfind("\n", start, end)
|
||||
if newline_pos > start + CHUNK_SIZE // 2:
|
||||
if newline_pos > start + chunk_size // 2:
|
||||
end = newline_pos
|
||||
|
||||
chunk = content[start:end].strip()
|
||||
if len(chunk) >= MIN_CHUNK_SIZE:
|
||||
if len(chunk) >= min_chunk_size:
|
||||
chunks.append(
|
||||
{
|
||||
"content": chunk,
|
||||
@@ -440,7 +484,7 @@ def chunk_text(content: str, source_file: str) -> list:
|
||||
)
|
||||
chunk_index += 1
|
||||
|
||||
start = end - CHUNK_OVERLAP if end < len(content) else end
|
||||
start = end - chunk_overlap if end < len(content) else end
|
||||
|
||||
return chunks
|
||||
|
||||
@@ -836,8 +880,12 @@ def process_file(
|
||||
agent: str,
|
||||
dry_run: bool,
|
||||
closets_col=None,
|
||||
chunk_size: int = None,
|
||||
chunk_overlap: int = None,
|
||||
min_chunk_size: int = None,
|
||||
) -> tuple:
|
||||
"""Read, chunk, route, and file one file. Returns (drawer_count, room_name)."""
|
||||
effective_min = min_chunk_size if min_chunk_size is not None else MIN_CHUNK_SIZE
|
||||
|
||||
# Skip if already filed
|
||||
source_file = str(filepath)
|
||||
@@ -850,11 +898,17 @@ def process_file(
|
||||
return 0, "general"
|
||||
|
||||
content = content.strip()
|
||||
if len(content) < MIN_CHUNK_SIZE:
|
||||
if len(content) < effective_min:
|
||||
return 0, "general"
|
||||
|
||||
room = detect_room(filepath, content, rooms, project_path)
|
||||
chunks = chunk_text(content, source_file)
|
||||
chunks = chunk_text(
|
||||
content,
|
||||
source_file,
|
||||
chunk_size=chunk_size,
|
||||
chunk_overlap=chunk_overlap,
|
||||
min_chunk_size=min_chunk_size,
|
||||
)
|
||||
|
||||
if len(chunks) > MAX_CHUNKS_PER_FILE:
|
||||
print(
|
||||
@@ -960,7 +1014,12 @@ def scan_project(
|
||||
respect_gitignore: bool = True,
|
||||
include_ignored: list = None,
|
||||
) -> list:
|
||||
"""Return list of all readable file paths."""
|
||||
"""Return list of all readable file paths under ``project_dir``.
|
||||
|
||||
Skips symlinks and oversized files. Each skipped symlink is logged to
|
||||
``sys.stderr`` with a `` SKIP: <relative-path> (symlink)`` line so the
|
||||
caller can tell why a directory looks empty after walking.
|
||||
"""
|
||||
project_path = Path(project_dir).expanduser().resolve()
|
||||
files = []
|
||||
active_matchers = []
|
||||
@@ -1008,6 +1067,11 @@ def scan_project(
|
||||
continue
|
||||
# Skip symlinks — prevents following links to /dev/urandom, etc.
|
||||
if filepath.is_symlink():
|
||||
rel = filepath.relative_to(project_path).as_posix()
|
||||
try:
|
||||
print(f" SKIP: {rel} (symlink)", file=sys.stderr)
|
||||
except OSError:
|
||||
pass
|
||||
continue
|
||||
# Skip files exceeding size limit
|
||||
try:
|
||||
@@ -1043,7 +1107,6 @@ def mine(
|
||||
prompt) avoids walking the tree twice. When ``None`` (the default),
|
||||
``mine`` walks the tree itself just like before.
|
||||
"""
|
||||
|
||||
if dry_run:
|
||||
return _mine_impl(
|
||||
project_dir,
|
||||
@@ -1085,8 +1148,15 @@ def _mine_impl(
|
||||
include_ignored: list = None,
|
||||
files: list = None,
|
||||
):
|
||||
from .config import MempalaceConfig
|
||||
|
||||
project_path = Path(project_dir).expanduser().resolve()
|
||||
config = load_config(project_dir)
|
||||
palace_config = MempalaceConfig()
|
||||
|
||||
cfg_chunk_size = palace_config.chunk_size
|
||||
cfg_chunk_overlap = palace_config.chunk_overlap
|
||||
cfg_min_chunk_size = palace_config.min_chunk_size
|
||||
|
||||
wing = wing_override or config["wing"]
|
||||
rooms = config.get("rooms", [{"name": "general", "description": "All project files"}])
|
||||
@@ -1143,6 +1213,9 @@ def _mine_impl(
|
||||
agent=agent,
|
||||
dry_run=dry_run,
|
||||
closets_col=closets_col,
|
||||
chunk_size=cfg_chunk_size,
|
||||
chunk_overlap=cfg_chunk_overlap,
|
||||
min_chunk_size=cfg_min_chunk_size,
|
||||
)
|
||||
except KeyboardInterrupt:
|
||||
# Re-raise so the outer handler prints the summary; we
|
||||
@@ -1283,11 +1356,8 @@ def _compute_topic_tunnels_for_wing(wing: str) -> int:
|
||||
|
||||
def status(palace_path: str):
|
||||
"""Show what's been filed in the palace."""
|
||||
try:
|
||||
col = get_collection(palace_path, create=False)
|
||||
except Exception:
|
||||
print(f"\n No palace found at {palace_path}")
|
||||
print(" Run: mempalace init <dir> then mempalace mine <dir>")
|
||||
col = _open_collection_or_explain(palace_path)
|
||||
if col is None:
|
||||
return
|
||||
|
||||
# Count by wing and room — paginate to avoid SQLite "too many SQL
|
||||
|
||||
+193
-9
@@ -13,6 +13,7 @@ import sys
|
||||
import threading
|
||||
from typing import Optional
|
||||
|
||||
from .backends import BackendClosedError, CollectionNotInitializedError, PalaceNotFoundError
|
||||
from .backends.chroma import ChromaBackend
|
||||
|
||||
logger = logging.getLogger("mempalace_mcp")
|
||||
@@ -78,6 +79,72 @@ def get_closets_collection(palace_path: str, create: bool = True):
|
||||
return get_collection(palace_path, collection_name="mempalace_closets", create=create)
|
||||
|
||||
|
||||
def _open_collection_or_explain(
|
||||
palace_path: str,
|
||||
*,
|
||||
collection_name: Optional[str] = None,
|
||||
out=None,
|
||||
):
|
||||
"""Open the palace collection or print a state-specific message and return ``None``.
|
||||
|
||||
For CLI and repair commands that want consistent, actionable user-facing
|
||||
messages distinguishing four "not-healthy" states from one another. MCP
|
||||
and library callers should catch
|
||||
:class:`mempalace.backends.PalaceNotFoundError` /
|
||||
:class:`mempalace.backends.CollectionNotInitializedError` directly.
|
||||
|
||||
The MCP server (``mcp_server.tool_status``) deliberately does NOT use
|
||||
this helper: it uses ``_get_collection(create=db_exists)`` so a valid
|
||||
palace whose collection was never bootstrapped lazily gets one on the
|
||||
first status call, and a corruption-detection sqlite-only probe fires
|
||||
first when the vector path is disabled (see PR #831 / issue #830).
|
||||
|
||||
State A: palace dir is absent.
|
||||
State B: dir is present but ``chroma.sqlite3`` is absent. The helper
|
||||
short-circuits to a message before reaching the backend, because
|
||||
``chromadb.PersistentClient`` lazily creates the DB file on first
|
||||
open — calling the backend on this state would silently mutate
|
||||
the filesystem for what should be a read-only inspection.
|
||||
State C: DB is present but the ``mempalace_drawers`` collection has
|
||||
never been bootstrapped (``init`` ran, ``mine`` has not).
|
||||
State D: healthy — returns the opened collection.
|
||||
State E: an unexpected error opens the backend — message points the
|
||||
user at ``repair-status`` for further diagnosis.
|
||||
|
||||
``out`` is the message sink; defaults to the builtin ``print``. Pass a
|
||||
callable (e.g. a repair progress emitter) to route messages through it.
|
||||
"""
|
||||
emit = out if out is not None else print
|
||||
|
||||
if not os.path.isdir(palace_path):
|
||||
emit(f"\n No palace found at {palace_path}")
|
||||
emit(" Run: mempalace init <dir> then mempalace mine <dir>")
|
||||
return None
|
||||
if not os.path.isfile(os.path.join(palace_path, "chroma.sqlite3")):
|
||||
emit(f"\n Palace dir at {palace_path} exists but has no chroma.sqlite3 yet.")
|
||||
emit(" Run: mempalace mine <dir>")
|
||||
return None
|
||||
try:
|
||||
return get_collection(palace_path, collection_name=collection_name, create=False)
|
||||
except CollectionNotInitializedError:
|
||||
emit(f"\n Palace at {palace_path} is initialized but empty (no drawers yet).")
|
||||
emit(" Run: mempalace mine <dir>")
|
||||
return None
|
||||
except PalaceNotFoundError:
|
||||
emit(f"\n No palace found at {palace_path}")
|
||||
emit(" Run: mempalace init <dir> then mempalace mine <dir>")
|
||||
return None
|
||||
except BackendClosedError:
|
||||
# Surface this as a programmer error, not a palace-state UX message:
|
||||
# a closed backend means the caller violated the backend lifecycle,
|
||||
# not that the palace on disk is in a recoverable state.
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 — backend exceptions vary (chromadb, OSError, lock errors)
|
||||
emit(f"\n Error opening palace at {palace_path}: {e!r}")
|
||||
emit(" Try: mempalace repair-status --palace <path>")
|
||||
return None
|
||||
|
||||
|
||||
CLOSET_CHAR_LIMIT = 1500 # fill closet until ~1500 chars, then start a new one
|
||||
CLOSET_EXTRACT_WINDOW = 5000 # how many chars of source content to scan for entities/topics
|
||||
|
||||
@@ -387,7 +454,10 @@ def _read_lock_holder(lock_file) -> str:
|
||||
"""Read the prior holder's identity from the lock-file body, best-effort."""
|
||||
try:
|
||||
lock_file.seek(_LOCK_SENTINEL_BYTES)
|
||||
content = lock_file.read().strip()
|
||||
content = lock_file.read()
|
||||
if isinstance(content, bytes):
|
||||
content = content.decode("utf-8", errors="replace")
|
||||
content = content.strip()
|
||||
except OSError:
|
||||
return "another writer (identity not recorded)"
|
||||
if not content:
|
||||
@@ -404,11 +474,12 @@ def _write_lock_holder(lock_file) -> None:
|
||||
"""
|
||||
try:
|
||||
ident = f"{os.getpid()} {' '.join(sys.argv[:3])}".strip()
|
||||
ident_bytes = ident.encode("utf-8")
|
||||
lock_file.seek(_LOCK_SENTINEL_BYTES)
|
||||
lock_file.truncate(_LOCK_SENTINEL_BYTES + len(ident.encode("utf-8")))
|
||||
lock_file.write(ident)
|
||||
lock_file.truncate(_LOCK_SENTINEL_BYTES + len(ident_bytes))
|
||||
lock_file.write(ident_bytes)
|
||||
lock_file.flush()
|
||||
except OSError:
|
||||
except (OSError, UnicodeError):
|
||||
pass
|
||||
|
||||
|
||||
@@ -470,7 +541,7 @@ def mine_palace_lock(palace_path: str):
|
||||
os.close(fd)
|
||||
except FileExistsError:
|
||||
pass
|
||||
lf = open(lock_path, "r+")
|
||||
lf = open(lock_path, "r+b")
|
||||
acquired = False
|
||||
try:
|
||||
# Lock byte 0 explicitly. msvcrt.locking is byte-position dependent;
|
||||
@@ -531,7 +602,19 @@ def mine_palace_lock(palace_path: str):
|
||||
mine_global_lock = mine_palace_lock
|
||||
|
||||
|
||||
def file_already_mined(collection, source_file: str, check_mtime: bool = False) -> bool:
|
||||
def _metadata_matches_extract_mode(meta: dict, extract_mode: Optional[str]) -> bool:
|
||||
if extract_mode is None:
|
||||
return True
|
||||
stored_mode = meta.get("extract_mode")
|
||||
return stored_mode == extract_mode or (extract_mode == "exchange" and stored_mode is None)
|
||||
|
||||
|
||||
def file_already_mined(
|
||||
collection,
|
||||
source_file: str,
|
||||
check_mtime: bool = False,
|
||||
extract_mode: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""Check if a file has already been filed in the palace.
|
||||
|
||||
Returns False (so the file gets re-mined) when:
|
||||
@@ -543,12 +626,43 @@ def file_already_mined(collection, source_file: str, check_mtime: bool = False)
|
||||
When check_mtime=True (used by project miner), also re-mines on content
|
||||
change. When check_mtime=False (used by convo miner), transcripts are
|
||||
assumed immutable, so only the version gate triggers a rebuild.
|
||||
|
||||
When extract_mode is set (used by convo miner), idempotency is scoped to
|
||||
that extraction mode so exchange-mode and general-mode drawers can coexist
|
||||
for the same source transcript. Legacy drawers without extract_mode are
|
||||
treated as exchange-mode drawers.
|
||||
"""
|
||||
try:
|
||||
results = collection.get(where={"source_file": source_file}, limit=1)
|
||||
if not results.get("ids"):
|
||||
stored_meta = None
|
||||
if extract_mode is None:
|
||||
results = collection.get(where={"source_file": source_file}, limit=1)
|
||||
if not results.get("ids"):
|
||||
return False
|
||||
stored_meta = results.get("metadatas", [{}])[0] or {}
|
||||
else:
|
||||
offset = 0
|
||||
while True:
|
||||
results = collection.get(
|
||||
where={"source_file": source_file},
|
||||
limit=1000,
|
||||
offset=offset,
|
||||
include=["metadatas"],
|
||||
)
|
||||
ids = results.get("ids") or []
|
||||
metadatas = results.get("metadatas") or []
|
||||
stored_meta = next(
|
||||
(
|
||||
meta or {}
|
||||
for meta in metadatas
|
||||
if _metadata_matches_extract_mode(meta or {}, extract_mode)
|
||||
),
|
||||
None,
|
||||
)
|
||||
if stored_meta is not None or not ids:
|
||||
break
|
||||
offset += len(ids)
|
||||
if stored_meta is None:
|
||||
return False
|
||||
stored_meta = results.get("metadatas", [{}])[0] or {}
|
||||
# Pre-v2 drawers have no version field — treat them as stale.
|
||||
stored_version = stored_meta.get("normalize_version", 1)
|
||||
if stored_version < NORMALIZE_VERSION:
|
||||
@@ -562,3 +676,73 @@ def file_already_mined(collection, source_file: str, check_mtime: bool = False)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def bulk_check_mined(collection) -> dict[str, float]:
|
||||
"""Pre-fetch source_file/source_mtime pairs for all documents in the collection.
|
||||
|
||||
Returns a dict mapping source_file -> source_mtime (as float) for every
|
||||
document that has both fields. Callers can check membership and compare
|
||||
mtimes locally instead of issuing one ChromaDB query per file.
|
||||
|
||||
Fetches the full collection in paginated batches (like palace_graph.py)
|
||||
since a WHERE-IN filter on thousands of paths is not supported by ChromaDB.
|
||||
"""
|
||||
mined: dict[str, float] = {}
|
||||
try:
|
||||
total = collection.count()
|
||||
offset = 0
|
||||
while offset < total:
|
||||
batch = collection.get(limit=1000, offset=offset, include=["metadatas"])
|
||||
for meta in batch["metadatas"]:
|
||||
src = meta.get("source_file")
|
||||
mtime = meta.get("source_mtime")
|
||||
if src and mtime is not None:
|
||||
mined[src] = float(mtime)
|
||||
if not batch["ids"]:
|
||||
break
|
||||
offset += len(batch["ids"])
|
||||
except Exception:
|
||||
logger.warning("bulk_check_mined: partial fetch, %d files loaded", len(mined))
|
||||
return mined
|
||||
|
||||
|
||||
def prefetch_mined_set(collection, extract_mode: Optional[str] = None) -> set[str]:
|
||||
"""Pre-fetch the set of source_files already mined at the current NORMALIZE_VERSION.
|
||||
|
||||
Mirrors file_already_mined()'s version-gate semantics (check_mtime=False
|
||||
branch) but in one bulk pass instead of one ChromaDB query per file.
|
||||
Returns a set of source_file paths whose stored drawers are at or above
|
||||
NORMALIZE_VERSION; callers do `if path in result_set: skip`.
|
||||
|
||||
When extract_mode is set, mirrors file_already_mined(..., extract_mode=...)
|
||||
so conversation mines skip per extraction mode rather than per source file.
|
||||
|
||||
The convo miner walks thousands of transcript files; per-file
|
||||
`collection.get(where={"source_file": X})` costs ~2s on a 150k-drawer
|
||||
palace, making a 2000-file sweep take >1h of pure skip-checking. This
|
||||
helper drops that to a single paginated scan plus O(1) lookups.
|
||||
"""
|
||||
mined: set[str] = set()
|
||||
try:
|
||||
total = collection.count()
|
||||
offset = 0
|
||||
while offset < total:
|
||||
batch = collection.get(limit=1000, offset=offset, include=["metadatas"])
|
||||
for meta in batch["metadatas"]:
|
||||
meta = meta or {}
|
||||
src = meta.get("source_file")
|
||||
if not src:
|
||||
continue
|
||||
if not _metadata_matches_extract_mode(meta, extract_mode):
|
||||
continue
|
||||
# Same default as file_already_mined: missing version == 1
|
||||
version = meta.get("normalize_version", 1)
|
||||
if version >= NORMALIZE_VERSION:
|
||||
mined.add(src)
|
||||
if not batch["ids"]:
|
||||
break
|
||||
offset += len(batch["ids"])
|
||||
except Exception:
|
||||
logger.warning("prefetch_mined_set: partial fetch, %d files loaded", len(mined))
|
||||
return mined
|
||||
|
||||
+55
-13
@@ -43,8 +43,12 @@ def _normalize_wing(wing: str | None) -> str | None:
|
||||
(e.g. ``mempalace_public``). Callers that pass the raw directory name
|
||||
(``mempalace-public``) would silently miss. This helper aligns the lookup
|
||||
key with the stored metadata.
|
||||
|
||||
Non-string inputs (from corrupt or hand-edited ``tunnels.json``) return
|
||||
``None`` rather than raising, so a single malformed record cannot break
|
||||
the read-path filters that iterate the whole file.
|
||||
"""
|
||||
if wing is None:
|
||||
if not isinstance(wing, str):
|
||||
return None
|
||||
wing = wing.strip()
|
||||
if not wing:
|
||||
@@ -432,7 +436,8 @@ def create_tunnel(
|
||||
Tunnels are undirected: ``create_tunnel(A, B)`` and ``create_tunnel(B, A)``
|
||||
resolve to the same canonical ID. A second call with the same endpoints
|
||||
updates the stored label (and drawer IDs, if provided) rather than
|
||||
creating a duplicate.
|
||||
creating a duplicate. Endpoints are compared **verbatim** — ``"my-wing"``
|
||||
and ``"my_wing"`` are distinct (see Note below and #1504).
|
||||
|
||||
The ``source`` / ``target`` fields on the returned dict preserve the
|
||||
argument order the caller used, so callers can display it directionally
|
||||
@@ -457,15 +462,19 @@ def create_tunnel(
|
||||
|
||||
Raises:
|
||||
ValueError: if any wing or room is empty or non-string.
|
||||
|
||||
Note:
|
||||
Wing slugs are stored verbatim — passing ``"my-wing"`` and ``"my_wing"``
|
||||
produces two distinct tunnels (canonical IDs differ). Read-path helpers
|
||||
(``list_tunnels`` / ``follow_tunnels``) normalize both sides at compare
|
||||
time so legacy underscore data and explicit-flag hyphen data both
|
||||
match queries in either form. See #1504.
|
||||
"""
|
||||
source_wing = _require_name(source_wing, "source_wing")
|
||||
source_room = _require_name(source_room, "source_room")
|
||||
target_wing = _require_name(target_wing, "target_wing")
|
||||
target_room = _require_name(target_room, "target_room")
|
||||
|
||||
source_wing = _normalize_wing(source_wing)
|
||||
target_wing = _normalize_wing(target_wing)
|
||||
|
||||
tunnel_id = _canonical_tunnel_id(source_wing, source_room, target_wing, target_room)
|
||||
|
||||
tunnel = {
|
||||
@@ -509,10 +518,17 @@ def list_tunnels(wing: str = None):
|
||||
norm_wing = _normalize_wing(wing)
|
||||
tunnels = _load_tunnels()
|
||||
if norm_wing:
|
||||
# Normalize stored wings too: older tunnels.json records hold the
|
||||
# underscore form (from the prior write-path normalization), while
|
||||
# post-#1504 records hold whatever the caller passed. Comparing
|
||||
# normalized-on-both-sides matches either.
|
||||
# ``t.get(k) or {}`` (not ``t.get(k, {})``) handles ``"source": null``
|
||||
# from a hand-edited file — ``.get`` defaults only on missing keys.
|
||||
tunnels = [
|
||||
t
|
||||
for t in tunnels
|
||||
if t["source"]["wing"] == norm_wing or t["target"]["wing"] == norm_wing
|
||||
if _normalize_wing((t.get("source") or {}).get("wing")) == norm_wing
|
||||
or _normalize_wing((t.get("target") or {}).get("wing")) == norm_wing
|
||||
]
|
||||
return tunnels
|
||||
|
||||
@@ -532,15 +548,23 @@ def follow_tunnels(wing: str, room: str, col=None, config=None):
|
||||
Given a location (wing/room), finds all tunnels leading from or to it,
|
||||
and optionally fetches the connected drawer content.
|
||||
"""
|
||||
# Fall back to raw ``wing`` so an empty/whitespace query string still
|
||||
# produces a value to compare with; ``_normalize_wing`` returns ``None``
|
||||
# for empty input. Stored wings are normalized on the read path so the
|
||||
# mempalace.yaml slug (underscore) and an explicit ``--wing`` slug
|
||||
# (verbatim) both resolve through the same comparison.
|
||||
norm_wing = _normalize_wing(wing) or wing
|
||||
tunnels = _load_tunnels()
|
||||
connections = []
|
||||
|
||||
for t in tunnels:
|
||||
src = t["source"]
|
||||
tgt = t["target"]
|
||||
# ``or {}`` (not ``.get(k, {})``) handles ``"source": null`` from a
|
||||
# hand-edited file — ``.get`` defaults only on missing keys, not on
|
||||
# explicit ``null`` values.
|
||||
src = t.get("source") or {}
|
||||
tgt = t.get("target") or {}
|
||||
|
||||
if src["wing"] == norm_wing and src["room"] == room:
|
||||
if _normalize_wing(src.get("wing")) == norm_wing and src.get("room") == room:
|
||||
connections.append(
|
||||
{
|
||||
"direction": "outgoing",
|
||||
@@ -551,7 +575,7 @@ def follow_tunnels(wing: str, room: str, col=None, config=None):
|
||||
"tunnel_id": t["id"],
|
||||
}
|
||||
)
|
||||
elif tgt["wing"] == norm_wing and tgt["room"] == room:
|
||||
elif _normalize_wing(tgt.get("wing")) == norm_wing and tgt.get("room") == room:
|
||||
connections.append(
|
||||
{
|
||||
"direction": "incoming",
|
||||
@@ -669,7 +693,12 @@ def compute_topic_tunnels(
|
||||
continue
|
||||
bucket.setdefault(key, n.strip())
|
||||
if bucket:
|
||||
wing_topics[wing.strip()] = bucket
|
||||
# Auto-generated topic tunnels normalize the wing key so repeated
|
||||
# mining runs with mixed slug forms (``my-wing`` vs ``my_wing``)
|
||||
# produce one canonical record, not two parallel ones. User-issued
|
||||
# ``create_tunnel`` calls (e.g. via MCP) preserve verbatim slugs;
|
||||
# only this auto-generation path canonicalizes the key.
|
||||
wing_topics[normalize_wing_name(wing.strip())] = bucket
|
||||
|
||||
wings = sorted(wing_topics.keys())
|
||||
created: list[dict] = []
|
||||
@@ -713,8 +742,19 @@ def topic_tunnels_for_wing(
|
||||
if not topics_by_wing or not isinstance(wing, str) or not wing.strip():
|
||||
return []
|
||||
|
||||
wing = wing.strip()
|
||||
# Canonicalize the lookup key so a hyphenated arg still finds an
|
||||
# underscore-normalized entry (and vice versa). ``compute_topic_tunnels``
|
||||
# canonicalizes the keys it writes, so callers can pass either form.
|
||||
wing = normalize_wing_name(wing.strip())
|
||||
own = topics_by_wing.get(wing)
|
||||
if own is None:
|
||||
# Fallback: caller may have built ``topics_by_wing`` with verbatim
|
||||
# keys (unusual but allowed). Try every entry, normalized, before
|
||||
# giving up.
|
||||
for k, v in topics_by_wing.items():
|
||||
if isinstance(k, str) and normalize_wing_name(k.strip()) == wing:
|
||||
own = v
|
||||
break
|
||||
if not isinstance(own, (list, tuple)) or not own:
|
||||
return []
|
||||
|
||||
@@ -724,7 +764,9 @@ def topic_tunnels_for_wing(
|
||||
# one place.
|
||||
created: list[dict] = []
|
||||
for other, other_topics in topics_by_wing.items():
|
||||
if not isinstance(other, str) or not other.strip() or other == wing:
|
||||
if not isinstance(other, str) or not other.strip():
|
||||
continue
|
||||
if normalize_wing_name(other.strip()) == wing:
|
||||
continue
|
||||
if not isinstance(other_topics, (list, tuple)) or not other_topics:
|
||||
continue
|
||||
|
||||
+175
-33
@@ -35,8 +35,10 @@ import shutil
|
||||
import sqlite3
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from contextlib import closing
|
||||
from datetime import datetime
|
||||
from typing import Iterator, Optional
|
||||
import re
|
||||
from typing import Callable, Iterator, Optional
|
||||
|
||||
from chromadb.errors import NotFoundError as ChromaNotFoundError
|
||||
|
||||
@@ -139,7 +141,17 @@ def _extract_drawers(col, total: int, batch_size: int):
|
||||
break
|
||||
all_ids.extend(batch["ids"])
|
||||
all_docs.extend(batch["documents"])
|
||||
all_metas.extend(batch["metadatas"])
|
||||
# chromadb 1.5.x's upsert validates that every metadatas[i] is a
|
||||
# non-empty dict (chromadb/api/types.py:validate_metadata). Drawers
|
||||
# extracted from sqlite ground truth can come back with None or {}
|
||||
# for sparse historical writes — coerce those to a sentinel so the
|
||||
# rebuild upsert can complete instead of raising ValueError ~80%
|
||||
# through a multi-hour run. See #1458 for full context.
|
||||
sanitized_metas = [
|
||||
m if (isinstance(m, dict) and len(m) > 0) else {"_repaired_empty_meta": True}
|
||||
for m in batch["metadatas"]
|
||||
]
|
||||
all_metas.extend(sanitized_metas)
|
||||
offset += len(batch["ids"])
|
||||
return all_ids, all_docs, all_metas
|
||||
|
||||
@@ -587,9 +599,7 @@ def maybe_repair_poisoned_max_seq_id_before_rebuild(
|
||||
" This can make writes report success while embeddings_queue grows "
|
||||
"and embeddings stay static."
|
||||
)
|
||||
print(
|
||||
" Running the non-destructive max_seq_id repair instead of rebuilding " "the collection."
|
||||
)
|
||||
print(" Running the non-destructive max_seq_id repair instead of rebuilding the collection.")
|
||||
print(
|
||||
" Queued writes remain in chroma.sqlite3 for Chroma to drain after "
|
||||
"the bookmark is unpoisoned."
|
||||
@@ -603,10 +613,113 @@ def maybe_repair_poisoned_max_seq_id_before_rebuild(
|
||||
)
|
||||
|
||||
|
||||
_PROGRESS_RE_STAGED = re.compile(r"Staged\s+(\d+)/(\d+)")
|
||||
_PROGRESS_RE_REFILED = re.compile(r"Re-filed\s+(\d+)/(\d+)")
|
||||
|
||||
|
||||
def _format_eta(seconds: float) -> str:
|
||||
"""Pretty-print an ETA in the smallest reasonable unit."""
|
||||
if seconds < 60:
|
||||
return f"{seconds:.0f}s"
|
||||
if seconds < 3600:
|
||||
return f"{seconds / 60:.0f}m"
|
||||
return f"{seconds / 3600:.1f}h"
|
||||
|
||||
|
||||
class _DefaultProgress:
|
||||
"""Default ``progress`` callable for :func:`rebuild_index`.
|
||||
|
||||
Behaves like ``print`` for non-progress lines. For ``"Staged N/M"`` /
|
||||
``"Re-filed N/M"`` lines it appends elapsed/rate/ETA to give the
|
||||
operator a sense of how long the rebuild has left:
|
||||
|
||||
Staged 5000/182953 drawers... (elapsed 7m, rate 11.3/s, ETA 4h)
|
||||
|
||||
The clock resets at the stage→refile transition so the rate is
|
||||
accurate within each phase (refile re-embeds from scratch and runs
|
||||
at potentially different throughput than stage).
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._start: Optional[float] = None
|
||||
self._phase: Optional[str] = None
|
||||
self._initial_completed: int = 0
|
||||
|
||||
def __call__(self, msg) -> None:
|
||||
msg = str(msg)
|
||||
decorated = self._maybe_decorate(msg)
|
||||
print(decorated)
|
||||
|
||||
def _maybe_decorate(self, msg: str) -> str:
|
||||
for pattern, phase in (
|
||||
(_PROGRESS_RE_STAGED, "stage"),
|
||||
(_PROGRESS_RE_REFILED, "refile"),
|
||||
):
|
||||
m = pattern.search(msg)
|
||||
if m is None:
|
||||
continue
|
||||
completed = int(m.group(1))
|
||||
expected = int(m.group(2))
|
||||
return msg + self._eta_suffix(phase, completed, expected)
|
||||
return msg
|
||||
|
||||
def _eta_suffix(self, phase: str, completed: int, expected: int) -> str:
|
||||
now = time.monotonic()
|
||||
# Reset clock + baseline at first call OR at phase transition,
|
||||
# so refile-phase rate isn't muddied by the slower stage phase.
|
||||
if self._phase != phase:
|
||||
self._phase = phase
|
||||
self._start = now
|
||||
self._initial_completed = completed
|
||||
elapsed = now - (self._start or now)
|
||||
done_this_phase = completed - self._initial_completed
|
||||
rate = done_this_phase / elapsed if elapsed > 0 and done_this_phase > 0 else 0.0
|
||||
remaining = max(0, expected - completed)
|
||||
if rate <= 0:
|
||||
return f" (elapsed {_format_eta(elapsed)})"
|
||||
eta = remaining / rate
|
||||
return f" (elapsed {_format_eta(elapsed)}, rate {rate:.1f}/s, ETA {_format_eta(eta)})"
|
||||
|
||||
|
||||
def _vacuum_and_rebuild_fts5(palace_path: str, progress=print) -> None:
|
||||
"""VACUUM the palace SQLite file and rebuild the FTS5 index if present.
|
||||
|
||||
Repeated ``repair --yes`` runs delete and recreate the drawers collection,
|
||||
leaving freed SQLite pages unreclaimable without an explicit VACUUM. The
|
||||
FTS5 virtual table (``embedding_fulltext_search``) can also become
|
||||
internally inconsistent after multiple collection deletes; the rebuild
|
||||
command fixes it atomically without touching any row data.
|
||||
|
||||
Failures are non-fatal: a warning is printed and the caller continues.
|
||||
The repair itself succeeded at this point — VACUUM/FTS5 are best-effort
|
||||
cleanup, not correctness requirements.
|
||||
"""
|
||||
sqlite_path = os.path.join(palace_path, "chroma.sqlite3")
|
||||
if not os.path.exists(sqlite_path):
|
||||
return
|
||||
try:
|
||||
with closing(sqlite3.connect(sqlite_path, isolation_level=None)) as conn:
|
||||
tables = {
|
||||
r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
||||
}
|
||||
if "embedding_fulltext_search" in tables:
|
||||
conn.execute(
|
||||
"INSERT INTO embedding_fulltext_search"
|
||||
"(embedding_fulltext_search) VALUES('rebuild')"
|
||||
)
|
||||
conn.commit()
|
||||
progress(" FTS5 index rebuilt.")
|
||||
conn.execute("VACUUM")
|
||||
progress(" SQLite VACUUM complete.")
|
||||
except Exception as exc:
|
||||
progress(f" Warning: post-repair cleanup failed (non-fatal): {exc}")
|
||||
|
||||
|
||||
def rebuild_index(
|
||||
palace_path=None,
|
||||
confirm_truncation_ok: bool = False,
|
||||
collection_name: Optional[str] = None,
|
||||
progress: Optional[Callable[[str], None]] = None,
|
||||
):
|
||||
"""Rebuild the HNSW index from scratch.
|
||||
|
||||
@@ -620,18 +733,26 @@ def rebuild_index(
|
||||
Set to ``True`` only when you have independently verified that the
|
||||
palace genuinely contains exactly the extracted number of drawers
|
||||
(typically only a concern for palaces sized at exactly 10 000 rows).
|
||||
|
||||
``progress`` is the callable used for status output. Defaults to
|
||||
:class:`_DefaultProgress` which prints with elapsed/rate/ETA
|
||||
annotations on ``Staged N/M`` and ``Re-filed N/M`` lines. Pass a
|
||||
custom callable (e.g. a daemon-side capture for HTTP status, or a
|
||||
silent ``lambda *_: None`` for tests) to override.
|
||||
"""
|
||||
if progress is None:
|
||||
progress = _DefaultProgress()
|
||||
palace_path = palace_path or _get_palace_path()
|
||||
collection_name = collection_name or _drawers_collection_name()
|
||||
|
||||
if not os.path.isdir(palace_path):
|
||||
print(f"\n No palace found at {palace_path}")
|
||||
progress(f"\n No palace found at {palace_path}")
|
||||
return
|
||||
|
||||
print(f"\n{'=' * 55}")
|
||||
print(" MemPalace Repair — Index Rebuild")
|
||||
print(f"{'=' * 55}\n")
|
||||
print(f" Palace: {palace_path}")
|
||||
progress(f"\n{'=' * 55}")
|
||||
progress(" MemPalace Repair — Index Rebuild")
|
||||
progress(f"{'=' * 55}\n")
|
||||
progress(f" Palace: {palace_path}")
|
||||
|
||||
# Run the SQLite integrity preflight before any chromadb client open.
|
||||
# ChromaDB's rust binding raises pyo3_runtime.PanicException (which is
|
||||
@@ -656,21 +777,21 @@ def rebuild_index(
|
||||
col = backend.get_collection(palace_path, collection_name)
|
||||
total = col.count()
|
||||
except Exception as e:
|
||||
print(f" Error reading palace: {e}")
|
||||
print(" Palace may need to be re-mined from source files.")
|
||||
progress(f" Error reading palace: {e}")
|
||||
progress(" Palace may need to be re-mined from source files.")
|
||||
return
|
||||
|
||||
print(f" Drawers found: {total}")
|
||||
progress(f" Drawers found: {total}")
|
||||
|
||||
if total == 0:
|
||||
print(" Nothing to repair.")
|
||||
progress(" Nothing to repair.")
|
||||
return
|
||||
|
||||
# Extract all drawers in batches
|
||||
print("\n Extracting drawers...")
|
||||
progress("\n Extracting drawers...")
|
||||
batch_size = 5000
|
||||
all_ids, all_docs, all_metas = _extract_drawers(col, total, batch_size)
|
||||
print(f" Extracted {len(all_ids)} drawers")
|
||||
progress(f" Extracted {len(all_ids)} drawers")
|
||||
|
||||
# ── #1208 guard ──────────────────────────────────────────────────
|
||||
# Refuse to ``delete_collection`` + rebuild when extraction looks
|
||||
@@ -684,19 +805,19 @@ def rebuild_index(
|
||||
collection_name=collection_name,
|
||||
)
|
||||
except TruncationDetected as e:
|
||||
print(e.message)
|
||||
progress(e.message)
|
||||
return
|
||||
|
||||
# Back up ONLY the SQLite database, not the bloated HNSW files
|
||||
sqlite_path = os.path.join(palace_path, "chroma.sqlite3")
|
||||
backup_path = sqlite_path + ".backup"
|
||||
if os.path.exists(sqlite_path):
|
||||
print(f" Backing up chroma.sqlite3 ({os.path.getsize(sqlite_path) / 1e6:.0f} MB)...")
|
||||
progress(f" Backing up chroma.sqlite3 ({os.path.getsize(sqlite_path) / 1e6:.0f} MB)...")
|
||||
shutil.copy2(sqlite_path, backup_path)
|
||||
print(f" Backup: {backup_path}")
|
||||
progress(f" Backup: {backup_path}")
|
||||
|
||||
# Rebuild with correct HNSW settings
|
||||
print(" Rebuilding collection with hnsw:space=cosine...")
|
||||
progress(" Rebuilding collection with hnsw:space=cosine...")
|
||||
try:
|
||||
filed = _rebuild_collection_via_temp(
|
||||
backend,
|
||||
@@ -706,27 +827,30 @@ def rebuild_index(
|
||||
all_metas,
|
||||
batch_size,
|
||||
collection_name=collection_name,
|
||||
progress=print,
|
||||
progress=progress,
|
||||
)
|
||||
except RebuildCollectionError as e:
|
||||
print(f"\n ERROR during rebuild: {e}")
|
||||
print(" Rebuild aborted before completion.")
|
||||
progress(f"\n ERROR during rebuild: {e}")
|
||||
progress(" Rebuild aborted before completion.")
|
||||
if e.live_replaced and os.path.exists(backup_path):
|
||||
print(f" Restoring from backup: {backup_path}")
|
||||
progress(f" Restoring from backup: {backup_path}")
|
||||
try:
|
||||
_close_chroma_handles(palace_path, backend=backend)
|
||||
_delete_collection_if_exists(backend, palace_path, collection_name)
|
||||
shutil.copy2(backup_path, sqlite_path)
|
||||
print(" Backup restored. Palace is back to pre-repair state.")
|
||||
progress(" Backup restored. Palace is back to pre-repair state.")
|
||||
except Exception as restore_error:
|
||||
print(f" Backup restore failed: {restore_error}")
|
||||
print(f" Manual restore required from: {backup_path}")
|
||||
progress(f" Backup restore failed: {restore_error}")
|
||||
progress(f" Manual restore required from: {backup_path}")
|
||||
elif e.live_replaced:
|
||||
print(" No backup available. Re-mine from source files to recover.")
|
||||
progress(" No backup available. Re-mine from source files to recover.")
|
||||
else:
|
||||
print(" Live collection was not replaced; leaving the original palace untouched.")
|
||||
raise
|
||||
|
||||
_close_chroma_handles(palace_path, backend=backend)
|
||||
_vacuum_and_rebuild_fts5(palace_path, progress=progress)
|
||||
|
||||
print(f"\n Repair complete. {filed} drawers rebuilt.")
|
||||
print(" HNSW index is now clean with cosine distance metric.")
|
||||
print(f"\n{'=' * 55}\n")
|
||||
@@ -806,11 +930,14 @@ def _rebuild_one_collection(
|
||||
for emb_id, doc, meta in extract_via_sqlite(source_palace, collection_name):
|
||||
ids.append(emb_id)
|
||||
docs.append(doc or "")
|
||||
# chromadb 1.5.x rejects None entries in the metadatas list
|
||||
# but accepts empty dicts. Mempalace drawers always carry at
|
||||
# least wing/room, so this branch is defensive — corruption
|
||||
# in embedding_metadata could yield an emb_id with no rows.
|
||||
metas.append(meta if meta else {})
|
||||
# chromadb 1.5.x rejects both None and empty-dict entries in
|
||||
# the metadatas list (ValueError: Expected metadata to be a
|
||||
# non-empty dict). Mempalace drawers always carry at least
|
||||
# wing/room, so this branch is defensive — corruption in
|
||||
# embedding_metadata could yield an emb_id with no rows.
|
||||
# Coerce to a sentinel that satisfies validation and is
|
||||
# discoverable later via `where={"_repaired_empty_meta": True}`.
|
||||
metas.append(meta if (meta and len(meta) > 0) else {"_repaired_empty_meta": True})
|
||||
if len(ids) >= batch_size:
|
||||
_flush()
|
||||
_flush()
|
||||
@@ -1133,6 +1260,21 @@ def status(palace_path=None, collection_name: Optional[str] = None) -> dict:
|
||||
print(" No palace found.\n")
|
||||
return {"status": "unknown", "message": "no palace at path"}
|
||||
|
||||
db_path = os.path.join(palace_path, "chroma.sqlite3")
|
||||
if not os.path.isfile(db_path):
|
||||
print(f" Palace dir at {palace_path} exists but has no chroma.sqlite3 yet.\n")
|
||||
return {"status": "uninitialized", "message": "palace has no chroma.sqlite3 yet"}
|
||||
|
||||
# Cheap collection-existence check via sqlite. By design this function
|
||||
# never opens a chromadb client (see the docstring); sqlite_drawer_count
|
||||
# reads chroma.sqlite3 directly and returns None on any schema/lock error
|
||||
# (chromadb version drift, missing tables, locked file). None means fall
|
||||
# through and let hnsw_capacity_status report "unknown".
|
||||
drawer_row_count = sqlite_drawer_count(palace_path, collection_name)
|
||||
if isinstance(drawer_row_count, int) and drawer_row_count == 0:
|
||||
print(" Palace is initialized but empty (no drawers yet).\n")
|
||||
return {"status": "empty", "message": "palace has no drawers yet"}
|
||||
|
||||
drawers = hnsw_capacity_status(palace_path, collection_name)
|
||||
closets = hnsw_capacity_status(palace_path, CLOSETS_COLLECTION_NAME)
|
||||
|
||||
|
||||
+22
-1
@@ -16,6 +16,7 @@ import re
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from .backends import CollectionNotInitializedError, PalaceNotFoundError
|
||||
from .palace import get_closets_collection, get_collection
|
||||
|
||||
# Closet pointer line format: "topic|entities|→drawer_id_a,drawer_id_b"
|
||||
@@ -295,9 +296,29 @@ def search(query: str, palace_path: str, wing: str = None, room: str = None, n_r
|
||||
Search the palace. Returns verbatim drawer content.
|
||||
Optionally filter by wing (project) or room (aspect).
|
||||
"""
|
||||
# Filesystem-first checks distinguish State A / State B before reaching
|
||||
# chromadb. PersistentClient lazily creates chroma.sqlite3 on first open
|
||||
# of an empty palace dir, so without these checks State B collapses into
|
||||
# the "initialized but empty" State C message and mutates the dir as a
|
||||
# side effect of a read-only search call (#1498).
|
||||
if not os.path.isdir(palace_path):
|
||||
print(f"\n No palace found at {palace_path}")
|
||||
print(" Run: mempalace init <dir> then mempalace mine <dir>")
|
||||
raise SearchError(f"No palace found at {palace_path}")
|
||||
if not os.path.isfile(os.path.join(palace_path, "chroma.sqlite3")):
|
||||
print(f"\n Palace dir at {palace_path} exists but has no chroma.sqlite3 yet.")
|
||||
print(" Run: mempalace mine <dir>")
|
||||
raise SearchError(f"No palace database at {palace_path}")
|
||||
try:
|
||||
col = get_collection(palace_path, create=False)
|
||||
except Exception as e:
|
||||
except CollectionNotInitializedError as e:
|
||||
# State C from #1498: palace initialized but never mined.
|
||||
print(f"\n Palace at {palace_path} is initialized but empty (no drawers yet).")
|
||||
print(" Run: mempalace mine <dir>")
|
||||
raise SearchError(f"Palace at {palace_path} is initialized but empty") from e
|
||||
except PalaceNotFoundError as e:
|
||||
# Backend filesystem-race fallback: dir was deleted between our
|
||||
# check above and the backend call. Same message as State A.
|
||||
print(f"\n No palace found at {palace_path}")
|
||||
print(" Run: mempalace init <dir> then mempalace mine <dir>")
|
||||
raise SearchError(f"No palace found at {palace_path}") from e
|
||||
|
||||
+2
-2
@@ -61,7 +61,7 @@ chroma = "mempalace.backends.chroma:ChromaBackend"
|
||||
[project.entry-points."mempalace.sources"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=7.0", "pytest-cov>=4.0", "ruff>=0.4.0", "psutil>=5.9"]
|
||||
dev = ["pytest>=7.0", "pytest-cov>=4.0", "ruff==0.15.9", "psutil>=5.9"]
|
||||
spellcheck = ["autocorrect>=2.0"]
|
||||
# Hardware acceleration for the ONNX embedding model. Install exactly one:
|
||||
# pip install mempalace[gpu] — NVIDIA CUDA
|
||||
@@ -76,7 +76,7 @@ coreml = ["onnxruntime>=1.16"]
|
||||
multilingual = []
|
||||
|
||||
[dependency-groups]
|
||||
dev = ["pytest>=7.0", "pytest-cov>=4.0", "ruff>=0.4.0", "psutil>=5.9"]
|
||||
dev = ["pytest>=7.0", "pytest-cov>=4.0", "ruff==0.15.9", "psutil>=5.9"]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
|
||||
+98
-6
@@ -9,7 +9,9 @@ import chromadb
|
||||
import pytest
|
||||
|
||||
from mempalace.backends import (
|
||||
CollectionNotInitializedError,
|
||||
GetResult,
|
||||
PalaceNotFoundError,
|
||||
PalaceRef,
|
||||
QueryResult,
|
||||
UnsupportedFilterError,
|
||||
@@ -821,9 +823,9 @@ def test_make_client_quarantines_only_on_first_call_per_palace(tmp_path, monkeyp
|
||||
ChromaBackend.make_client(palace_path)
|
||||
ChromaBackend.make_client(palace_path)
|
||||
|
||||
assert calls == [
|
||||
palace_path
|
||||
], "quarantine_stale_hnsw should fire once per palace per process, not on every reconnect"
|
||||
assert calls == [palace_path], (
|
||||
"quarantine_stale_hnsw should fire once per palace per process, not on every reconnect"
|
||||
)
|
||||
|
||||
|
||||
def test_make_client_gates_invalid_metadata_on_first_call(tmp_path, monkeypatch):
|
||||
@@ -939,9 +941,9 @@ def test_client_quarantines_only_on_first_call_per_palace(tmp_path, monkeypatch)
|
||||
finally:
|
||||
backend.close()
|
||||
|
||||
assert (
|
||||
calls == [palace_path]
|
||||
), "quarantine_stale_hnsw should fire once per palace per process from _client(), not on every call"
|
||||
assert calls == [palace_path], (
|
||||
"quarantine_stale_hnsw should fire once per palace per process from _client(), not on every call"
|
||||
)
|
||||
|
||||
|
||||
# ── _pin_hnsw_threads (per-process retrofit, separate from this PR's gate) ──
|
||||
@@ -993,6 +995,43 @@ def test_get_collection_applies_retrofit_on_existing_palace(tmp_path):
|
||||
assert wrapper._collection.configuration_json["hnsw"]["num_threads"] == 1
|
||||
|
||||
|
||||
def test_get_collection_raises_palace_not_found_when_dir_missing(tmp_path):
|
||||
"""create=False on a missing dir raises PalaceNotFoundError, not the
|
||||
new CollectionNotInitializedError. The two states must be distinguishable
|
||||
so callers can render state-specific messages (#1498)."""
|
||||
missing = tmp_path / "no-such-dir"
|
||||
with pytest.raises(PalaceNotFoundError) as excinfo:
|
||||
ChromaBackend().get_collection(
|
||||
str(missing),
|
||||
collection_name="mempalace_drawers",
|
||||
create=False,
|
||||
)
|
||||
# Must be the parent class, not the new subclass: dir is genuinely absent.
|
||||
assert not isinstance(excinfo.value, CollectionNotInitializedError)
|
||||
|
||||
|
||||
def test_get_collection_raises_collection_not_initialized_on_empty_palace(tmp_path):
|
||||
"""When the palace dir + DB exist but the collection has never been
|
||||
created, ChromaBackend.get_collection(create=False) raises the new
|
||||
CollectionNotInitializedError instead of leaking chromadb.NotFoundError
|
||||
(#1498)."""
|
||||
palace_path = tmp_path / "palace"
|
||||
palace_path.mkdir()
|
||||
# PersistentClient lazily creates chroma.sqlite3 — no collection yet.
|
||||
chromadb.PersistentClient(path=str(palace_path))
|
||||
assert (palace_path / "chroma.sqlite3").is_file()
|
||||
|
||||
with pytest.raises(CollectionNotInitializedError) as excinfo:
|
||||
ChromaBackend().get_collection(
|
||||
str(palace_path),
|
||||
collection_name="mempalace_drawers",
|
||||
create=False,
|
||||
)
|
||||
# Backward-compat: subclass of PalaceNotFoundError (and FileNotFoundError).
|
||||
assert isinstance(excinfo.value, PalaceNotFoundError)
|
||||
assert isinstance(excinfo.value, FileNotFoundError)
|
||||
|
||||
|
||||
def test_quarantine_invalid_hnsw_metadata_renames_missing_dimensionality(tmp_path):
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
@@ -1008,6 +1047,59 @@ def test_quarantine_invalid_hnsw_metadata_renames_missing_dimensionality(tmp_pat
|
||||
assert not seg.exists()
|
||||
|
||||
|
||||
def test_quarantine_invalid_hnsw_metadata_keeps_consistent_missing_dimensionality(tmp_path):
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
seg = palace / "abcd-1234-5678"
|
||||
seg.mkdir()
|
||||
(seg / "data_level0.bin").write_bytes(b"x" * 2048)
|
||||
(seg / "link_lists.bin").write_bytes(b"x" * 128)
|
||||
with open(seg / "index_metadata.pickle", "wb") as f:
|
||||
pickle.dump(
|
||||
{
|
||||
"dimensionality": None,
|
||||
"total_elements_added": 2,
|
||||
"max_seq_id": None,
|
||||
"id_to_label": {"a": 1, "b": 2},
|
||||
"label_to_id": {1: "a", 2: "b"},
|
||||
"id_to_seq_id": {},
|
||||
},
|
||||
f,
|
||||
)
|
||||
|
||||
moved = quarantine_invalid_hnsw_metadata(str(palace))
|
||||
|
||||
assert moved == []
|
||||
assert seg.exists()
|
||||
|
||||
|
||||
def test_quarantine_invalid_hnsw_metadata_renames_mismatched_missing_dimensionality(tmp_path):
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
seg = palace / "abcd-1234-5678"
|
||||
seg.mkdir()
|
||||
(seg / "data_level0.bin").write_bytes(b"x" * 2048)
|
||||
(seg / "link_lists.bin").write_bytes(b"x" * 128)
|
||||
with open(seg / "index_metadata.pickle", "wb") as f:
|
||||
pickle.dump(
|
||||
{
|
||||
"dimensionality": None,
|
||||
"total_elements_added": 2,
|
||||
"max_seq_id": None,
|
||||
"id_to_label": {"a": 1, "b": 2},
|
||||
"label_to_id": {1: "b", 2: "a"},
|
||||
"id_to_seq_id": {},
|
||||
},
|
||||
f,
|
||||
)
|
||||
|
||||
moved = quarantine_invalid_hnsw_metadata(str(palace))
|
||||
|
||||
assert len(moved) == 1
|
||||
assert ".corrupt-" in moved[0]
|
||||
assert not seg.exists()
|
||||
|
||||
|
||||
def test_quarantine_invalid_hnsw_metadata_allows_uninitialized_segment(tmp_path):
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
|
||||
@@ -317,9 +317,9 @@ def test_read_path_does_not_acquire_lock(tmp_path, monkeypatch):
|
||||
if method is None:
|
||||
continue
|
||||
src = inspect.getsource(method)
|
||||
assert (
|
||||
"_write_lock" not in src
|
||||
), f"{read_attr} must NOT acquire the write lock (read path)"
|
||||
assert "_write_lock" not in src, (
|
||||
f"{read_attr} must NOT acquire the write lock (read path)"
|
||||
)
|
||||
finally:
|
||||
open(release, "w").close()
|
||||
holder.join(timeout=5)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Schema tests for Claude plugin hook config: timeout must be bounded."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
HOOK_CONFIG = REPO_ROOT / ".claude-plugin" / "hooks" / "hooks.json"
|
||||
|
||||
# Per-event hook-level timeout bounds (seconds): (floor, ceiling).
|
||||
#
|
||||
# Stop is fire-and-forget for the mine subprocess (_spawn_mine returns
|
||||
# after a detached Popen), but the handler also calls _save_diary_direct
|
||||
# synchronously, which touches chromadb. 10..30s is generous for that
|
||||
# work without leaving room for runaway hangs to freeze the session.
|
||||
#
|
||||
# PreCompact runs _mine_sync synchronously with a per-target subprocess
|
||||
# timeout of 60s in mempalace/hooks_cli.py. The hook-level floor of 60
|
||||
# keeps the inner bound from being truncated, and the ceiling of 90
|
||||
# bounds the worst case at ~30s above that.
|
||||
EVENT_TIMEOUT_BOUNDS: dict[str, tuple[int, int]] = {
|
||||
"Stop": (10, 30),
|
||||
"PreCompact": (60, 90),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def hook_config() -> dict:
|
||||
return json.loads(HOOK_CONFIG.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event", sorted(EVENT_TIMEOUT_BOUNDS))
|
||||
def test_plugin_hook_timeout_within_bounds(hook_config: dict, event: str) -> None:
|
||||
"""Each declared plugin hook must declare a positive bounded timeout (#1465).
|
||||
|
||||
Without ``timeout``, Claude Code falls back to the 600s command default
|
||||
and a hung ``mempalace hook run`` freezes the interactive session for
|
||||
up to ten minutes before being canceled.
|
||||
"""
|
||||
floor, ceiling = EVENT_TIMEOUT_BOUNDS[event]
|
||||
assert event in hook_config.get("hooks", {}), f"missing event {event!r} in hook config"
|
||||
entries = hook_config["hooks"][event]
|
||||
assert isinstance(entries, list) and entries, f"no entries declared for {event}"
|
||||
# Pin cardinality: the plugin config intentionally declares exactly one
|
||||
# command per event. A duplicate entry would silently double-fire the
|
||||
# hook and pass per-hook bounds, so cardinality drift must fail loudly.
|
||||
assert len(entries) == 1, (
|
||||
f"{event} expected exactly one entry, found {len(entries)}; "
|
||||
"duplicate entries would double-fire the hook"
|
||||
)
|
||||
for entry in entries:
|
||||
sub_hooks = entry.get("hooks")
|
||||
assert isinstance(sub_hooks, list) and sub_hooks, (
|
||||
f"{event} entry missing non-empty 'hooks' array"
|
||||
)
|
||||
assert len(sub_hooks) == 1, (
|
||||
f"{event} entry expected exactly one hook command, found {len(sub_hooks)}"
|
||||
)
|
||||
for hook in sub_hooks:
|
||||
assert hook.get("type") == "command", (
|
||||
f"unexpected hook type for {event}: {hook.get('type')!r}"
|
||||
)
|
||||
assert "timeout" in hook, f"{event} hook missing 'timeout' key"
|
||||
timeout = hook["timeout"]
|
||||
# bool subclasses int, so reject it explicitly: True == 1 must fail.
|
||||
is_real_int = isinstance(timeout, int) and not isinstance(timeout, bool)
|
||||
assert is_real_int and floor <= timeout <= ceiling, (
|
||||
f"{event} hook timeout must be an int in [{floor}, {ceiling}]s; got {timeout!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_no_unbounded_events_in_plugin_config(hook_config: dict) -> None:
|
||||
"""No plugin hook event may ship without an explicit bounds entry.
|
||||
|
||||
Adding a new event (SessionStart, PreToolUse, etc.) to
|
||||
``.claude-plugin/hooks/hooks.json`` without registering bounds in
|
||||
``EVENT_TIMEOUT_BOUNDS`` would silently fall back to the 600s
|
||||
Claude Code command default and re-introduce the regression.
|
||||
"""
|
||||
declared_events = set(hook_config.get("hooks", {}).keys())
|
||||
bounded_events = set(EVENT_TIMEOUT_BOUNDS)
|
||||
unbounded = declared_events - bounded_events
|
||||
assert not unbounded, (
|
||||
f"plugin hook events without timeout bounds: {sorted(unbounded)}. "
|
||||
"Add a (floor, ceiling) entry to EVENT_TIMEOUT_BOUNDS in this test "
|
||||
"after deciding the worst-case freeze the event can tolerate."
|
||||
)
|
||||
+109
-16
@@ -1,8 +1,10 @@
|
||||
"""Tests for mempalace.cli — the main CLI dispatcher."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import shlex
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, call, patch
|
||||
@@ -24,6 +26,68 @@ from mempalace.cli import (
|
||||
)
|
||||
|
||||
|
||||
# ── CLI entry point: PYTHONPATH stripping ────────────────────────────────
|
||||
|
||||
|
||||
_LEAK_PREFIX = "/__mempalace_cli_leak_sentinel__"
|
||||
|
||||
|
||||
def test_cli_main_strips_leaked_pythonpath_from_env():
|
||||
"""mempalace.cli:main must drop PYTHONPATH from the process env so
|
||||
any subprocess the CLI spawns starts clean. Mirrors the
|
||||
sys.path-filter test in test_init.py but for the env half of the
|
||||
split fix. See #1423.
|
||||
|
||||
Three assertions cover the full split contract:
|
||||
- ENV_MID (after import, before main) is preserved verbatim:
|
||||
regression detector for someone moving the env pop back into
|
||||
__init__.py.
|
||||
- SENTINEL_IN_PATH is False at import time: package-level sys.path
|
||||
filter half of the split actually ran.
|
||||
- ENV_AFTER (after main) is None: CLI entry-point env strip ran.
|
||||
|
||||
SystemExit is caught with a narrowed exit-code check so a future
|
||||
argparse change that exits with a non-zero code (e.g. usage error)
|
||||
surfaces as a test failure instead of being swallowed."""
|
||||
expected_env = f"{_LEAK_PREFIX}/a{os.pathsep}{_LEAK_PREFIX}/b"
|
||||
env = os.environ.copy()
|
||||
env["PYTHONPATH"] = expected_env
|
||||
# Run main() with --version so it exits cleanly without entering any
|
||||
# subcommand. argparse raises SystemExit(0) on --version; the wrapper
|
||||
# asserts the exit code is clean and prints the post-main PYTHONPATH
|
||||
# so the assertion is observable.
|
||||
code = (
|
||||
"import os, sys\n"
|
||||
"from mempalace.cli import main\n"
|
||||
f"prefix = {_LEAK_PREFIX!r}\n"
|
||||
"print('ENV_MID:', repr(os.environ.get('PYTHONPATH')))\n"
|
||||
"print('SENTINEL_IN_PATH:', any(prefix in (p or '') for p in sys.path))\n"
|
||||
"sys.argv = ['mempalace', '--version']\n"
|
||||
"try:\n"
|
||||
" main()\n"
|
||||
"except SystemExit as exc:\n"
|
||||
" assert exc.code in (0, None), f'unexpected exit code: {exc.code!r}'\n"
|
||||
"print('ENV_AFTER:', repr(os.environ.get('PYTHONPATH')))\n"
|
||||
)
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", code],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=30,
|
||||
)
|
||||
diag = f"rc={result.returncode}; stdout={result.stdout!r}; stderr={result.stderr!r}"
|
||||
assert result.returncode == 0, f"subprocess failed: {diag}"
|
||||
assert f"ENV_MID: {expected_env!r}" in result.stdout, (
|
||||
f"package import unexpectedly stripped env (regression in __init__.py): {diag}"
|
||||
)
|
||||
assert "SENTINEL_IN_PATH: False" in result.stdout, (
|
||||
f"package import did not filter sys.path (regression in __init__.py): {diag}"
|
||||
)
|
||||
assert "ENV_AFTER: None" in result.stdout, f"CLI did not strip PYTHONPATH: {diag}"
|
||||
|
||||
|
||||
# ── cmd_status ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -977,16 +1041,45 @@ def test_cmd_repair_aborts_without_confirmation(mock_config_cls, tmp_path, capsy
|
||||
|
||||
|
||||
@patch("mempalace.cli.MempalaceConfig")
|
||||
def test_cmd_compress_no_palace(mock_config_cls, capsys):
|
||||
mock_config_cls.return_value.palace_path = "/fake/palace"
|
||||
def test_cmd_sync_no_palace_dir(mock_config_cls, tmp_path, capsys):
|
||||
"""cmd_sync on a missing palace dir prints the State A message (#1498)."""
|
||||
from mempalace.cli import cmd_sync
|
||||
|
||||
palace_path = tmp_path / "nonexistent"
|
||||
mock_config_cls.return_value.palace_path = str(palace_path)
|
||||
args = argparse.Namespace(palace=None, dir=None, root=[], wing=None, dry_run=False)
|
||||
cmd_sync(args)
|
||||
captured = capsys.readouterr()
|
||||
assert "No palace found" in captured.out + captured.err
|
||||
|
||||
|
||||
@patch("mempalace.cli.MempalaceConfig")
|
||||
def test_cmd_sync_palace_dir_no_db(mock_config_cls, tmp_path, capsys):
|
||||
"""cmd_sync on a palace dir without chroma.sqlite3 prints the State B
|
||||
message and does NOT trigger chromadb's lazy DB creation (#1498)."""
|
||||
from mempalace.cli import cmd_sync
|
||||
|
||||
mock_config_cls.return_value.palace_path = str(tmp_path)
|
||||
args = argparse.Namespace(palace=None, dir=None, root=[], wing=None, dry_run=False)
|
||||
cmd_sync(args)
|
||||
captured = capsys.readouterr()
|
||||
assert "has no chroma.sqlite3 yet" in captured.out + captured.err
|
||||
# Side-effect-free: backend not invoked.
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
|
||||
|
||||
@patch("mempalace.cli.MempalaceConfig")
|
||||
def test_cmd_compress_no_palace(mock_config_cls, tmp_path, capsys):
|
||||
"""cmd_compress exits non-zero with a 'No palace found' message on a missing dir.
|
||||
|
||||
Uses a real non-existent tmp_path so the stratified state helper (#1498)
|
||||
walks the State A branch instead of hitting the chromadb backend.
|
||||
"""
|
||||
mock_config_cls.return_value.palace_path = str(tmp_path / "nonexistent")
|
||||
args = argparse.Namespace(palace=None, wing=None, dry_run=False, config=None)
|
||||
mock_backend = MagicMock()
|
||||
mock_backend.get_collection.side_effect = Exception("no palace")
|
||||
with (
|
||||
patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend),
|
||||
pytest.raises(SystemExit),
|
||||
):
|
||||
with pytest.raises(SystemExit):
|
||||
cmd_compress(args)
|
||||
assert "No palace found" in capsys.readouterr().out
|
||||
|
||||
|
||||
@patch("mempalace.cli.MempalaceConfig")
|
||||
@@ -996,7 +1089,10 @@ def test_cmd_compress_no_drawers(mock_config_cls, capsys):
|
||||
mock_col = MagicMock()
|
||||
mock_col.get.return_value = {"documents": [], "metadatas": [], "ids": []}
|
||||
mock_backend = _mock_backend_for(col=mock_col)
|
||||
with patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend):
|
||||
with (
|
||||
patch("mempalace.palace._open_collection_or_explain", return_value=mock_col),
|
||||
patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend),
|
||||
):
|
||||
cmd_compress(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "No drawers found" in out
|
||||
@@ -1039,6 +1135,7 @@ def test_cmd_compress_dry_run(mock_config_cls, capsys):
|
||||
mock_dialect_mod = _make_mock_dialect_module(mock_dialect)
|
||||
|
||||
with (
|
||||
patch("mempalace.palace._open_collection_or_explain", return_value=mock_col),
|
||||
patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend),
|
||||
patch.dict("sys.modules", {"mempalace.dialect": mock_dialect_mod}),
|
||||
):
|
||||
@@ -1063,6 +1160,7 @@ def test_cmd_compress_with_config(mock_config_cls, tmp_path, capsys):
|
||||
mock_dialect_mod = _make_mock_dialect_module(mock_dialect)
|
||||
|
||||
with (
|
||||
patch("mempalace.palace._open_collection_or_explain", return_value=mock_col),
|
||||
patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend),
|
||||
patch.dict("sys.modules", {"mempalace.dialect": mock_dialect_mod}),
|
||||
):
|
||||
@@ -1103,7 +1201,8 @@ def test_cmd_compress_stores_results(mock_config_cls, capsys):
|
||||
mock_dialect_mod = _make_mock_dialect_module(mock_dialect)
|
||||
|
||||
with (
|
||||
patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend),
|
||||
patch("mempalace.palace._open_collection_or_explain", return_value=mock_col),
|
||||
patch("mempalace.palace.get_closets_collection", return_value=mock_comp_col),
|
||||
patch.dict("sys.modules", {"mempalace.dialect": mock_dialect_mod}),
|
||||
):
|
||||
cmd_compress(args)
|
||||
@@ -1111,12 +1210,6 @@ def test_cmd_compress_stores_results(mock_config_cls, capsys):
|
||||
assert "Stored" in out
|
||||
assert "Total:" in out
|
||||
mock_comp_col.upsert.assert_called_once()
|
||||
# Verify the compress output goes to the closets collection so that
|
||||
# palace.get_closets_collection() / searcher can read it back (#1244).
|
||||
(call_args, _kwargs) = mock_backend.get_or_create_collection.call_args
|
||||
assert (
|
||||
call_args[1] == "mempalace_closets"
|
||||
), f"compress should write to mempalace_closets, got {call_args[1]!r}"
|
||||
assert "mempalace_closets" in out
|
||||
|
||||
|
||||
|
||||
@@ -312,9 +312,9 @@ class TestRegenerateClosets:
|
||||
survivors = closets.get(where={"source_file": source}, include=["documents", "metadatas"])
|
||||
assert survivors["ids"], "LLM closets should have been written"
|
||||
joined = "\n".join(survivors["documents"])
|
||||
assert (
|
||||
"STALE_REGEX_TOPIC" not in joined
|
||||
), "pre-existing regex closet was not purged before LLM write"
|
||||
assert "STALE_REGEX_TOPIC" not in joined, (
|
||||
"pre-existing regex closet was not purged before LLM write"
|
||||
)
|
||||
assert "jwt auth" in joined
|
||||
for meta in survivors["metadatas"]:
|
||||
assert meta.get("generated_by", "").startswith("llm:")
|
||||
@@ -399,9 +399,9 @@ class TestRegenerateClosets:
|
||||
# Three paginated calls: (limit=5000, offset=0), (5000, 5000), (5000, 10000).
|
||||
assert len(get_calls) == 3, f"expected 3 batched fetches, got {len(get_calls)}"
|
||||
for call in get_calls:
|
||||
assert (
|
||||
call["limit"] == 5000
|
||||
), f"batch must be 5000 — got {call['limit']} (would risk SQLITE_MAX_VARIABLE_NUMBER)"
|
||||
assert call["limit"] == 5000, (
|
||||
f"batch must be 5000 — got {call['limit']} (would risk SQLITE_MAX_VARIABLE_NUMBER)"
|
||||
)
|
||||
# include must still request both documents and metadatas
|
||||
assert "documents" in call["include"]
|
||||
assert "metadatas" in call["include"]
|
||||
|
||||
+13
-13
@@ -140,9 +140,9 @@ class TestMineLock:
|
||||
# Sort by entry time and verify the second entry is after the first exit.
|
||||
intervals.sort(key=lambda iv: iv[1])
|
||||
(_, enter_a, exit_a), (_, enter_b, exit_b) = intervals
|
||||
assert (
|
||||
enter_a < exit_a <= enter_b < exit_b
|
||||
), f"critical sections overlapped — lock failed to serialize: {intervals}"
|
||||
assert enter_a < exit_a <= enter_b < exit_b, (
|
||||
f"critical sections overlapped — lock failed to serialize: {intervals}"
|
||||
)
|
||||
|
||||
|
||||
# ── build_closet_lines ─────────────────────────────────────────────────
|
||||
@@ -315,15 +315,15 @@ class TestMinerClosetRebuild:
|
||||
second_docs = "\n".join(second_pass["documents"]).lower()
|
||||
assert "only topic now" in second_docs
|
||||
for i in range(15):
|
||||
assert (
|
||||
f"topic {i}\n" not in second_docs
|
||||
), f"stale 'Topic {i}' from first mine survived the rebuild"
|
||||
assert f"topic {i}\n" not in second_docs, (
|
||||
f"stale 'Topic {i}' from first mine survived the rebuild"
|
||||
)
|
||||
# Numbered closets that existed only in the larger first run must be gone.
|
||||
leftover = first_ids - set(second_pass["ids"])
|
||||
for stale_id in leftover:
|
||||
assert not col.get(ids=[stale_id])[
|
||||
"ids"
|
||||
], f"orphan closet {stale_id} from larger first run survived purge"
|
||||
assert not col.get(ids=[stale_id])["ids"], (
|
||||
f"orphan closet {stale_id} from larger first run survived purge"
|
||||
)
|
||||
|
||||
|
||||
# ── _extract_drawer_ids_from_closet ───────────────────────────────────
|
||||
@@ -702,9 +702,9 @@ class TestDiaryIngest:
|
||||
|
||||
# No state file inside the user's diary dir.
|
||||
for entry in diary_dir.iterdir():
|
||||
assert (
|
||||
"diary_ingest" not in entry.name
|
||||
), f"state file leaked into user diary dir: {entry}"
|
||||
assert "diary_ingest" not in entry.name, (
|
||||
f"state file leaked into user diary dir: {entry}"
|
||||
)
|
||||
|
||||
# State file does exist under ~/.mempalace/state/.
|
||||
state_path = _state_file_for(str(palace_dir), diary_dir.resolve())
|
||||
@@ -905,7 +905,7 @@ class TestTunnels:
|
||||
assert not errors, f"worker raised: {errors}"
|
||||
tunnels = list_tunnels()
|
||||
assert len(tunnels) == 5, (
|
||||
f"expected 5 concurrent tunnels, got {len(tunnels)} — " "write race dropped some"
|
||||
f"expected 5 concurrent tunnels, got {len(tunnels)} — write race dropped some"
|
||||
)
|
||||
|
||||
def test_created_at_is_timezone_aware(self):
|
||||
|
||||
@@ -345,3 +345,220 @@ def test_iso_temporal_error_names_field():
|
||||
|
||||
def test_iso_temporal_normalizes_plus_zero_offset_to_z():
|
||||
assert sanitize_iso_temporal("2026-05-06T14:23:00+00:00") == "2026-05-06T14:23:00Z"
|
||||
|
||||
|
||||
# ── Chunk-config validation ────────────────────────────────────────────
|
||||
# Backs the validated chunk_* properties added in #1024. Every property
|
||||
# resolves through ``_validated_chunk_config`` which (a) coerces to int
|
||||
# (or falls back to the documented default), (b) enforces the invariants
|
||||
# ``chunk_text()`` needs (chunk_size >= 1, chunk_overlap < chunk_size,
|
||||
# min_chunk_size <= chunk_size). A bad config.json must NEVER hang
|
||||
# ingest — repair, don't raise.
|
||||
|
||||
|
||||
def _write_config(tmp_path, **values):
|
||||
"""Helper: drop a config.json with the given keys into tmp_path."""
|
||||
with open(tmp_path / "config.json", "w") as f:
|
||||
json.dump(values, f)
|
||||
return MempalaceConfig(config_dir=str(tmp_path))
|
||||
|
||||
|
||||
def test_chunk_config_defaults_when_unset(tmp_path):
|
||||
"""No config.json → documented defaults."""
|
||||
cfg = MempalaceConfig(config_dir=str(tmp_path))
|
||||
assert cfg.chunk_size == 800
|
||||
assert cfg.chunk_overlap == 100
|
||||
assert cfg.min_chunk_size == 50
|
||||
|
||||
|
||||
def test_chunk_config_user_overrides_honored(tmp_path):
|
||||
"""Valid file values pass through unchanged."""
|
||||
cfg = _write_config(tmp_path, chunk_size=1200, chunk_overlap=200, min_chunk_size=80)
|
||||
assert cfg.chunk_size == 1200
|
||||
assert cfg.chunk_overlap == 200
|
||||
assert cfg.min_chunk_size == 80
|
||||
|
||||
|
||||
def test_chunk_config_string_coerced_to_int(tmp_path):
|
||||
"""Hand-edited config can drop quotes around numbers — accept ``"1500"``."""
|
||||
cfg = _write_config(tmp_path, chunk_size="1500", chunk_overlap="50")
|
||||
assert cfg.chunk_size == 1500
|
||||
assert cfg.chunk_overlap == 50
|
||||
|
||||
|
||||
def test_chunk_config_garbage_string_falls_back_to_default(tmp_path):
|
||||
cfg = _write_config(tmp_path, chunk_size="not a number")
|
||||
assert cfg.chunk_size == 800 # default, not a crash
|
||||
|
||||
|
||||
def test_chunk_config_bool_falls_back_to_default(tmp_path):
|
||||
"""``bool`` is a subclass of ``int`` in Python — a JSON ``true``
|
||||
would otherwise coerce to 1 and quietly break ingest. Treat as bad
|
||||
input."""
|
||||
cfg = _write_config(tmp_path, chunk_size=True)
|
||||
assert cfg.chunk_size == 800
|
||||
|
||||
|
||||
def test_chunk_config_negative_falls_back(tmp_path):
|
||||
"""Negative chunk_size/min_chunk_size violates ``minimum`` and reverts."""
|
||||
cfg = _write_config(tmp_path, chunk_size=-100, min_chunk_size=-5)
|
||||
assert cfg.chunk_size == 800
|
||||
assert cfg.min_chunk_size == 50
|
||||
|
||||
|
||||
def test_chunk_config_zero_chunk_size_falls_back(tmp_path):
|
||||
"""``chunk_size=0`` would loop forever — must revert to default."""
|
||||
cfg = _write_config(tmp_path, chunk_size=0)
|
||||
assert cfg.chunk_size == 800
|
||||
|
||||
|
||||
def test_chunk_config_overlap_at_or_above_size_repaired(tmp_path):
|
||||
"""``chunk_overlap >= chunk_size`` is the hang condition; repair to
|
||||
the documented default when the default fits, otherwise to
|
||||
``chunk_size - 1``."""
|
||||
cfg = _write_config(tmp_path, chunk_size=900, chunk_overlap=900)
|
||||
assert cfg.chunk_size == 900
|
||||
# 100 (default) fits inside 900 → use the default.
|
||||
assert cfg.chunk_overlap == 100
|
||||
assert cfg.chunk_overlap < cfg.chunk_size
|
||||
|
||||
|
||||
def test_chunk_config_overlap_repair_when_default_doesnt_fit(tmp_path):
|
||||
"""Tiny chunk_size where the default overlap (100) wouldn't fit:
|
||||
repair to ``chunk_size - 1`` instead."""
|
||||
cfg = _write_config(tmp_path, chunk_size=50, chunk_overlap=100)
|
||||
assert cfg.chunk_size == 50
|
||||
assert cfg.chunk_overlap == 49 # max(0, chunk_size - 1)
|
||||
assert cfg.chunk_overlap < cfg.chunk_size
|
||||
|
||||
|
||||
def test_chunk_config_min_chunk_size_above_size_repaired(tmp_path):
|
||||
"""``min_chunk_size > chunk_size`` would silently produce 0 drawers
|
||||
on every ingest — repair to default if it fits, else clamp to
|
||||
chunk_size."""
|
||||
cfg = _write_config(tmp_path, chunk_size=1000, min_chunk_size=2000)
|
||||
assert cfg.min_chunk_size == 50 # default fits inside 1000
|
||||
|
||||
cfg2 = _write_config(tmp_path, chunk_size=20, min_chunk_size=200)
|
||||
assert cfg2.min_chunk_size == 20 # default (50) > chunk_size, clamp
|
||||
|
||||
|
||||
# ── min_chunk_size_explicit (convo-path validated accessor) ────────────
|
||||
# Backs the #1024-review fix: convo_miner must distinguish "user tuned
|
||||
# min_chunk_size" from "untuned" WITHOUT reaching into raw _file_config.
|
||||
# Untuned/unusable → None (convo keeps its 30 floor). Usable → validated
|
||||
# int. A bad key must never reach the convo length-gate / chunk_exchanges
|
||||
# as a non-int and crash ingest.
|
||||
|
||||
|
||||
def test_min_chunk_size_explicit_none_when_unset(tmp_path):
|
||||
cfg = MempalaceConfig(config_dir=str(tmp_path))
|
||||
assert cfg.min_chunk_size_explicit is None
|
||||
|
||||
|
||||
def test_min_chunk_size_explicit_none_when_json_null(tmp_path):
|
||||
"""Explicit JSON ``null`` is treated as untuned (preserves the prior
|
||||
``_file_config.get(...) is None`` sentinel semantics)."""
|
||||
cfg = _write_config(tmp_path, min_chunk_size=None)
|
||||
assert cfg.min_chunk_size_explicit is None
|
||||
|
||||
|
||||
def test_min_chunk_size_explicit_returns_validated_value(tmp_path):
|
||||
cfg = _write_config(tmp_path, min_chunk_size=80)
|
||||
assert cfg.min_chunk_size_explicit == 80
|
||||
|
||||
|
||||
def test_min_chunk_size_explicit_coerces_numeric_string(tmp_path):
|
||||
cfg = _write_config(tmp_path, min_chunk_size="42")
|
||||
assert cfg.min_chunk_size_explicit == 42
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["abc", -5, True, "", " "])
|
||||
def test_min_chunk_size_explicit_none_on_unusable_value(tmp_path, bad):
|
||||
"""Garbage / negative / bool / blank → None, NOT a crash and NOT the
|
||||
miner.py default. convo_miner then falls back to its own 30 floor.
|
||||
This is the exact class of value that used to TypeError the convo
|
||||
length-gate or ValueError out of chunk_exchanges."""
|
||||
cfg = _write_config(tmp_path, min_chunk_size=bad)
|
||||
assert cfg.min_chunk_size_explicit is None
|
||||
|
||||
|
||||
def test_min_chunk_size_explicit_none_when_above_chunk_size(tmp_path):
|
||||
"""min_chunk_size > chunk_size would zero out ingest — treat as
|
||||
unusable so convo falls back to its floor instead."""
|
||||
cfg = _write_config(tmp_path, chunk_size=100, min_chunk_size=500)
|
||||
assert cfg.min_chunk_size_explicit is None
|
||||
|
||||
|
||||
def test_convo_min_chunk_fallback_is_always_safe_int(tmp_path):
|
||||
"""Regression for #1024 review: the convo_miner fallback expression
|
||||
must yield a usable int for ANY config — never a str/bool/negative
|
||||
that would crash the length gate or chunk_exchanges."""
|
||||
from mempalace.convo_miner import MIN_CHUNK_SIZE
|
||||
|
||||
for bad in ("not-a-number", -10, True, {}, []):
|
||||
cfg = _write_config(tmp_path, min_chunk_size=bad)
|
||||
explicit = cfg.min_chunk_size_explicit
|
||||
effective = explicit if explicit is not None else MIN_CHUNK_SIZE
|
||||
assert isinstance(effective, int) and not isinstance(effective, bool)
|
||||
assert effective == MIN_CHUNK_SIZE # untuned floor, no crash
|
||||
|
||||
cfg = _write_config(tmp_path, min_chunk_size=15)
|
||||
explicit = cfg.min_chunk_size_explicit
|
||||
assert (explicit if explicit is not None else MIN_CHUNK_SIZE) == 15
|
||||
|
||||
|
||||
def test_min_chunk_size_explicit_handles_json_infinity(tmp_path):
|
||||
"""JSON ``Infinity`` round-trips to float('inf'); ``int(inf)`` raises
|
||||
OverflowError. That is still garbage config, not a crash — must fall
|
||||
back to None (untuned), same as any other unusable value."""
|
||||
cfg = _write_config(tmp_path, min_chunk_size=float("inf"))
|
||||
assert cfg.min_chunk_size_explicit is None
|
||||
# chunk_size path coerces the same value → documented default, no crash.
|
||||
cfg2 = _write_config(tmp_path, chunk_size=float("inf"))
|
||||
assert cfg2.chunk_size == 800
|
||||
|
||||
|
||||
def test_chunk_text_rejects_non_positive_chunk_size():
|
||||
"""Direct callers (tests, library users) that pass ``chunk_size <= 0``
|
||||
must hit a clear ValueError, not loop forever."""
|
||||
from mempalace.miner import chunk_text
|
||||
|
||||
with pytest.raises(ValueError, match="chunk_size"):
|
||||
chunk_text("some content", "src.txt", chunk_size=0)
|
||||
with pytest.raises(ValueError, match="chunk_size"):
|
||||
chunk_text("some content", "src.txt", chunk_size=-1)
|
||||
|
||||
|
||||
def test_chunk_text_rejects_overlap_at_or_above_size():
|
||||
from mempalace.miner import chunk_text
|
||||
|
||||
with pytest.raises(ValueError, match="chunk_overlap"):
|
||||
chunk_text("some content", "src.txt", chunk_size=100, chunk_overlap=100)
|
||||
with pytest.raises(ValueError, match="chunk_overlap"):
|
||||
chunk_text("some content", "src.txt", chunk_size=100, chunk_overlap=200)
|
||||
|
||||
|
||||
def test_chunk_text_rejects_negative_overlap():
|
||||
from mempalace.miner import chunk_text
|
||||
|
||||
with pytest.raises(ValueError, match="chunk_overlap"):
|
||||
chunk_text("some content", "src.txt", chunk_overlap=-1)
|
||||
|
||||
|
||||
def test_miner_constants_alias_config_defaults():
|
||||
"""Single source of truth: the legacy ``CHUNK_SIZE`` / ``CHUNK_OVERLAP``
|
||||
/ ``MIN_CHUNK_SIZE`` re-exports in ``mempalace.miner`` must equal the
|
||||
canonical ``DEFAULT_CHUNK_*`` constants in ``mempalace.config``.
|
||||
Pinned by this test so a future drift would surface as a unit failure.
|
||||
"""
|
||||
from mempalace.miner import CHUNK_SIZE, CHUNK_OVERLAP, MIN_CHUNK_SIZE
|
||||
from mempalace.config import (
|
||||
DEFAULT_CHUNK_SIZE,
|
||||
DEFAULT_CHUNK_OVERLAP,
|
||||
DEFAULT_MIN_CHUNK_SIZE,
|
||||
)
|
||||
|
||||
assert CHUNK_SIZE == DEFAULT_CHUNK_SIZE == 800
|
||||
assert CHUNK_OVERLAP == DEFAULT_CHUNK_OVERLAP == 100
|
||||
assert MIN_CHUNK_SIZE == DEFAULT_MIN_CHUNK_SIZE == 50
|
||||
|
||||
@@ -77,6 +77,38 @@ def test_mine_convos_does_not_reprocess_empty_chunk_files(capsys):
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
|
||||
def test_mine_convos_allows_general_after_exchange(capsys):
|
||||
"""A transcript mined as exchange can later be mined as general memories."""
|
||||
tmpdir = tempfile.mkdtemp()
|
||||
try:
|
||||
convo_path = Path(tmpdir) / "chat.txt"
|
||||
convo_path.write_text(
|
||||
"> What did we decide?\n"
|
||||
"We decided to use SQLite because it keeps the local setup simple.\n\n"
|
||||
"> What broke?\n"
|
||||
"The search failed because the old index was stale, and the fix was rebuild.\n"
|
||||
)
|
||||
palace_path = os.path.join(tmpdir, "palace")
|
||||
|
||||
mine_convos(tmpdir, palace_path, wing="test", extract_mode="exchange")
|
||||
capsys.readouterr()
|
||||
mine_convos(tmpdir, palace_path, wing="test", extract_mode="general")
|
||||
out = capsys.readouterr().out
|
||||
|
||||
assert "Files skipped (already filed): 0" in out
|
||||
|
||||
client = chromadb.PersistentClient(path=palace_path)
|
||||
col = client.get_collection("mempalace_drawers")
|
||||
resolved = str(Path(tmpdir).resolve() / "chat.txt")
|
||||
rows = col.get(where={"source_file": resolved}, include=["metadatas"])
|
||||
modes = {meta.get("extract_mode") for meta in rows["metadatas"]}
|
||||
assert {"exchange", "general"} <= modes
|
||||
assert any(drawer_id.startswith("drawer_test_decision_") for drawer_id in rows["ids"])
|
||||
del col, client
|
||||
finally:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
|
||||
def test_mine_convos_rebuilds_stale_drawers_after_schema_bump(capsys):
|
||||
"""When stored drawers have an older normalize_version, the next mine
|
||||
silently purges them and refiles — no manual erase required.
|
||||
@@ -140,9 +172,9 @@ def test_mine_convos_rebuilds_stale_drawers_after_schema_bump(capsys):
|
||||
# Second mine — version gate should trigger rebuild
|
||||
mine_convos(tmpdir, palace_path, wing="test")
|
||||
out = capsys.readouterr().out
|
||||
assert (
|
||||
"Files skipped (already filed): 0" in out
|
||||
), "stale drawers should force a rebuild, not a skip"
|
||||
assert "Files skipped (already filed): 0" in out, (
|
||||
"stale drawers should force a rebuild, not a skip"
|
||||
)
|
||||
|
||||
client = chromadb.PersistentClient(path=palace_path)
|
||||
col = client.get_collection("mempalace_drawers")
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"""Unit tests for convo_miner pure functions (no chromadb needed)."""
|
||||
|
||||
import contextlib
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from mempalace.convo_miner import (
|
||||
_file_chunks_locked,
|
||||
@@ -50,6 +53,39 @@ class TestChunkExchanges:
|
||||
# Too short to produce chunks (below MIN_CHUNK_SIZE)
|
||||
assert isinstance(chunks, list)
|
||||
|
||||
def test_chunk_size_zero_raises_valueerror(self):
|
||||
"""Reject chunk_size == 0 explicitly.
|
||||
|
||||
Without this guard, `_chunk_by_exchange` enters an infinite loop:
|
||||
content[:0] is empty, content[0:] is the whole string, and the
|
||||
remainder never shrinks.
|
||||
"""
|
||||
content = (
|
||||
"> What is memory?\nMemory is persistence.\n\n" * 4 # force the split branch
|
||||
)
|
||||
with pytest.raises(ValueError, match="chunk_size must be > 0"):
|
||||
chunk_exchanges(content, chunk_size=0)
|
||||
|
||||
def test_chunk_size_negative_raises_valueerror(self):
|
||||
"""Reject chunk_size < 0. Negative slicing would also loop forever
|
||||
(content[:-1] → all but last, remainder[-1:] → last char repeated)."""
|
||||
content = "> hi\nsome response text here that is long enough to chunk\n\n" * 4
|
||||
with pytest.raises(ValueError, match="chunk_size must be > 0"):
|
||||
chunk_exchanges(content, chunk_size=-10)
|
||||
|
||||
def test_min_chunk_size_negative_raises_valueerror(self):
|
||||
"""Reject min_chunk_size < 0. A negative threshold silently
|
||||
breaks the `if len(part.strip()) > min_chunk_size` gate — every
|
||||
chunk including empty ones gets appended."""
|
||||
with pytest.raises(ValueError, match="min_chunk_size must be >= 0"):
|
||||
chunk_exchanges("> hi\nbye", min_chunk_size=-1)
|
||||
|
||||
def test_min_chunk_size_zero_allowed(self):
|
||||
"""min_chunk_size == 0 is legal — means 'accept any non-empty chunk'."""
|
||||
content = "> What is memory?\nMemory is persistence of information.\n" * 3
|
||||
chunks = chunk_exchanges(content, min_chunk_size=0)
|
||||
assert isinstance(chunks, list)
|
||||
|
||||
def test_long_ai_response_not_truncated(self):
|
||||
"""AI responses longer than 8 lines must be stored in full (verbatim principle)."""
|
||||
lines = [f"Step {i}: important detail that must be stored" for i in range(1, 14)]
|
||||
@@ -115,6 +151,75 @@ class TestScanConvos:
|
||||
files = scan_convos(str(tmp_path))
|
||||
assert files == []
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform == "win32",
|
||||
reason="symlink creation requires elevated privileges on Windows",
|
||||
)
|
||||
def test_scan_convos_logs_skipped_symlinks(self, tmp_path, capsys):
|
||||
real_target = tmp_path / "outside" / "real.jsonl"
|
||||
real_target.parent.mkdir()
|
||||
real_target.write_text('{"role":"user","content":"hi"}\n', encoding="utf-8")
|
||||
link_root = tmp_path / "link_root"
|
||||
link_root.mkdir()
|
||||
(link_root / "link.jsonl").symlink_to(real_target)
|
||||
(link_root / "regular.jsonl").write_text(
|
||||
'{"role":"user","content":"hello"}\n', encoding="utf-8"
|
||||
)
|
||||
|
||||
files = scan_convos(str(link_root))
|
||||
|
||||
names = {f.name for f in files}
|
||||
assert "link.jsonl" not in names
|
||||
assert "regular.jsonl" in names
|
||||
err = capsys.readouterr().err
|
||||
assert err.count("SKIP:") == 1
|
||||
assert " SKIP:" in err
|
||||
assert "link.jsonl" in err
|
||||
assert "(symlink)" in err
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform == "win32",
|
||||
reason="symlink creation requires elevated privileges on Windows",
|
||||
)
|
||||
def test_scan_convos_logs_dangling_symlink(self, tmp_path, capsys):
|
||||
real_target = tmp_path / "outside" / "ghost.jsonl"
|
||||
real_target.parent.mkdir()
|
||||
real_target.touch()
|
||||
link_root = tmp_path / "link_root"
|
||||
link_root.mkdir()
|
||||
(link_root / "dangling.jsonl").symlink_to(real_target)
|
||||
real_target.unlink() # target deleted, link dangles
|
||||
|
||||
files = scan_convos(str(link_root))
|
||||
|
||||
assert files == []
|
||||
err = capsys.readouterr().err
|
||||
assert err.count("SKIP:") == 1
|
||||
assert "dangling.jsonl" in err
|
||||
assert "(symlink)" in err
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform == "win32",
|
||||
reason="symlink creation requires elevated privileges on Windows",
|
||||
)
|
||||
def test_scan_convos_logs_nested_symlink_with_relative_path(self, tmp_path, capsys):
|
||||
real_target = tmp_path / "outside" / "real.jsonl"
|
||||
real_target.parent.mkdir()
|
||||
real_target.write_text('{"x":1}\n', encoding="utf-8")
|
||||
link_root = tmp_path / "link_root"
|
||||
subdir = link_root / "deep" / "subdir"
|
||||
subdir.mkdir(parents=True)
|
||||
(subdir / "nested.jsonl").symlink_to(real_target)
|
||||
|
||||
files = scan_convos(str(link_root))
|
||||
|
||||
assert files == []
|
||||
err = capsys.readouterr().err
|
||||
# Forward slash even on Windows (as_posix) and full relative path,
|
||||
# not just the leaf — proves relative_to(convo_path) over .name.
|
||||
assert "deep/subdir/nested.jsonl" in err
|
||||
assert "(symlink)" in err
|
||||
|
||||
|
||||
class TestFileChunksLocked:
|
||||
def test_uses_bounded_upsert_batches(self, monkeypatch):
|
||||
@@ -134,7 +239,7 @@ class TestFileChunksLocked:
|
||||
col = FakeCol()
|
||||
monkeypatch.setattr(convo_miner, "DRAWER_UPSERT_BATCH_SIZE", 2)
|
||||
monkeypatch.setattr(
|
||||
convo_miner, "file_already_mined", lambda collection, source_file: False
|
||||
convo_miner, "file_already_mined", lambda collection, source_file, **kwargs: False
|
||||
)
|
||||
monkeypatch.setattr(convo_miner, "mine_lock", lambda source_file: contextlib.nullcontext())
|
||||
monkeypatch.setattr(convo_miner, "_detect_hall_cached", lambda content: "conversations")
|
||||
|
||||
+21
-21
@@ -112,17 +112,17 @@ class TestHeuristic:
|
||||
"anthropic's haiku model is cheap enough to run on every drawer",
|
||||
]
|
||||
result = detect_origin_heuristic(samples)
|
||||
assert (
|
||||
result.likely_ai_dialogue is True
|
||||
), f"lowercase brand terms missed; evidence: {result.evidence}"
|
||||
assert result.likely_ai_dialogue is True, (
|
||||
f"lowercase brand terms missed; evidence: {result.evidence}"
|
||||
)
|
||||
# Evidence must show MULTIPLE distinct case-insensitive brand matches.
|
||||
# 'chatgpt' lowercase only matches under case-insensitive search
|
||||
# (the brand list has 'ChatGPT' proper-cased only).
|
||||
evidence_str = " ".join(result.evidence).lower()
|
||||
matched = sum(t in evidence_str for t in ("chatgpt", "anthropic", "haiku", "gemini-pro"))
|
||||
assert (
|
||||
matched >= 2
|
||||
), f"case-insensitive brand matches did not fire — only got: {result.evidence}"
|
||||
assert matched >= 2, (
|
||||
f"case-insensitive brand matches did not fire — only got: {result.evidence}"
|
||||
)
|
||||
|
||||
def test_zodiac_corpus_not_flagged_as_ai(self):
|
||||
"""An astrology forum post with high 'Gemini' density but ZERO
|
||||
@@ -138,9 +138,9 @@ class TestHeuristic:
|
||||
"The Gemini twins in Greek mythology are Castor and Pollux.",
|
||||
]
|
||||
result = detect_origin_heuristic(samples)
|
||||
assert (
|
||||
result.likely_ai_dialogue is False
|
||||
), f"zodiac corpus wrongly flagged AI; evidence: {result.evidence}"
|
||||
assert result.likely_ai_dialogue is False, (
|
||||
f"zodiac corpus wrongly flagged AI; evidence: {result.evidence}"
|
||||
)
|
||||
|
||||
def test_french_novel_with_claude_name_not_flagged(self):
|
||||
"""A French novel where 'Claude' is a character name (Claude is a
|
||||
@@ -155,9 +155,9 @@ class TestHeuristic:
|
||||
"Les amis de Claude s'étaient réunis chez lui pour fêter ses soixante ans.",
|
||||
]
|
||||
result = detect_origin_heuristic(samples)
|
||||
assert (
|
||||
result.likely_ai_dialogue is False
|
||||
), f"French novel wrongly flagged AI; evidence: {result.evidence}"
|
||||
assert result.likely_ai_dialogue is False, (
|
||||
f"French novel wrongly flagged AI; evidence: {result.evidence}"
|
||||
)
|
||||
|
||||
def test_poetry_corpus_with_haiku_sonnet_not_flagged(self):
|
||||
"""A poetry corpus with high 'haiku', 'sonnet', 'opus' density
|
||||
@@ -172,9 +172,9 @@ class TestHeuristic:
|
||||
"Her first opus, published at twenty, was a song cycle for soprano.",
|
||||
]
|
||||
result = detect_origin_heuristic(samples)
|
||||
assert (
|
||||
result.likely_ai_dialogue is False
|
||||
), f"poetry corpus wrongly flagged AI; evidence: {result.evidence}"
|
||||
assert result.likely_ai_dialogue is False, (
|
||||
f"poetry corpus wrongly flagged AI; evidence: {result.evidence}"
|
||||
)
|
||||
|
||||
def test_word_boundary_brand_matching(self):
|
||||
"""Brand-term matching must use word boundaries. Embedded matches
|
||||
@@ -208,9 +208,9 @@ class TestHeuristic:
|
||||
)
|
||||
|
||||
# And classification should be not-AI (no real AI signals present).
|
||||
assert (
|
||||
result.likely_ai_dialogue is False
|
||||
), f"corpus has no real AI signals; evidence: {result.evidence}"
|
||||
assert result.likely_ai_dialogue is False, (
|
||||
f"corpus has no real AI signals; evidence: {result.evidence}"
|
||||
)
|
||||
|
||||
def test_ambiguous_brand_with_unambiguous_signal_flagged(self):
|
||||
"""When an ambiguous brand term ('Gemini') co-occurs with an
|
||||
@@ -224,9 +224,9 @@ class TestHeuristic:
|
||||
"MCP server config: Gemini as primary, OpenAI as fallback.",
|
||||
]
|
||||
result = detect_origin_heuristic(samples)
|
||||
assert (
|
||||
result.likely_ai_dialogue is True
|
||||
), f"ambiguous+unambiguous co-occurrence missed; evidence: {result.evidence}"
|
||||
assert result.likely_ai_dialogue is True, (
|
||||
f"ambiguous+unambiguous co-occurrence missed; evidence: {result.evidence}"
|
||||
)
|
||||
|
||||
|
||||
# ── Tier 2: LLM-assisted (mocked) ─────────────────────────────────────────
|
||||
|
||||
@@ -178,7 +178,7 @@ def test_corpus_origin_reclassifies_personas(
|
||||
# All three personas land in the new bucket.
|
||||
expected_personas = {"Echo", "Sparrow", "Cipher"}
|
||||
assert expected_personas <= persona_names_in_bucket, (
|
||||
f"Expected all three personas in agent_personas, got: " f"{persona_names_in_bucket}"
|
||||
f"Expected all three personas in agent_personas, got: {persona_names_in_bucket}"
|
||||
)
|
||||
|
||||
# And NONE of them remain in the people bucket.
|
||||
@@ -293,8 +293,7 @@ def test_init_pass_zero_writes_origin_json_to_palace(ai_dialogue_corpus: Path, t
|
||||
assert isinstance(data["result"].get("likely_ai_dialogue"), bool)
|
||||
# Fixture is heavy AI-dialogue — heuristic should classify as such.
|
||||
assert data["result"]["likely_ai_dialogue"] is True, (
|
||||
"Heuristic should classify the AI-dialogue fixture as AI-dialogue. "
|
||||
f"Got: {data['result']}"
|
||||
f"Heuristic should classify the AI-dialogue fixture as AI-dialogue. Got: {data['result']}"
|
||||
)
|
||||
|
||||
|
||||
@@ -744,9 +743,9 @@ def test_init_graceful_fallback_when_provider_unavailable(
|
||||
out = capsys.readouterr().out
|
||||
# The fallback message should mention how to silence (--no-llm) so the
|
||||
# user knows what flipped.
|
||||
assert (
|
||||
"no-llm" in out.lower() or "--no-llm" in out
|
||||
), f"Graceful fallback message must point at --no-llm. Got: {out!r}"
|
||||
assert "no-llm" in out.lower() or "--no-llm" in out, (
|
||||
f"Graceful fallback message must point at --no-llm. Got: {out!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_init_graceful_fallback_on_provider_construction_error(
|
||||
@@ -1308,9 +1307,9 @@ def test_integration_llm_refine_corpus_origin_preamble_does_not_break_topic_labe
|
||||
"TOPIC label instructions disappeared from SYSTEM_PROMPT — "
|
||||
"corpus-origin preamble appears to have replaced rather than appended"
|
||||
)
|
||||
assert (
|
||||
"CORPUS CONTEXT" in captured["system"]
|
||||
), "corpus-origin corpus context preamble missing from prompt"
|
||||
assert "CORPUS CONTEXT" in captured["system"], (
|
||||
"corpus-origin corpus context preamble missing from prompt"
|
||||
)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
@@ -1546,12 +1545,12 @@ def test_merge_tier_fields_heuristic_no_no_personas_leak():
|
||||
|
||||
assert wrapped is not None
|
||||
res = wrapped["result"]
|
||||
assert (
|
||||
res["likely_ai_dialogue"] is False
|
||||
), f"Both tiers said NOT AI-dialogue; merged result must be False. Got: {res}"
|
||||
assert (
|
||||
res["agent_persona_names"] == []
|
||||
), f"No personas should leak when both tiers report none. Got: {res}"
|
||||
assert res["likely_ai_dialogue"] is False, (
|
||||
f"Both tiers said NOT AI-dialogue; merged result must be False. Got: {res}"
|
||||
)
|
||||
assert res["agent_persona_names"] == [], (
|
||||
f"No personas should leak when both tiers report none. Got: {res}"
|
||||
)
|
||||
# Heuristic owns confidence. Mocked LLM returned 0.95; heuristic's
|
||||
# narrative-branch confidence is 0.9. Verifying we kept 0.9 catches
|
||||
# any future regression that lets LLM confidence override heuristic.
|
||||
@@ -1609,24 +1608,23 @@ def test_merge_tier_fields_heuristic_yes_llm_yes_combines_evidence():
|
||||
# LLM produced its own; the merged result should include both signal
|
||||
# trails for audit purposes.
|
||||
evidence_text = " ".join(res["evidence"])
|
||||
assert (
|
||||
"LLM-extracted" in evidence_text
|
||||
), f"LLM evidence string missing from merged result. Got: {res['evidence']}"
|
||||
assert "LLM-extracted" in evidence_text, (
|
||||
f"LLM evidence string missing from merged result. Got: {res['evidence']}"
|
||||
)
|
||||
# Heuristic always produces at least one evidence line for AI-dialogue
|
||||
# input (brand-term match), so the combined list has more than just LLM's.
|
||||
assert len(res["evidence"]) >= 2, (
|
||||
f"Combined evidence should include both heuristic + LLM lines. " f"Got: {res['evidence']}"
|
||||
f"Combined evidence should include both heuristic + LLM lines. Got: {res['evidence']}"
|
||||
)
|
||||
# Each entry must carry its tier prefix so on-disk origin.json is
|
||||
# auditable — readers can tell which tier produced which signal line.
|
||||
tier1_lines = [e for e in res["evidence"] if e.startswith("Tier-1 heuristic: ")]
|
||||
tier2_lines = [e for e in res["evidence"] if e.startswith("Tier-2 LLM: ")]
|
||||
assert tier1_lines, (
|
||||
f"Expected at least one 'Tier-1 heuristic: ' prefixed evidence line. "
|
||||
f"Got: {res['evidence']}"
|
||||
f"Expected at least one 'Tier-1 heuristic: ' prefixed evidence line. Got: {res['evidence']}"
|
||||
)
|
||||
assert tier2_lines, (
|
||||
f"Expected at least one 'Tier-2 LLM: ' prefixed evidence line. " f"Got: {res['evidence']}"
|
||||
f"Expected at least one 'Tier-2 LLM: ' prefixed evidence line. Got: {res['evidence']}"
|
||||
)
|
||||
# Every entry should be tier-prefixed (no untagged passthrough).
|
||||
untagged = [
|
||||
@@ -1759,11 +1757,11 @@ def test_init_prints_privacy_warning_when_provider_is_external(
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert "EXTERNAL API" in out, (
|
||||
f"Privacy warning must mention 'EXTERNAL API' when provider is external. " f"Got: {out!r}"
|
||||
f"Privacy warning must mention 'EXTERNAL API' when provider is external. Got: {out!r}"
|
||||
)
|
||||
assert "--no-llm" in out, (
|
||||
f"Privacy warning must point users at --no-llm to opt out. Got: {out!r}"
|
||||
)
|
||||
assert (
|
||||
"--no-llm" in out
|
||||
), f"Privacy warning must point users at --no-llm to opt out. Got: {out!r}"
|
||||
# The warning should also tell users MemPalace isn't responsible
|
||||
# for downstream provider behavior.
|
||||
assert (
|
||||
@@ -1804,7 +1802,7 @@ def test_init_no_privacy_warning_when_provider_is_local(
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert "EXTERNAL API" not in out, (
|
||||
f"Privacy warning fired for a LOCAL provider — should not have. " f"Got: {out!r}"
|
||||
f"Privacy warning fired for a LOCAL provider — should not have. Got: {out!r}"
|
||||
)
|
||||
|
||||
|
||||
@@ -1827,9 +1825,9 @@ def test_init_no_privacy_warning_with_no_llm_flag(ai_dialogue_corpus: Path, tmp_
|
||||
|
||||
mock_get.assert_not_called(), "--no-llm must short-circuit before provider acquisition"
|
||||
out = capsys.readouterr().out
|
||||
assert (
|
||||
"EXTERNAL API" not in out
|
||||
), f"Privacy warning fired on --no-llm path — should not have. Got: {out!r}"
|
||||
assert "EXTERNAL API" not in out, (
|
||||
f"Privacy warning fired on --no-llm path — should not have. Got: {out!r}"
|
||||
)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
@@ -1988,9 +1986,9 @@ def test_init_accept_external_llm_flag_bypasses_consent_prompt(
|
||||
"--accept-external-llm must bypass the consent prompt for "
|
||||
"non-interactive / CI use. input() was called anyway."
|
||||
)
|
||||
assert (
|
||||
fake_provider.classify.called
|
||||
), "With --accept-external-llm, init must proceed with the LLM."
|
||||
assert fake_provider.classify.called, (
|
||||
"With --accept-external-llm, init must proceed with the LLM."
|
||||
)
|
||||
|
||||
|
||||
def test_init_no_consent_prompt_when_endpoint_is_local(
|
||||
|
||||
@@ -7,6 +7,7 @@ onnxruntime.InferenceSession to keep CI fast and network-free.
|
||||
Skipped when the multilingual extra isn't installed (huggingface_hub/
|
||||
tokenizers/numpy) — CI runs only core deps by default.
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
@@ -192,7 +193,9 @@ def test_cache_key_separates_models(monkeypatch):
|
||||
ml_again = embedding.get_embedding_function(device="cpu", model="minilm")
|
||||
|
||||
assert ml is ml_again, "minilm should cache-hit on second call"
|
||||
assert isinstance(eg, embedding.EmbeddinggemmaONNX), "embeddinggemma should not collide with minilm cache"
|
||||
assert isinstance(eg, embedding.EmbeddinggemmaONNX), (
|
||||
"embeddinggemma should not collide with minilm cache"
|
||||
)
|
||||
assert ml is not eg
|
||||
|
||||
|
||||
|
||||
@@ -115,6 +115,52 @@ def test_save_preserves_previous_on_serialization_failure(tmp_path, monkeypatch)
|
||||
# Restore os.replace before reading so the assertion can rely on it.
|
||||
monkeypatch.setattr(_os, "replace", real_replace)
|
||||
assert target.read_text(encoding="utf-8") == original
|
||||
# The .tmp sidecar must also be cleaned up — otherwise it litters the
|
||||
# palace directory and a future diagnostic cannot distinguish stale
|
||||
# debris from an in-flight write.
|
||||
leftover = list(tmp_path.glob("entity_registry.json.tmp*"))
|
||||
assert leftover == [], f"atomic write leaked tmp on rename failure: {leftover}"
|
||||
|
||||
|
||||
def test_save_cleans_tmp_on_write_failure(tmp_path, monkeypatch):
|
||||
# Failure BEFORE the rename (disk full, FUSE break, IO error during
|
||||
# write/fsync) must also clean up the .tmp sidecar. The existing
|
||||
# rename-failure test only covers the post-write path; this exercises
|
||||
# the gap between write and rename.
|
||||
registry = EntityRegistry.load(config_dir=tmp_path)
|
||||
registry.seed(
|
||||
mode="personal",
|
||||
people=[{"name": "Alice", "relationship": "friend", "context": "personal"}],
|
||||
projects=[],
|
||||
)
|
||||
registry.save()
|
||||
target = tmp_path / "entity_registry.json"
|
||||
original = target.read_text(encoding="utf-8")
|
||||
|
||||
# Force os.fsync to raise — simulates IO error after the bytes are in
|
||||
# the kernel page cache but before they hit the platter.
|
||||
import os as _os
|
||||
|
||||
real_fsync = _os.fsync
|
||||
|
||||
def boom(fd):
|
||||
raise OSError("simulated fsync failure")
|
||||
|
||||
monkeypatch.setattr(_os, "fsync", boom)
|
||||
with pytest.raises(OSError):
|
||||
registry.seed(
|
||||
mode="personal",
|
||||
people=[{"name": "Bob", "relationship": "friend", "context": "personal"}],
|
||||
projects=[],
|
||||
)
|
||||
registry.save()
|
||||
monkeypatch.setattr(_os, "fsync", real_fsync)
|
||||
|
||||
# Previous registry intact (rename never happened — atomic guarantee).
|
||||
assert target.read_text(encoding="utf-8") == original
|
||||
# And the .tmp sidecar is gone, not litter on disk.
|
||||
leftover = list(tmp_path.glob("entity_registry.json.tmp*"))
|
||||
assert leftover == [], f"atomic write leaked tmp on fsync failure: {leftover}"
|
||||
|
||||
|
||||
# ── seed ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -111,3 +111,48 @@ def test_quarantine_leaves_reasonable_payload_in_place(tmp_path):
|
||||
|
||||
assert moved == []
|
||||
assert seg_dir.exists()
|
||||
|
||||
|
||||
def test_segment_health_rejects_zero_byte_link_lists_with_payload(tmp_path):
|
||||
"""Regression #1457: real HNSW payload with empty link_lists.bin is corrupt."""
|
||||
seg_dir = tmp_path / "11111111-2222-3333-4444-555555555555"
|
||||
|
||||
_write_segment(
|
||||
seg_dir,
|
||||
data_size=2_000,
|
||||
link_size=0,
|
||||
write_metadata=True,
|
||||
)
|
||||
|
||||
assert not _segment_appears_healthy(str(seg_dir))
|
||||
|
||||
|
||||
def test_quarantine_catches_zero_byte_link_lists_when_stale(tmp_path):
|
||||
"""Regression #1457: stale segments with empty link_lists.bin are quarantined."""
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
|
||||
db_path = palace / "chroma.sqlite3"
|
||||
db_path.write_text("sqlite placeholder")
|
||||
|
||||
seg_dir = palace / "11111111-2222-3333-4444-555555555555"
|
||||
_write_segment(
|
||||
seg_dir,
|
||||
data_size=2_000,
|
||||
link_size=0,
|
||||
write_metadata=True,
|
||||
)
|
||||
|
||||
hnsw_time = 1_700_000_000
|
||||
sqlite_time = hnsw_time + 1_000
|
||||
os.utime(seg_dir / "data_level0.bin", (hnsw_time, hnsw_time))
|
||||
os.utime(db_path, (sqlite_time, sqlite_time))
|
||||
|
||||
moved = quarantine_stale_hnsw(str(palace), stale_seconds=300)
|
||||
|
||||
assert len(moved) == 1
|
||||
assert not seg_dir.exists()
|
||||
|
||||
moved_path = Path(moved[0])
|
||||
assert moved_path.exists()
|
||||
assert moved_path.name.startswith("11111111-2222-3333-4444-555555555555.drift-")
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
"""Regression tests for the bash 3.2 compatibility fix (#1440).
|
||||
|
||||
The legacy hooks/*.sh scripts run on the user's system. On stock macOS
|
||||
that is GNU bash 3.2.57 (Apple GPLv3 freeze, 2006). Using bash 4.0-only
|
||||
builtins like ``mapfile`` silently breaks parsing: every JSON field
|
||||
falls back to its default, the hook logs ``Session unknown: 0 exchanges``,
|
||||
and zero drawers are saved.
|
||||
|
||||
These tests cover:
|
||||
1. Source-level shape (mapfile/readarray absent, sed-based extraction).
|
||||
2. Behavioral parse contract (session_id reaches the log, not 'unknown').
|
||||
3. The fail-loud guard: fires only when the parser sentinel is missing,
|
||||
never on a legitimately empty/unicode/literal-'unknown' session_id.
|
||||
4. The guard's disk discipline (bounded dump, overwrite-not-append, 0600).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
SAVE_HOOK = REPO_ROOT / "hooks" / "mempal_save_hook.sh"
|
||||
PRECOMPACT_HOOK = REPO_ROOT / "hooks" / "mempal_precompact_hook.sh"
|
||||
|
||||
# Re-used by every parametrize decorator that runs the same test against
|
||||
# both hooks. ``ids=`` keeps pytest output readable (`...[save_hook]`
|
||||
# rather than the default `hook0`/`hook1`).
|
||||
_BOTH_HOOKS = pytest.mark.parametrize(
|
||||
"hook",
|
||||
[SAVE_HOOK, PRECOMPACT_HOOK],
|
||||
ids=["save_hook", "precompact_hook"],
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.skipif(os.name == "nt", reason="bash hook scripts are POSIX-only")
|
||||
|
||||
|
||||
def _hook_src_no_comments(hook: Path) -> str:
|
||||
return "\n".join(
|
||||
line for line in hook.read_text().splitlines() if not line.lstrip().startswith("#")
|
||||
)
|
||||
|
||||
|
||||
def _run_hook(
|
||||
hook: Path,
|
||||
stdin: str,
|
||||
home: Path,
|
||||
*,
|
||||
expected_rc: int = 0,
|
||||
extra_env: dict | None = None,
|
||||
) -> tuple[str, str]:
|
||||
"""Run a hook with a controlled environment and assert its exit code.
|
||||
|
||||
Returns ``(stdout, stderr)``. On unexpected exit the assertion message
|
||||
surfaces the captured stderr so CI failures are not silent. The hook's
|
||||
primary diagnostic stream is ``$STATE_DIR/hook.log`` plus the two
|
||||
sidecar dumps ``last_input.log`` / ``last_python_err.log``; the
|
||||
subprocess's stderr is typically empty on the documented exit paths
|
||||
and is captured here only to surface unexpected interpreter failures
|
||||
(e.g., a bash syntax error on a future edit).
|
||||
|
||||
Forces ``umask 0o022`` in the child so the hook's own ``umask 077``
|
||||
inside the parse subshell is provably the sole reason the diagnostic
|
||||
files end up at mode 0600 — without this, a permissive ambient umask
|
||||
on the CI runner would mask a regression that drops the in-hook
|
||||
``umask`` line.
|
||||
"""
|
||||
env = {
|
||||
"HOME": str(home),
|
||||
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
|
||||
}
|
||||
if extra_env:
|
||||
env.update(extra_env)
|
||||
p = subprocess.run(
|
||||
["bash", str(hook)],
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env=env,
|
||||
timeout=30,
|
||||
preexec_fn=lambda: os.umask(0o022),
|
||||
)
|
||||
assert p.returncode == expected_rc, (
|
||||
f"{hook.name} exited {p.returncode} (expected {expected_rc}); "
|
||||
f"stderr={p.stderr!r}; stdout={p.stdout!r}"
|
||||
)
|
||||
return p.stdout, p.stderr
|
||||
|
||||
|
||||
class TestNoBash4OnlyBuiltins:
|
||||
"""Source-level regression: bash 4.0 array-read builtins are unavailable on macOS bash 3.2."""
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_no_mapfile(self, hook):
|
||||
code = _hook_src_no_comments(hook)
|
||||
assert "mapfile" not in code, (
|
||||
f"{hook.name} uses mapfile, unavailable on macOS /bin/bash 3.2 (#1440)"
|
||||
)
|
||||
assert "readarray" not in code, (
|
||||
f"{hook.name} uses readarray, unavailable on macOS /bin/bash 3.2 (#1440)"
|
||||
)
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_sed_extraction_present(self, hook):
|
||||
# Strip ``#`` line comments before counting so the assertion fails
|
||||
# if all live ``sed -n 'Np'`` calls are deleted but the explanatory
|
||||
# comments above the parse block (which mention ``sed -n 'Np'``
|
||||
# several times in prose) are left behind — otherwise the test
|
||||
# would false-pass on a regression that swapped the extraction
|
||||
# method back to ``mapfile`` while keeping the old commentary.
|
||||
src = _hook_src_no_comments(hook)
|
||||
# Each hook reads at least two values via ``sed -n 'Np'`` (sentinel + session_id).
|
||||
assert src.count("sed -n '") >= 2, (
|
||||
f"{hook.name} must use sed -n 'Np' for POSIX-portable line extraction"
|
||||
)
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_bash_syntax_clean(self, hook):
|
||||
p = subprocess.run(
|
||||
["bash", "-n", str(hook)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert p.returncode == 0, f"{hook.name} syntax error: {p.stderr}"
|
||||
|
||||
|
||||
class TestSessionIdExtraction:
|
||||
"""Hook must parse session_id from valid JSON, not fall back to 'unknown'."""
|
||||
|
||||
def test_save_hook_extracts_session_id(self, tmp_path):
|
||||
out, _ = _run_hook(
|
||||
SAVE_HOOK,
|
||||
json.dumps(
|
||||
{"session_id": "abc12345", "stop_hook_active": False, "transcript_path": ""}
|
||||
),
|
||||
tmp_path,
|
||||
)
|
||||
# Stdout must be valid JSON; Claude Code parses it. A regression that
|
||||
# leaks debug output here would silently break the harness contract.
|
||||
assert json.loads(out) == {}, f"hook stdout must be valid JSON, got: {out!r}"
|
||||
log = (tmp_path / ".mempalace" / "hook_state" / "hook.log").read_text()
|
||||
assert "Session abc12345:" in log, f"got fallback 'unknown'; log was: {log!r}"
|
||||
# Negative cross-check: the sentinel-distinguishes-success-from-failure
|
||||
# contract has no value if the guard fires on the happy path too.
|
||||
assert "WARN: input parse failed" not in log
|
||||
state_dir = tmp_path / ".mempalace" / "hook_state"
|
||||
assert not (state_dir / "last_input.log").exists()
|
||||
assert not (state_dir / "last_python_err.log").exists(), (
|
||||
"successful parse must leave no last_python_err.log behind"
|
||||
)
|
||||
|
||||
def test_precompact_hook_extracts_session_id(self, tmp_path):
|
||||
out, _ = _run_hook(
|
||||
PRECOMPACT_HOOK,
|
||||
json.dumps({"session_id": "abc12345", "transcript_path": ""}),
|
||||
tmp_path,
|
||||
)
|
||||
assert json.loads(out) == {}, f"hook stdout must be valid JSON, got: {out!r}"
|
||||
log = (tmp_path / ".mempalace" / "hook_state" / "hook.log").read_text()
|
||||
assert "PRE-COMPACT triggered for session abc12345" in log
|
||||
assert "WARN: input parse failed" not in log
|
||||
state_dir = tmp_path / ".mempalace" / "hook_state"
|
||||
assert not (state_dir / "last_input.log").exists()
|
||||
assert not (state_dir / "last_python_err.log").exists(), (
|
||||
"successful parse must leave no last_python_err.log behind"
|
||||
)
|
||||
|
||||
|
||||
class TestFailLoudGuard:
|
||||
"""Non-parseable stdin must dump the input and warn in hook.log so
|
||||
future silent failures are loud, and the dump must stay bounded and
|
||||
user-private. The guard must NOT fire on legitimately empty inputs
|
||||
or on sanitizer-stripped session_ids (#1440)."""
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_malformed_input_logs_warning_and_dumps_input(self, hook, tmp_path):
|
||||
_run_hook(hook, "not-json garbage", tmp_path)
|
||||
state_dir = tmp_path / ".mempalace" / "hook_state"
|
||||
log = (state_dir / "hook.log").read_text()
|
||||
last_input = (state_dir / "last_input.log").read_text()
|
||||
assert "WARN: input parse failed (sentinel missing)" in log
|
||||
assert "not-json garbage" in last_input
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_empty_stdin_does_not_dump_or_warn(self, hook, tmp_path):
|
||||
"""Empty stdin is a legitimate state (e.g. a hook re-fire on Stop
|
||||
with no message body). The guard's ``[ -n "$INPUT" ]`` short-circuit
|
||||
must hold so nothing is written to last_input.log."""
|
||||
_run_hook(hook, "", tmp_path)
|
||||
state_dir = tmp_path / ".mempalace" / "hook_state"
|
||||
assert not (state_dir / "last_input.log").exists()
|
||||
log_path = state_dir / "hook.log"
|
||||
if log_path.exists():
|
||||
assert "WARN: input parse failed" not in log_path.read_text()
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_unicode_session_id_does_not_trip_guard(self, hook, tmp_path):
|
||||
"""A session_id with non-ASCII characters (Cyrillic, CJK, emoji)
|
||||
is stripped by the sanitizer to '', defaults to 'unknown'. The
|
||||
sentinel still printed, so the guard must skip and NOT spam disk.
|
||||
Parametrized over both hooks: each has its own inline Python
|
||||
parser and its own sanitizer regex, so a copy-paste regression
|
||||
in only one would otherwise be invisible. The precompact parser
|
||||
ignores the ``stop_hook_active`` key, so the same payload works
|
||||
for both."""
|
||||
_run_hook(
|
||||
hook,
|
||||
json.dumps({"session_id": "сессия", "stop_hook_active": False, "transcript_path": ""}),
|
||||
tmp_path,
|
||||
)
|
||||
state_dir = tmp_path / ".mempalace" / "hook_state"
|
||||
assert not (state_dir / "last_input.log").exists(), (
|
||||
"unicode-only session_id sanitized to empty must NOT trip the guard"
|
||||
)
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_literal_unknown_session_id_does_not_trip_guard(self, hook, tmp_path):
|
||||
"""A user who literally passes session_id='unknown' is parsing
|
||||
cleanly; the sentinel-based guard must distinguish that from a
|
||||
crash and skip the dump. Parametrized over both hooks for the
|
||||
same reason as the unicode test: the sentinel logic is duplicated
|
||||
between the two parsers."""
|
||||
_run_hook(
|
||||
hook,
|
||||
json.dumps({"session_id": "unknown", "stop_hook_active": False, "transcript_path": ""}),
|
||||
tmp_path,
|
||||
)
|
||||
state_dir = tmp_path / ".mempalace" / "hook_state"
|
||||
assert not (state_dir / "last_input.log").exists(), (
|
||||
"literal session_id='unknown' must NOT trip the guard"
|
||||
)
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_dump_is_bounded_and_overwritten(self, hook, tmp_path):
|
||||
"""The dump caps at exactly 4096 bytes and overwrites on each
|
||||
failure so a repeating misconfiguration cannot grow the file
|
||||
unbounded. Both payloads here are intentionally not-valid-JSON so
|
||||
the guard fires on each call — the overwrite contract is what
|
||||
is being tested, not the validation logic. Parametrized over
|
||||
both hooks because each hook has its own ``head -c 4096 > ...``
|
||||
line — a future edit that flips one to ``>>`` would not be caught
|
||||
by a save-only test."""
|
||||
# 4097 bytes: one over the cap, proves the cutoff fires at exactly
|
||||
# 4096 (a regression that silently shrinks the cap to e.g. 1024
|
||||
# would slip past a looser ``<= 4096`` check).
|
||||
big_payload = "x" * 4097
|
||||
_run_hook(hook, big_payload, tmp_path)
|
||||
last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log"
|
||||
assert last_input.stat().st_size == 4096, (
|
||||
f"cap must be exactly 4096 bytes; got {last_input.stat().st_size}"
|
||||
)
|
||||
# Second failure with a smaller payload (also not valid JSON, so the
|
||||
# guard fires) overwrites the first; the file shrinks instead of
|
||||
# accumulating.
|
||||
_run_hook(hook, "tiny", tmp_path)
|
||||
assert last_input.exists(), "second guard fire must produce a file, not skip the write"
|
||||
assert last_input.read_text() == "tiny", "dump must overwrite on each failure, not append"
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_dump_cap_holds_under_utf8_locale(self, hook, tmp_path):
|
||||
"""Under a UTF-8 locale, a multibyte payload of 2000 CJK chars =
|
||||
6000 bytes would slip a character-counted substring (`${var:0:N}`)
|
||||
past the 4096-byte cap. The hook uses ``head -c`` precisely so
|
||||
the bound stays byte-based regardless of locale."""
|
||||
# ``C.UTF-8`` is available on every mainstream Linux distribution
|
||||
# (Debian/Ubuntu, Fedora, RHEL 8+, Alpine via musl) and macOS
|
||||
# bash falls back to the byte-based C locale gracefully;
|
||||
# ``en_US.UTF-8`` would silently degrade to no-op on minimal CI
|
||||
# images (Alpine, distroless) where that locale is not generated.
|
||||
# 2000 copies of U+4E2D (3 bytes each in UTF-8) = 6000 bytes.
|
||||
big_payload = "中" * 2000
|
||||
_run_hook(
|
||||
hook,
|
||||
big_payload,
|
||||
tmp_path,
|
||||
extra_env={"LANG": "C.UTF-8", "LC_ALL": "C.UTF-8"},
|
||||
)
|
||||
last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log"
|
||||
size = last_input.stat().st_size
|
||||
assert size == 4096, (
|
||||
f"UTF-8 payload must still cap at 4096 bytes (got {size}); "
|
||||
"regression to ${var:0:N} would let multibyte input bypass the bound"
|
||||
)
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_dump_is_not_world_readable(self, hook, tmp_path):
|
||||
"""The dump mirrors the raw hook payload (transcript_path reveals
|
||||
the user's home + project layout). Permissions must be 600 so
|
||||
other users on a shared box cannot read it."""
|
||||
_run_hook(hook, "not-json garbage", tmp_path)
|
||||
last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log"
|
||||
mode = stat.S_IMODE(last_input.stat().st_mode)
|
||||
assert mode == 0o600, f"last_input.log mode should be 0600, got {oct(mode)}"
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_python_stderr_captured_on_parse_failure(self, hook, tmp_path):
|
||||
"""When the inline Python parser crashes (malformed JSON, missing
|
||||
interpreter, future regression), its stderr must land in
|
||||
last_python_err.log so a debugger can distinguish 'bad user
|
||||
input' from 'broken interpreter or broken inline script'."""
|
||||
_run_hook(hook, "not-json garbage", tmp_path)
|
||||
err_log = tmp_path / ".mempalace" / "hook_state" / "last_python_err.log"
|
||||
assert err_log.exists(), "Python stderr must be captured on parse failure"
|
||||
contents = err_log.read_text()
|
||||
# Python's json.load raises JSONDecodeError with a recognizable
|
||||
# traceback. Don't pin the exact message (it varies by Python
|
||||
# version) but assert at least one canonical marker is present.
|
||||
assert "Traceback" in contents or "json" in contents.lower(), (
|
||||
f"expected Python traceback or json error, got: {contents!r}"
|
||||
)
|
||||
|
||||
@_BOTH_HOOKS
|
||||
def test_python_stderr_log_is_not_world_readable_on_failure(self, hook, tmp_path):
|
||||
"""The stderr capture mirrors the privacy expectation of
|
||||
last_input.log: on a populated failure write it must be 0600."""
|
||||
_run_hook(hook, "not-json garbage", tmp_path)
|
||||
err_log = tmp_path / ".mempalace" / "hook_state" / "last_python_err.log"
|
||||
mode = stat.S_IMODE(err_log.stat().st_mode)
|
||||
assert mode == 0o600, f"last_python_err.log mode should be 0600 on failure, got {oct(mode)}"
|
||||
+191
-8
@@ -31,6 +31,39 @@ from mempalace.hooks_cli import (
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolated_existing_palace_root(monkeypatch, tmp_path):
|
||||
"""Give every test an isolated, *existing* PALACE_ROOT/STATE_DIR.
|
||||
|
||||
Regression for #1510: nine save / log / precompact tests assumed
|
||||
``~/.mempalace`` existed and only passed in the full suite because an
|
||||
earlier test file (``test_cli.py``) created it as a side effect, so
|
||||
the ``_palace_root_exists()`` kill-switch was satisfied. Run in
|
||||
isolation they short-circuited and failed.
|
||||
|
||||
Defaulting every test to a per-test palace root that exists makes
|
||||
them robust on their own and protects future tests from the same
|
||||
trap. ``_MINE_PID_DIR`` is patched too: it is derived from
|
||||
``STATE_DIR`` *at module import* (hooks_cli.py:277), so patching
|
||||
``STATE_DIR`` alone would leave mine-spawning tests writing PID files
|
||||
under the import-time location instead of the per-test root. The
|
||||
state dir is created so the docstring's "existing" promise holds.
|
||||
|
||||
Tests that exercise the absent-root kill-switch path call
|
||||
``_redirect_palace_root`` (or set their own PALACE_ROOT) *after* this
|
||||
fixture; ``monkeypatch``'s last-write-wins means they keep their
|
||||
absent/file root and teardown still restores the real module value.
|
||||
"""
|
||||
root = tmp_path / ".mempalace"
|
||||
state_dir = root / "hook_state"
|
||||
state_dir.mkdir(parents=True, exist_ok=True)
|
||||
monkeypatch.setattr(hooks_cli_mod, "PALACE_ROOT", root)
|
||||
monkeypatch.setattr(hooks_cli_mod, "STATE_DIR", state_dir)
|
||||
monkeypatch.setattr(hooks_cli_mod, "_MINE_PID_DIR", state_dir / "mine_pids")
|
||||
monkeypatch.setattr(hooks_cli_mod, "_state_dir_initialized", False)
|
||||
return root
|
||||
|
||||
|
||||
# --- _mempalace_python ---
|
||||
|
||||
|
||||
@@ -328,21 +361,171 @@ def test_wing_from_transcript_path_lowercases():
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_non_projects_layout():
|
||||
# Linux users with code under ~/dev/, ~/src/, ~/code/ — no -Projects- segment.
|
||||
# Project name is the final dash-separated token of the encoded folder.
|
||||
# Linux user with code under ~/dev/. The encoded form ``dev-MemPalace-mempalace``
|
||||
# is ambiguous between ``~/dev/MemPalace/mempalace/`` (project = mempalace) and
|
||||
# ``~/dev/MemPalace-mempalace/`` (hyphenated single-name project). With no JSONL
|
||||
# cwd to disambiguate, we preserve all post-``dev-`` segments rather than silently
|
||||
# truncating to the last token (which would drop ``MemPalace`` here and collide
|
||||
# with any other ``-mempalace`` leaf elsewhere on the system).
|
||||
path = "/home/igor/.claude/projects/-home-igor-dev-MemPalace-mempalace/session.jsonl"
|
||||
assert _wing_from_transcript_path(path) == "wing_mempalace"
|
||||
assert _wing_from_transcript_path(path) == "wing_mempalace_mempalace"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_macos_users_layout():
|
||||
# macOS ~/ layout without a Projects/ segment.
|
||||
# macOS ~/ layout without a Projects/ segment — single-token project name
|
||||
# so the heuristic produces the same result as the leaf-only approach.
|
||||
path = "/Users/alice/.claude/projects/-Users-alice-code-MyApp/session.jsonl"
|
||||
assert _wing_from_transcript_path(path) == "wing_myapp"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_nested_deep():
|
||||
# Deep tree: ``-home-bob-work-clients-acme-frontend``. Without JSONL cwd we
|
||||
# can't tell whether ``frontend`` is the project, ``acme-frontend`` is a
|
||||
# hyphenated project, or the project lives several levels in. Strip the
|
||||
# user-home and one common parent (``work-``), then keep the remaining
|
||||
# path as the wing — collision-safe even if multiple clients have a
|
||||
# ``frontend/`` subdir.
|
||||
path = "/home/bob/.claude/projects/-home-bob-work-clients-acme-frontend/session.jsonl"
|
||||
assert _wing_from_transcript_path(path) == "wing_frontend"
|
||||
assert _wing_from_transcript_path(path) == "wing_clients_acme_frontend"
|
||||
|
||||
|
||||
# --- _wing_from_transcript_path: hyphenated project names (issue #1410) ---
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_hyphenated_claude_code():
|
||||
"""Regression: ``claude-code`` was truncated to ``wing_code`` (#1410)."""
|
||||
path = "/Users/me/.claude/projects/-Users-me-claude-code/abc.jsonl"
|
||||
assert _wing_from_transcript_path(path) == "wing_claude_code"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_hyphenated_react_native():
|
||||
"""Regression: ``react-native`` was truncated to ``wing_native`` (#1410)."""
|
||||
path = "/Users/me/.claude/projects/-Users-me-react-native/abc.jsonl"
|
||||
assert _wing_from_transcript_path(path) == "wing_react_native"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_no_collision_between_hyphenated_siblings():
|
||||
"""Regression: ``customer-portal`` and ``admin-portal`` both truncated to
|
||||
``wing_portal`` under the old heuristic, merging diary entries from two
|
||||
independent projects into one wing (#1410)."""
|
||||
customer = _wing_from_transcript_path(
|
||||
"/Users/me/.claude/projects/-Users-me-customer-portal/abc.jsonl"
|
||||
)
|
||||
admin = _wing_from_transcript_path(
|
||||
"/Users/me/.claude/projects/-Users-me-admin-portal/abc.jsonl"
|
||||
)
|
||||
assert customer == "wing_customer_portal"
|
||||
assert admin == "wing_admin_portal"
|
||||
assert customer != admin
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_strips_parent_dir_with_hyphenated_project():
|
||||
"""Reporter's example: ``-home-alice-projects-react-native`` should keep
|
||||
the full project name after stripping the ``projects-`` parent (#1410)."""
|
||||
path = "/home/alice/.claude/projects/-home-alice-projects-react-native/abc.jsonl"
|
||||
assert _wing_from_transcript_path(path) == "wing_react_native"
|
||||
|
||||
|
||||
# --- _wing_from_transcript_path: cwd-from-JSONL primary path ---
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_uses_cwd_from_jsonl(tmp_path):
|
||||
"""When the JSONL records ``cwd``, the leaf segment of cwd is the wing —
|
||||
even if the encoded folder name would have produced a different (and
|
||||
noisier) wing."""
|
||||
# Encoded folder says ``-home-igor-dev-MemPalace-mempalace`` (would yield
|
||||
# ``wing_mempalace_mempalace`` via fallback), but cwd is the truth.
|
||||
project_dir = tmp_path / "-home-igor-dev-MemPalace-mempalace"
|
||||
project_dir.mkdir()
|
||||
transcript = project_dir / "session.jsonl"
|
||||
transcript.write_text(
|
||||
'{"type":"queue-operation","operation":"enqueue","timestamp":"2026-05-09T00:00:00Z"}\n'
|
||||
'{"type":"user","cwd":"/home/igor/dev/MemPalace/mempalace","content":"hi"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert _wing_from_transcript_path(str(transcript)) == "wing_mempalace"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_cwd_with_hyphenated_project(tmp_path):
|
||||
"""cwd primary path correctly handles hyphenated project names without
|
||||
truncation."""
|
||||
project_dir = tmp_path / "-Users-me-claude-code"
|
||||
project_dir.mkdir()
|
||||
transcript = project_dir / "session.jsonl"
|
||||
transcript.write_text(
|
||||
'{"type":"user","cwd":"/Users/me/git/claude-code","content":"hi"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert _wing_from_transcript_path(str(transcript)) == "wing_claude_code"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_cwd_skips_lines_without_cwd(tmp_path):
|
||||
"""Lines that lack ``cwd`` (queue-operation, etc.) are skipped; the first
|
||||
line that records cwd wins."""
|
||||
project_dir = tmp_path / "-Users-me-foo"
|
||||
project_dir.mkdir()
|
||||
transcript = project_dir / "session.jsonl"
|
||||
lines = [
|
||||
'{"type":"queue-operation","operation":"enqueue"}',
|
||||
'{"type":"queue-operation","operation":"dequeue"}',
|
||||
'{"type":"queue-operation","operation":"complete"}',
|
||||
'{"type":"tool_use","cwd":"/Users/me/work/real-project","content":"ok"}',
|
||||
'{"type":"user","cwd":"/Users/me/somewhere-else","content":"later"}',
|
||||
]
|
||||
transcript.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
# First cwd record wins (line 4, real-project).
|
||||
assert _wing_from_transcript_path(str(transcript)) == "wing_real_project"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_cwd_falls_back_when_no_cwd_in_jsonl(tmp_path):
|
||||
"""If no JSONL line has cwd, fall through to the encoded-folder heuristic."""
|
||||
project_dir = tmp_path / "-Users-me-no-cwd-project"
|
||||
project_dir.mkdir()
|
||||
transcript = project_dir / "session.jsonl"
|
||||
transcript.write_text(
|
||||
'{"type":"queue-operation","operation":"enqueue"}\n'
|
||||
'{"type":"queue-operation","operation":"complete"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
# tmp_path leaks into the path before .claude/projects, so the regex
|
||||
# won't match and we hit the wing_sessions default. The point of this
|
||||
# test: the cwd reader doesn't crash and returns None cleanly.
|
||||
result = _wing_from_transcript_path(str(transcript))
|
||||
assert result == "wing_sessions"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_cwd_handles_malformed_jsonl(tmp_path):
|
||||
"""Malformed JSON lines must not crash the wing extraction."""
|
||||
project_dir = tmp_path / "-Users-me-broken-project"
|
||||
project_dir.mkdir()
|
||||
transcript = project_dir / "session.jsonl"
|
||||
transcript.write_text(
|
||||
"this is not json at all\n"
|
||||
'{"type":"broken",\n' # truncated mid-record
|
||||
'{"type":"valid","cwd":"/Users/me/git/clean-name","content":"ok"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert _wing_from_transcript_path(str(transcript)) == "wing_clean_name"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_cwd_handles_missing_file():
|
||||
"""Nonexistent transcript path falls back cleanly to the encoded heuristic."""
|
||||
path = "/Users/me/.claude/projects/-Users-me-claude-code/does-not-exist.jsonl"
|
||||
assert _wing_from_transcript_path(path) == "wing_claude_code"
|
||||
|
||||
|
||||
def test_wing_from_transcript_path_cwd_handles_non_string_cwd(tmp_path):
|
||||
"""A cwd field that isn't a string (e.g. null, number) must be skipped."""
|
||||
project_dir = tmp_path / "-Users-me-fallback-name"
|
||||
project_dir.mkdir()
|
||||
transcript = project_dir / "session.jsonl"
|
||||
transcript.write_text(
|
||||
'{"type":"x","cwd":null}\n'
|
||||
'{"type":"x","cwd":42}\n'
|
||||
'{"type":"x","cwd":"/Users/me/git/proper-name"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert _wing_from_transcript_path(str(transcript)) == "wing_proper_name"
|
||||
|
||||
|
||||
# --- _log ---
|
||||
@@ -700,9 +883,9 @@ def test_spawn_mine_releases_slot_on_oserror(tmp_path):
|
||||
with patch("mempalace.hooks_cli.subprocess.Popen", side_effect=OSError("spawn fail")):
|
||||
with pytest.raises(OSError):
|
||||
_spawn_mine(cmd)
|
||||
assert (
|
||||
not pid_file.exists()
|
||||
), "slot must be released so the next hook fire isn't permanently blocked"
|
||||
assert not pid_file.exists(), (
|
||||
"slot must be released so the next hook fire isn't permanently blocked"
|
||||
)
|
||||
|
||||
|
||||
def test_spawn_mine_passes_pid_file_env_var(tmp_path):
|
||||
|
||||
+12
-12
@@ -123,13 +123,13 @@ class TestMempalPythonOverride:
|
||||
{"session_id": "abc", "stop_hook_active": False, "transcript_path": ""},
|
||||
env_overrides={"MEMPAL_PYTHON": str(fake), "HOME": str(tmp_path)},
|
||||
)
|
||||
assert (
|
||||
result.returncode == 0
|
||||
), f"hook exited non-zero: stderr={result.stderr!r} stdout={result.stdout!r}"
|
||||
assert result.returncode == 0, (
|
||||
f"hook exited non-zero: stderr={result.stderr!r} stdout={result.stdout!r}"
|
||||
)
|
||||
invocations = marker.read_text().splitlines() if marker.exists() else []
|
||||
assert (
|
||||
"override_python" in invocations
|
||||
), f"MEMPAL_PYTHON override was not used. Marker log: {invocations!r}"
|
||||
assert "override_python" in invocations, (
|
||||
f"MEMPAL_PYTHON override was not used. Marker log: {invocations!r}"
|
||||
)
|
||||
|
||||
def test_ignores_override_when_not_executable(self, tmp_path):
|
||||
"""If MEMPAL_PYTHON is set but the file isn't executable, the
|
||||
@@ -143,9 +143,9 @@ class TestMempalPythonOverride:
|
||||
{"session_id": "abc", "stop_hook_active": False, "transcript_path": ""},
|
||||
env_overrides={"MEMPAL_PYTHON": str(bogus), "HOME": str(tmp_path)},
|
||||
)
|
||||
assert (
|
||||
result.returncode == 0
|
||||
), f"hook crashed on non-executable MEMPAL_PYTHON: {result.stderr!r}"
|
||||
assert result.returncode == 0, (
|
||||
f"hook crashed on non-executable MEMPAL_PYTHON: {result.stderr!r}"
|
||||
)
|
||||
|
||||
def test_falls_back_to_path_when_unset(self, tmp_path):
|
||||
"""With MEMPAL_PYTHON unset, the hook uses whatever ``python3``
|
||||
@@ -165,6 +165,6 @@ class TestMempalPythonOverride:
|
||||
)
|
||||
assert result.returncode == 0
|
||||
invocations = marker.read_text().splitlines() if marker.exists() else []
|
||||
assert (
|
||||
"python3" in invocations
|
||||
), f"fallback-to-PATH did not use the shimmed python3. Marker log: {invocations!r}"
|
||||
assert "python3" in invocations, (
|
||||
f"fallback-to-PATH did not use the shimmed python3. Marker log: {invocations!r}"
|
||||
)
|
||||
|
||||
@@ -79,8 +79,7 @@ class TestCandidateUnion:
|
||||
result = search_memories(_NARRATIVE_QUERY, palace, n_results=5, candidate_strategy="union")
|
||||
ids = [h["source_file"] for h in result["results"]]
|
||||
assert "brand_voice_D4.md" in ids, (
|
||||
"union mode must surface BM25-strong docs even when vector signal "
|
||||
f"is weak; got {ids}"
|
||||
f"union mode must surface BM25-strong docs even when vector signal is weak; got {ids}"
|
||||
)
|
||||
|
||||
def test_union_preserves_vector_hits(self, tmp_path):
|
||||
@@ -138,9 +137,9 @@ class TestCandidateUnion:
|
||||
# 4-doc corpus, n_results=2 → union pool can grow to ~8 candidates,
|
||||
# rerank reorders them, but final list must respect the cap.
|
||||
result = search_memories(_NARRATIVE_QUERY, palace, n_results=2, candidate_strategy="union")
|
||||
assert (
|
||||
len(result["results"]) <= 2
|
||||
), f"union must trim to n_results=2; got {len(result['results'])} results"
|
||||
assert len(result["results"]) <= 2, (
|
||||
f"union must trim to n_results=2; got {len(result['results'])} results"
|
||||
)
|
||||
|
||||
def test_union_skipped_when_max_distance_set(self, tmp_path):
|
||||
"""``max_distance`` is a vector-distance threshold; BM25-only
|
||||
|
||||
+3
-3
@@ -155,7 +155,7 @@ def test_direct_address_key_is_singular_string_for_all_locales():
|
||||
)
|
||||
if "direct_address_pattern" in section:
|
||||
val = section["direct_address_pattern"]
|
||||
assert isinstance(
|
||||
val, str
|
||||
), f"{lang}: 'direct_address_pattern' must be str, got {type(val).__name__}"
|
||||
assert isinstance(val, str), (
|
||||
f"{lang}: 'direct_address_pattern' must be str, got {type(val).__name__}"
|
||||
)
|
||||
assert val, f"{lang}: 'direct_address_pattern' is empty"
|
||||
|
||||
@@ -74,9 +74,9 @@ def test_get_entity_patterns_shares_cache_across_cases():
|
||||
cache_keys = list(i18n._entity_cache.keys())
|
||||
get_entity_patterns(("ZH-CN",))
|
||||
get_entity_patterns(("zh-cn",))
|
||||
assert len(i18n._entity_cache) == len(
|
||||
cache_keys
|
||||
), "different casings of the same language must not create new cache entries"
|
||||
assert len(i18n._entity_cache) == len(cache_keys), (
|
||||
"different casings of the same language must not create new cache entries"
|
||||
)
|
||||
|
||||
|
||||
def test_unknown_language_still_falls_back_to_english():
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""__init__-level guards that must take effect before transitive imports."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
_LEAK_PREFIX = "/__mempalace_leak_test_sentinel__"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"pythonpath",
|
||||
[
|
||||
f"{_LEAK_PREFIX}/single",
|
||||
f"{_LEAK_PREFIX}/a{os.pathsep}{_LEAK_PREFIX}/b",
|
||||
f"{_LEAK_PREFIX}/with-trailing{os.sep}",
|
||||
f"{os.pathsep}{_LEAK_PREFIX}/leading-sep",
|
||||
".",
|
||||
"",
|
||||
None,
|
||||
],
|
||||
ids=["single", "multi", "trailing-sep", "leading-pathsep", "dot", "empty", "unset"],
|
||||
)
|
||||
def test_init_filters_sys_path_from_leaked_pythonpath(pythonpath):
|
||||
"""Package init must remove sentinel-prefixed entries from sys.path
|
||||
so transitive imports do not pull compiled extensions from the
|
||||
leaked PYTHONPATH. os.environ['PYTHONPATH'] is left intact so host
|
||||
applications embedding mempalace as a library keep their env for
|
||||
their own subprocesses; the env strip lives in the CLI/MCP entry
|
||||
points (see test_cli.py / test_mcp_server.py).
|
||||
|
||||
Asserts on the sentinel substring directly so the test does not
|
||||
couple to the production normalization logic. The dot/empty/unset
|
||||
cases additionally exercise the early-return / collision paths
|
||||
without crashing."""
|
||||
env = os.environ.copy()
|
||||
if pythonpath is None:
|
||||
env.pop("PYTHONPATH", None)
|
||||
else:
|
||||
env["PYTHONPATH"] = pythonpath
|
||||
code = (
|
||||
"import mempalace, os, sys; "
|
||||
f"prefix = {_LEAK_PREFIX!r}; "
|
||||
"mempalace_parent = os.path.dirname(os.path.dirname(mempalace.__file__)); "
|
||||
"print('ENV:', repr(os.environ.get('PYTHONPATH'))); "
|
||||
"print('SENTINEL_IN_PATH:', any(prefix in (p or '') for p in sys.path)); "
|
||||
"print('MEMPALACE_PARENT_PRESENT:', any("
|
||||
"os.path.normcase(os.path.normpath(p)) == os.path.normcase(os.path.normpath(mempalace_parent)) "
|
||||
"for p in sys.path if p))"
|
||||
)
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", code],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
diag = (
|
||||
f"input={pythonpath!r}; rc={result.returncode}; "
|
||||
f"stdout={result.stdout!r}; stderr={result.stderr!r}"
|
||||
)
|
||||
assert result.returncode == 0, f"subprocess failed: {diag}"
|
||||
out = result.stdout
|
||||
# Env must be preserved verbatim: embedded callers may need it.
|
||||
expected_env = repr(pythonpath) if pythonpath is not None else repr(None)
|
||||
assert f"ENV: {expected_env}" in out, (
|
||||
f"PYTHONPATH should be preserved by package import: {diag}"
|
||||
)
|
||||
assert "SENTINEL_IN_PATH: False" in out, f"sentinel-prefix leak: {diag}"
|
||||
# Filter must not over-strip: the mempalace package itself must remain
|
||||
# importable, so its parent directory must survive on sys.path.
|
||||
assert "MEMPALACE_PARENT_PRESENT: True" in out, (
|
||||
f"filter over-stripped sys.path (mempalace parent gone): {diag}"
|
||||
)
|
||||
|
||||
|
||||
def test_init_preserves_cwd_marker_when_pythonpath_collides():
|
||||
"""PYTHONPATH='.' normalizes to the same value as the empty-string
|
||||
CWD marker on sys.path. The strip must remove '.' from sys.path
|
||||
without collapsing the implicit current-directory entry."""
|
||||
env = os.environ.copy()
|
||||
env["PYTHONPATH"] = "."
|
||||
code = (
|
||||
"import mempalace, sys; "
|
||||
"print('CWD_IN_PATH:', '' in sys.path); "
|
||||
"print('DOT_IN_PATH:', '.' in sys.path)"
|
||||
)
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", code],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
diag = f"rc={result.returncode}; stdout={result.stdout!r}; stderr={result.stderr!r}"
|
||||
assert result.returncode == 0, f"subprocess failed: {diag}"
|
||||
assert "CWD_IN_PATH: True" in result.stdout, f"cwd marker dropped: {diag}"
|
||||
assert "DOT_IN_PATH: False" in result.stdout, f"dot leak survived: {diag}"
|
||||
+12
-12
@@ -445,9 +445,9 @@ def test_openai_compat_api_key_source_flag_when_explicit(monkeypatch):
|
||||
monkeypatch.setenv("OPENAI_API_KEY", "sk-from-env-irrelevant")
|
||||
p = OpenAICompatProvider(model="x", endpoint="http://h", api_key="sk-from-flag")
|
||||
assert p.api_key == "sk-from-flag"
|
||||
assert (
|
||||
p.api_key_source == "flag"
|
||||
), f"Explicit api_key arg must produce api_key_source='flag'; got {p.api_key_source!r}"
|
||||
assert p.api_key_source == "flag", (
|
||||
f"Explicit api_key arg must produce api_key_source='flag'; got {p.api_key_source!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_openai_compat_api_key_source_env_when_fallback(monkeypatch):
|
||||
@@ -458,9 +458,9 @@ def test_openai_compat_api_key_source_env_when_fallback(monkeypatch):
|
||||
monkeypatch.setenv("OPENAI_API_KEY", "sk-from-env")
|
||||
p = OpenAICompatProvider(model="x", endpoint="http://h")
|
||||
assert p.api_key == "sk-from-env"
|
||||
assert (
|
||||
p.api_key_source == "env"
|
||||
), f"Env-fallback api_key must produce api_key_source='env'; got {p.api_key_source!r}"
|
||||
assert p.api_key_source == "env", (
|
||||
f"Env-fallback api_key must produce api_key_source='env'; got {p.api_key_source!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_anthropic_api_key_source_tracking(monkeypatch):
|
||||
@@ -468,14 +468,14 @@ def test_anthropic_api_key_source_tracking(monkeypatch):
|
||||
passed explicitly, 'env' when resolved from ANTHROPIC_API_KEY env."""
|
||||
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-env")
|
||||
p_flag = AnthropicProvider(model="claude-haiku", api_key="sk-ant-flag")
|
||||
assert (
|
||||
p_flag.api_key_source == "flag"
|
||||
), f"Explicit api_key must produce 'flag'; got {p_flag.api_key_source!r}"
|
||||
assert p_flag.api_key_source == "flag", (
|
||||
f"Explicit api_key must produce 'flag'; got {p_flag.api_key_source!r}"
|
||||
)
|
||||
p_env = AnthropicProvider(model="claude-haiku")
|
||||
assert p_env.api_key == "sk-ant-env"
|
||||
assert (
|
||||
p_env.api_key_source == "env"
|
||||
), f"Env-fallback must produce 'env'; got {p_env.api_key_source!r}"
|
||||
assert p_env.api_key_source == "env", (
|
||||
f"Env-fallback must produce 'env'; got {p_env.api_key_source!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_ollama_api_key_source_is_none():
|
||||
|
||||
+1007
-10
File diff suppressed because it is too large
Load Diff
@@ -78,6 +78,6 @@ def test_mcp_server_no_stdout_noise_on_clean_exit():
|
||||
capture_output=True,
|
||||
timeout=60,
|
||||
)
|
||||
assert (
|
||||
proc.stdout == b""
|
||||
), f"stdout must be empty before the first JSON-RPC response, but got: {proc.stdout!r}"
|
||||
assert proc.stdout == b"", (
|
||||
f"stdout must be empty before the first JSON-RPC response, but got: {proc.stdout!r}"
|
||||
)
|
||||
|
||||
+87
-1
@@ -1,10 +1,16 @@
|
||||
"""Tests for destructive-operation safety in mempalace.migrate."""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from mempalace.migrate import collection_write_roundtrip_works, _restore_stale_palace, migrate
|
||||
from mempalace.migrate import (
|
||||
_restore_stale_palace,
|
||||
collection_write_roundtrip_works,
|
||||
extract_drawers_from_sqlite,
|
||||
migrate,
|
||||
)
|
||||
|
||||
|
||||
def test_migrate_requires_palace_database(tmp_path, capsys):
|
||||
@@ -157,6 +163,38 @@ def test_collection_write_roundtrip_fails_when_delete_silently_drops():
|
||||
assert len(col.ids) == 1
|
||||
|
||||
|
||||
def _make_minimal_chromadb_sqlite(tmp_path):
|
||||
"""Build a SQLite file with the minimal schema extract_drawers_from_sqlite reads."""
|
||||
db = tmp_path / "chroma.sqlite3"
|
||||
conn = sqlite3.connect(str(db))
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE embeddings (id INTEGER PRIMARY KEY, embedding_id TEXT);
|
||||
CREATE TABLE embedding_metadata (
|
||||
id INTEGER, key TEXT,
|
||||
string_value TEXT, int_value INTEGER,
|
||||
float_value REAL, bool_value INTEGER
|
||||
);
|
||||
INSERT INTO embeddings VALUES (1, 'd-001');
|
||||
INSERT INTO embedding_metadata VALUES (1, 'chroma:document', 'hello', NULL, NULL, NULL);
|
||||
INSERT INTO embedding_metadata VALUES (1, 'wing', 'personal', NULL, NULL, NULL);
|
||||
INSERT INTO embedding_metadata VALUES (1, 'room', '2026-04-26', NULL, NULL, NULL);
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return str(db)
|
||||
|
||||
|
||||
def test_extract_drawers_returns_drawers(tmp_path):
|
||||
db_path = _make_minimal_chromadb_sqlite(tmp_path)
|
||||
drawers = extract_drawers_from_sqlite(db_path)
|
||||
assert len(drawers) == 1
|
||||
assert drawers[0]["id"] == "d-001"
|
||||
assert drawers[0]["document"] == "hello"
|
||||
assert drawers[0]["metadata"] == {"wing": "personal", "room": "2026-04-26"}
|
||||
|
||||
|
||||
def test_migrate_dry_run_rebuilds_when_collection_is_readable_but_not_writable(tmp_path, capsys):
|
||||
palace_dir = tmp_path / "palace"
|
||||
palace_dir.mkdir()
|
||||
@@ -200,3 +238,51 @@ def test_migrate_dry_run_rebuilds_when_collection_is_readable_but_not_writable(t
|
||||
assert "Rebuilding from SQLite" in out
|
||||
assert "Extracted 1 drawers from SQLite" in out
|
||||
assert "DRY RUN" in out
|
||||
|
||||
|
||||
def test_migrate_cleans_temp_palace_on_chromadb_failure(tmp_path):
|
||||
"""If chromadb fails after the temp palace is created, mkdtemp's
|
||||
directory must be removed — without try/finally it leaked into the
|
||||
system temp root forever."""
|
||||
import tempfile as _tempfile
|
||||
|
||||
palace_dir = tmp_path / "palace"
|
||||
palace_dir.mkdir()
|
||||
(palace_dir / "chroma.sqlite3").write_text("db")
|
||||
|
||||
captured_temp_paths = []
|
||||
real_mkdtemp = _tempfile.mkdtemp
|
||||
|
||||
def tracking_mkdtemp(*args, **kwargs):
|
||||
path = real_mkdtemp(*args, **kwargs)
|
||||
captured_temp_paths.append(path)
|
||||
return path
|
||||
|
||||
failing_backend = MagicMock()
|
||||
# First ChromaBackend().get_collection() must raise so we drop into
|
||||
# the SQL-extraction path; the second ChromaBackend().get_or_create_collection()
|
||||
# raises to trigger the cleanup we are testing.
|
||||
failing_backend.get_collection.side_effect = Exception("unreadable")
|
||||
failing_backend.get_or_create_collection.side_effect = RuntimeError("chromadb boom")
|
||||
|
||||
import mempalace.backends.chroma as _chroma_mod
|
||||
|
||||
with (
|
||||
patch("mempalace.migrate.detect_chromadb_version", return_value="0.5.x"),
|
||||
patch(
|
||||
"mempalace.migrate.extract_drawers_from_sqlite",
|
||||
return_value=[{"id": "id1", "document": "doc", "metadata": {"wing": "w", "room": "r"}}],
|
||||
),
|
||||
patch("builtins.input", return_value="y"),
|
||||
patch("mempalace.migrate.shutil.copytree"),
|
||||
patch("mempalace.migrate.tempfile.mkdtemp", side_effect=tracking_mkdtemp),
|
||||
patch.object(_chroma_mod, "ChromaBackend", return_value=failing_backend),
|
||||
):
|
||||
try:
|
||||
migrate(str(palace_dir), confirm=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
assert captured_temp_paths, "mkdtemp was never called — flow short-circuited"
|
||||
for p in captured_temp_paths:
|
||||
assert not os.path.exists(p), f"temp palace was not cleaned up: {p}"
|
||||
|
||||
+185
-4
@@ -1,14 +1,16 @@
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import chromadb
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from mempalace.miner import detect_room, load_config, mine, scan_project, status
|
||||
from mempalace.palace import NORMALIZE_VERSION, file_already_mined
|
||||
from mempalace.palace import NORMALIZE_VERSION, file_already_mined, prefetch_mined_set
|
||||
|
||||
|
||||
def write_file(path: Path, content: str):
|
||||
@@ -253,6 +255,74 @@ def test_scan_project_skip_dirs_still_apply_without_override():
|
||||
shutil.rmtree(tmpdir)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform == "win32",
|
||||
reason="symlink creation requires elevated privileges on Windows",
|
||||
)
|
||||
def test_scan_project_logs_skipped_symlinks(tmp_path, capsys):
|
||||
project_root = tmp_path / "proj"
|
||||
project_root.mkdir()
|
||||
real_target = tmp_path / "outside" / "real.md"
|
||||
write_file(real_target, "real content\n" * 5)
|
||||
(project_root / "link.md").symlink_to(real_target)
|
||||
write_file(project_root / "regular.md", "regular content\n" * 5)
|
||||
|
||||
files = scanned_files(project_root, respect_gitignore=False)
|
||||
|
||||
assert "link.md" not in files
|
||||
assert "regular.md" in files
|
||||
err = capsys.readouterr().err
|
||||
assert err.count("SKIP:") == 1
|
||||
assert " SKIP:" in err
|
||||
assert "link.md" in err
|
||||
assert "(symlink)" in err
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform == "win32",
|
||||
reason="symlink creation requires elevated privileges on Windows",
|
||||
)
|
||||
def test_scan_project_logs_dangling_symlink(tmp_path, capsys):
|
||||
project_root = tmp_path / "proj"
|
||||
project_root.mkdir()
|
||||
real_target = tmp_path / "outside" / "ghost.md"
|
||||
real_target.parent.mkdir()
|
||||
real_target.touch()
|
||||
(project_root / "dangling.md").symlink_to(real_target)
|
||||
real_target.unlink() # target deleted, link dangles
|
||||
|
||||
files = scanned_files(project_root, respect_gitignore=False)
|
||||
|
||||
assert files == []
|
||||
err = capsys.readouterr().err
|
||||
assert err.count("SKIP:") == 1
|
||||
assert "dangling.md" in err
|
||||
assert "(symlink)" in err
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform == "win32",
|
||||
reason="symlink creation requires elevated privileges on Windows",
|
||||
)
|
||||
def test_scan_project_logs_nested_symlink_with_relative_path(tmp_path, capsys):
|
||||
project_root = tmp_path / "proj"
|
||||
project_root.mkdir()
|
||||
real_target = tmp_path / "outside" / "real.md"
|
||||
write_file(real_target, "real content\n" * 5)
|
||||
deep = project_root / "deep" / "subdir"
|
||||
deep.mkdir(parents=True)
|
||||
(deep / "nested.md").symlink_to(real_target)
|
||||
|
||||
files = scanned_files(project_root, respect_gitignore=False)
|
||||
|
||||
assert files == []
|
||||
err = capsys.readouterr().err
|
||||
# Forward slash even on Windows (as_posix) and full relative path,
|
||||
# not just the leaf — proves relative_to(project_path) over .name.
|
||||
assert "deep/subdir/nested.md" in err
|
||||
assert "(symlink)" in err
|
||||
|
||||
|
||||
def test_entity_metadata_finds_cyrillic_names(monkeypatch):
|
||||
"""Entity extraction must find non-Latin names when entity_languages includes the locale."""
|
||||
import mempalace.palace as palace_mod
|
||||
@@ -336,6 +406,82 @@ def test_file_already_mined_check_mtime():
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
|
||||
def test_file_already_mined_scopes_convo_extract_mode():
|
||||
tmpdir = tempfile.mkdtemp()
|
||||
try:
|
||||
palace_path = os.path.join(tmpdir, "palace")
|
||||
os.makedirs(palace_path)
|
||||
client = chromadb.PersistentClient(path=palace_path)
|
||||
col = client.get_or_create_collection(
|
||||
"mempalace_drawers", metadata={"hnsw:space": "cosine"}
|
||||
)
|
||||
|
||||
source_file = os.path.join(tmpdir, "chat.jsonl")
|
||||
col.add(
|
||||
ids=["exchange"],
|
||||
documents=["exchange drawer"],
|
||||
metadatas=[
|
||||
{
|
||||
"source_file": source_file,
|
||||
"extract_mode": "exchange",
|
||||
"normalize_version": NORMALIZE_VERSION,
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
assert file_already_mined(col, source_file, extract_mode="exchange") is True
|
||||
assert file_already_mined(col, source_file, extract_mode="general") is False
|
||||
assert source_file in prefetch_mined_set(col, extract_mode="exchange")
|
||||
assert source_file not in prefetch_mined_set(col, extract_mode="general")
|
||||
|
||||
col.add(
|
||||
ids=["general"],
|
||||
documents=["general drawer"],
|
||||
metadatas=[
|
||||
{
|
||||
"source_file": source_file,
|
||||
"extract_mode": "general",
|
||||
"normalize_version": NORMALIZE_VERSION,
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
assert file_already_mined(col, source_file, extract_mode="general") is True
|
||||
assert source_file in prefetch_mined_set(col, extract_mode="general")
|
||||
finally:
|
||||
del col, client
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
|
||||
def test_file_already_mined_extract_mode_paginates_large_sources():
|
||||
source_file = "/tmp/long-chat.jsonl"
|
||||
metadatas = [
|
||||
{
|
||||
"source_file": source_file,
|
||||
"extract_mode": "exchange",
|
||||
"normalize_version": NORMALIZE_VERSION,
|
||||
}
|
||||
for _ in range(1000)
|
||||
]
|
||||
metadatas.append(
|
||||
{
|
||||
"source_file": source_file,
|
||||
"extract_mode": "general",
|
||||
"normalize_version": NORMALIZE_VERSION,
|
||||
}
|
||||
)
|
||||
|
||||
class FakeCollection:
|
||||
def get(self, where=None, limit=1, offset=0, include=None):
|
||||
batch = metadatas[offset : offset + limit]
|
||||
return {
|
||||
"ids": [f"id-{i}" for i in range(offset, offset + len(batch))],
|
||||
"metadatas": batch,
|
||||
}
|
||||
|
||||
assert file_already_mined(FakeCollection(), source_file, extract_mode="general") is True
|
||||
|
||||
|
||||
def test_mine_dry_run_with_tiny_file_no_crash():
|
||||
"""Dry-run must not crash when process_file returns 0 drawers (room was None)."""
|
||||
tmpdir = tempfile.mkdtemp()
|
||||
@@ -372,6 +518,41 @@ def test_status_missing_palace_does_not_create_empty_collection(tmp_path, capsys
|
||||
assert not palace_path.exists()
|
||||
|
||||
|
||||
def test_status_initialized_but_empty_palace_reports_empty(tmp_path, capsys):
|
||||
"""State C from #1498: palace dir + chroma.sqlite3 exist but no drawers
|
||||
have been mined yet. status() must print the 'initialized but empty'
|
||||
message and suggest `mempalace mine`, not the misleading 'No palace
|
||||
found' / 'Run init' message."""
|
||||
import chromadb
|
||||
|
||||
palace_path = tmp_path / "empty-palace"
|
||||
palace_path.mkdir()
|
||||
chromadb.PersistentClient(path=str(palace_path)) # creates chroma.sqlite3
|
||||
assert (palace_path / "chroma.sqlite3").is_file()
|
||||
|
||||
status(str(palace_path))
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert "initialized but empty" in out
|
||||
assert "mempalace mine" in out
|
||||
assert "No palace found" not in out
|
||||
|
||||
|
||||
def test_status_palace_dir_without_db_reports_uninitialized(tmp_path, capsys):
|
||||
"""State B from #1498: palace dir exists but chroma.sqlite3 is absent.
|
||||
Helper must short-circuit before invoking chromadb (which would lazily
|
||||
create the DB file as a side effect of a read-only inspection)."""
|
||||
palace_path = tmp_path / "no-db-palace"
|
||||
palace_path.mkdir()
|
||||
|
||||
status(str(palace_path))
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert "has no chroma.sqlite3 yet" in out
|
||||
# Side-effect check: chromadb was never touched.
|
||||
assert list(palace_path.iterdir()) == []
|
||||
|
||||
|
||||
def test_status_handles_none_metadata_without_crash(tmp_path, capsys):
|
||||
"""status must not crash when col.get returns a None entry in metadatas.
|
||||
|
||||
@@ -392,7 +573,7 @@ def test_status_handles_none_metadata_without_crash(tmp_path, capsys):
|
||||
"metadatas": [{"wing": "proj", "room": "r"}, None],
|
||||
}
|
||||
|
||||
with patch("mempalace.miner.get_collection", return_value=FakeCol()):
|
||||
with patch("mempalace.miner._open_collection_or_explain", return_value=FakeCol()):
|
||||
status(str(tmp_path))
|
||||
|
||||
out = capsys.readouterr().out
|
||||
@@ -423,7 +604,7 @@ def test_process_file_uses_bounded_upsert_batches(tmp_path, monkeypatch):
|
||||
chunks = [{"content": f"chunk {i} " * 20, "chunk_index": i} for i in range(5)]
|
||||
col = FakeCol()
|
||||
monkeypatch.setattr(miner, "DRAWER_UPSERT_BATCH_SIZE", 2)
|
||||
monkeypatch.setattr(miner, "chunk_text", lambda content, source_file: chunks)
|
||||
monkeypatch.setattr(miner, "chunk_text", lambda content, source_file, **kwargs: chunks)
|
||||
monkeypatch.setattr(miner, "detect_hall", lambda content: "code")
|
||||
monkeypatch.setattr(miner, "_extract_entities_for_metadata", lambda content: "")
|
||||
|
||||
@@ -819,7 +1000,7 @@ def test_process_file_skips_when_chunks_exceed_max(tmp_path, monkeypatch):
|
||||
|
||||
monkeypatch.setattr(miner, "MAX_CHUNKS_PER_FILE", 5)
|
||||
over_cap = [{"content": f"chunk {i}", "chunk_index": i} for i in range(7)]
|
||||
monkeypatch.setattr(miner, "chunk_text", lambda content, source_file: over_cap)
|
||||
monkeypatch.setattr(miner, "chunk_text", lambda content, source_file, **kwargs: over_cap)
|
||||
|
||||
source = tmp_path / "huge.csv"
|
||||
source.write_text("col1,col2\n" + "x,y\n" * 500, encoding="utf-8")
|
||||
|
||||
@@ -1336,11 +1336,7 @@ class TestStripNoiseRemovesSystemChrome:
|
||||
|
||||
def test_strips_line_anchored_system_reminder_block(self):
|
||||
text = (
|
||||
"> User:\n"
|
||||
"<system-reminder>\n"
|
||||
"Auto-save reminder...\n"
|
||||
"</system-reminder>\n"
|
||||
"> Real message."
|
||||
"> User:\n<system-reminder>\nAuto-save reminder...\n</system-reminder>\n> Real message."
|
||||
)
|
||||
out = strip_noise(text)
|
||||
assert "system-reminder" not in out
|
||||
@@ -1350,7 +1346,7 @@ class TestStripNoiseRemovesSystemChrome:
|
||||
def test_strips_system_reminder_with_blockquote_prefix(self):
|
||||
# _messages_to_transcript prefixes lines with "> ", so the line
|
||||
# anchor must also accept that shape.
|
||||
text = "> User:\n" "> <system-reminder>Injected noise</system-reminder>\n" "> Real message."
|
||||
text = "> User:\n> <system-reminder>Injected noise</system-reminder>\n> Real message."
|
||||
out = strip_noise(text)
|
||||
assert "Injected noise" not in out
|
||||
assert "Real message." in out
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Tests for mempalace.palace shared helpers."""
|
||||
|
||||
import chromadb
|
||||
|
||||
from mempalace.backends import CollectionNotInitializedError, PalaceNotFoundError
|
||||
from mempalace.palace import _open_collection_or_explain, get_collection
|
||||
|
||||
|
||||
def _capture():
|
||||
"""Return (emit, lines) — emit appends to lines for inspection."""
|
||||
lines: list[str] = []
|
||||
return lines.append, lines
|
||||
|
||||
|
||||
def test_open_collection_or_explain_state_a_missing_dir(tmp_path):
|
||||
"""State A: palace dir does not exist."""
|
||||
emit, lines = _capture()
|
||||
missing = tmp_path / "no-such-palace"
|
||||
|
||||
result = _open_collection_or_explain(str(missing), out=emit)
|
||||
|
||||
assert result is None
|
||||
assert any("No palace found" in line for line in lines)
|
||||
assert any("mempalace init" in line for line in lines)
|
||||
# Helper must not create the directory.
|
||||
assert not missing.exists()
|
||||
|
||||
|
||||
def test_open_collection_or_explain_state_b_no_db(tmp_path):
|
||||
"""State B: dir exists but chroma.sqlite3 does not.
|
||||
|
||||
Critical invariant: the helper must NOT trigger chromadb's lazy DB
|
||||
creation by reaching the backend. The dir must remain empty after
|
||||
the call so a read-only inspection stays read-only.
|
||||
"""
|
||||
emit, lines = _capture()
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
assert not (palace / "chroma.sqlite3").exists()
|
||||
|
||||
result = _open_collection_or_explain(str(palace), out=emit)
|
||||
|
||||
assert result is None
|
||||
assert any("has no chroma.sqlite3 yet" in line for line in lines)
|
||||
# No side-effect: backend was not invoked.
|
||||
assert list(palace.iterdir()) == []
|
||||
|
||||
|
||||
def test_open_collection_or_explain_state_c_no_collection(tmp_path):
|
||||
"""State C: DB file exists but the collection has never been created."""
|
||||
emit, lines = _capture()
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
chromadb.PersistentClient(path=str(palace)) # creates DB, no collection
|
||||
assert (palace / "chroma.sqlite3").is_file()
|
||||
|
||||
result = _open_collection_or_explain(str(palace), out=emit)
|
||||
|
||||
assert result is None
|
||||
assert any("initialized but empty" in line for line in lines)
|
||||
assert any("mempalace mine" in line for line in lines)
|
||||
|
||||
|
||||
def test_open_collection_or_explain_state_d_healthy(tmp_path):
|
||||
"""State D: healthy palace — returns the opened collection silently."""
|
||||
emit, lines = _capture()
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
get_collection(str(palace), create=True) # bootstrap collection
|
||||
|
||||
result = _open_collection_or_explain(str(palace), out=emit)
|
||||
|
||||
assert result is not None
|
||||
assert lines == [] # healthy path is silent
|
||||
|
||||
|
||||
def test_open_collection_or_explain_state_e_unexpected_error(tmp_path, monkeypatch):
|
||||
"""State E: unexpected error opening the backend routes to repair hint."""
|
||||
emit, lines = _capture()
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
(palace / "chroma.sqlite3").touch() # pass the isfile guard
|
||||
|
||||
def boom(*args, **kwargs):
|
||||
raise RuntimeError("disk on fire")
|
||||
|
||||
monkeypatch.setattr("mempalace.palace.get_collection", boom)
|
||||
|
||||
result = _open_collection_or_explain(str(palace), out=emit)
|
||||
|
||||
assert result is None
|
||||
assert any("Error opening palace" in line for line in lines)
|
||||
assert any("repair-status" in line for line in lines)
|
||||
|
||||
|
||||
def test_open_collection_or_explain_default_sink_is_print(tmp_path, capsys):
|
||||
"""When out is None, messages go through builtin print → stdout."""
|
||||
missing = tmp_path / "no-such-palace"
|
||||
|
||||
result = _open_collection_or_explain(str(missing))
|
||||
|
||||
assert result is None
|
||||
assert "No palace found" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_open_collection_or_explain_propagates_palace_not_found_from_backend(tmp_path, monkeypatch):
|
||||
"""If the backend raises bare PalaceNotFoundError after our filesystem
|
||||
guards (rare race or backend-internal "not found"), the helper still
|
||||
prints the State A message and returns None."""
|
||||
emit, lines = _capture()
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
(palace / "chroma.sqlite3").touch()
|
||||
|
||||
def raise_pnf(*args, **kwargs):
|
||||
raise PalaceNotFoundError(str(palace))
|
||||
|
||||
monkeypatch.setattr("mempalace.palace.get_collection", raise_pnf)
|
||||
|
||||
result = _open_collection_or_explain(str(palace), out=emit)
|
||||
|
||||
assert result is None
|
||||
assert any("No palace found" in line for line in lines)
|
||||
|
||||
|
||||
def test_open_collection_or_explain_reraises_backend_closed_error(tmp_path, monkeypatch):
|
||||
"""BackendClosedError is a programmer error (caller violated the backend
|
||||
lifecycle), not a palace-state UX condition. The helper must propagate
|
||||
it instead of swallowing it into the State E "repair-status" hint.
|
||||
|
||||
Without this re-raise, a closed default backend would silently mask
|
||||
every call site as "Error opening palace ... Try: repair-status"
|
||||
even when the actual fix is to stop using a closed backend handle.
|
||||
"""
|
||||
from mempalace.backends import BackendClosedError
|
||||
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
(palace / "chroma.sqlite3").touch()
|
||||
|
||||
def raise_closed(*args, **kwargs):
|
||||
raise BackendClosedError("ChromaBackend has been closed")
|
||||
|
||||
monkeypatch.setattr("mempalace.palace.get_collection", raise_closed)
|
||||
|
||||
import pytest
|
||||
|
||||
with pytest.raises(BackendClosedError):
|
||||
_open_collection_or_explain(str(palace))
|
||||
|
||||
|
||||
def test_open_collection_or_explain_distinguishes_collection_subclass(tmp_path, monkeypatch):
|
||||
"""The helper must surface CollectionNotInitializedError as the
|
||||
'empty' message rather than the broader 'No palace found' message,
|
||||
even though the former subclasses the latter."""
|
||||
emit, lines = _capture()
|
||||
palace = tmp_path / "palace"
|
||||
palace.mkdir()
|
||||
(palace / "chroma.sqlite3").touch()
|
||||
|
||||
def raise_cnie(*args, **kwargs):
|
||||
raise CollectionNotInitializedError(str(palace))
|
||||
|
||||
monkeypatch.setattr("mempalace.palace.get_collection", raise_cnie)
|
||||
|
||||
result = _open_collection_or_explain(str(palace), out=emit)
|
||||
|
||||
assert result is None
|
||||
assert any("initialized but empty" in line for line in lines)
|
||||
assert not any("No palace found" in line for line in lines)
|
||||
@@ -63,9 +63,9 @@ class TestTunnelStorage:
|
||||
assert file_mode == 0o600, f"tunnels.json mode is {oct(file_mode)}, expected 0o600"
|
||||
|
||||
parent_mode = stat.S_IMODE(os.stat(tunnel_file.parent).st_mode)
|
||||
assert (
|
||||
parent_mode == 0o700
|
||||
), f"tunnels.json parent dir mode is {oct(parent_mode)}, expected 0o700"
|
||||
assert parent_mode == 0o700, (
|
||||
f"tunnels.json parent dir mode is {oct(parent_mode)}, expected 0o700"
|
||||
)
|
||||
|
||||
|
||||
class TestExplicitTunnels:
|
||||
@@ -73,6 +73,10 @@ class TestExplicitTunnels:
|
||||
assert palace_graph._normalize_wing(" Mempalace-Public ") == "mempalace_public"
|
||||
assert palace_graph._normalize_wing(" ") is None
|
||||
assert palace_graph._normalize_wing(None) is None
|
||||
# Non-string inputs (corrupt or hand-edited tunnels.json) return None
|
||||
# instead of raising — keeps read-path filters robust to bad records.
|
||||
assert palace_graph._normalize_wing(42) is None
|
||||
assert palace_graph._normalize_wing(["x"]) is None
|
||||
|
||||
def test_create_tunnel_deduplicates_reverse_order_and_updates_label(
|
||||
self, tmp_path, monkeypatch
|
||||
@@ -287,6 +291,17 @@ class TestTopicTunnels:
|
||||
assert palace_graph.topic_tunnels_for_wing("wing_missing", topics_by_wing) == []
|
||||
assert palace_graph.list_tunnels() == []
|
||||
|
||||
def test_topic_tunnels_for_wing_matches_across_slug_forms(self, tmp_path, monkeypatch):
|
||||
"""The wing arg and ``topics_by_wing`` keys may carry different slug
|
||||
forms (hyphen vs underscore). ``topic_tunnels_for_wing`` resolves
|
||||
the lookup through ``normalize_wing_name`` so a caller passing
|
||||
``"my-wing"`` against a registry keyed by ``"my_wing"`` still wires
|
||||
up the topic tunnels."""
|
||||
_use_tmp_tunnel_file(monkeypatch, tmp_path)
|
||||
topics_by_wing = {"my_wing": ["Angular"], "wing_people": ["Angular"]}
|
||||
created = palace_graph.topic_tunnels_for_wing("my-wing", topics_by_wing)
|
||||
assert len(created) == 1
|
||||
|
||||
def test_compute_topic_tunnels_dedupe_on_recompute(self, tmp_path, monkeypatch):
|
||||
_use_tmp_tunnel_file(monkeypatch, tmp_path)
|
||||
topics_by_wing = {
|
||||
@@ -335,13 +350,39 @@ class TestTopicTunnels:
|
||||
kinds = sorted(t["kind"] for t in tunnels)
|
||||
assert kinds == ["explicit", "topic"]
|
||||
|
||||
def test_compute_topic_tunnels_normalizes_wing_keys(self, tmp_path, monkeypatch):
|
||||
"""Auto-generated topic tunnels canonicalize the wing slug so two
|
||||
mining runs with mixed forms (``my-wing`` then ``my_wing``) produce
|
||||
a single deduped record. Only user-issued ``create_tunnel`` calls
|
||||
preserve verbatim slugs (#1504); the topic-tunnel auto-generator
|
||||
owns its own slugs and stays canonical."""
|
||||
_use_tmp_tunnel_file(monkeypatch, tmp_path)
|
||||
|
||||
palace_graph.compute_topic_tunnels(
|
||||
{"my-wing": ["Angular"], "wing_people": ["Angular"]}, min_count=1
|
||||
)
|
||||
palace_graph.compute_topic_tunnels(
|
||||
{"my_wing": ["Angular"], "wing_people": ["Angular"]}, min_count=1
|
||||
)
|
||||
|
||||
tunnels = palace_graph.list_tunnels()
|
||||
assert len(tunnels) == 1
|
||||
stored_wings = {tunnels[0]["source"]["wing"], tunnels[0]["target"]["wing"]}
|
||||
assert stored_wings == {"my_wing", "wing_people"}
|
||||
|
||||
|
||||
class TestHyphenatedWingNormalization:
|
||||
"""Wing names with hyphens or spaces are normalized to underscores on init.
|
||||
"""Wing names may reach ``tunnels.json`` in either form:
|
||||
|
||||
Tunnel helpers must apply the same normalization at lookup time so that
|
||||
``mempalace-public`` resolves to ``mempalace_public`` and matches the
|
||||
metadata written by ``room_detector_local.py``.
|
||||
* ``mempalace mine`` without ``--wing`` derives the slug from the dir
|
||||
name through ``normalize_wing_name`` → stored as ``mempalace_public``.
|
||||
* ``mempalace mine --wing my-wing`` (or any explicit slug) is stored
|
||||
verbatim by ``create_tunnel`` (regression #1504) → ``my-wing``.
|
||||
|
||||
Read-path helpers (``list_tunnels`` / ``follow_tunnels``) must accept
|
||||
queries in either form and match both storage forms — normalization
|
||||
is applied on both the stored value and the query key at comparison
|
||||
time, never at write time.
|
||||
"""
|
||||
|
||||
def test_list_tunnels_filters_hyphenated_wing(self, tmp_path, monkeypatch):
|
||||
@@ -363,14 +404,18 @@ class TestHyphenatedWingNormalization:
|
||||
assert len(by_under) == 1
|
||||
assert by_hyphen[0]["connected_wing"] == "wing_people"
|
||||
|
||||
def test_create_tunnel_normalizes_wing_names(self, tmp_path, monkeypatch):
|
||||
def test_create_tunnel_preserves_hyphenated_wing_names(self, tmp_path, monkeypatch):
|
||||
"""Regression for #1504: wings created via ``mempalace mine --wing my-wing``
|
||||
keep the hyphen in metadata, so ``create_tunnel`` must store the slug
|
||||
verbatim. Read-path normalization in ``list_tunnels``/``follow_tunnels``
|
||||
keeps both query forms working."""
|
||||
_use_tmp_tunnel_file(monkeypatch, tmp_path)
|
||||
|
||||
t = palace_graph.create_tunnel("my-project", "src", "your-project", "dst", label="cross")
|
||||
assert t["source"]["wing"] == "my_project"
|
||||
assert t["target"]["wing"] == "your_project"
|
||||
assert len(palace_graph.list_tunnels("my_project")) == 1
|
||||
assert t["source"]["wing"] == "my-project"
|
||||
assert t["target"]["wing"] == "your-project"
|
||||
assert len(palace_graph.list_tunnels("my-project")) == 1
|
||||
assert len(palace_graph.list_tunnels("my_project")) == 1
|
||||
|
||||
def test_find_tunnels_warns_on_empty_result(self, tmp_path, monkeypatch, caplog):
|
||||
_use_tmp_tunnel_file(monkeypatch, tmp_path)
|
||||
@@ -379,3 +424,60 @@ class TestHyphenatedWingNormalization:
|
||||
result = palace_graph.find_tunnels("nonexistent-wing")
|
||||
assert result == []
|
||||
assert "No tunnels found" in caplog.text
|
||||
|
||||
def test_read_path_skips_records_with_null_endpoints(self, tmp_path, monkeypatch):
|
||||
"""A hand-edited ``tunnels.json`` may carry ``"source": null`` or
|
||||
``"target": null``. The read-path filters must skip such rows
|
||||
instead of crashing the whole iteration with ``AttributeError``."""
|
||||
_use_tmp_tunnel_file(monkeypatch, tmp_path)
|
||||
palace_graph._save_tunnels(
|
||||
[
|
||||
{
|
||||
"id": "broken",
|
||||
"source": None,
|
||||
"target": None,
|
||||
"label": "corrupt",
|
||||
"kind": "explicit",
|
||||
"created_at": "2026-05-01T00:00:00+00:00",
|
||||
},
|
||||
{
|
||||
"id": "ok",
|
||||
"source": {"wing": "wing_a", "room": "r1"},
|
||||
"target": {"wing": "wing_b", "room": "r2"},
|
||||
"label": "good",
|
||||
"kind": "explicit",
|
||||
"created_at": "2026-05-02T00:00:00+00:00",
|
||||
},
|
||||
]
|
||||
)
|
||||
|
||||
# Both filters must skip the broken record and return the good one.
|
||||
assert {t["id"] for t in palace_graph.list_tunnels("wing_a")} == {"ok"}
|
||||
connections = palace_graph.follow_tunnels("wing_a", "r1")
|
||||
assert [c["tunnel_id"] for c in connections] == ["ok"]
|
||||
|
||||
def test_pre_1504_underscore_tunnels_remain_findable(self, tmp_path, monkeypatch):
|
||||
"""A ``tunnels.json`` written before #1504 stored wings in normalized
|
||||
underscore form (the write-path normalization is now gone). Read-path
|
||||
queries with either hyphen or underscore must still find those
|
||||
records after the fix."""
|
||||
tunnel_file = _use_tmp_tunnel_file(monkeypatch, tmp_path)
|
||||
palace_graph._save_tunnels(
|
||||
[
|
||||
{
|
||||
"id": "pre_1504_record",
|
||||
"source": {"wing": "mempalace_public", "room": "auth"},
|
||||
"target": {"wing": "wing_people", "room": "users"},
|
||||
"label": "pre-#1504 record",
|
||||
"kind": "explicit",
|
||||
"created_at": "2026-05-10T00:00:00+00:00",
|
||||
}
|
||||
]
|
||||
)
|
||||
assert tunnel_file.exists()
|
||||
|
||||
assert len(palace_graph.list_tunnels("mempalace_public")) == 1
|
||||
assert len(palace_graph.list_tunnels("mempalace-public")) == 1
|
||||
|
||||
assert len(palace_graph.follow_tunnels("mempalace_public", "auth")) == 1
|
||||
assert len(palace_graph.follow_tunnels("mempalace-public", "auth")) == 1
|
||||
|
||||
@@ -12,10 +12,12 @@ from __future__ import annotations
|
||||
import multiprocessing
|
||||
import os
|
||||
import time
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from mempalace.palace import (
|
||||
_write_lock_holder,
|
||||
MineAlreadyRunning,
|
||||
mine_global_lock,
|
||||
mine_palace_lock,
|
||||
@@ -197,9 +199,9 @@ def test_reentrant_same_thread_passes_through(tmp_path, monkeypatch):
|
||||
child = ctx.Process(target=_try_acquire_expect_busy, args=(palace, result_q))
|
||||
try:
|
||||
child.start()
|
||||
assert (
|
||||
result_q.get(timeout=10) == "busy"
|
||||
), "outer lock should still be held by parent after inner re-entrant exit"
|
||||
assert result_q.get(timeout=10) == "busy", (
|
||||
"outer lock should still be held by parent after inner re-entrant exit"
|
||||
)
|
||||
child.join(timeout=5)
|
||||
assert child.exitcode == 0
|
||||
finally:
|
||||
@@ -265,14 +267,56 @@ def test_lock_failure_message_names_holder(tmp_path, monkeypatch):
|
||||
pytest.fail("second acquire of same palace should have raised")
|
||||
|
||||
msg = str(excinfo.value)
|
||||
assert (
|
||||
f"PID {holder_pid}" in msg
|
||||
), f"lock-failure message must name the holder PID; got: {msg!r}"
|
||||
assert f"PID {holder_pid}" in msg, (
|
||||
f"lock-failure message must name the holder PID; got: {msg!r}"
|
||||
)
|
||||
finally:
|
||||
open(release, "w").close()
|
||||
holder.join(timeout=5)
|
||||
|
||||
|
||||
def test_write_lock_holder_writes_utf8_bytes_for_non_ascii_argv(tmp_path, monkeypatch):
|
||||
"""Regression #1435: lock-holder identity must be written as UTF-8 bytes.
|
||||
|
||||
The holder byte count and the on-disk bytes must agree even when argv
|
||||
contains characters that are not representable in a Windows ANSI codepage.
|
||||
"""
|
||||
monkeypatch.setattr(
|
||||
sys,
|
||||
"argv",
|
||||
["mempalace", "mine", "café/北"],
|
||||
)
|
||||
|
||||
lock_path = tmp_path / "holder.lock"
|
||||
lock_path.write_bytes(b"\0stale-holder-identity-that-must-be-truncated")
|
||||
|
||||
with lock_path.open("r+b") as lock_file:
|
||||
_write_lock_holder(lock_file)
|
||||
|
||||
ident = f"{os.getpid()} {' '.join(sys.argv[:3])}".strip()
|
||||
assert lock_path.read_bytes() == b"\0" + ident.encode("utf-8")
|
||||
|
||||
|
||||
def test_write_lock_holder_is_best_effort_on_unicode_error(monkeypatch):
|
||||
"""Regression #1435: holder-write failures must not block lock acquisition."""
|
||||
|
||||
class UnicodeFailingLock:
|
||||
def seek(self, _offset):
|
||||
pass
|
||||
|
||||
def truncate(self, _size):
|
||||
pass
|
||||
|
||||
def write(self, _data):
|
||||
raise UnicodeEncodeError("cp1252", "北", 0, 1, "not representable")
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(sys, "argv", ["mempalace", "mine", "北"])
|
||||
_write_lock_holder(UnicodeFailingLock())
|
||||
|
||||
|
||||
def test_lock_holder_identity_persists_across_release(tmp_path, monkeypatch):
|
||||
"""The holder line is overwritten by each new acquirer, not appended.
|
||||
|
||||
|
||||
+15
-15
@@ -597,13 +597,13 @@ class TestBackendAbstraction:
|
||||
"""Claim: pluggable backends.
|
||||
backends/base.py must define an abstract base class."""
|
||||
path = MEMPALACE_PKG / "backends" / "base.py"
|
||||
assert (
|
||||
path.is_file()
|
||||
), "mempalace/backends/base.py does not exist. Backend abstraction layer is missing."
|
||||
assert path.is_file(), (
|
||||
"mempalace/backends/base.py does not exist. Backend abstraction layer is missing."
|
||||
)
|
||||
src = _read(path)
|
||||
assert (
|
||||
"ABC" in src or "abstractmethod" in src
|
||||
), "backends/base.py does not define an abstract base class."
|
||||
assert "ABC" in src or "abstractmethod" in src, (
|
||||
"backends/base.py does not define an abstract base class."
|
||||
)
|
||||
|
||||
def test_backends_chroma_exists(self):
|
||||
"""Claim: ChromaDB backend implementation.
|
||||
@@ -611,9 +611,9 @@ class TestBackendAbstraction:
|
||||
path = MEMPALACE_PKG / "backends" / "chroma.py"
|
||||
assert path.is_file(), "mempalace/backends/chroma.py does not exist."
|
||||
src = _read(path)
|
||||
assert (
|
||||
"BaseCollection" in src or "base" in src
|
||||
), "backends/chroma.py does not reference the base class."
|
||||
assert "BaseCollection" in src or "base" in src, (
|
||||
"backends/chroma.py does not reference the base class."
|
||||
)
|
||||
|
||||
def test_backends_importable(self):
|
||||
"""Both backend modules should be importable."""
|
||||
@@ -650,9 +650,9 @@ class TestI18n:
|
||||
def test_english_baseline_exists(self):
|
||||
"""en.json must exist as the baseline language file."""
|
||||
path = MEMPALACE_PKG / "i18n" / "en.json"
|
||||
assert (
|
||||
path.is_file()
|
||||
), "mempalace/i18n/en.json does not exist. English baseline is required."
|
||||
assert path.is_file(), (
|
||||
"mempalace/i18n/en.json does not exist. English baseline is required."
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -737,9 +737,9 @@ class TestReadmeToolCountConsistency:
|
||||
counts = re.findall(r"(\d+)\s+tools", readme)
|
||||
if len(counts) > 1:
|
||||
unique = set(counts)
|
||||
assert (
|
||||
len(unique) == 1
|
||||
), f"README mentions different tool counts: {counts}. All occurrences must agree."
|
||||
assert len(unique) == 1, (
|
||||
f"README mentions different tool counts: {counts}. All occurrences must agree."
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
+275
-3
@@ -76,6 +76,94 @@ def test_paginate_ids_offset_exception_fallback():
|
||||
assert "id1" in ids
|
||||
|
||||
|
||||
# ── _extract_drawers ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_extract_drawers_preserves_valid_metadata():
|
||||
"""Non-empty dict metadata passes through unchanged."""
|
||||
col = MagicMock()
|
||||
col.get.return_value = {
|
||||
"ids": ["id1", "id2"],
|
||||
"documents": ["doc1", "doc2"],
|
||||
"metadatas": [{"wing": "a", "room": "1"}, {"wing": "b", "room": "2"}],
|
||||
}
|
||||
all_ids, all_docs, all_metas = repair._extract_drawers(col, total=2, batch_size=2)
|
||||
assert all_ids == ["id1", "id2"]
|
||||
assert all_docs == ["doc1", "doc2"]
|
||||
assert all_metas == [{"wing": "a", "room": "1"}, {"wing": "b", "room": "2"}]
|
||||
|
||||
|
||||
def test_extract_drawers_sanitizes_none_metadata():
|
||||
"""None entries in metadatas are coerced to the sentinel dict.
|
||||
|
||||
chromadb 1.5.x's `validate_metadata` raises `ValueError: Expected metadata
|
||||
to be a non-empty dict, got 0 metadata attributes in add.` if it sees a
|
||||
None entry; the sanitizer keeps the rebuild upsert from crashing.
|
||||
"""
|
||||
col = MagicMock()
|
||||
col.get.return_value = {
|
||||
"ids": ["id1", "id2", "id3"],
|
||||
"documents": ["doc1", "doc2", "doc3"],
|
||||
"metadatas": [{"wing": "a"}, None, {"wing": "c"}],
|
||||
}
|
||||
_, _, all_metas = repair._extract_drawers(col, total=3, batch_size=3)
|
||||
assert all_metas[0] == {"wing": "a"}
|
||||
assert all_metas[1] == {"_repaired_empty_meta": True}
|
||||
assert all_metas[2] == {"wing": "c"}
|
||||
|
||||
|
||||
def test_extract_drawers_sanitizes_empty_dict_metadata():
|
||||
"""Empty dict {} entries are coerced to the sentinel dict.
|
||||
|
||||
chromadb 1.5.x rejects `{}` the same way it rejects `None`. The comment
|
||||
in the previous code path mistakenly assumed otherwise.
|
||||
"""
|
||||
col = MagicMock()
|
||||
col.get.return_value = {
|
||||
"ids": ["id1", "id2"],
|
||||
"documents": ["doc1", "doc2"],
|
||||
"metadatas": [{}, {"wing": "b"}],
|
||||
}
|
||||
_, _, all_metas = repair._extract_drawers(col, total=2, batch_size=2)
|
||||
assert all_metas[0] == {"_repaired_empty_meta": True}
|
||||
assert all_metas[1] == {"wing": "b"}
|
||||
|
||||
|
||||
def test_extract_drawers_sanitization_preserves_alignment():
|
||||
"""Sanitized output keeps the same length and ordering as input.
|
||||
|
||||
Critical invariant: ids[i] / documents[i] / metadatas[i] must stay in
|
||||
lockstep through the sanitizer; otherwise the rebuild upsert mis-pairs
|
||||
documents with metadata.
|
||||
"""
|
||||
col = MagicMock()
|
||||
col.get.return_value = {
|
||||
"ids": ["id1", "id2", "id3", "id4"],
|
||||
"documents": ["d1", "d2", "d3", "d4"],
|
||||
"metadatas": [None, {"k": "v"}, {}, None],
|
||||
}
|
||||
all_ids, all_docs, all_metas = repair._extract_drawers(col, total=4, batch_size=4)
|
||||
assert len(all_ids) == len(all_docs) == len(all_metas) == 4
|
||||
assert all_ids == ["id1", "id2", "id3", "id4"]
|
||||
assert all_metas[0] == {"_repaired_empty_meta": True}
|
||||
assert all_metas[1] == {"k": "v"}
|
||||
assert all_metas[2] == {"_repaired_empty_meta": True}
|
||||
assert all_metas[3] == {"_repaired_empty_meta": True}
|
||||
|
||||
|
||||
def test_extract_drawers_multiple_batches():
|
||||
"""Pagination handles batch boundaries without losing/duplicating rows."""
|
||||
col = MagicMock()
|
||||
col.get.side_effect = [
|
||||
{"ids": ["id1", "id2"], "documents": ["d1", "d2"], "metadatas": [{"a": 1}, None]},
|
||||
{"ids": ["id3"], "documents": ["d3"], "metadatas": [{}]},
|
||||
{"ids": [], "documents": [], "metadatas": []},
|
||||
]
|
||||
all_ids, all_docs, all_metas = repair._extract_drawers(col, total=3, batch_size=2)
|
||||
assert all_ids == ["id1", "id2", "id3"]
|
||||
assert all_metas == [{"a": 1}, {"_repaired_empty_meta": True}, {"_repaired_empty_meta": True}]
|
||||
|
||||
|
||||
# ── scan_palace ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -450,9 +538,104 @@ def test_rebuild_index_default_uses_configured_collection(mock_backend_cls, mock
|
||||
]
|
||||
|
||||
|
||||
def test_status_returns_uninitialized_when_db_missing(tmp_path, capsys):
|
||||
"""repair.status on a palace dir without chroma.sqlite3 returns a
|
||||
structured status (no chromadb client opened, per the design that
|
||||
repair-status must work even on corrupted palaces — #1498)."""
|
||||
# tmp_path exists, no chroma.sqlite3
|
||||
result = repair.status(palace_path=str(tmp_path))
|
||||
|
||||
assert result["status"] == "uninitialized"
|
||||
assert "no chroma.sqlite3" in result["message"]
|
||||
captured = capsys.readouterr()
|
||||
assert "has no chroma.sqlite3 yet" in captured.out + captured.err
|
||||
|
||||
|
||||
def test_status_returns_empty_when_db_present_no_drawers(tmp_path, capsys):
|
||||
"""repair.status on a palace with chroma.sqlite3 but zero drawer rows
|
||||
returns a structured 'empty' status, distinguishable from 'unknown' /
|
||||
'uninitialized' (#1498). Mocks sqlite_drawer_count to assert the
|
||||
return-shape contract; see the real-disk sibling below for the
|
||||
no-chromadb-client invariant."""
|
||||
(tmp_path / "chroma.sqlite3").touch()
|
||||
with patch("mempalace.repair.sqlite_drawer_count", return_value=0):
|
||||
result = repair.status(palace_path=str(tmp_path))
|
||||
|
||||
assert result["status"] == "empty"
|
||||
assert "no drawers yet" in result["message"]
|
||||
captured = capsys.readouterr()
|
||||
assert "initialized but empty" in captured.out + captured.err
|
||||
|
||||
|
||||
def test_status_empty_palace_never_opens_chromadb_client(tmp_path):
|
||||
"""Design invariant from #1498: repair.status on an initialized-but-empty
|
||||
palace must NOT open a chromadb client. Opening would materialize HNSW
|
||||
segment state files on disk, breaking the promise that repair-status is
|
||||
safe to run on corrupted palaces.
|
||||
|
||||
Real-disk sibling of test_status_returns_empty_when_db_present_no_drawers:
|
||||
bootstrap a real chroma.sqlite3 via PersistentClient (creates the DB
|
||||
file but no collection), then assert repair.status returns 'empty' and
|
||||
no chromadb segment artifacts appeared in the dir."""
|
||||
import chromadb
|
||||
|
||||
chromadb.PersistentClient(path=str(tmp_path))
|
||||
before = sorted(p.name for p in tmp_path.iterdir())
|
||||
|
||||
result = repair.status(palace_path=str(tmp_path))
|
||||
|
||||
after = sorted(p.name for p in tmp_path.iterdir())
|
||||
assert result["status"] == "empty", result
|
||||
# repair.status must not create new files; chromadb writes HNSW segment
|
||||
# state and *.bin payloads on collection open — none of those should
|
||||
# appear here.
|
||||
assert before == after, f"repair.status mutated palace on disk: before={before} after={after}"
|
||||
|
||||
|
||||
def test_status_falls_through_to_capacity_when_sqlite_count_unreadable(tmp_path):
|
||||
"""When sqlite_drawer_count returns None (schema drift / locked file),
|
||||
repair.status must fall through to hnsw_capacity_status instead of
|
||||
short-circuiting on 'empty' (#1498)."""
|
||||
(tmp_path / "chroma.sqlite3").touch()
|
||||
with (
|
||||
patch("mempalace.repair.sqlite_drawer_count", return_value=None),
|
||||
patch("mempalace.repair.hnsw_capacity_status") as capacity_status,
|
||||
):
|
||||
capacity_status.side_effect = [
|
||||
{
|
||||
"sqlite_count": None,
|
||||
"hnsw_count": None,
|
||||
"divergence": None,
|
||||
"diverged": False,
|
||||
"status": "unknown",
|
||||
"message": "",
|
||||
},
|
||||
{
|
||||
"sqlite_count": None,
|
||||
"hnsw_count": None,
|
||||
"divergence": None,
|
||||
"diverged": False,
|
||||
"status": "unknown",
|
||||
"message": "",
|
||||
},
|
||||
]
|
||||
result = repair.status(palace_path=str(tmp_path))
|
||||
|
||||
# Did not short-circuit on 'empty': fell through to capacity check.
|
||||
# The healthy/fall-through path returns {drawers, closets} dicts, no top-level "status" key.
|
||||
assert "status" not in result or result["status"] != "empty"
|
||||
assert "drawers" in result and "closets" in result
|
||||
assert capacity_status.called
|
||||
|
||||
|
||||
def test_status_default_uses_configured_drawer_collection(tmp_path):
|
||||
# Provide the on-disk preconditions the stratified state helper (#1498)
|
||||
# checks before reaching the capacity probe: chroma.sqlite3 file exists
|
||||
# and sqlite_drawer_count returns a positive number (palace not empty).
|
||||
(tmp_path / "chroma.sqlite3").touch()
|
||||
with (
|
||||
patch("mempalace.repair._drawers_collection_name", return_value="custom_drawers"),
|
||||
patch("mempalace.repair.sqlite_drawer_count", return_value=1),
|
||||
patch("mempalace.repair.hnsw_capacity_status") as capacity_status,
|
||||
):
|
||||
capacity_status.side_effect = [
|
||||
@@ -1198,9 +1381,9 @@ def test_rebuild_index_runs_sqlite_preflight_before_chromadb_open(tmp_path, caps
|
||||
PAGE = 4096
|
||||
CORRUPT_BYTES = 16384 # 4 pages
|
||||
HEADER_GUARD = PAGE * 2 # leave header + root pages intact
|
||||
assert (
|
||||
pre_size >= HEADER_GUARD + CORRUPT_BYTES
|
||||
), f"sqlite db too small to mangle without truncating: {pre_size} bytes"
|
||||
assert pre_size >= HEADER_GUARD + CORRUPT_BYTES, (
|
||||
f"sqlite db too small to mangle without truncating: {pre_size} bytes"
|
||||
)
|
||||
# Round (pre_size - CORRUPT_BYTES) down to a page boundary so we
|
||||
# mangle whole pages. Cap at offset 40960 (page 10) for stable
|
||||
# diagnostics across SQLite versions that may grow the file.
|
||||
@@ -1672,3 +1855,92 @@ def test_rebuild_from_sqlite_honors_configured_drawer_collection_name(tmp_path,
|
||||
)
|
||||
except Exception:
|
||||
pass # Expected: collection wasn't created.
|
||||
|
||||
|
||||
# ── _vacuum_and_rebuild_fts5 ──────────────────────────────────────────
|
||||
|
||||
|
||||
def test_vacuum_and_rebuild_fts5_vacuums_and_rebuilds(tmp_path):
|
||||
"""VACUUM runs and FTS5 index is rebuilt when the table is present."""
|
||||
sqlite_path = tmp_path / "chroma.sqlite3"
|
||||
with closing(sqlite3.connect(str(sqlite_path))) as conn:
|
||||
conn.execute(
|
||||
"CREATE VIRTUAL TABLE embedding_fulltext_search"
|
||||
" USING fts5(string_value, tokenize='unicode61')"
|
||||
)
|
||||
conn.execute("INSERT INTO embedding_fulltext_search(string_value) VALUES('hello world')")
|
||||
conn.commit()
|
||||
|
||||
repair._vacuum_and_rebuild_fts5(str(tmp_path))
|
||||
|
||||
with closing(sqlite3.connect(str(sqlite_path))) as conn:
|
||||
result = conn.execute("PRAGMA integrity_check").fetchall()
|
||||
assert result == [("ok",)]
|
||||
|
||||
|
||||
def test_vacuum_and_rebuild_fts5_no_fts5_table(tmp_path):
|
||||
"""VACUUM runs without error when embedding_fulltext_search is absent."""
|
||||
sqlite_path = tmp_path / "chroma.sqlite3"
|
||||
with closing(sqlite3.connect(str(sqlite_path))) as conn:
|
||||
conn.execute("CREATE TABLE dummy (id INTEGER PRIMARY KEY)")
|
||||
conn.commit()
|
||||
|
||||
# Must not raise even without the FTS5 table.
|
||||
repair._vacuum_and_rebuild_fts5(str(tmp_path))
|
||||
|
||||
with closing(sqlite3.connect(str(sqlite_path))) as conn:
|
||||
result = conn.execute("PRAGMA integrity_check").fetchall()
|
||||
assert result == [("ok",)]
|
||||
|
||||
|
||||
def test_vacuum_and_rebuild_fts5_missing_sqlite(tmp_path):
|
||||
"""Silently skips when chroma.sqlite3 does not exist."""
|
||||
repair._vacuum_and_rebuild_fts5(str(tmp_path)) # no file — must not raise
|
||||
|
||||
|
||||
@patch("mempalace.repair.shutil")
|
||||
@patch("mempalace.repair.ChromaBackend")
|
||||
def test_rebuild_index_calls_vacuum(mock_backend_cls, mock_shutil, tmp_path):
|
||||
"""rebuild_index closes chroma handles then calls _vacuum_and_rebuild_fts5.
|
||||
|
||||
ChromaDB's PersistentClient holds an open connection to chroma.sqlite3;
|
||||
VACUUM requires an exclusive lock so _close_chroma_handles must be called
|
||||
before _vacuum_and_rebuild_fts5.
|
||||
"""
|
||||
sqlite_path = tmp_path / "chroma.sqlite3"
|
||||
with closing(sqlite3.connect(str(sqlite_path))) as conn:
|
||||
conn.execute("CREATE TABLE dummy(id INTEGER PRIMARY KEY)")
|
||||
conn.commit()
|
||||
|
||||
mock_col = MagicMock()
|
||||
mock_col.count.return_value = 1
|
||||
mock_col.get.return_value = {
|
||||
"ids": ["id1"],
|
||||
"documents": ["doc1"],
|
||||
"metadatas": [{"wing": "a"}],
|
||||
}
|
||||
mock_new_col = MagicMock()
|
||||
mock_new_col.count.return_value = 1
|
||||
mock_temp_col = MagicMock()
|
||||
mock_temp_col.count.return_value = 1
|
||||
mock_backend = _install_mock_backend(mock_backend_cls, mock_col)
|
||||
mock_backend.create_collection.side_effect = [mock_temp_col, mock_new_col]
|
||||
|
||||
call_order = []
|
||||
with (
|
||||
patch.object(
|
||||
repair, "_close_chroma_handles", side_effect=lambda *a, **kw: call_order.append("close")
|
||||
) as mock_close,
|
||||
patch.object(
|
||||
repair,
|
||||
"_vacuum_and_rebuild_fts5",
|
||||
side_effect=lambda *a, **kw: call_order.append("vacuum"),
|
||||
) as mock_vacuum,
|
||||
):
|
||||
repair.rebuild_index(palace_path=str(tmp_path))
|
||||
mock_close.assert_called_once()
|
||||
mock_vacuum.assert_called_once()
|
||||
assert call_order == ["close", "vacuum"], "backend must be closed before VACUUM"
|
||||
args, kwargs = mock_vacuum.call_args
|
||||
assert args[0] == str(tmp_path)
|
||||
assert "progress" in kwargs
|
||||
|
||||
@@ -33,12 +33,12 @@ class TestSaveHookAutoMines:
|
||||
# `--mode convos` so the convo miner runs (not the projects miner).
|
||||
assert "TRANSCRIPT_PATH" in src, "hook must read transcript_path"
|
||||
assert "mempalace mine" in src, "hook must invoke `mempalace mine`"
|
||||
assert (
|
||||
'dirname "$TRANSCRIPT_PATH"' in src
|
||||
), "hook must mine the transcript's parent directory"
|
||||
assert (
|
||||
"--mode convos" in src
|
||||
), "transcript mine must use --mode convos, not the projects miner"
|
||||
assert 'dirname "$TRANSCRIPT_PATH"' in src, (
|
||||
"hook must mine the transcript's parent directory"
|
||||
)
|
||||
assert "--mode convos" in src, (
|
||||
"transcript mine must use --mode convos, not the projects miner"
|
||||
)
|
||||
|
||||
def test_mempal_dir_default_not_empty(self):
|
||||
"""If MEMPAL_DIR is still used, it should have a sensible default,
|
||||
@@ -86,16 +86,16 @@ class TestShellHookTranscriptValidation:
|
||||
def test_save_hook_defines_and_uses_validator(self):
|
||||
src = self._strip_comments(self._hook_src("mempal_save_hook.sh"))
|
||||
assert "is_valid_transcript_path() {" in src, "validator function must be defined"
|
||||
assert (
|
||||
'is_valid_transcript_path "$TRANSCRIPT_PATH"' in src
|
||||
), "validator must be invoked against TRANSCRIPT_PATH before mining"
|
||||
assert 'is_valid_transcript_path "$TRANSCRIPT_PATH"' in src, (
|
||||
"validator must be invoked against TRANSCRIPT_PATH before mining"
|
||||
)
|
||||
|
||||
def test_precompact_hook_defines_and_uses_validator(self):
|
||||
src = self._strip_comments(self._hook_src("mempal_precompact_hook.sh"))
|
||||
assert "is_valid_transcript_path() {" in src, "validator function must be defined"
|
||||
assert (
|
||||
'is_valid_transcript_path "$TRANSCRIPT_PATH"' in src
|
||||
), "validator must be invoked against TRANSCRIPT_PATH before mining"
|
||||
assert 'is_valid_transcript_path "$TRANSCRIPT_PATH"' in src, (
|
||||
"validator must be invoked against TRANSCRIPT_PATH before mining"
|
||||
)
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform == "win32",
|
||||
@@ -112,9 +112,7 @@ class TestShellHookTranscriptValidation:
|
||||
end = src.index("\n}\n", start) + 2
|
||||
func_src = src[start:end]
|
||||
script = tmp_path / "v.sh"
|
||||
script.write_text(
|
||||
f"{func_src}\n" 'is_valid_transcript_path "$1" && echo OK || echo NO\n'
|
||||
)
|
||||
script.write_text(f'{func_src}\nis_valid_transcript_path "$1" && echo OK || echo NO\n')
|
||||
|
||||
def run(arg: str) -> str:
|
||||
return subprocess.run(
|
||||
|
||||
+32
-20
@@ -184,12 +184,11 @@ class TestSearchMemories:
|
||||
|
||||
# Invariants on every hit.
|
||||
for h in hits:
|
||||
assert (
|
||||
0.0 <= h["similarity"] <= 1.0
|
||||
), f"similarity out of range: {h['similarity']} for {h['source_file']}"
|
||||
assert 0.0 <= h["similarity"] <= 1.0, (
|
||||
f"similarity out of range: {h['similarity']} for {h['source_file']}"
|
||||
)
|
||||
assert 0.0 <= h["effective_distance"] <= 2.0, (
|
||||
f"effective_distance out of range: {h['effective_distance']} "
|
||||
f"for {h['source_file']}"
|
||||
f"effective_distance out of range: {h['effective_distance']} for {h['source_file']}"
|
||||
)
|
||||
|
||||
# With the clamp, the closet-boosted a.md still ranks ahead of b.md —
|
||||
@@ -239,6 +238,17 @@ class TestBM25NoneSafety:
|
||||
# ── search() (CLI print function) ─────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_palace_path(tmp_path):
|
||||
"""tmp_path with chroma.sqlite3 touched so searcher.search's
|
||||
filesystem-first state checks (#1498) pass through to the mocked
|
||||
backend instead of raising on State A / State B."""
|
||||
p = tmp_path / "palace"
|
||||
p.mkdir()
|
||||
(p / "chroma.sqlite3").touch()
|
||||
return str(p)
|
||||
|
||||
|
||||
class TestSearchCLI:
|
||||
def test_search_prints_results(self, palace_path, seeded_collection, capsys):
|
||||
search("JWT authentication", palace_path)
|
||||
@@ -273,14 +283,14 @@ class TestSearchCLI:
|
||||
# Either prints "No results" or returns None
|
||||
assert result is None or "No results" in captured.out
|
||||
|
||||
def test_search_query_error_raises(self):
|
||||
def test_search_query_error_raises(self, fake_palace_path):
|
||||
"""search raises SearchError when query fails."""
|
||||
mock_col = MagicMock()
|
||||
mock_col.query.side_effect = RuntimeError("boom")
|
||||
|
||||
with patch("mempalace.searcher.get_collection", return_value=mock_col):
|
||||
with pytest.raises(SearchError, match="Search error"):
|
||||
search("test", "/fake/path")
|
||||
search("test", fake_palace_path)
|
||||
|
||||
def test_search_n_results(self, palace_path, seeded_collection, capsys):
|
||||
search("code", palace_path, n_results=1)
|
||||
@@ -288,7 +298,7 @@ class TestSearchCLI:
|
||||
# Should have output with at least one result block
|
||||
assert "[1]" in captured.out
|
||||
|
||||
def test_search_applies_bm25_hybrid_rerank(self, capsys):
|
||||
def test_search_applies_bm25_hybrid_rerank(self, fake_palace_path, capsys):
|
||||
"""CLI search must call the same hybrid rerank that the MCP path uses.
|
||||
|
||||
Regression for a bug where the CLI only consulted ChromaDB cosine
|
||||
@@ -323,20 +333,20 @@ class TestSearchCLI:
|
||||
"distances": [[1.5, 1.5, 1.5]],
|
||||
}
|
||||
with patch("mempalace.searcher.get_collection", return_value=mock_col):
|
||||
search("foo bar baz", "/fake/path")
|
||||
search("foo bar baz", fake_palace_path)
|
||||
captured = capsys.readouterr()
|
||||
first_block, _, _ = captured.out.partition("[2]")
|
||||
# Lexical match must rank first
|
||||
assert (
|
||||
"b.md" in first_block
|
||||
), f"expected lexical match 'b.md' at rank 1, got:\n{captured.out}"
|
||||
assert "b.md" in first_block, (
|
||||
f"expected lexical match 'b.md' at rank 1, got:\n{captured.out}"
|
||||
)
|
||||
# Non-zero bm25 reported
|
||||
assert "bm25=" in first_block
|
||||
assert "bm25=0.0" not in first_block
|
||||
# Cosine still reported for transparency
|
||||
assert "cosine=" in first_block
|
||||
|
||||
def test_search_warns_when_palace_uses_wrong_distance_metric(self, capsys):
|
||||
def test_search_warns_when_palace_uses_wrong_distance_metric(self, fake_palace_path, capsys):
|
||||
"""Legacy palaces created without `hnsw:space=cosine` silently
|
||||
use L2, which breaks similarity interpretation. CLI must warn
|
||||
the user and point them at `mempalace repair` rather than
|
||||
@@ -349,12 +359,14 @@ class TestSearchCLI:
|
||||
"distances": [[1.2]],
|
||||
}
|
||||
with patch("mempalace.searcher.get_collection", return_value=mock_col):
|
||||
search("anything", "/fake/path")
|
||||
search("anything", fake_palace_path)
|
||||
captured = capsys.readouterr()
|
||||
assert "mempalace repair" in captured.err
|
||||
assert "cosine" in captured.err.lower()
|
||||
|
||||
def test_search_does_not_warn_when_palace_is_correctly_configured(self, capsys):
|
||||
def test_search_does_not_warn_when_palace_is_correctly_configured(
|
||||
self, fake_palace_path, capsys
|
||||
):
|
||||
mock_col = MagicMock()
|
||||
mock_col.metadata = {"hnsw:space": "cosine"}
|
||||
mock_col.query.return_value = {
|
||||
@@ -363,11 +375,11 @@ class TestSearchCLI:
|
||||
"distances": [[0.3]],
|
||||
}
|
||||
with patch("mempalace.searcher.get_collection", return_value=mock_col):
|
||||
search("anything", "/fake/path")
|
||||
search("anything", fake_palace_path)
|
||||
captured = capsys.readouterr()
|
||||
assert "mempalace repair" not in captured.err
|
||||
|
||||
def test_search_handles_none_metadata_without_crash(self, palace_path, capsys):
|
||||
def test_search_handles_none_metadata_without_crash(self, fake_palace_path, capsys):
|
||||
"""ChromaDB can return `None` entries in the metadatas list when a
|
||||
drawer has no metadata. The CLI print path must not crash on them
|
||||
mid-render — it used to raise `AttributeError: 'NoneType' object has
|
||||
@@ -379,14 +391,14 @@ class TestSearchCLI:
|
||||
"distances": [[0.1, 0.2]],
|
||||
}
|
||||
with patch("mempalace.searcher.get_collection", return_value=mock_col):
|
||||
search("anything", "/fake/path")
|
||||
search("anything", fake_palace_path)
|
||||
captured = capsys.readouterr()
|
||||
assert "[1]" in captured.out
|
||||
assert "[2]" in captured.out
|
||||
# Second result renders with fallback '?' values instead of crashing
|
||||
assert "second doc" in captured.out
|
||||
|
||||
def test_search_handles_none_document_without_crash(self, capsys):
|
||||
def test_search_handles_none_document_without_crash(self, fake_palace_path, capsys):
|
||||
mock_col = MagicMock()
|
||||
mock_col.metadata = {"hnsw:space": "cosine"}
|
||||
mock_col.query.return_value = {
|
||||
@@ -395,7 +407,7 @@ class TestSearchCLI:
|
||||
"distances": [[0.1, 0.2]],
|
||||
}
|
||||
with patch("mempalace.searcher.get_collection", return_value=mock_col):
|
||||
search("anything", "/fake/path")
|
||||
search("anything", fake_palace_path)
|
||||
captured = capsys.readouterr()
|
||||
assert "[1]" in captured.out
|
||||
assert "[2]" in captured.out
|
||||
|
||||
@@ -97,9 +97,9 @@ class TestSweeperParsing:
|
||||
records = list(parse_claude_jsonl(str(mock_claude_jsonl)))
|
||||
assistant_rec = records[1]
|
||||
assert assistant_rec["role"] == "assistant"
|
||||
assert (
|
||||
"Paris" in assistant_rec["content"]
|
||||
), f"Assistant content blocks must be flattened to text; got: {assistant_rec['content']!r}"
|
||||
assert "Paris" in assistant_rec["content"], (
|
||||
f"Assistant content blocks must be flattened to text; got: {assistant_rec['content']!r}"
|
||||
)
|
||||
|
||||
def test_parse_preserves_tool_blocks_verbatim(self, tmp_path):
|
||||
"""Per the design principle "verbatim always", tool_use and
|
||||
|
||||
+30
-30
@@ -444,9 +444,9 @@ class TestSyncPalace:
|
||||
# Allow-list — params must be exactly the documented audit shape so
|
||||
# any future leak (source_file, content, ID lists, etc.) trips a
|
||||
# test failure rather than slipping through a deny-list.
|
||||
assert set(params.keys()) <= {
|
||||
"first_id"
|
||||
}, f"WAL params drifted from the audit allow-list: {params.keys()}"
|
||||
assert set(params.keys()) <= {"first_id"}, (
|
||||
f"WAL params drifted from the audit allow-list: {params.keys()}"
|
||||
)
|
||||
|
||||
def test_registry_sentinels_preserved_on_apply(self, tmp_dir, palace_path):
|
||||
"""F2 regression: convo miner `_reg_*` sentinels must survive sync apply.
|
||||
@@ -567,9 +567,9 @@ class TestSyncPalace:
|
||||
inner_resolved = inner.resolve(strict=False)
|
||||
outer_resolved = outer.resolve(strict=False)
|
||||
assert inner_resolved in roots, f"expected inner in roots, got {roots}"
|
||||
assert (
|
||||
outer_resolved not in roots
|
||||
), f"deepest should win exclusively: roots={roots}, outer leaked"
|
||||
assert outer_resolved not in roots, (
|
||||
f"deepest should win exclusively: roots={roots}, outer leaked"
|
||||
)
|
||||
|
||||
def test_apply_with_empty_project_dirs_raises(self, palace_path):
|
||||
"""Round-2 P1: `project_dirs=[]` (empty list) with apply must raise,
|
||||
@@ -608,9 +608,9 @@ class TestSyncPalace:
|
||||
project_dirs=[synced_world["repo_path"]],
|
||||
dry_run=False,
|
||||
)
|
||||
assert any(
|
||||
"Closet purge skipped" in record.getMessage() for record in caplog.records
|
||||
), f"expected closet-skip warning, got: {[r.getMessage() for r in caplog.records]}"
|
||||
assert any("Closet purge skipped" in record.getMessage() for record in caplog.records), (
|
||||
f"expected closet-skip warning, got: {[r.getMessage() for r in caplog.records]}"
|
||||
)
|
||||
|
||||
def test_metadata_cache_cleared_on_exception(self, monkeypatch, config, synced_world, kg):
|
||||
"""F9 regression: tool_sync's try/finally must clear `_metadata_cache`
|
||||
@@ -651,9 +651,9 @@ class TestSyncPalace:
|
||||
assert result.get("success") is False
|
||||
assert "simulated" in result.get("error", "")
|
||||
|
||||
assert (
|
||||
mcp_server._metadata_cache is None
|
||||
), "F9: cache must be cleared even when sync_palace raises"
|
||||
assert mcp_server._metadata_cache is None, (
|
||||
"F9: cache must be cleared even when sync_palace raises"
|
||||
)
|
||||
|
||||
def test_sync_report_keys_stable(self, synced_world):
|
||||
"""Regression: SyncReport schema must not silently drop a field."""
|
||||
@@ -946,9 +946,9 @@ class TestSyncPalace:
|
||||
wing="demo",
|
||||
dry_run=True,
|
||||
)
|
||||
assert (
|
||||
report["gitignored"] == 1
|
||||
), f"symmetric resolve broken: drawer mis-bucketed; report={report}"
|
||||
assert report["gitignored"] == 1, (
|
||||
f"symmetric resolve broken: drawer mis-bucketed; report={report}"
|
||||
)
|
||||
assert report["out_of_scope"] == 0
|
||||
|
||||
def test_classification_cache_avoids_redundant_disk_hits(
|
||||
@@ -1005,9 +1005,9 @@ class TestSyncPalace:
|
||||
)
|
||||
assert report["scanned"] == 5
|
||||
assert report["gitignored"] == 5
|
||||
assert (
|
||||
call_count["n"] == 1
|
||||
), f"cache miss: expected 1 _classify_drawer call (4 cache hits), got {call_count['n']}"
|
||||
assert call_count["n"] == 1, (
|
||||
f"cache miss: expected 1 _classify_drawer call (4 cache hits), got {call_count['n']}"
|
||||
)
|
||||
|
||||
def test_closet_batch_purge_single_call(self, synced_world, monkeypatch):
|
||||
"""Batched $in closet purge: one delete() call across all removable
|
||||
@@ -1074,16 +1074,16 @@ class TestSyncPalace:
|
||||
str(repo_path / "deleted.py"),
|
||||
}
|
||||
expected = len(seeded_sources & set(report["by_source"].keys()))
|
||||
assert (
|
||||
report["removed_closets"] == expected
|
||||
), f"removed_closets ({report['removed_closets']}) != |seeded ∩ removable| ({expected})"
|
||||
assert report["removed_closets"] == expected, (
|
||||
f"removed_closets ({report['removed_closets']}) != |seeded ∩ removable| ({expected})"
|
||||
)
|
||||
assert "wrapper" in captured, "get_closets_collection patch not invoked"
|
||||
assert (
|
||||
captured["wrapper"].delete_calls == 1
|
||||
), f"expected one batch delete call, got {captured['wrapper'].delete_calls}"
|
||||
assert (
|
||||
captured["wrapper"].get_calls == 1
|
||||
), f"expected one batch get call, got {captured['wrapper'].get_calls}"
|
||||
assert captured["wrapper"].delete_calls == 1, (
|
||||
f"expected one batch delete call, got {captured['wrapper'].delete_calls}"
|
||||
)
|
||||
assert captured["wrapper"].get_calls == 1, (
|
||||
f"expected one batch get call, got {captured['wrapper'].get_calls}"
|
||||
)
|
||||
|
||||
def test_registry_check_runs_before_cache_lookup(self, tmp_dir, palace_path):
|
||||
"""A non-registry drawer with the same source_file must NOT poison
|
||||
@@ -1148,9 +1148,9 @@ class TestSyncPalace:
|
||||
finally:
|
||||
del client
|
||||
assert "a_regular" not in survivors
|
||||
assert (
|
||||
"_reg_zzz_sentinel" in survivors
|
||||
), "registry sentinel was incorrectly pruned via cached non-registry verdict"
|
||||
assert "_reg_zzz_sentinel" in survivors, (
|
||||
"registry sentinel was incorrectly pruned via cached non-registry verdict"
|
||||
)
|
||||
|
||||
def test_normalize_project_dirs_sort_stable_on_equal_length(self):
|
||||
"""`_normalize_project_dirs` must sort by `(-len, str)` so equal-length
|
||||
|
||||
@@ -70,7 +70,7 @@ def main():
|
||||
]
|
||||
out.write("\n".join(header))
|
||||
for ts, role, text in turns:
|
||||
out.write(f"\n[{ts}] {role.upper()}\n{text}\n\n{'-'*72}\n")
|
||||
out.write(f"\n[{ts}] {role.upper()}\n{text}\n\n{'-' * 72}\n")
|
||||
if out is not sys.stdout:
|
||||
out.close()
|
||||
print(f"Wrote {len(turns)} turns to {sys.argv[2]}")
|
||||
|
||||
@@ -1232,7 +1232,7 @@ requires-dist = [
|
||||
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0" },
|
||||
{ name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0" },
|
||||
{ name = "pyyaml", specifier = ">=6.0,<7" },
|
||||
{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.4.0" },
|
||||
{ name = "ruff", marker = "extra == 'dev'", specifier = "==0.15.9" },
|
||||
{ name = "tokenizers", specifier = ">=0.15" },
|
||||
{ name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0.0" },
|
||||
]
|
||||
@@ -1243,7 +1243,7 @@ dev = [
|
||||
{ name = "psutil", specifier = ">=5.9" },
|
||||
{ name = "pytest", specifier = ">=7.0" },
|
||||
{ name = "pytest-cov", specifier = ">=4.0" },
|
||||
{ name = "ruff", specifier = ">=0.4.0" },
|
||||
{ name = "ruff", specifier = "==0.15.9" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user