One-time mechanical reformat so `ruff format --check .` passes under the
newly pinned ruff. Layout only (assert-message parenthesization etc.),
no behavior change. 29 files: 28 under tests/ + 1 tools helper, no core
mempalace/ modules. Produced by `ruff format .`.
CI pins ruff>=0.4.0,<0.5 (resolves 0.4.10); one new assert block was
laid out in ruff-0.5+ style, failing `ruff format --check .`.
Reformat with the exact CI ruff version (assertion layout only, no
semantic change). `ruff check .` + `ruff format --check .` both pass
under 0.4.10.
CI pins ruff>=0.4.0,<0.5 (resolves 0.4.10); the PR's two new assert
blocks were laid out in ruff-0.5+ style, so `ruff format --check .`
failed. Reformat with ruff 0.4.10 (the exact CI version) — assertion
layout only, no semantic change. `ruff check .` + `ruff format --check .`
both pass under 0.4.10.
The PR reformatted two pre-existing assertions with a newer ruff
(0.5+ `assert X, (\n msg\n)` style) that CI's pinned ruff
(>=0.4.0,<0.5) rejects, failing `ruff format --check .`. Revert those
two unrelated blocks to develop's 0.4.x form; the genuine #1435 fix and
its new regression tests are untouched.
- searcher.search: add filesystem-first isdir/isfile checks before
get_collection so State B (palace dir exists, chroma.sqlite3 absent)
is distinguished from State C ("initialized but empty") instead of
triggering chromadb's lazy DB creation as a side effect of a
read-only search call. Preserves the SearchError(...) from e chain
via the typed exception catches that follow.
- cli.cmd_compress: replace the redundant `ChromaBackend()` instance
used for the mempalace_closets write with
`palace.get_closets_collection(create=True)`. The closets write now
reuses the module-level _DEFAULT_BACKEND, avoiding the WAL-lock
contention risk on Windows that Gemini flagged.
- tests: new `fake_palace_path` fixture for searcher CLI unit tests so
the filesystem-first state checks pass through to mocked backends
instead of raising on State A / B; cmd_compress stores-results test
patches `palace.get_closets_collection` to mirror the new write path.
`mempalace status`, `search`, and `compress` printed the same misleading
"No palace found / Run: mempalace init" output for three distinct
palace states (no dir / no DB / no collection). Most user-visible on
the first-run state where `init` had run but `mine` had not: the hint
to re-run `init` is a no-op and wastes the user's time.
Backend gets a new typed exception `CollectionNotInitializedError`
(subclass of `PalaceNotFoundError`, transitively `FileNotFoundError`,
so legacy callers keep working). `ChromaBackend.get_collection(
create=False)` wraps chromadb's bare `NotFoundError` as the new typed
exception instead of leaking the chromadb-specific class to callers.
A new internal helper `_open_collection_or_explain` in `palace.py`
runs filesystem-first state checks before the backend call to avoid
chromadb's lazy `chroma.sqlite3` creation as a side-effect of a
read-only inspection, then catches the typed exceptions and prints a
state-specific actionable message. `BackendClosedError` is explicitly
re-raised so a programmer error is not masked as a UX hint.
Two CLI bug sites route through the helper: `miner.status` and
`cli.cmd_compress`. `searcher.search` catches the typed exceptions
directly so it can preserve the cause chain in `SearchError(...) from
e` for programmatic search-API consumers. `cli.cmd_sync` gained an
inline filesystem distinction (no helper needed: it does not use the
collection handle). `repair.status` (capacity check, which by design
must work on corrupted palaces without opening a chromadb client) got
the same distinction via `sqlite_drawer_count`-based empty detection.
The MCP `tool_status` is intentionally left alone: PR #831 already
fixed it there with a `create=True` bootstrap strategy appropriate
for programmatic clients.
MCP clients (Claude Code, Claude Desktop) surface the cold-load of the
ONNX/CoreML embedder + HNSW segment as -32000 "Internal tool error"
without a recoverable trace, because the first chromadb-touching tool
call after a fresh mempalace-mcp boot can exceed the client timeout.
Two opt-in env vars, both default off, both fail-soft:
- MEMPALACE_LOG_FILE: append-mode FileHandler so the server-side
traceback that the MCP client never surfaces stays diagnosable. Invalid
path falls back to stderr-only with a warning naming the env var, so
it cannot itself become a server-start failure. basicConfig uses
force=True so the FileHandler is not silently dropped when something
already configured root logging. (OSError, ValueError) catch covers
Windows NUL-byte paths in addition to POSIX missing-dir / EPERM.
- MEMPALACE_EAGER_WARMUP: pre-loads embedder + HNSW segment at the end
of main() startup via _get_collection(create=False).query(...) — a
single call drives ONNX _download_model_if_not_exists +
InferenceSession AND HNSW data_level0.bin segment load (HNSW chunks
are read lazily on the first chromadb collection op). Fresh-install
pre-check on os.path.isfile(palace/chroma.sqlite3) skips the warmup
before any chromadb client call so the chromadb constructor cannot
materialize the palace scaffold before `mempalace init` (preserves
CLAUDE.md "Incremental only" invariant). Truthy 1/true/yes/on; falsy
0/false/no/off and empty are silent; unrecognized values warn so
typos like "tru" do not silently disable the feature. All failure
paths (collection-open-raise, returned-None, query-raise) log with
palace path + device + error class so ops can disambiguate.
Empirical evidence (Linux, CPU-only ONNX, ~1k drawers): first
diary_write t_handoff = 7.60s baseline vs 0.17s with warmup
(-7.4s shifted off the first-call window into startup). CoreML cold-load
on macOS is reported at 5-30s in the issue's empirical record
(paideia#114); the CPU baseline above is the floor.
Tests (24 cases) cover both env vars across set/unset/empty/invalid/
garbage paths, warmup truthy/falsy/garbage parsing, fresh-install (real
integration, no monkeypatch — pins zero on-disk side effect),
collection-open-raise / returned-None / query-raise fail modes, and
two regression pins: warning-before-banner ordering (guards delay=True
regression) + truthy path actually invokes col.query (guards no-op
warmup regression). Probe text is a sentinel so it cannot semantically
match real drawer content.
Co-Authored-By: StarshipSuperjam <33380501+StarshipSuperjam@users.noreply.github.com>
create_tunnel no longer normalizes hyphen->underscore on write. Wings
created via "mempalace mine --wing my-wing" are stored verbatim in
tunnels.json. list_tunnels and follow_tunnels filters normalize both
the stored value and the query at compare time so previously-stored
underscore tunnels and post-fix verbatim tunnels both resolve via
either query form.
compute_topic_tunnels canonicalizes its wing keys via
normalize_wing_name so repeated mining runs with mixed slug forms
cannot accumulate parallel duplicate tunnels. topic_tunnels_for_wing
gains a symmetric lookup so a hyphenated argument finds an
underscore-keyed registry entry.
_normalize_wing now returns None for non-string inputs instead of
raising; read-path filters use the (t.get(k) or {}) idiom so
hand-edited records with "source": null no longer crash iteration.
Mining a transcript with --extract general was silently skipped when the
same file had already been mined with --extract exchange (or vice versa)
because file_already_mined() and prefetch_mined_set() only looked at
source_file. The two extraction modes produce different drawer content
and rooms, so they should coexist for the same source.
Changes:
- file_already_mined() and prefetch_mined_set() take an optional
extract_mode arg and only return True when stored drawer metadata
matches. Legacy drawers without extract_mode are treated as
exchange-mode for back-compat.
- _file_chunks_locked() purges only same-mode drawers when rebuilding
on a normalize-version bump, so a schema bump on one mode does not
drop drawers filed under the other.
- Drawer ids and sentinel ids include extract_mode so the two modes
cannot collide on hash.
- Pagination on the direct skip-check path so large transcripts (>1k
drawers) are classified correctly when the bulk prefetch is skipped.
Adds regression coverage for the extract-mode-aware helper, the
pagination path, and an end-to-end mine_convos run that files
exchange then general for the same transcript without skipping.
Cycle 2 follow-up: harden the permission tests so they actively
falsify the "ambient umask masking a regression" hypothesis raised
during the adversarial review pass.
- `_run_hook` now sets `preexec_fn=lambda: os.umask(0o022)` on the
bash subprocess. The child starts with a permissive 022 umask so a
bare file would land at mode 0644. The hook's own `umask 077` in
the parse subshell remains the only thing protecting
`last_python_err.log` and `last_input.log`, so `test_dump_is_not_world_readable`
and `test_python_stderr_log_is_not_world_readable_on_failure` now
empirically prove that protection rather than passively benefitting
from a CI runner's restrictive ambient umask.
- Docstring precision: the helper's primary diagnostic surface is
`hook.log` (a file under `STATE_DIR`), not the subprocess's stderr.
Subprocess stderr is captured here only to surface unexpected
interpreter failures (e.g., a bash syntax error introduced by a
future edit), and the docstring now says so.
No production-code changes. 26/26 tests still pass.
Follow-up on c271e7b after the bot review and an adversarial pass.
- Replace `echo "$INPUT"` with `printf '%s' "$INPUT"` in both hooks
so payloads with leading `-n`/`-e`/`-E` or backslashes are not
eaten by echo flag parsing.
- Wrap the `last_python_err.log` and `last_input.log` writes in a
`( umask 077; ... )` subshell so the files are created at mode
0600 atomically. The existing `chmod 600` calls stay as
belt-and-suspenders.
- Refactor the `_run_hook` test helper: internal assert on
returncode with stderr surfaced in the failure message; new
`extra_env=` kwarg subsumes the ad-hoc `subprocess.run` in the
UTF-8 locale test.
- Promote the world-readable, bounded-overwrite, UTF-8, unicode and
literal-unknown tests to a shared `_BOTH_HOOKS` parametrize with
readable ids so the symmetry across both hooks is enforced.
- `test_sed_extraction_present` strips line comments before counting
`sed -n '` occurrences so a regression that swapped sed back to
mapfile while keeping the prose cannot false-pass.
- Rewrite the precompact hook header docblock: the previous
"ALWAYS blocks" wording was stale (the hook returns `{}` and
does not emit a `decision: block` payload to the Stop-hook
protocol; the "always run" guarantee comes from the synchronous
mine call).
- Apply ruff 0.4.x format to the new test file (matches CI pin
`pip install "ruff>=0.4.0,<0.5"`).
Tests: 1749 passed (was 21 cases in c271e7b's test file; now 26 after
parametrize promotions, +5 cases).
The legacy hook scripts used `mapfile -t` (introduced in #1231) to read
sanitized values from the inline Python JSON parser. On stock macOS
/bin/bash is GNU 3.2.57 (Apple GPLv3 freeze) and `mapfile` only landed
in bash 4.0, so the hook silently failed: every parsed value fell back
to its default, the log wrote "Session unknown: 0 exchanges", and zero
drawers were saved.
This commit replaces the array read with `sed -n 'Np'` line extraction,
which is POSIX and runs on /bin/bash 3.2 unmodified. It also adds a
defense-in-depth fail-loud guard: Python prints a `__MEMPAL_PARSE_OK__`
sentinel and the hook surfaces the raw input plus Python traceback to
0600-mode sibling files when the sentinel is missing, so the next silent
failure has a debuggable trail instead of an unsolved zero-drawer day.
_get_kg now accepts an optional canonical_path argument and uses it
verbatim when given. _call_kg passes its top-of-function captured key
through, so the dict insertion that _get_kg performs and the eviction
lookup _call_kg performs always agree on the key -- even if env state
(MEMPALACE_PALACE_PATH rotation) or FS state (symlink remap) mutates
between attempts. Without the pass-through, _get_kg's internal call
to _canonicalize_kg_path(_resolve_kg_path()) could land on a different
key than the captured path, leaving a closed handle in the cache under
a stale key the eviction lookup no longer matches.
Tests:
test_call_kg_passes_captured_path_through_resolve_drift -- patches
_resolve_kg_path with a shifting iterator + identity canonicalize,
pre-seeds the closed handle under the captured key; asserts both
_get_kg calls receive the captured key and the closed handle is
evicted by retry.
test_call_kg_oserror_at_top_propagates_unmasked -- patches
_canonicalize_kg_path to raise OSError; asserts it propagates without
conversion (the rationale for capturing at the top before the retry
loop -- prevents an OSError mid-handler from masking a
sqlite3.ProgrammingError it can't retry through).
_patch_mcp_server test helper updated to a varargs lambda so existing
tests that patch _get_kg as a no-arg fixture stay compatible with the
new optional-arg signature.
Patch both realpath and normcase with sentinel wrappers and assert the
result composes them as normcase(realpath(p)). Swapping the order would
leave Windows symlinks under the original case, defeating the dedup.
The previous assertion (result == seen[-1].lower()) was tautological --
the fake normcase already returned p.lower(), so any implementation
that lowercased anything would pass.
Switch _kg_by_path lookups in _get_kg and _call_kg from os.path.abspath
to a new _canonicalize_kg_path helper applying realpath (collapses
symlink aliases) + normcase (Windows drive-letter casing). Two tenants
pointing at /srv/A and /srv/link-to-A no longer open duplicate
sqlite3.Connection handles over the same file.
Addresses review-bot feedback on #1519:
- gemini: JSON `Infinity`/`1e1000` round-trips to float('inf'); int(inf)
raises OverflowError, which _try_coerce_int did not catch — bad config
could still crash ingest. Catch it alongside TypeError/ValueError and
fall back like any other garbage value. Regression test added.
- Copilot: the 30-char convo floor was described as "stricter" than the
50-char project default. It is the opposite — lower, i.e. more
permissive (keeps short exchanges the project default would drop).
Reworded the docstring and comments to state this accurately.
The #1024 merge added `import pytest` to tests/test_convo_miner_unit.py
while a pytest import already existed from another merged change. The
collision was textually clean so git didn't flag it, but CI ruff
reports F811 (redefinition of unused `pytest`), turning lint red on
develop and every branch cut from it.
Drop the duplicate import. `ruff check .` (0.4.x, CI pin) clean;
test_convo_miner_unit 23 passed.
#1024 routed min_chunk_size for the project miner through the repairing
MempalaceConfig validation, but the convo path read the raw, unvalidated
_file_config["min_chunk_size"]. A garbage/negative/bool config value
would TypeError the convo length gate or ValueError out of
chunk_exchanges and abort the whole convo mine — breaking the PR's own
"a bad config.json key never takes ingest down" guarantee for one path
only.
Extract _try_coerce_int helper (shared with _coerce_config_int) and add
a public MempalaceConfig.min_chunk_size_explicit accessor that returns
the validated value when the user set it, else None. convo_miner uses
the None sentinel to keep its stricter 30-char floor for untuned users
while honoring a valid override, with no raw _file_config reach.
Adds accessor + convo-fallback regression tests.
Unknown kwargs (wrong parameter name, e.g. text= instead of content=)
were silently dropped by the schema-filter, surfacing only indirectly
as a later "Missing required 'X'". Emit -32602 naming the offending
kwarg instead — symmetric with #1500's missing-required path. Gated by
the existing accepts_var_keyword check; wait_for_previous excluded.
Closes#1512.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Split the bare except in handle_request tools/call: TypeError matching
Python's signature-mismatch shape (gated on handler __qualname__) returns
-32602 with parsed parameter name(s); handler-internal TypeError and
non-TypeError exceptions stay on the existing generic -32000 path so
internals never leak. Adds TestParamShapeDiagnostics with 6 cases.
Closes#1351
Co-authored-by: anastasiiaanfimova <271004602+anastasiiaanfimova@users.noreply.github.com>
A direct ``hook["type"]`` subscript raised ``KeyError`` before the
assert evaluated when the ``"type"`` key was missing, so the
diagnostic message naming the event and the unexpected value was
never shown. ``hook.get("type")`` lets the assert fail gracefully
with the intended feedback.
A duplicate hook entry inside `entries[0]["hooks"]` (or a second
entry under `Stop`/`PreCompact`) silently passes the per-hook
bounds check and would double-fire the hook. Pin `len(entries) == 1`
and `len(sub_hooks) == 1` so cardinality drift fails loudly with a
diagnostic message naming the event and the unexpected count.
The `.claude-plugin/hooks/hooks.json` Stop and PreCompact entries
shipped without an explicit `timeout`, so a hung `mempalace hook
run` (reported on Windows under CLI/plugin version drift) blocks
the Claude Code UI for the full 600s `"type": "command"` default.
Set explicit bounds: Stop = 30s (fire-and-forget save path with
synchronous chromadb diary write, detached mine via _spawn_mine),
PreCompact = 90s (60s inner _mine_sync subprocess timeout in
mempalace/hooks_cli.py plus a 30s slack so legitimate mines for
users with MEMPAL_DIR are not truncated mid-flight).
Schema test in tests/test_claude_plugin_hook_config.py pins both
per-event (floor, ceiling) bounds and catches future events added
to the plugin config without a registered bounds entry.
* Move SKIP log from stdout to sys.stderr, matching the existing
warning-channel pattern (the "No mempalace.yaml" notice and
topic-tunnel warnings). Stdout stays clean for "Files: N" /
"Drawers filed: N" markers that downstream callers parse.
* Show the path relative to the scan root via
Path.relative_to(...).as_posix() instead of the leaf filename, so
a nested symlink in a deep subdirectory is unambiguous and the log
renders with forward slashes on every platform.
* Wrap the print in try/except OSError, mirroring the existing guard
around filepath.stat() below; a broken pipe or closed stderr no
longer aborts the scan mid-walk.
* Document the stderr side effect in both scan_convos and
scan_project docstrings.
* Gate the new tests with @pytest.mark.skipif(sys.platform == "win32",
...) because Path.symlink_to requires SeCreateSymbolicLinkPrivilege
on Windows.
* Add dangling-symlink and nested-subdirectory tests for both miners,
locking the two-space " SKIP:" prefix, the "(symlink)" reason
marker, and the full relative path format.
Both scan_convos() and scan_project() silently drop symlinked files,
leaving callers staging a temp directory of symlinks with no diagnostic
for the "Files: 0" outcome. Keep the existing skip-symlinks behavior
and add a " SKIP: {name} (symlink)" log per skipped file, matching
the convention already used by split_mega_files.py for the
oversized-file skip case.
Three-way assertions in test_cli and test_mcp_server now also assert
SENTINEL_IN_PATH is False at import, so a regression in the package
sys.path filter is caught by the same test that catches the env pop
regression. SystemExit catch is narrowed to exit codes (0, None) so a
future argparse change surfaces as a failure instead of being swallowed.
cli.py:main and mcp_server.py:main docstrings document the PYTHONPATH
pop side effect for callers that invoke main() programmatically.
Refs #1423.
Split the leaked-PYTHONPATH workaround: __init__.py now only filters
sys.path (fixes the ABI crash from #1423 at import time), while
os.environ.pop("PYTHONPATH") moves to cli:main() and mcp_server:main()
where the strip affects only subprocesses we spawn ourselves.
Host applications that import mempalace as a library and rely on
PYTHONPATH for their own child subprocesses are no longer affected.
Refs #1423.
When PYTHONPATH is `.`, both the leaked entry and the implicit
empty-string CWD marker on sys.path normalize to `.`. The previous
filter would remove the CWD marker too, silently changing import
resolution. The sys.path filter now preserves any empty-string entry
unconditionally.
Also drop the asymmetric `.strip()` on PYTHONPATH tokens. CPython
does not strip whitespace from PYTHONPATH before populating sys.path,
so stripping on one side only could let whitespace-padded leaks
through.
Test extended with a `dot` parametrize case and a dedicated
test_init_preserves_cwd_marker_when_pythonpath_collides. Test child
code now asserts on the sentinel-prefix substring directly instead of
re-implementing the production normalization, so future changes to
_norm cannot silently mask test regressions.
Previous commit compared sys.path entries to PYTHONPATH tokens by
byte-exact string equality, which let leaks slip through on Windows
(case-insensitive paths) and across trailing-separator or whitespace
quirks (a leading or trailing space in PYTHONPATH would not match the
trimmed sys.path entry the interpreter actually populated).
Both sides of the comparison now run through os.path.normcase +
os.path.normpath so case differences and trailing separators no longer
defeat the filter, and PYTHONPATH tokens are trimmed before the
match.
Test extended to 6 parametrized cases (single, multi-path, trailing
separator, leading pathsep, empty, unset) with explicit ids and
stderr included in assertion diagnostics. Synthetic leak placeholder
replaces /tmp so the test is portable across CI runners.
Popping PYTHONPATH from os.environ alone is insufficient: the interpreter
populates sys.path from PYTHONPATH at startup, before package init runs.
Transitive imports of compiled extensions (pydantic_core,
chromadb_rust_bindings) would still resolve from the leaked path even
after the env var is cleared.
Now also remove the matching entries from sys.path so the import search
path no longer contains the wrong Python's site-packages.
Test extended with a multi-path PYTHONPATH case and assertions on both
os.environ and sys.path after import.
Venvs do not strip PYTHONPATH from inheritance. On multi-Python systems
where PYTHONPATH points at a different Python's site-packages, transitive
imports of compiled extensions (pydantic_core, chromadb_rust_bindings)
load the wrong ABI and crash with ModuleNotFoundError on
pydantic_core._pydantic_core.
Place the pop in mempalace/__init__.py (instead of cli.py as the reporter
proposed) so all entry points are covered: the mempalace shell command,
python -m mempalace, and import mempalace from a library.
Tests: tests/test_init.py runs the strip in a subprocess, parametrized
over set / unset PYTHONPATH.
Closes#1423.
Addresses @Copilot's review feedback on #1459. Five tests:
- test_extract_drawers_preserves_valid_metadata: non-empty dict
passes through unchanged (regression guard against breaking happy
path).
- test_extract_drawers_sanitizes_none_metadata: None entries
coerce to {"_repaired_empty_meta": True} (the core fix).
- test_extract_drawers_sanitizes_empty_dict_metadata: empty dict
{} entries also coerce to the sentinel (chromadb 1.5.x rejects
both shapes equally).
- test_extract_drawers_sanitization_preserves_alignment: critical
invariant — ids[i] / documents[i] / metadatas[i] stay in
lockstep through the sanitizer; mis-pairing would silently
corrupt rebuilds.
- test_extract_drawers_multiple_batches: pagination boundary
correctness (sanitizer applied per-batch, no drops/duplicates).
Verified passing locally against mempalace fork main + chromadb
1.5.8 in the palace-daemon venv (5 passed, 67 deselected in 1.88s).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>