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.
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.
Previously rebuild_index() printed "Staged N/M" / "Re-filed N/M" lines
with no time information, leaving operators to do mental math against
wall-clock to estimate completion on a large palace. On a 183k-drawer
rebuild, it's the difference between "this is a 20-min job" and "this
is an 8-hour job" — non-trivial scheduling information that the
function already has and could easily share.
This patch:
1. Adds a `progress: Optional[Callable[[str], None]] = None` parameter
to `rebuild_index()`. Defaults to a new `_DefaultProgress` class
when omitted (backward-compatible default behavior — same content
plus ETA decoration).
2. `_DefaultProgress.__call__` recognizes `Staged N/M` and `Re-filed N/M`
lines via regex, computes elapsed/rate/ETA, and appends them:
Staged 5000/182953 drawers... (elapsed 7m, rate 11.3/s, ETA 4h)
Non-progress lines (e.g. "Backing up chroma.sqlite3...") pass
through unchanged.
3. The clock + baseline counter reset at the stage→refile transition
so refile-phase rate isn't muddied by the slower stage phase
(refile re-embeds the same drawers and may run at different
throughput).
4. Replaces the in-function `print(...)` status calls with `progress(...)`
so a custom callable receives the full status stream — not just the
batch progress lines.
5. Passes `progress=progress` (instead of hardcoded `progress=print`)
into `_rebuild_collection_via_temp`.
Use cases for a custom `progress` callable:
- Daemon-side capture for HTTP `/repair/status` (this is the motivating
case — palace-daemon was tailing the output to surface progress to
operators via the status endpoint; a callback avoids stdout capture
trickery)
- Test silence: `progress=lambda *_: None`
- Custom formatting: structured logging, JSON event stream, etc.
The default behavior is unchanged for callers that omit the parameter;
they just get a nicer message format.
Closes#1485.
Pass the GA Measurement ID from the GitHub Actions repo variable into the
docs build so the published site at mempalaceofficial.com actually emits
the gtag tags. Also escape the ID via encodeURIComponent / JSON.stringify
so a malformed value can't break the page.
mine_convos was calling file_already_mined() once per file inside the
main loop. On a 150k-drawer palace, each per-file query
(`collection.get(where={"source_file": X}, limit=1)`) costs ~2 seconds
because chromadb has to scan the metadata index. A 2000-transcript
directory took >1h of wall-clock just to decide every file should be
skipped — and pegged multiple cores doing so, starving the daemon's
other endpoints.
bulk_check_mined() already existed for exactly this anti-pattern (its
docstring says "Callers can check membership and compare mtimes locally
instead of issuing one ChromaDB query per file") but only the project
miner used it; the convo miner kept the slow per-file path.
This patch adds a third helper, prefetch_mined_set(), that mirrors
file_already_mined()'s version-gate semantics (the check_mtime=False
branch used by mine_convos) and returns a set[str] for O(1) lookups.
mine_convos now calls it once before the loop; the loop body becomes
a set-membership check.
Observed on a 172k-drawer palace probing 10 files:
before: 21.2s (2.12s/file)
after: single bulk pass should be 30–60s for the whole 172k scan,
then 2000 O(1) checks ≈ free
file_already_mined() is kept for callers that genuinely need the
per-file semantics (the post-lock race-check in _file_chunks_locked
at convo_miner.py:350 still uses it intentionally).
Surfaced via jphein/familiar.realm.watch foundation-rework debugging
on 2026-05-11. Originally filed as #51.
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>
Belt-and-suspenders on top of the repair.py sanitization in the
previous commit. A 151,478-drawer rebuild test still failed at
~120K with the same `ValueError: Expected metadata to be a
non-empty dict` from chromadb, even with the repair.py sanitizers
in place. Traceback:
mempalace/backends/chroma.py:add → chromadb Collection.add
→ validate_insert_record_set → validate_metadatas
→ validate_metadata → ValueError
Likely cause: chromadb's `upsert()` internally calls `add()` for
new records, and somewhere between repair.py's batch upsert and
chromadb's final write, the metadatas list gets reprocessed in a
way that re-introduces empty/None entries.
Sanitizing at the chromadb-client chokepoint catches everything:
no caller can leak bad metadata regardless of upstream sanitization
state. Same `{"_repaired_empty_meta": True}` sentinel, searchable
via `where={"_repaired_empty_meta": True}`.
Cost: one list comprehension per write call; negligible vs the
embedding + HNSW work each upsert already does.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two functions construct the metadatas[] list that gets fed to
chromadb's upsert/add, both vulnerable to the same ValueError:
ValueError: Expected metadata to be a non-empty dict, got 0
metadata attributes in add.
chromadb 1.5.x's validate_metadata rejects both `None` and `{}`
entries — see chromadb/api/types.py:validate_metadata (line ~1071).
This commit patches both:
1. `_extract_drawers` (line ~131) — the chromadb-collection-based
extractor, used when the source palace's collection is openable
via the chromadb client. Sanitizes None/{} entries in the
`batch["metadatas"]` list to `{"_repaired_empty_meta": True}`
before extending `all_metas`.
2. `_rebuild_one_collection` (line ~813) — the SQLite-direct
extract path used by `rebuild_from_sqlite()`, invoked when the
source palace can't be opened via chromadb (the recovery path
for palaces with corrupt HNSW segments). Old code was:
metas.append(meta if meta else {})
The trailing `{}` was the bug; chromadb 1.5.x rejects empty
dicts the same as None. Replaced with the same sentinel.
Why `_repaired_empty_meta: True` as the sentinel:
- Satisfies chromadb's non-empty-dict requirement
- Bool-valued (valid chromadb metadata type, trivially serializable)
- Namespaced + descriptive so an operator can find which drawers
were coerced via `where={"_repaired_empty_meta": True}` later
- Idempotent on re-runs (a future repair over a sanitized palace
sees the sentinel as already-valid)
Verified on a 151,478-drawer production palace that previously
crashed at drawer 120,000 in both extract paths.
Fixes#1458
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Tasks that score via semantic similarity (memory_extraction,
room_classification open-set) depend on nomic-embed-text. If the model
was absent, embed_text() returned None silently and every sample scored
0.0 — indistinguishable from a genuinely bad model.
_ensure_embed_model() now probes the endpoint before the warmup step.
On a 404 it pulls the model automatically via `ollama pull`, verifies
the endpoint responds, and only then proceeds. Fixes:
- OLLAMA_HOST is now forwarded to `ollama pull` so non-localhost
endpoints are targeted correctly
- FileNotFoundError is caught and re-raised as RuntimeError with an
install hint if ollama is not on PATH
- Diagnostic prints go to stderr, not stdout
- If the pull or re-probe fails, returns a Result with a clear error
message instead of silent zeros
Restores --candidates local to its documented meaning (all non-cloud
models). Adds --candidates community for third-party GGUF variants.
Ten fixes across code, documentation, and committed baselines:
Code fixes:
1. prompts.py: closed-set prompt said "no punctuation" while room
slugs contain "/". Replaced with explicit "copy the slug verbatim
including / and -" wording. Empirical impact on accuracy is within
reproducibility noise (qwen3:4b q4 was 0.610, retest shows 0.594
on the now-101-sample dataset — same vs new sample noise).
2. orchestrator.py: orchestrator now opens the CSV once, writes the
header, and flushes after each row. README's "writes incrementally,
safe to Ctrl-C" claim is now accurate. Long matrix runs no longer
lose all progress on a crash.
3. metrics.py: gather_host_info() now strips trailing newline from
`hostname` command output. Stops embedded newlines from leaking
into committed CSVs.
4. runner.py: passed `endpoint=endpoint` to vram_resident_mb() so
non-default Ollama endpoints are queried correctly.
5. summarize.py: CSV reader and report writer now use
encoding="utf-8" with explicit newline handling for cross-platform
consistency.
Documentation fixes:
6. entity_extraction/score.py: docstring claimed "case-sensitive on
type" while implementation lowercases both. Corrected.
7. dataset.jsonl rc_101: removed mempalace-private URL since the PR
lands on the public repo. Will be linkable after OpenClaw merges.
8. datasets/README.md: sample counts updated (room_classification 100
→ 101, total 210 → 211) to match the cherry-picked real-format
sample.
9. runner.py / orchestrator.py: docstring example paths corrected
(tests/fixtures/mempalace_bench → benchmarks/model_eval/datasets).
Baseline regeneration:
10. Stripped embedded \n from `host` column in all five committed
CSVs (2026-05-10 main local + spotcheck, 2026-05-10 + 2026-05-11
cloud, 2026-05-11 modern). 165 rows cleaned in place via Python
csv reader/writer. Each row is now line-oriented for diff and
grep friendliness without changing any measured values.
Adds a "Contributions welcome" section to the README covering:
1. Adding models we missed. The published candidate list is one
engineer + one search pass. Particularly call out function-calling-
tuned variants (Phi-4 mini, Nemotron-mini), research-lab instruct
models (Hermes, Dolphin), and quantization-aware-trained variants
as worth-adding categories.
2. Adding other inference backends. mempalace.llm_client.get_provider
already supports openai-compat, which means LM Studio, llama.cpp
server, vLLM, unsloth studio, Docker Model Runner, HF TGI all
plug in with minimal harness changes. Documents the four pieces a
backend contributor would need to touch:
- Backend-selection flag in runner/orchestrator
- Backend-specific timing extraction in metrics.py
- Backend-specific VRAM probe
- candidates.yaml backend field
Notes that accuracy numbers stay comparable across backends since
the dataset and scoring code are backend-agnostic.
Also calls out niche runtimes worth cross-comparison: Apple MLX,
Intel OpenVINO, AMD ROCm, edge-device runtimes.
Existing harness-maintainer notes (cloud structured-outputs gotcha,
memory hallucination metric caveat, cloud reproducibility variance)
moved under a separate heading.
The previous README had a minimal quick-start section. Replaced with
a proper end-to-end reproduction guide for contributors who want to
validate the published numbers on their own hardware.
New sections:
- Prerequisites: GPU, Ollama version, Python, disk, optional cloud auth
- Set up the environment
- Pull candidate models (with a bulk-pull Python snippet that reads
candidates.yaml directly so it stays in sync with future additions)
- Smoke test (~30 sec, confirms harness works)
- Run the matrix (Tier 1 / all local / cloud, with time estimates)
- Render a report
- Compare with the published baseline (what kind of agreement to expect
on accuracy vs speed vs VRAM)
- Sharing your results (how to attach a CSV to a follow-up PR or
open an issue if numbers diverge)
- Notes for new contributors to the harness itself (the known cloud
structured-output limitation, the memory-extraction hallucination
metric caveat, cloud reproducibility variance)
Tier filter docs now include the `modern` filter added in the
modern-tier expansion. Single-model runs by exact tag are documented.
Goal: someone cloning the repo for the first time should be able to
reproduce a Tier 1 matrix in ~45 min without reading anything else.