Addresses Copilot review: the ruff pin was incomplete.
- .pre-commit-config.yaml stayed on ruff-pre-commit v0.4.10, so
contributors running pre-commit would reintroduce the exact 0.4-vs-0.5
formatter drift this PR removes. Bumped rev to v0.15.9 and rewrote the
lock-step comment to point at pyproject as the source of truth.
- uv.lock still constrained dev ruff at >=0.4.0, so `uv sync --extra dev`
(the documented setup) would not honor the new exact pin. Regenerated;
the dev specifier is now ==0.15.9 in both lock entries.
ruff check/format still pass; no formatting delta from these files.
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 installed `ruff>=0.4.0,<0.5` (resolves 0.4.10) while contributors
run modern ruff (0.5+). ruff 0.5 changed assert-message formatting, so
valid code formatted by a current ruff fails CI's `ruff format --check .`
on layout alone. This blocked #1438, #1445, and #1528 — each needing a
manual reformat-and-push cycle with no actual code defect.
Pin an exact, modern ruff in both pyproject dev lists and in ci.yml so
CI and `pip install -e ".[dev]"` format/lint identically. No new
`ruff check` violations under the existing E/F/W/C901 select.
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.
Address PR #1528 review feedback (gemini-code-assist, medium):
_source_file_delete_ids duplicated the legacy-drawer matching logic
that already lives in palace._metadata_matches_extract_mode.
Import the helper and call it instead so the back-compat rule
(legacy drawers without extract_mode count as exchange-mode) has a
single source of truth.
No behavior change. All 71 miner/convo tests still pass.
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.
Move _canonicalize_kg_path call from inside the except branch to the
top of _call_kg so OSError from realpath (e.g. transient Windows
junction loss) propagates cleanly instead of masking the original
sqlite3.ProgrammingError mid-handler. Also keeps the eviction key
identical to the insertion key if FS state mutates between attempts,
preventing a closed handle from leaking into the cache under a stale
key the lookup no longer matches.
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.