Address review feedback: `with sqlite3.connect() as conn:` only
manages transactions, it does not close the connection. An open
connection before PersistentClient instantiation can leave WAL state.
Use explicit `try...finally: conn.close()` matching the read-only
helpers elsewhere in the module.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
chromadb <= 1.5.8 writes config_json_str = '{}' (empty JSON) when
creating collections. chromadb 1.5.9 introduced a strict _type check
in the collection config deserialization path -- its absence raises
KeyError: '_type' on palace open. Since the pin allows >=1.5.4,<2,
any upgrade pulls 1.5.9 and breaks every existing palace.
Add a fourth pre-open migration step (_fix_missing_collection_type)
that injects "_type": "CollectionConfigurationInternal" into
collections.config_json_str rows that lack it. Same lifecycle and
marker-file pattern as the existing _fix_blob_seq_ids.
Co-Authored-By: nautis <nautis@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Resolves conflicts in miner.py and palace.py against the COCA-hoist
work from #1612 just merged. Both files had local imports for
_get_coca_filter / _candidate_entity_words in the function bodies;
after #1612 those moved to module top. Resolution: hoist
_apply_known_systems_prepass alongside _get_coca_filter at module
top in both files, drop the now-empty local imports.
No behavior change; just removes the local-import duplication that
would have been left in place if the merge auto-resolved naively.
Addresses gemini-code-assist MEDIUM finding on PR #1613: the previous
implementation of _apply_known_systems_prepass compiled a regex pattern
for every compound on every call, repeating the work on every drawer
mined and every closet built. With 59 compounds × N drawers, that's
59N re.compile() calls for a workload where the patterns never change.
The fix moves compilation into _get_known_systems (already lru_cache'd
to size=1), which now returns tuple[tuple[str, re.Pattern], ...] —
pairs of (canonical name, pre-compiled case-insensitive word-bounded
regex). _apply_known_systems_prepass consumes the cached tuple and
does zero compilation in the hot path.
Behavior is identical: same word boundaries, same case-insensitive
matching, same longest-first ordering, same graceful-degrade on
malformed json. All 74 entity_detector tests still pass on macOS plus
the full 2258-test suite on Linux Py 3.9 / 3.11 / 3.13.
Adds a curated list of multi-word product/system names ("Claude Code",
"GitHub Copilot", "Visual Studio Code", "GPT-4", …) and a compound
pre-pass that detects them atomically before the existing single-word
extraction runs. Without this, the regex-based detector decomposes
"Claude Code" into "Claude" + "Code" — and the COCA filter (shipped
in v3.3.6) then drops "Code" as a content word, leaving "Claude" alone
with the wrong attribution.
What ships
- mempalace/data/known_systems.json — 59 curated compounds covering
common AI assistants, IDEs, model names, cloud platforms, and
Office/Google apps. Each entry is multi-word or hyphenated;
single-word product names ("ChatGPT", "Cursor") have no
decomposition risk and stay handled by the existing regex.
- mempalace/entity_detector.py — _get_known_systems() (cached loader,
mirrors _get_coca_filter from Tier 2) and _apply_known_systems_prepass
which scans for each compound case-insensitively with word boundaries,
counts occurrences, and returns the masked text + count dict so the
subsequent single-word + multi-word loops don't re-decompose.
- mempalace/miner.py and mempalace/palace.py — same pre-pass wired
into _extract_entities_for_metadata (per-drawer tagger) and
build_closet_lines (closet pointer construction). Without these,
the new behavior would only apply at init-time and per-drawer
metadata would still decompose compounds.
How it interacts with Tier 2
Tier 2 (COCA filter) blocks single-word content nouns like "Code"
and "Brutal". Tier 3 protects multi-word product names so they
don't get decomposed in the first place. They complement each
other: the compound pre-pass runs FIRST and masks compounds out
of the text; the COCA filter then runs on the remaining
single-word candidates.
Behavior verification
Before this PR, mining a document containing "Claude Code wrote the
patch" three times emitted entities:
Claude;Claude Code;Code (Code filtered by COCA);
After this PR, the same document emits:
Claude Code
The standalone "Claude" no longer appears (it never actually appeared
alone in the source) and decomposition stops at the compound boundary.
Tests
Nine new tests in tests/test_entity_detector.py covering:
- "Claude Code" detected as atomic compound at extract_candidates
- "Claude" alone NOT in results when only mentioned as part of compound
- Case-insensitive compound matching (claude code, CLAUDE CODE, etc.)
- Single-word "Code" still filtered by COCA (no Tier 2 regression)
- Single-word real name "Aya" still detected (no regression on names)
- Multiple distinct compounds in one text both detected
- Unknown two-word phrase still detected via existing multi-word regex
- known_systems.json ships with expected schema (>=20 entries, all multi-token)
- known_systems.json contains expected high-value entries
Verification
Full pytest 2267 passed / 3 skipped on macOS, coverage 85.34%.
Linux Py 3.9 / 3.11 / 3.13 via CI-matching pip install -e ".[dev]":
2258 passed each. End-to-end mine of a compound-rich corpus
confirms chromadb entities metadata now shows compounds atomic
(Claude Code, GPT-4, GitHub Copilot, Visual Studio Code) with no
decomposition.
The COCA content-word filter shipped in PR #1605 imported
`_get_coca_filter` and `_candidate_entity_words` locally inside two
hot paths:
- `palace.build_closet_lines` — runs per source file during mine
- `miner._extract_entities_for_metadata` — runs per drawer during mine
Both imports are now at module top, where they're resolved once at
import time instead of on every per-drawer call. Module-top imports
also make the dependency graph visible to static analysis (pylint's
C0415 was flagging the locals).
No behavior change. The `_get_coca_filter()` call is unchanged — only
the import statement moved. End-to-end mining produces identical
chromadb output. Addresses the MEDIUM finding gemini-code-assist
raised on PR #1605 review.
Verification: full pytest 2258 passed / 3 skipped / coverage 85.35%.
ruff check + format clean. Linux Py 3.9 / 3.11 / 3.13 via CI-matching
`pip install -e ".[dev]"`: 2249 passed each. End-to-end mine of a
test corpus produces the expected drawer + closet pointer.
The two pre-existing entries for #1467 (tunnels.json path) and #1468
(create_tunnel endpoint validation) were sitting at the bottom of the
[Unreleased] block before this release-prep PR. Inserting the new
Performance section between the freshly-backfilled Bug Fixes and these
two pre-existing entries put them under Performance, which is wrong —
they're bug fixes. Moves them back ahead of Performance.
The scam-alert and Claude-Code-retention admonitions were the first
content visitors saw on the repo page — louder than the project
introduction. Moves both below the logo/title/badges so the project
identity reads first, and softens the scam block (drops the H1
"CRITICAL SECURITY WARNING" + all-caps shouting + redundant emoji)
to a single-paragraph CAUTION. All factual content preserved:
impostor-domain warning, official sources, malware caveat, link to
docs/HISTORY.md.
Resolves conflicts in CHANGELOG.md and pyproject.toml by combining
the multilingual-embedder additions (huggingface_hub/tokenizers/numpy
core deps, [multilingual] alias, Features section) with develop's
additions (python-dateutil core dep, [extract] extra, tunnel Bug
Fixes and Internal sections).
Prepares PR #1483 for merge into v3.3.6.
Push the surrogate-cleaning behaviour from per-call-site _clean() helpers
into sanitize_content, sanitize_kg_value, and sanitize_query so every
caller (existing and future) gets the fix automatically. New MCP tools
no longer need to remember to call a separate helper.
- Add strip_lone_surrogates() in mempalace/config.py as the single
regex-based implementation (one U+FFFD per surrogate, not three).
- Wire it into sanitize_content and sanitize_kg_value.
- Wire it into sanitize_query so embedding lookups can't crash either.
- Drop the _clean() helper from mcp_server.py and the per-site calls;
retain a direct strip_lone_surrogates() for source_file/added_by
metadata which doesn't route through any sanitizer.
- Move the ONNX model-cache patch out of the test module and into
conftest.py so it's session-scoped instead of duplicated locally.
- Update tests to assert one U+FFFD per surrogate and exercise the
sanitizer-level entry points directly.
Add tests/test_clean_lone_surrogates.py covering:
Unit tests (TestCleanLoneSurrogates, 11 cases):
- _clean() passes normal ASCII and CJK strings unchanged
- lone surrogates (high/low, single/multiple) are replaced with U+FFFD
- real emoji (\U0001f600 astral code points) pass through unchanged
- empty string, all-surrogate string, SHA-256-hash-after-clean
- the specific \udcad surrogate observed in WorkBuddy production logs
Integration tests (TestLoneSurrogateCleaning, 6 cases):
- tool_add_drawer: surrogate in content and in metadata fields
- tool_check_duplicate: surrogate in query
- tool_search: surrogate in search query
- tool_update_drawer: surrogate in updated content
- tool_diary_write: surrogate in diary entry
Fix test environment issue:
- conftest.py redirects HOME to a temp dir, causing chromadb's
ONNXMiniLM_L6_V2 to look for its ONNX model in the wrong location
and trigger a 79 MB network download on every run.
- Fix: at module import time, recover the real USERPROFILE from
conftest._original_env and patch ONNXMiniLM_L6_V2.DOWNLOAD_PATH
before any ChromaDB collection fixture is invoked.
- Fix _clean() docstring (paired surrogate description was misleading)
- Apply _clean() to source_file and added_by metadata fields
- Remove redundant surrogatepass from SHA256 hashes (content already cleaned)
- Apply _clean() to content in tool_check_duplicate
- Apply _clean() to new_doc in tool_update_drawer
- Apply _clean() to sanitized query in tool_search
Addresses feedback from gemini-code-assist[bot] on PR #1422.
MCP clients can emit lone surrogates (\udc00–\udfff) that
cause Python's str.encode('utf-8') to raise UnicodeEncodeError,
which bubbles up as -32000 Internal Error from ChromaDB.
Add _clean(text) helper that uses 'surrogatepass'/'replace' to
remove lone surrogates before the string reaches ChromaDB.
Apply it in tool_add_drawer and tool_diary_write, and use
'surrogatepass' error handler on the SHA256 hash inputs for
defensive idempotency.
Wires _validate_palace_fts5_after_mine into all three mine entry
points so corrupted-FTS5 palaces cannot silently exit 0 from any
of them:
- _mine_impl (mempalace/miner.py) — project file miner
- mine_convos (mempalace/convo_miner.py) — conversation exports
- mine_formats (mempalace/format_miner.py) — binary office documents
via --mode extract, introduced on develop by #1555 (3.3.6 release)
between this PR's open date and its rebase
cmd_mine surfaces MineValidationError as exit 1 + the same
print_sqlite_integrity_abort banner cmd_repair already prints,
appended with a mine-specific stderr note that hedges attribution
(quick_check cannot tell pre-existing corruption from corruption
this mine produced). 17 tests in tests/test_miner_fts5_validation.py
cover the helper, the three call sites, dry-run / KeyboardInterrupt
skip semantics, and the MineValidationError constructor invariants.
Closes#1537.
Co-authored-by: Caleb Wells <15988028+calebcwells@users.noreply.github.com>
The previous commit landed the code referencing mempalace/data/coca_content_words.json
but the data file itself was never actually staged (likely a multi-line paste mishap
during the initial commit). CI on every platform failed because the file isn't in
the repo. This commit ships the wordlist + adds TypeError to the COCA loader's
graceful-degradation exception tuple per gemini-code-assist review on PR #1605.
Common English content words ("Code", "Brutal", "Phase", "Line", "Note",
"Planning", "Chat", ...) frequently appear capitalized at sentence
start, in headings, or in markdown — and the existing regex-based entity
detector treats every capitalized word appearing 3+ times as a proper
noun candidate. This produces false positives that pollute
known_entities.json, the per-drawer entities metadata, and closet
pointer entity lists.
Adds a curated list of ~1000 common English content words (nouns,
adjectives, verbs — no proper nouns, no known product names) at
mempalace/data/coca_content_words.json, derived from the COCA top-2000
frequency list and from observed false positives in real palaces.
The list is loaded once at module import via _get_coca_filter() (cached
frozenset) and consulted at three sites:
- entity_detector.extract_candidates — init-time entity detection
- palace.build_closet_lines — closet pointer construction
- miner._extract_entities_for_metadata — per-drawer entity tagging
Matching is case-insensitive: the candidate is lowercased before
membership check, so "Code", "CODE", and "code" are all blocked.
Only single-word candidates are filtered; multi-word phrases (e.g.
"Claude Code") are NOT filtered, so legitimate compound names continue
to be detected. A future PR will add a known-systems lexicon that
explicitly protects compound names — for now, the multi-word pass
provides the implicit protection.
Adds 8 new tests in tests/test_entity_detector.py covering:
- "Code" appearing 5x is filtered
- All known false positives from real palaces are filtered
- Case-insensitive matching works
- Real names ("Aya", "Riley") are NOT filtered
- Multi-word phrases like "Claude Code" are NOT filtered
- The data file ships in the wheel with the expected schema
- The data file contains every known false positive
Note: this filter prevents NEW false positives at detection time. It
does NOT retroactively scrub existing entries from a user's
~/.mempalace/known_entities.json. Stale entries from previous runs
must be removed via a future entity-management CLI (planned).
Verification: pytest 2191 passed / 3 skipped / 0 failed on macOS.
ruff check + format --check both clean. Cross-platform via
pip install -e ".[dev]" on python:3.9-slim / 3.11-slim / 3.13-slim
containers, each running 65 entity-detector tests including the new
data-file-presence test that imports from the installed package.
End-to-end pipeline test mining a deterministic corpus into an
isolated palace confirmed entity metadata is empty (no false
positives surface in real chromadb-backed storage).
test_precompact_hook_enabled_by_default asserted
result["decision"] == "block", but hook_precompact has never emitted
decision — it mines synchronously and returns {}. Assertion was
copy-pasted from the stop-hook test. Fix to assert result == {} with
_mine_sync mocked so the test verifies the real contract (enabled →
mine + pass through) without actually mining.
Plus ruff format on 6 test files the CI pin flagged.
- Add parenthetical hints to block reasons so AI knows what each tool
saves (session summary, quotes/decisions/code)
- Remove dead config file creation from test_stop_hook_disabled_by_config
- Add missing test for MEMPALACE_HOOKS_AUTO_SAVE=no env var
- Replace bare except: with except Exception: in shell scripts
Add a clean opt-out for auto-save hook blocking (closes#494).
- New `hooks.auto_save` config option (default: true) in
~/.mempalace/config.json and MEMPALACE_HOOKS_AUTO_SAVE env var
- When disabled, stop and precompact hooks pass through without blocking
- Shorten block reason text from 6-line instructions to single-line
prompts — reduces UI noise while keeping tool names explicit
- Both Python (hooks_cli.py) and standalone shell scripts respect the
toggle via config file or env var
Lock-step with pyproject.toml `[project.optional-dependencies].dev`
(ruff bumped from 0.15.9 → 0.15.14 via PR #1583). The
`.pre-commit-config.yaml` header explicitly requires this rev to
match the pyproject pin — without this bump, contributors who run
`pre-commit install` will hit the same version-mismatch debacle this
PR was opened to prevent.
Adds two test-discipline tools to the dev extras and closes a real
contributor-onboarding gap in CONTRIBUTING.md that allowed PR #1579's
2026-05-22 4 AM ruff-version-mismatch lint failure.
Adds to ``[project.optional-dependencies].dev`` (and matching
``[dependency-groups].dev`` for uv users):
- **``hypothesis>=6.0``** — property-based testing framework.
Generates hundreds of random inputs per test and shrinks failing
cases to a minimal counterexample. Used opt-in (sprinkle
``@given(...)`` on a test); zero runtime cost on tests that don't
use it. Would have caught the Tier 6a dateutil-fuzzy hallucination
on PR #1584 with one property test.
- **``pre-commit>=3.0``** — the pre-commit framework itself.
``.pre-commit-config.yaml`` already lives in the repo (committed
by @igorls on 2026-05-18, pinned to ruff 0.15.9 in lockstep with
CI). What was missing was making the framework a declared dev
dependency so ``pip install -e .[dev]`` / ``uv sync --extra dev``
actually pulls it in.
Adds a ``pre-commit install`` line to the Getting Started bash block
plus a short paragraph explaining why this step is required (the
hook file at ``.git/hooks/pre-commit`` is per-machine and NOT tracked
by git, so the repo's ``.pre-commit-config.yaml`` only takes effect
after each developer runs ``pre-commit install`` once locally).
Adds an optional "Property-based tests" subsection under Running
Tests showing the minimal ``@given(...)`` pattern, so contributors
who want to reach for the new tool know it's available.
On 2026-05-22 at 4:30 AM, PR #1579 (Tier 6a) hit a CI lint failure
caused by a ruff version mismatch: my local machine had ruff 0.4.10,
CI runs ruff 0.15.9 (pinned in pyproject.toml). The two versions
produce different ``ruff format`` output for the same code. The repo
HAD ``.pre-commit-config.yaml`` pinning ruff 0.15.9 — but the local
git hook had never been wired on my machine because nothing in
CONTRIBUTING.md said to run ``pre-commit install``. The protection
existed at the project layer; the activation gap was at the
contributor-onboarding layer.
This commit closes that gap structurally. Anyone cloning the repo
from now on sees ``pre-commit install`` as part of the Getting Started
flow and is protected from the same failure.
- **No ``mutmut`` in dev deps.** Mutation testing is heavier (runs
the whole test suite per mutation) and useful periodically rather
than every commit. Contributors who want to run it can install
manually. Adding it to dev deps would bloat the install footprint
for every contributor when most will never use it.
- **No new property tests.** This PR ships the TOOL, not new test
coverage. Property tests should land alongside the specific
functions they cover, in their own PRs.
- **No changes to ``.pre-commit-config.yaml``.** That file is correct
as Igor wrote it. The fix here is purely making the framework
installable + documenting the activation step.
ruff check .
→ All checks passed.
pre-commit run --all-files (locally)
→ ruff (legacy alias): Passed
→ ruff format: Passed
OrbStack triple-Linux verify (Py 3.9 / 3.11 / 3.13)
→ ``pip install -e .[dev]`` resolves cleanly; hypothesis +
pre_commit import successfully; existing test suite unaffected.
Igor's review on PR #1584 (2026-05-22) flagged four issues:
1. The feature wasn't wired into any production caller — the new
``drawer_metas`` kwarg on ``build_closet_lines`` had no real
consumer in ``miner.py`` / ``diary_ingest.py``, so the 4-segment
pointer form only existed in tests. Real palaces kept emitting
the legacy 3-segment shape.
2. ``_extract_content_date`` hallucinated dates on benign inputs.
``dateutil.parser.parse(fuzzy=True)`` would accept anything with
digits and return a plausible-looking but wrong date —
``Version 3.3.6`` → ``2006-03-03``, ``Tested with 1000 drawers``
→ ``1000-05-22``, ``tmp_random_file_5`` → ``2026-05-05``, etc.
Mtime almost never got reached because fuzzy returned *something*
from filename or body first. Bad dates were silently persisted
to ChromaDB.
3. ``python-dateutil`` was an undeclared dependency, available only
transitively via ``chromadb → kubernetes → python-dateutil``. Not
a contract — upstream kubernetes has been trending toward
stdlib-only.
4. Two-digit-year disambiguation (70 → 19xx / 00-69 → 20xx) had no
test pinning the boundary.
This commit addresses all four.
## Changes
### Issue 2 — kill the hallucination (the load-bearing fix)
``mempalace/miner.py``:
- New ``_VALID_DATE_RE`` gate. Three accepted shapes (all require a
4-digit year explicitly):
1. Numeric YYYY-MM-DD with ``[-/.\\s]`` separators
(covers ISO and space-normalized filenames)
2. Month-name + day + year ("November 8 2024", "Nov 8 2024")
3. Day + month-name + year ("8 November 2024")
Partial dates ("2024-06", "April 6", "notes.2024") are
DELIBERATELY rejected — without all three components we'd pad from
today's date, which is hallucination not extraction.
- ``_try_filename_date`` and ``_try_content_body_date`` now run the
gate BEFORE invoking dateutil, and pass ``fuzzy=True`` is REMOVED.
Dateutil only runs in strict mode on a substring the gate already
validated.
### Issue 1 — wire the feature into production
``mempalace/miner.py`` batched-upsert path:
- Accumulate ``batch_metas`` across all batches into ``all_metas``
- Pass ``drawer_metas=all_metas`` to ``build_closet_lines``
End-to-end integration test added that mines a real file with a
filename-derived content date and asserts the produced closet
documents contain the 4-segment pointer with that date.
``diary_ingest.py`` is left as-is for this PR. Diary entries are
entry-keyed, not chunk-keyed — they carry no natural
``line_start`` / ``line_end``, so the 4-segment form would return
None for them regardless. Wiring the diary path can land cleanly in
a follow-up once Tier 6a gains an "approximate line range for diary
entries" story.
### Issue 3 — declare the dateutil dependency
``pyproject.toml``: add ``python-dateutil>=2.8`` to
``[project].dependencies``. One-line change; cheaper than the
stdlib-only refactor alternative and keeps the natural-language
recall surface.
### Issue 4 — pin the two-digit-year boundary
Four new tests cover the 1969/1970/1999/2000 corner cases of the
slash-date locale heuristic.
## Tests added (RED-first then GREEN)
tests/test_miner.py::TestExtractContentDate (11 new):
Hallucination cases verbatim from Igor's review:
- test_no_hallucination_junk_filename_with_trailing_digit
- test_no_hallucination_untitled_with_index
- test_no_hallucination_filename_year_only
- test_no_hallucination_filename_year_and_month_only
- test_no_hallucination_content_with_issue_number
- test_no_hallucination_content_with_count
- test_no_hallucination_content_with_version_number
Two-digit-year boundary cases:
- test_two_digit_year_69_is_2069
- test_two_digit_year_70_is_1970
- test_two_digit_year_99_is_1999
- test_two_digit_year_00_is_2000
tests/test_closets.py::TestMinerClosetRebuild (1 new):
- test_production_miner_emits_4_segment_pointers_with_content_date
(regression for Issue #1 — real ``mine()`` end-to-end produces
4-segment closet pointers via the new ``drawer_metas`` wiring)
## Verification
pytest tests/test_miner.py tests/test_closets.py
tests/test_format_miner.py tests/test_palace.py
→ 242 passed, 2 skipped, 0 regressions
pytest tests/test_miner.py::TestExtractContentDate
→ 26 passed (15 prior + 11 new)
pytest tests/test_closets.py::TestMinerClosetRebuild
→ end-to-end wiring test GREEN
Sanity (Igor's exact repros):
"tmp_random_file_5" → None (was: 2026-05-05)
"untitled-1" → None (was: 2026-05-01)
"notes.2024.md" → None (was: 2024-05-22)
"2024-06.md" → None (was: 2024-06-22)
"Bug fix for issue 42 in module 7" → None (was: 2042-07-22)
"Tested with 1000 drawers" → None (was: 1000-05-22)
"Version 3.3.6 released" → None (was: 2006-03-03)
Real dates still extract correctly:
"2024-11-08.md" → "2024-11-08"
"April-6th-2011-notes.md" → "2011-04-06"
"Nov-8-2024.md" → "2024-11-08"
ruff check + ruff format --check (pinned 0.15.9)
→ All checks passed
OrbStack triple-Linux verify (Py 3.9 / 3.11 / 3.13)
→ all targeted tests pass; python-dateutil installs explicitly
via the new declared dependency.