Commit Graph
834 Commits
Author SHA1 Message Date
Igor Lins e Silva 29d686e5d4 Merge pull request #1024 from techempower-org/pr/configurable-chunking
feat: configurable chunk_size, chunk_overlap, min_chunk_size
2026-05-15 10:39:10 -03:00
Igor Lins e Silva 6ba75851df Merge pull request #1470 from mvalentsev/fix/plugin-hooks-bounded-timeout
fix(hooks): add bounded timeout to plugin Stop/PreCompact (#1465)
2026-05-15 10:28:57 -03:00
Igor Lins e Silva b348483e21 Merge pull request #1466 from mvalentsev/fix/mine-log-skipped-symlinks
fix(miner): log skipped symlinks in mine paths (#1462)
2026-05-15 10:08:04 -03:00
Anastasiia AnfimovaandClaude Opus 4.7 51c03a0c5c fix(mcp): structured -32602 for unknown parameter name (#1512)
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>
2026-05-15 13:48:29 +02:00
Igor Lins e Silva 9893100ca4 Merge pull request #1439 from mvalentsev/fix/init-strip-leaked-pythonpath
fix: drop leaked PYTHONPATH on package init (#1423)
2026-05-15 08:05:47 -03:00
Igor Lins e Silva 73d0fe31ec Merge pull request #1424 from arnoldwender/fix/wing-truncation-hyphenated-projects
fix(hooks): correct wing extraction for hyphenated project names (#1410)
2026-05-15 07:54:56 -03:00
Bruno Leal 6bd164e4b1 style: ruff format test_hnsw_payload_health.py (#1461 follow-up)
Collapse the multi-line assert startswith() added in #1461 into a
single line as required by ruff format. No logic change.
2026-05-14 19:17:26 -03:00
Igor Lins e Silva a1bf6dea35 Merge pull request #1461 from fatkobra/patch-2
Fix: Reject zero-byte HNSW link lists during quarantine (#1457)
2026-05-14 18:57:01 -03:00
Igor Lins e Silva 8a6537d2fb feat(onboarding): multilingual embedder by default for new installs
Onboarding now asks the user once, on first run, whether to use the
multilingual embedding model. The default answer is yes — defaulting to
English-only made the recall promise effectively unreachable for any
non-English content (cross-lingual cos ~0.35 vs ~0.88 for the multilingual
model). The choice is written to config.json so subsequent runs pick the
right EF without re-prompting; existing installs that never set the env
var or ran onboarding stay on minilm for back-compat. MEMPALACE_EMBEDDING_MODEL
still overrides both.

Multilingual deps (huggingface_hub, tokenizers, numpy) move from the
[multilingual] extra into core. The extra is kept as a no-op alias so
existing install scripts keep working. The 300 MB ONNX model is still
lazy-downloaded on first use, not at install time.

`quick_setup` (the programmatic non-interactive path) grows an optional
`embedding_model` arg so tests and benchmark scripts can pick a model
without writing config.json by accident.

EmbeddinggemmaONNX's "missing deps" error now points at the right
recovery path (reinstall mempalace, since the deps are core) rather
than the obsolete pip install mempalace[multilingual] hint.

Tests: 9 new (3 _ask_embedding_model variants + 2 run_onboarding
persistence + 2 quick_setup + 2 set_embedding_model round-trips). The
existing 2 run_onboarding tests now patch _ask_embedding_model so they
don't print to stdout.
2026-05-14 06:40:27 -03:00
Igor Lins e Silva cef1c62fe7 feat(embedding): EF-mismatch error helper, offline tests, migration docs
Three follow-ups bundled for the embeddinggemma EF added in 51702e9:

1. Offline tests for EmbeddinggemmaONNX (10 tests, 0.08s, no network).
   Mocks huggingface_hub.hf_hub_download, tokenizers.Tokenizer.from_file,
   and onnxruntime.InferenceSession so CI never pulls the 300 MB model.
   Guarded with pytest.importorskip so the file is skipped when the
   multilingual extra isn't installed. Covers: stable name(), lazy-load
   runs exactly once, output shape (n, 384) after MRL truncation, L2
   normalization, sim prefix applied, dispatch from
   get_embedding_function(model="embeddinggemma"), cache key separates
   models, helpful ImportError when deps missing, env override.

2. Friendlier ChromaDB EF-name-mismatch error. Switching
   MEMPALACE_EMBEDDING_MODEL on an existing palace previously surfaced
   ChromaDB's bare "Embedding function conflict: new: X vs persisted: Y"
   ValueError. Now ChromaBackend.get_collection() wraps that error and
   points users at the two recovery paths: revert the env var, or run
   `mempalace repair rebuild-index --palace <path>`. New
   _explain_ef_mismatch helper + 3 tests (unit + end-to-end).

3. Docs: CHANGELOG [Unreleased] entry covers both the new EF and the
   error wrapper. README Requirements section mentions the multilingual
   extra and points at the embedding.py docstring for the migration note.
2026-05-14 05:00:48 -03:00
mvalentsevandanastasiiaanfimova 982adcf09b fix(mcp): structured error for param-shape mismatch (#1351)
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>
2026-05-14 01:03:31 +05:00
mvalentsev cab41c8a75 test(hooks): use hook.get("type") for graceful assert message
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.
2026-05-13 22:53:48 +05:00
mvalentsev 706237476c test(hooks): pin single-entry cardinality in plugin config schema
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.
2026-05-13 22:53:48 +05:00
mvalentsev d17d14d8d9 fix(hooks): add bounded timeout to plugin Stop/PreCompact (#1465)
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.
2026-05-13 22:53:48 +05:00
mvalentsev d7d9604887 fix(miner): polish symlink skip diagnostic (#1462)
* 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.
2026-05-13 22:53:43 +05:00
mvalentsev becf56172a fix(miner): log skipped symlinks in mine paths (#1462)
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.
2026-05-13 22:53:43 +05:00
mvalentsev 068930b710 test(init): probe sys.path filter in CLI/MCP env strip tests; docstring side effect
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.
2026-05-13 22:53:36 +05:00
mvalentsev 4b1ab50750 fix(init): keep PYTHONPATH env for embedded callers, strip only in CLI entry points
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.
2026-05-13 22:53:36 +05:00
mvalentsev d09cd9dab1 fix(init): preserve cwd marker; decouple test (#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.
2026-05-13 22:53:36 +05:00
mvalentsev c4fdc1ed8c fix(init): normalize path comparison for sys.path strip (#1423)
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.
2026-05-13 22:53:36 +05:00
mvalentsev 765478d37a fix(init): also strip leaked sys.path entries (#1423)
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.
2026-05-13 22:53:36 +05:00
mvalentsev af7b6dfebc fix: drop leaked PYTHONPATH on package init (#1423)
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.
2026-05-13 22:53:36 +05:00
Fergus ChingandClaude Opus 4.7 96e3be9fe2 fix(convo_miner): wrap mine_convos in mine_palace_lock to stop pile-up
The project-files mine path (miner.mine) has wrapped _mine_impl in
mine_palace_lock since #1264 — a non-blocking flock that raises
MineAlreadyRunning so the second runner exits cleanly instead of
queueing as a waiter that drives parallel HNSW inserts. The convos
mine path (convo_miner.mine_convos) was missing the same guard.

In practice this meant any caller that spawned `mempalace mine
--mode convos` repeatedly against the same palace — most notably
the Stop-hook transcript ingest before the per-target PID slot
landed — could stack up arbitrarily many concurrent mines, each
holding a ChromaDB client open, each writing to the same HNSW
index. Recently observed: 28 stuck convos mines on one machine
consuming ~18 GB of RAM and contributing to a load spike.

Fix: refactor mine_convos into a thin wrapper that holds the
per-palace flock around _mine_convos_impl, mirroring miner.mine
exactly. Dry-run skips the lock since it never writes.

Tests: two cross-process tests in tests/test_convo_miner.py —
one asserts MineAlreadyRunning when a child process holds the
lock, one asserts dry-run is unaffected. Same spawn-context
pattern as test_palace_locks.py (fork-with-chromadb deadlocks
on Python 3.13).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 12:47:36 +00:00
jpandClaude Opus 4.7 0a1adf9962 test(repair): unit coverage for empty-metadata sanitization in _extract_drawers
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>
2026-05-11 14:17:07 -07:00
fatkobra bc7fe88846 Add regression tests for zero-byte HNSW link lists 2026-05-11 19:06:05 +02:00
yonefive71 afaedc68cf fix(mcp): tolerate None metadata cells (#1426)
ChromaDB's col.get() and col.query() can return None for the metadata
cell of a partially-flushed row, or for any row written without metadata
in older formats. The MCP handler then crashes with:

    AttributeError: 'NoneType' object has no attribute 'get'

This crashed the path before the embeddings_queue cleanup step, so the
queue grew without bound while writes kept appearing successful.

Add a small _safe_meta() boundary helper that coerces None (or any other
non-dict) to {}, and route every direct metadatas[i]/metadatas[0] read in
mcp_server through it: tool_get_drawer, tool_list_drawers,
tool_update_drawer, tool_delete_drawer (audit-log path),
tool_check_duplicate, and tool_diary_read.

The contract — *metadata is always a dict by the time it leaves the
boundary* — is documented on the helper and self-documents at each call
site.

Regression coverage: tests/test_mcp_server.py::TestNoneMetadataSafety
covers the helper and each affected handler with a stub collection that
returns None metadatas (Chroma rejects None at write time, so we can't
reproduce upstream state through the real backend).

Closes #1426.
2026-05-11 04:26:39 +00:00
jpandClaude Opus 4.7 b1d75b30af feat(config): validate chunk_* properties + DRY defaults + chunk_text guard
Addresses all four findings from @copilot-pull-request-reviewer on

1. **Type/range validation on chunk_size / chunk_overlap /
   min_chunk_size.** New ``MempalaceConfig._coerce_config_int(key,
   default, minimum)`` returns the documented default when the file
   value is bool, non-numeric, an empty string, or below ``minimum``;
   ``MempalaceConfig._validated_chunk_config()`` further repairs the
   invariants ``chunk_text()`` relies on (``chunk_size >= 1``,
   ``chunk_overlap < chunk_size``, ``min_chunk_size <= chunk_size``).
   Each property now resolves through that helper, so a hand-edited
   ``config.json`` with garbage values can't silently break ingest.

2. **chunk_text() infinite-loop guard.** Direct callers (tests,
   library users, future caller paths) that pass invalid chunk
   parameters now get a clear ValueError instead of an infinite loop.
   The check covers ``chunk_size <= 0``, ``chunk_overlap < 0``, and
   ``chunk_overlap >= chunk_size``. Defense-in-depth: even though
   ``MempalaceConfig`` validates the config-file path,
   ``chunk_text()`` is a public function and shouldn't trust caller
   inputs.

3. **DRY default constants.** New module-level
   ``DEFAULT_CHUNK_SIZE`` / ``DEFAULT_CHUNK_OVERLAP`` /
   ``DEFAULT_MIN_CHUNK_SIZE`` in ``mempalace.config`` are the
   single source of truth. ``mempalace.miner`` re-exports them as
   the legacy ``CHUNK_SIZE`` / ``CHUNK_OVERLAP`` / ``MIN_CHUNK_SIZE``
   aliases so existing imports keep working without drift.

4. **Test coverage.** 15 new tests in ``tests/test_config.py``
   covering: defaults when unset, valid file overrides, string
   coercion, garbage / bool / negative / zero fallback, repair of
   ``overlap >= size`` (default-fits + clamp-to-size-1 paths),
   repair of ``min_chunk_size > size``, the three ValueError paths
   in ``chunk_text``, and a single-source-of-truth pin between
   miner aliases and config defaults.

Suite total: 1323 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 18:12:36 -07:00
jp d20ae4f3f5 fix(convo_miner): reject non-positive chunk_size to prevent infinite loop
Qodo review flagged on #1024 (2026-04-22): ``_chunk_by_exchange`` can
loop forever when ``chunk_size <= 0`` because ``content[:0]`` returns
an empty string while ``content[0:]`` returns the whole input, so the
remainder never shrinks. Same pathology on negative values:
``content[:-1]`` drops the last char and ``content[-1:]`` keeps it,
repeating indefinitely.

Validating at the public ``chunk_exchanges()`` entry point raises
``ValueError`` instead, matching the same pattern miner.py's
``chunk_text`` uses for its ``chunk_overlap`` guard. Four new tests
in test_convo_miner_unit.py cover the rejection paths plus the
``min_chunk_size == 0`` legal case.

Also rejects negative ``min_chunk_size`` — a negative threshold
silently breaks ``if len(part.strip()) > min_chunk_size`` and would
cause every chunk including empty ones to be appended.

Full test_convo_miner_unit.py suite: 19 passed (4 new).
2026-05-10 18:11:33 -07:00
jpandClaude Sonnet 4.6 fd63703686 feat: configurable chunk_size, chunk_overlap, min_chunk_size
Chunk sizing was hardcoded via module-level constants
(CHUNK_SIZE=800, CHUNK_OVERLAP=100, MIN_CHUNK_SIZE=50). One size
does not fit all — source material varies (dense code vs prose
transcripts vs sparse logs) and so do users' context-window
budgets.

This makes all three values overridable via ~/.mempalace/config.json:

    {
      "chunk_size": 1200,
      "chunk_overlap": 150,
      "min_chunk_size": 40
    }

Values are exposed as MempalaceConfig properties, threaded
through mine() -> process_file() -> chunk_text() as optional
keyword arguments. Defaults (800/100/50) are preserved when the
config keys are absent, so existing palaces behave identically.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 18:11:33 -07:00
fatkobra c49c10f6e4 Add regression tests for UTF-8 lock holder writes 2026-05-10 16:56:10 +02:00
Ivan Dergachev 385fc1825c docs: make Codex MCP setup discoverable 2026-05-10 17:06:36 +04:00
Arnold Wender cb1303694d fix(migrate): close SQLite connection and clean temp palace on exception
Two resource leaks in mempalace.migrate that bite hardest on Windows:

1. extract_drawers_from_sqlite() opened a sqlite3 connection at the
   top and only closed it in the happy path. Any exception during
   query/iteration leaked the handle, leaving a file lock on
   chroma.sqlite3 that prevented the rest of the migration from
   touching the palace directory. Wrap with contextlib.closing().

2. migrate() called tempfile.mkdtemp() and never cleaned it up if a
   later step (chromadb open, batch import, count, swap) raised.
   The orphaned palace under the system temp root could be 100s of
   MB and never gets reclaimed. Wrap the import-and-swap dance in
   try/finally and rmtree the temp dir if it still exists at the
   end (os.replace consumes it on the happy path so the existence
   guard makes that case a no-op).

Tests cover the happy-path extraction and verify mkdtemp's directory
is removed when ChromaBackend.get_or_create_collection() raises.
2026-05-10 13:06:40 +02:00
Arnold Wender e6f73983fb fix(entity_registry): clean up .tmp sidecar on write or rename failure (#1373)
#1215 made `EntityRegistry.save()` atomic via temp-file + fsync + os.replace.
Crash-mid-write durability is correct: the previous registry stays intact on
any failure. But if `f.write()` / `f.flush()` / `os.fsync()` / `os.replace()`
raise (disk full, perms flip, broken FUSE mount, IO error), the `.tmp` sidecar
was left on disk. Subsequent saves overwrite the same path so it does not
grow unboundedly, but it litters the palace directory and obscures
diagnostics — a user inspecting `entity_registry.json.tmp` after a crash
cannot distinguish in-flight writes from stale debris.

Wrap the write+chmod+replace block in try/except. On any exception, attempt
`tmp_path.unlink(missing_ok=True)` before re-raising. The dir-fsync is
deliberately outside the try — that is durability for a successful rename,
not a write step that needs cleanup.

Tests:
- Augment `test_save_preserves_previous_on_serialization_failure` to also
  assert the .tmp sidecar is gone after a forced os.replace failure.
- New `test_save_cleans_tmp_on_write_failure` forces os.fsync to raise,
  covering the gap between write and rename that the existing test does
  not exercise.

Closes #1373.
2026-05-10 12:56:50 +02:00
Arnold Wender 601da04817 ci(test_hooks_cli): re-apply ruff 0.4.x format (CI pins ruff<0.5) 2026-05-10 12:56:28 +02:00
Arnold Wender a0129f5cff fix(hooks): correct wing extraction for hyphenated project names (#1410)
`_wing_from_transcript_path` derived the wing from the LAST dash-separated
token of Claude Code's encoded project folder. Because Claude Code encodes
the source directory by replacing `/` with `-`, any project whose folder
name itself contained a dash got silently truncated:

    -Users-me-claude-code     -> wing_code           (lost "claude")
    -Users-me-react-native    -> wing_native         (lost "react")
    -Users-me-customer-portal -> wing_portal         (collision risk)
    -Users-me-admin-portal    -> wing_portal         (same wing!)

Two real consequences:
1. Project-scoped queries (`wake-up --wing <project>`) miss diary entries
   because they're filed under the truncated wing.
2. Multi-project collision: any two projects whose folders end in the
   same final token get their diary entries merged into one wing,
   defeating the wing isolation model.

Fix uses a two-tier strategy:

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 and never truncates hyphenated names.
   Bounded scan (200 lines) keeps the lookup well within the hook's
   500ms budget.

2. FALLBACK — when cwd isn't recorded (older Claude Code, queue-only
   transcripts, etc.), decode the encoded folder. Strip the platform
   user-home prefix (`Users-<user>-` / `home-<user>-`) and one common
   parent-dir token (`git-`, `dev-`, `projects-`, `Projects-`, `src-`,
   `code-`, `work-`, `Documents-`), then convert remaining dashes to
   underscores. May include extra parent-dir noise in the wing name
   (`wing_dev_mempalace_mempalace`) but never silently truncates.

Two existing tests asserted the old truncation behavior (it gave the
right answer by coincidence on single-token leaf project names). They're
updated to reflect the new contract: collision-safe wing extraction even
when cwd is absent.

Tests added:
- hyphenated_claude_code, hyphenated_react_native (regression)
- no_collision_between_hyphenated_siblings (`customer-portal` vs
  `admin-portal` resolve to distinct wings)
- strips_parent_dir_with_hyphenated_project (reporter's example)
- uses_cwd_from_jsonl, cwd_with_hyphenated_project,
  cwd_skips_lines_without_cwd, cwd_falls_back_when_no_cwd_in_jsonl,
  cwd_handles_malformed_jsonl, cwd_handles_missing_file,
  cwd_handles_non_string_cwd (cwd-primary path coverage)

Closes #1410.
2026-05-10 12:56:28 +02:00
Igor Lins e Silva 40524d5b04 Merge develop into main for v3.3.5 release
# Conflicts:
#	.claude-plugin/marketplace.json
#	.claude-plugin/plugin.json
#	.codex-plugin/plugin.json
#	CHANGELOG.md
#	README.md
#	mempalace/version.py
#	pyproject.toml
#	uv.lock
2026-05-10 01:05:36 -03:00
Igor Lins e Silva b2bab382f3 Merge remote-tracking branch 'origin/develop' into pr-1417-fix-kg-datetimes
# Conflicts:
#	tests/test_palace_locks.py
2026-05-09 21:12:40 -03:00
Igor Lins e Silva df5ca114b2 chore(tests): wrap sqlite3 connections in contextlib.closing
Several tests opened sqlite3 connections without try/finally or
context-manager cleanup, relying on a flat conn.close() after the
work. Any assertion failure or exception between connect and close
leaked the connection until GC, producing
``ResourceWarning: unclosed database`` in CI logs.

On Python 3.13 / macOS the ResourceWarning isn't just noise: a
leaked connection can hold a SQLite advisory lock long enough for
later test setup to block on it, which appears to be the cause of
recent intermittent CI hangs on those two runners.

Wrap each affected ``conn = sqlite3.connect(...)`` block in
``contextlib.closing(...)`` so cleanup runs on the failure path too.
Mirrors the try/finally pattern already used in production code
(searcher.py, repair.py, backends/chroma.py).

No behavior change — same operations, same assertions, just
deterministic cleanup. All 162 affected tests pass locally.
2026-05-09 20:25:47 -03:00
Igor Lins e Silva 11d0a64202 fix(tests): use spawn instead of fork for lock-test subprocesses
test_palace_locks.py and test_chroma_collection_lock.py spawned child
processes with the ``fork`` start method on POSIX. Under Python 3.13
this deadlocks reliably enough to hang the Linux 3.13 and macOS CI jobs
indefinitely while Linux 3.9 / 3.11 / Windows complete normally.

Root cause: by the time these tests run, the pytest parent process is
multi-threaded — chromadb and onnxruntime both spawn background threads
on import. ``fork`` snapshots the parent's address space into the
child without those threads, so any lock another thread held at fork
time stays locked in the child forever. Python 3.13 widened the window
where Python's own internal threads can be holding locks (hence the new
DeprecationWarning that fired ten times in our local 3.13 run).

macOS hits a related but distinct issue: Apple's CoreFoundation
explicitly forbids fork-without-exec; once anything in the parent has
loaded a CF-using library (ONNX, anything via Objective-C bridges) a
forked child will silently hang the moment it touches the same
library.

Switching to ``spawn`` re-imports modules in the child (~0.5s overhead
per Process — measurable but bounded), which is the standard fix for
both classes of bug. Lock-file semantics are unchanged: ``spawn``
inherits ``os.environ`` (including monkeypatched ``HOME``), which is
all these tests need from the parent.

Locally on Python 3.13: all 14 lock tests pass in 6.58s.
2026-05-09 20:11:08 -03:00
Igor Lins e Silva d9e60d84ad Merge pull request #1396 from JPdeB61/fix/1315-mcp-search-retry-on-hnsw-flush
fix(mcp): retry tool_search once on Chroma "Error finding   id" transient (#1315)
2026-05-09 19:32:20 -03:00
Igor Lins e Silva b2ce45d301 style: ruff format tests/test_mcp_server.py for ruff <0.5 2026-05-09 18:09:51 -03:00
fatkobra 03f9a73d44 fix(tests): format palace lock test 2026-05-09 12:16:26 +02:00
fatkobra 710fa529c0 style: format test_palace_locks as part of fix(tests): isolate palace lock subprocess state 2026-05-09 11:45:51 +02:00
fatkobra 00041ca736 Update test_palace_locks.py as part of fix(tests): isolate palace lock subprocess state 2026-05-09 11:30:45 +02:00
fatkobra f34b78c8b1 Update conftest.py as part of fix(tests): isolate palace lock subprocess state 2026-05-09 11:20:33 +02:00
FBISiri a9a2c35e65 feat: add Gemini CLI / AI Studio JSON session import support
Adds _try_gemini_json parser to normalize.py for three layouts:

  1. Gemini API contents format (~/.gemini/sessions/*.json):
     {"contents": [{"role": "user", "parts": [{"text": "..."}]}, ...]}
  2. Messages-wrapper variant:
     {"messages": [{"role": "user", ...}, {"role": "model", ...}]}
  3. Flat top-level list with role="model".

This complements the existing _try_gemini_jsonl parser (which handles
~/.gemini/tmp/<hash>/chats/session-*.jsonl with session_metadata
sentinel) — JSONL covers Gemini CLI runtime sessions, JSON covers
exported / Studio-saved transcripts.

## Review feedback addressed (PR #204)

bgauryy review:
- #1 Parser-precedence bug: _try_gemini_json runs *before*
  _try_claude_ai_json so the {"messages":[..., role=model, ...]}
  layout is no longer silently claimed by the Claude parser. The
  Gemini parser's has_model_role guard prevents false-positives
  against Claude / ChatGPT data.
- #2 Layout 2a coverage: TestGeminiJson.test_messages_wrapper_format
  + test_messages_wrapper_does_not_get_claimed_by_claude pin the
  fix in place.
- #3 Test conflicts with current main: rebased onto develop;
  tests restructured into TestGeminiJson class.
- #4 tempfile/os.unlink → pytest tmp_path everywhere.
- #5 elif not text → else (the elif branch was dead).
- #6 Module docstring updated to mention Google AI Studio.

Tests: 9 new cases in TestGeminiJson covering all three layouts,
multi-part text joining, non-text part skipping, has_model_role
disambiguation, dispatch-chain regression for review #1.
2026-05-09 14:05:45 +08:00
Igor Lins e Silva 2fc47a52fc Merge pull request #1004 from coogie/coogie/fix/miner-routing
fix(miner): use token-boundary matching in detect_room
2026-05-09 01:36:51 -03:00
mvalentsev 1822756afe fix(test_sync): use tmp_dir for elsewhere path so it stays absolute on Windows
Windows runs treated `/tmp/elsewhere/x.md` as relative because Windows
absolute paths require a drive letter, so `_classify_drawer` routed
`drawer_out_of_scope` to `no_source` instead of `out_of_scope` and
`test_dry_run_classifies_correctly` failed on test-windows.

`Path(tmp_dir) / "elsewhere" / "x.md"` is absolute on every platform
and still lives outside the project root that the synced_world fixture
exposes via `repo_path`, so the bucket assertions hold cross-platform.
2026-05-09 04:12:18 +05:00
mvalentsev 18f877869b style(test_sync): match CI ruff 0.4.x format 2026-05-09 04:04:56 +05:00
mvalentsev 0ff4121404 fix(sync): symmetric source_file resolve + perf optimizations
CI fix: `_classify_drawer` now resolves `source_file` symmetric to
`project_roots` (which `_normalize_project_dirs` and
`_auto_detect_project_roots` already `.resolve()`). Without this, on
platforms where the temp directory is a symlink (macOS `/var/folders` ->
`/private/var/folders`, Windows 8.3 short-name normalization), every
drawer mis-bucketed as `out_of_scope` and survived prune.

Perf:
- `_resolve_project_root`: early-return on first match (sorted-desc
  precondition).
- `_normalize_project_dirs`: sort `(-len(str(p)), str(p))` desc for
  early-return + deterministic tie-break on equal-length paths.
- `_auto_detect_project_roots`: `seen_sources` dedupe so a 200-chunk
  file costs one disk walk, not 200.
- `sync_palace` main loop: per-file classification cache; registry
  sentinels (`_reg_*`, `room=_registry`, `ingest_mode=registry`) routed
  to "kept" before cache lookup so a sentinel sharing a `source_file`
  with a pruned drawer cannot inherit a stale "gitignored" verdict.
- Closet purge: collapse O(N) per-file purge into one
  `where={"source_file": {"$in": [...]}}` get + one bulk delete.

Tests (5 new in `TestSyncPalace`, 38 total):
- `test_symlinked_project_root_resolves`: pins symmetric resolve via
  real `os.symlink` (skipped on Windows).
- `test_classification_cache_avoids_redundant_disk_hits`: monkeypatch
  counter on `_classify_drawer` asserts `call_count == 1` for 5 chunks
  sharing one source_file.
- `test_closet_batch_purge_single_call`: wraps closets collection with
  `CallCountingCol` (forwards `.get`/`.delete`); asserts
  `delete_calls == 1` and `get_calls == 1`; expected `removed_closets`
  derived from `report["by_source"]` to stay robust to fixture changes.
- `test_registry_check_runs_before_cache_lookup`: a regular drawer
  caches "gitignored" first; a sentinel with the same source_file must
  still be kept.
- `test_normalize_project_dirs_sort_stable_on_equal_length`: pins the
  alphabetical secondary key when paths share length.
2026-05-09 04:01:34 +05:00