Commit Graph
834 Commits
Author SHA1 Message Date
Milla J fc13be568a feat(miner): integrate compute_hallways_for_wing into post-mine flow
Wires the hallway primitive (from PR #1558) into the project miner so
that every mine that touches a wing also materializes within-wing
entity hallways for that wing. Without this integration, the hallway
module is dead code — no miner triggers it, no hallways ever land in
~/.mempalace/hallways.json.

## What this commit does

1. Adds a module-level import of ``compute_hallways_for_wing`` from
   ``.hallways`` near the top of ``miner.py``. Module-level (not lazy)
   so tests can patch it as ``mempalace.miner.compute_hallways_for_wing``
   — lazy imports inside a function wouldn't expose the seam.

2. In ``_mine_impl``, immediately after the existing
   ``_compute_topic_tunnels_for_wing(wing)`` post-mine block, adds a
   parallel hallway block. The block:

   - calls ``compute_hallways_for_wing(wing, col=collection)``
   - prints the count if any hallways were materialized
   - wraps the whole thing in try/except so a hallway-compute failure
     is logged + degraded, never propagated. Mirrors the tunnel block's
     fault-tolerance pattern exactly. Hallway computation is a derived
     analytic, not load-bearing for the drawer write that already
     committed above.

## Stacking

This PR stacks on PR #1558 (which introduces the hallway primitive
module). PR #1558 is the prerequisite — without it, the import
``from .hallways import compute_hallways_for_wing`` doesn't resolve.

Base branch for this PR is ``feat/hallways-within-wing-connectors``
(PR #1558's branch). When PR #1558 merges to develop, GitHub will
auto-update this PR's base to develop and the diff will reduce to
just the miner.py and tests/test_miner.py changes.

## Out of scope (deferred to follow-up PRs)

- ``format_miner.py`` integration: lives on a different branch (PR #1555)
  so the parallel call there goes in as a follow-up amendment to that
  branch (or a separate post-merge PR).
- ``convo_miner.py`` integration: convo_miner currently doesn't call
  ``_compute_topic_tunnels_for_wing`` either. Adding both calls is a
  separate concerned PR about convo_miner parity, not just hallways.
- Refactoring ``_compute_topic_tunnels_for_wing`` to BUILD ON hallways
  (rather than computing from raw topic words): the architecturally
  meaningful follow-up that completes the Wing → Drawer-entities →
  Hallway → Tunnel sequence. Real refactor, separate PR.

## Tests

Two new RED-first tests in ``tests/test_miner.py``:

  test_mine_computes_hallways_for_wing_post_mine
      Stubs ``mempalace.miner.compute_hallways_for_wing`` via monkeypatch.
      Runs a real mine into a tmp palace. Asserts the stub was called
      exactly once, with the wing name from mempalace.yaml and a live
      ChromaDB collection (not None).

  test_mine_hallway_failure_does_not_crash_mine
      Stubs the hallway function to raise. Runs a real mine. Asserts
      mine() doesn't propagate, and that the drawer write (which
      happens BEFORE the hallway block) still committed.

Both RED before this commit (AttributeError — module had no attribute
``compute_hallways_for_wing``). Both GREEN after.

## Verification

  ruff check mempalace/miner.py tests/test_miner.py
    → All checks passed!
  ruff format --check ...
    → 2 files already formatted (pinned 0.15.9)
  pytest tests/test_miner.py
    → 47 passed (the 2 new + 45 pre-existing)
  pytest -q (full mempalace suite)
    → 1938 passed, 1 skipped, 0 regressions

Linux CI parity replicated locally via OrbStack containers
(Python 3.9, 3.11, 3.13): 2/2 new integration tests pass, ruff clean
on all three.
2026-05-20 04:08:02 -07:00
Milla J 07807ab8ab feat(hallways): within-wing entity-to-entity connector primitive
Introduces the missing primitive in mempalace's palace architecture.

## The architectural gap

Mempalace's data model today is Wing → Rooms → Tunnels. Tunnels connect
rooms ACROSS wings (via shared topic words). What's missing — and what
this commit adds — is the connector between ENTITIES (people, projects,
concepts, interests) inside one wing.

The intended full architecture is:

    WING → has DRAWERS (each tagged with entities)
            entities → connected to other entities by HALLWAYS
                       (within-wing, built from drawer co-occurrence)
                       hallways → are the primitive
                                   tunnels → use hallways to spawn
                                             cross-wing connections

A hallway is the structural fact of "these two entities travel together
inside this wing." If Aya and Lumi are mentioned together in 47 drawers
across diary, letters, and ideas rooms, that's a hallway between Aya
and Lumi. If Aya and "consciousness" co-occur in 19 drawers, that's
another hallway. Entities aren't only people — projects, concepts, and
interests share the same entity-tag substrate, so a hallway can connect
a person to a concept (Aya ↔ consciousness) just as easily as person to
person (Aya ↔ Lumi).

`palace_graph.py:253`'s docstring currently calls cross-wing tunnels
"hallways" — that conflation is fixed in a separate naming-disambiguation
follow-up. This commit just introduces the primitive.

## Public API

New module `mempalace/hallways.py`:

  compute_hallways_for_wing(wing, col=None, min_count=2) -> list[dict]
      Query drawers for wing. For each drawer with >=2 entities, every
      unordered pair of entities is one co-occurrence; increment a counter
      and track the room. For each entity pair with count >= min_count,
      materialize a hallway record. Persists to ~/.mempalace/hallways.json.
      Returns records created for this wing (records for other wings
      already on disk are preserved).

  list_hallways(wing=None) -> list[dict]
      Return all hallways, optionally filtered by wing.

  delete_hallway(hallway_id) -> bool
      Remove one record by id. Returns True on success.

  _load_hallways() / _save_hallways(state)
      JSON persistence at ~/.mempalace/hallways.json with 0600 perms on
      POSIX and atomic os.replace writes. Mirrors palace_graph's tunnel
      persistence pattern exactly.

## Data model (hallways.json)

```jsonc
{
  "schema_version": 1,
  "hallways": [
    {
      "id": "hallway_<wing>_<entity_a>_<entity_b>_<sha8>",
      "wing": "wing_aya",
      "entity_a": "Aya",
      "entity_b": "Lumi",
      "co_occurrence_count": 47,
      "rooms": ["diary", "letters", "ideas"],
      "label": "Aya ↔ Lumi (co-occur in 47 drawers across 3 rooms: diary, letters, ideas)",
      "created_at": "2026-05-20T03:30:00Z",
      "created_by": "auto"
    }
  ]
}
```

Hallway IDs are deterministic — `sha256(wing + sorted(entity_a, entity_b))`
truncated. Sorted-pair canonicalization means (Aya, Lumi) and (Lumi, Aya)
produce the same id, so re-runs upsert idempotently and the same drawer
appearing as "Aya;Lumi" or "Lumi;Aya" counts as one co-occurrence (not two).

## Tests

17 RED-first tests in `tests/test_hallways.py`:

Storage:
  - _load_hallways returns [] for missing file
  - _load_hallways returns [] for corrupt JSON
  - _save_hallways + _load_hallways round-trips

Algorithm:
  - returns [] for unknown wing
  - returns [] when no drawer has >=2 entities
  - creates hallway for entity pair when threshold met (Aya↔Lumi in 3 drawers)
  - connects person to concept (Aya↔consciousness — entities aren't only people)
  - respects min_count threshold (rejects 2 co-occurrences when min_count=3)
  - creates deterministic id per entity pair (idempotent re-runs)
  - entity pair is symmetric (Aya;Lumi and Lumi;Aya are the same pair)
  - persists to JSON file
  - tracks rooms across co-occurrences (rooms set vs. count distinction)
  - skips sentinel drawers (file_already_mined bookkeeping noise)

Query API:
  - list_hallways returns all when no filter
  - list_hallways filters by wing
  - delete_hallway removes record and persists
  - delete_hallway unknown id returns False

## Verification

  ruff check mempalace/hallways.py tests/test_hallways.py
    → All checks passed!
  ruff format --check ...
    → 2 files already formatted (pinned 0.15.9)
  pytest tests/test_hallways.py
    → 17 passed
  pytest -q (full mempalace suite)
    → 1936 passed, 1 skipped, 0 regressions caused by this PR

Linux CI parity replicated locally via OrbStack containers
(Python 3.9, 3.11, 3.13): 17/17 hallway tests pass, ruff clean on all
three.

## Not in this commit (deferred)

This PR introduces the primitive — the module, the entity-centric API,
the storage, the tests. It does NOT yet:

  - integrate compute_hallways_for_wing() into miner.py / convo_miner.py /
    format_miner.py post-mine flow (next PR — small one-line addition
    per miner alongside the existing _compute_topic_tunnels call)
  - refactor _compute_topic_tunnels_for_wing to BUILD ON hallways
    (the architecturally meaningful follow-up — own PR)
  - rename palace_graph.py:253's misleading docstring that calls
    cross-wing tunnels "hallways" (cleanup PR)
  - expose hallways through the MCP server (when there's a clear UX
    need for it)

Each follow-up is small enough to review in isolation. Shipping the
primitive first lets reviewers think about the API surface separately
from the integration choices.

Per the design sequence: Wing → Drawer-entities → Hallway → Tunnel.
Hallways come first. This is them.
2026-05-20 03:44:05 -07:00
Milla J 0b9c5629b7 fix(miner): mirror init's case-insensitive entity matching in per-drawer tagger
mempalace's init-time entity scanner (`entity_detector.py:276`) already
matches names case-insensitively against corpus content:

    name_line_indices = [i for i, line in enumerate(lines)
                         if name_lower in line.lower()]

That's how a corpus that mentions "aya" all in lowercase still surfaces
"Aya" as a confirmed entity during `mempalace init`.

But the per-drawer tagger in `miner.py:_extract_entities_for_metadata`
was never updated to use the same flag — it walks the same
`known_entities.json` seed list and matches case-sensitively:

    for name in known:
        if re.search(r"(?<!\w)" + re.escape(name) + r"(?!\w)", content):
                                                              # ^ no IGNORECASE
            matched.add(name)

So "Aya" in `known_entities.json` matches "Aya" in drawer content but
silently misses every "aya" / "AYA" mention. Chat transcripts,
voice-typed journals, and any lowercase-style corpus get their drawers
under-tagged in ways that don't show up in init's "we found Aya/Lumi/..."
confirmation list.

## The fix

One regex flag, line 788:

    -if re.search(r"(?<!\w)" + re.escape(name) + r"(?!\w)", content):
    +if re.search(r"(?<!\w)" + re.escape(name) + r"(?!\w)", content,
    +             re.IGNORECASE):

Plus an explanatory comment so the parity with `entity_detector.py:276`
is documented at the call site.

## Empirical proof of the bug (and the fix)

Before this commit, with the actual installed `~/.mempalace/known_entities.json`
containing "Aya", "Lumi":

    Content: "Aya talked to Lumi. Lumi answered."      → tagged 'Aya;Lumi'  ✓
    Content: "aya talked to lumi. lumi answered."      → tagged ''           ✗ MISS
    Content: "AYA mentioned LuMi to ben."              → tagged ''           ✗ MISS

After this commit (same content):

    Content: "Aya talked to Lumi. Lumi answered."      → tagged 'Aya;Lumi'  ✓
    Content: "aya talked to lumi. lumi answered."      → tagged 'Aya;Lumi'  ✓
    Content: "AYA mentioned LuMi to ben."              → tagged 'Aya;Ben;Lumi'  ✓

## Tests

New RED-first test in `tests/test_miner.py`:

    test_entity_metadata_matches_known_names_case_insensitively

Stubs `_load_known_entities` to a controlled `{"Aya", "Lumi"}` seed
and asserts that lowercase + mixed-case mentions both produce the
correctly capitalized tag. Failed on the pre-fix regex (confirmed RED
in CI parity runs across Linux 3.9 / 3.11 / 3.13); passes after the
one-line fix.

## No regressions

Full mempalace test suite: 1920 passed, 1 skipped, 0 failed.
Targeted dependent suites (`test_known_entities_registry`, `test_closets`,
`test_readme_claims`): 123 passed.
ruff check + ruff format clean on pinned 0.15.9.

CI parity replicated locally via Linux containers (Python 3.9, 3.11,
3.13): all three pass the new test and the full `test_miner.py`
sweep (46 tests).

## Why this matters

This is a quiet bug — there's no error message, no failed assertion,
just an empty `entities` field on drawers whose content actually
mentions people. The init phase looks fine ("we detected Aya, Lumi,
Ben") because init does its own case-insensitive scan; mining silently
drops the matches that init's scanner already proved are real.

Personal / journal / chat-style corpora (which use lowercase
conversational style) are the most affected. Code / docs corpora
(which use proper capitalization for names) work either way and saw
no behavior change.
2026-05-20 03:15:45 -07:00
Milla J 5c40cc3d70 feat(format_miner): detect_room + topic tunnel computation (miner.py parity)
Third amendment to PR #1555. Closes the remaining parity gaps between
format_miner and the existing project miner that Aya's palace audit
surfaced after amendment #2.

## What was broken

A smoke test against the just-mined v6 palace confirmed:

  WING: wing_aya
    ROOM: documents             2904 drawers   ← ALL in one room
  Tunnels for wing_aya:         0              ← no cross-wing links

Cause: format_miner hardcoded `room = "documents"` for every drawer and
never called `_compute_topic_tunnels_for_wing()` post-mine. miner.py
calls `detect_room()` per drawer and computes tunnels after the loop.
format_miner did neither.

## What this commit changes

1. Module-level imports of `detect_room`, `load_config`, and
   `_compute_topic_tunnels_for_wing` from `.miner`. Module-level (not
   lazy) so test seams `patch("mempalace.format_miner.detect_room", ...)`
   work — lazy imports inside a function don't expose attributes on the
   module object.

2. `mine_formats()` loads the project's `mempalace.yaml` via
   `load_config()` to get the rooms list. Falls back to a single
   "documents" room if no config exists.

3. The hardcoded `room = "documents"` line is replaced with:
       room = detect_room(filepath, text, rooms, format_path)
   Mirrors miner.py:904 exactly — folder-match → filename-match →
   content-keyword scoring → fallback "general".

4. After the per-file loop completes (in an `else` branch on the outer
   try, so it does NOT run on KeyboardInterrupt), call
   `_compute_topic_tunnels_for_wing(wing)` in try/except. Exact mirror
   of miner.py:1241-1249. Tunnel-compute failures must never fail a mine.

5. Import `sys` at module level (used by the tunnel-compute error path
   for `print(..., file=sys.stderr)`).

## Tests

5 new RED-first tests in `tests/test_format_miner.py`:

  - test_mine_formats_calls_load_config_for_rooms
  - test_mine_formats_calls_detect_room_per_file
  - test_mine_formats_uses_detected_room_in_drawer_metadata
  - test_mine_formats_calls_compute_topic_tunnels_after_loop
  - test_mine_formats_tunnel_failure_does_not_crash_mine

All 5 failed against pre-commit code with AttributeError on missing
module attributes (proof the bug existed). All 5 pass after the
implementation. Total format_miner test count: 62. Total proposal test
count (format_miner + line_numbers): 83. Full mempalace test suite:
2002 passed, 1 skipped (no regressions).

## Verification

  ruff check mempalace/format_miner.py tests/test_format_miner.py
    → All checks passed!
  ruff format --check ...
    → already formatted (pinned ruff 0.15.9)
  pytest tests/test_format_miner.py tests/test_line_numbers.py
    → 83 passed
  pytest -q  (full suite)
    → 2002 passed, 1 skipped

## Not in this commit (deferred)

Within-wing hallway primitives are a separate architectural addition
(separate PR — being designed). The current `_compute_topic_tunnels_for_wing`
matches miner.py exactly but inherits miner.py's gap: it computes
tunnels from raw topic words rather than from hallway primitives. That
refactor lands in its own PR after the hallway primitive ships.
2026-05-20 03:02:39 -07:00
Milla J e362dfa0af feat(format_miner): address bot review — parity fixes with miner.py
Six follow-up fixes addressing gemini-code-assist review on PR #1555.
All medium-priority parity gaps between format_miner.py and the
existing miner.py / convo_miner.py patterns.

1. Reuse palace.SKIP_DIRS instead of duplicating it locally.
   Replaces the local _SKIP_DIRS set with the shared constant so the
   format miner's directory-skip set stays in sync automatically.

2. scan_formats now explicitly skips symlinks. Prevents circular
   links, following symlinks to /dev/urandom, and processing the same
   file via multiple paths. Mirrors miner.py:1068 exactly.

3. mine_formats loads MempalaceConfig at start. The current chunker
   (miner.chunk_text) uses module-level CHUNK_SIZE constants and
   doesn't accept overrides, so the loaded config values aren't yet
   threaded into chunking; the load is wired so future chunk_text
   refactors that accept per-call sizing pick this up automatically.
   Honest scope note: this gives format_miner the same config-load
   stance as miner.py without overreaching what chunk_text supports.

4. source_mtime tracking + check_mtime=True. Each drawer's metadata
   now carries source_mtime, and file_already_mined is called with
   check_mtime=True so an edited PDF/DOCX is correctly re-mined on
   the next pass. Mirrors miner.py semantics exactly. Previously,
   updated documents would have been silently skipped.

5. Per-file try/except wrap + KeyboardInterrupt handling + PID
   cleanup. One malformed file in a mine of thousands no longer
   crashes the whole orchestrator — the error is logged, a counter
   bumps, and the loop continues with the next file. KeyboardInterrupt
   still produces a clean summary on Ctrl-C. _cleanup_mine_pid_file
   is called in a finally block so hook-spawned mines don't leak a
   stale PID file on exit.

6. hall + entities metadata on every drawer. Format-mined drawers
   now carry the same hall (via miner.detect_hall) and entities (via
   miner._extract_entities_for_metadata) tags as project-mined
   drawers. Matches the search-result quality the other miners ship.

Tests: 5 new tests covering the new behaviors:
  - test_scan_formats_skips_symlinks
  - test_mine_formats_uses_check_mtime_true
  - test_mine_formats_records_source_mtime_in_drawer_metadata
  - test_mine_formats_records_hall_in_drawer_metadata
  - test_mine_formats_continues_after_per_file_error

Total: 78 tests passing (was 73). Full mempalace test suite green
modulo one pre-existing flaky test (test_chroma_close_palace_..., a
sqlite-lock-timing flake unrelated to this change — passes 4/4 in
isolation). ruff check + ruff format clean on pinned 0.15.9.
Coverage on mempalace/format_miner.py: 84% (clears the 80% gate).

Refs: PR #1555 review comments from gemini-code-assist[bot]
2026-05-19 19:51:39 -07:00
Milla J 5e3d3dde2e feat(3.3.6): virtual line numbering + format coverage via --mode extract
Two additive features, both following the same read-time-transform pattern:

1. Virtual line numbering — new render_with_line_numbers() and
   extract_line_range() in mempalace/searcher.py. Closet pointers like
   2026-01-18:L55-L72 resolve to drawer slices rendered with [55] through
   [72] line prefixes without modifying any stored content. Lines already
   prefixed with [<digits>] pass through unchanged. Pure functions, no I/O.

2. Format coverage (mempalace mine --mode extract) — new mempalace/format_miner.py
   reads binary office formats and files drawers via the lock + purge +
   upsert pattern convo_miner uses. Source files never modified.

   Per-format transformer routing: MarkItDown 0.1.5 does not actually
   convert .rtf (returns raw control codes unchanged, verified live), so
   .rtf is routed to striprtf which does convert. Other formats stay on
   MarkItDown:

     .pdf .docx .pptx .xlsx .epub  -> MarkItDown
     .rtf                          -> striprtf

   13 fringe cases handled with dedicated ExtractionStatus codes:
   SKIP_NO_MARKITDOWN, SKIP_NO_STRIPRTF, SKIP_TOO_LARGE, SKIP_CLOUD_ONLY,
   SKIP_ENCRYPTED, SKIP_EMPTY, SKIP_PERMISSION, SKIP_BROKEN_SYMLINK,
   SKIP_UNRECOGNIZED, SKIP_EXTRACTION_ERROR, SKIP_NETWORK_TIMEOUT,
   SKIP_UNREADABLE, plus the encoding fallback handled internally.

   Drawers carry ingest_mode=extract + extract_mode=format so they are
   distinguishable from project / convo drawers in the palace.

Both transformers are optional extras: pip install mempalace[extract].
MarkItDown requires Python >= 3.10 (env marker ensures it only installs
where supported; Python 3.9 users still get RTF coverage via striprtf).

Tests: 94 new (21 line-numbering + 73 format-miner, including 9
mine_formats orchestrator tests). Full mempalace suite still green
(1992 passed locally). Coverage 86% on mempalace/format_miner.py.
ruff check + ruff format clean on the pinned 0.15.9.

Live verification: mempalace mine --mode extract on a directory with 2
RTFs + 1 PDF produced 90 drawers correctly; mempalace search found
content from both file types in the resulting wing.

Documented limits (out of scope for 3.3.6): custom PDF parsers, OCR on
scanned PDFs, DRM-locked files, pathological corrupt files. These get
reported via skip codes and skipped.

Refs: docs/format-coverage.md, docs/virtual-line-numbering.md
2026-05-19 19:15:40 -07:00
mvalentsevandDavid Glidden 5decc0c83b fix(miner): configurable + raised MAX_CHUNKS_PER_FILE (#1455)
Default raised from 500 to 50_000 so legitimate long-form content
(novels, scholarly editions) is not silently dropped on a typical
literary corpus. Cap configurable via MEMPALACE_MAX_CHUNKS_PER_FILE
env var or --max-chunks-per-file CLI flag; sentinel 0 disables.
Negative or non-int values from either source emit a stderr warning
and fall back to the default.

Separate counter (files_skipped_chunk_cap) and summary line surface
chunk-cap drops independently of the residual already-filed bucket;
counter fires under --dry-run too so a corpus audit shows the same
signal without writing. Skip notice routed to stderr alongside the
existing symlink-skip line.

ONNX bad_alloc protection preserved architecturally:
DRAWER_UPSERT_BATCH_SIZE=1000 bounds per-ONNX-call exposure
regardless of per-file cap. A 50_000-chunk file produces 50 forward
passes of 1_000 chunks each, identical to what 500-chunk files
already produced.

process_file return extended to a 3-tuple (drawers, room,
skip_reason); skip_reason is None on non-chunk-cap paths and
"chunk_cap" when the per-file cap triggered. Internal callers
(_mine_impl, benchmarks/mine_bench.py, tests) updated.

Closes #1455

Co-Authored-By: David Glidden <d@davidglidden.eu>
2026-05-20 02:20:29 +05:00
yonefive71 7550de27a0 fix(graph): repo-format tests, %s for tunnel paths, single config per call
Three changes addressing #1469 CI red + Gemini perf review:

1. ruff format (0.4.x) on tests/test_closets.py and
   tests/test_palace_graph_tunnels.py — the lint job pins
   ruff>=0.4.0,<0.5 and was flagging format drift.

2. Replace %r with '%s' in legacy / corrupt tunnel-file warnings.
   On Windows %r escapes backslashes in repr, so
   test_load_tunnels_warns_on_orphaned_legacy_file's
   'str(legacy) in caplog.text' assertion was failing on
   test-windows even though the warning was firing.

3. Address gemini-code-assist review on #1469: pass a single
   MempalaceConfig() through _get_tunnel_file / _load_tunnels /
   _save_tunnels per create_tunnel call instead of each helper
   re-instantiating its own (which re-reads mempalace.yaml from
   disk). Helpers keep their config=None defaults so external
   callers and existing tests are unaffected.
2026-05-19 05:12:48 +00:00
Igor Lins e Silva 1b94f4efb4 Merge pull request #1538 from mvalentsev/fix/1534-paragraph-chunk-size-enforcement
fix(convo_miner): enforce CHUNK_SIZE in paragraph chunker (#1534)
2026-05-18 21:32:40 -03:00
Igor Lins e Silva 100539d2ca Merge pull request #1543 from fatkobra/fix/1443-mine-slot-placeholder
Fix: Write placeholder PID when claiming mine slot
2026-05-18 21:32:21 -03:00
Igor Lins e Silva 1d8a800cca Merge origin/develop into feat/benchmark-multilingual
Resolve conflicts:
- backends/chroma.py: keep both new except handlers in get_collection
  (CollectionNotInitializedError from develop + EF-mismatch helper from
  this branch), ordered _ChromaNotFoundError before ValueError to match
  the create-branch handler order.
- uv.lock: regenerated from merged pyproject.toml.

Fix lint: ruff format mempalace/embedding.py + tests/test_embeddinggemma.py
(CI now pins ruff==0.15.9 via develop's workflow update).

Full suite: 1923 passed, 1 skipped.
2026-05-18 17:58:05 -03:00
Igor Lins e Silva 2c9dd398ef Merge pull request #1546 from MemPalace/fix/1473-tunnel-error-surface
fix(mcp): surface create_tunnel ValueError instead of masking it (#1473)
2026-05-18 17:47:13 -03:00
Igor Lins e Silva 90fece7628 test(hooks): also isolate _MINE_PID_DIR + create the state dir (#1510)
Review feedback: _MINE_PID_DIR is derived from STATE_DIR at module
import (hooks_cli.py:277), so patching STATE_DIR alone left
mine-spawning tests writing PID files under the import-time location
instead of the per-test root. Patch _MINE_PID_DIR too, and create the
state dir so the fixture's 'existing' docstring is accurate. Isolation
still 100 passed/1 skipped; ordering still 165 passed.
2026-05-18 17:39:12 -03:00
Igor Lins e Silva 426d164df4 test(hooks): isolate test_hooks_cli from test_cli side effect (#1510)
Nine save/log/precompact tests in test_hooks_cli.py passed only because
test_cli.py (alphabetically earlier) created ~/.mempalace in the session
tmp HOME as a side effect, satisfying the _palace_root_exists()
kill-switch. Run in isolation they short-circuited and failed (9 failed,
80 passed, 1 skipped).

Add a module autouse fixture that points PALACE_ROOT/STATE_DIR at a
per-test palace root that exists, so every test is robust standalone and
future tests don't inherit the trap. Kill-switch tests that need the
absent path call _redirect_palace_root after the fixture; monkeypatch
last-write-wins keeps their absent/file root and teardown restores the
real module value.

Isolation: pytest tests/test_hooks_cli.py -> 100 passed, 1 skipped.
Ordering preserved: test_cli + test_hooks_cli -> 165 passed.

Closes #1510
2026-05-18 17:28:50 -03:00
Igor Lins e Silva 3e92719710 fix(mcp): surface create_tunnel ValueError instead of masking it (#1473)
tool_create_tunnel sanitized names inside a try/except ValueError but
called create_tunnel() *outside* it, so any ValueError create_tunnel
raises (empty/non-string endpoints today, room-existence checks once
#1469 lands) escaped and the MCP framework wrapped it as the opaque
'Internal tool error'. Wrap the create_tunnel() call in the same
try/except and return {"error": str(e)}, mirroring sibling tools
(tool_add_drawer, tool_list_tunnels). Adds a regression test that
monkeypatches create_tunnel to raise and asserts the message is
surfaced verbatim.

Closes #1473
2026-05-18 17:25:09 -03:00
Igor Lins e Silva 34d8dde969 Merge pull request #1216 from arnoldwender/fix/migrate-resource-cleanup
fix(migrate): close SQLite connection and clean temp palace on exception
2026-05-18 17:18:28 -03:00
Igor Lins e Silva d74ca06282 Merge pull request #1523 from williamblair333/fix/repair-vacuum-fts5
fix: VACUUM + FTS5 rebuild after repair to reclaim SQLite space
2026-05-18 17:17:47 -03:00
William Blair 3da27d3c7e fix: VACUUM + FTS5 rebuild after repair to reclaim SQLite space
Repeated `repair --yes` runs leave freed SQLite pages unreclaimed and
can corrupt the FTS5 inverted index. This patch adds
`_vacuum_and_rebuild_fts5()`, called at the end of `rebuild_index()`,
which:

1. Closes all chroma handles (releases PersistentClient's sqlite lock).
2. Rebuilds the FTS5 index via the built-in content-table DDL trick.
3. Runs VACUUM (requires autocommit / isolation_level=None) to reclaim
   the freed pages.

The function is a no-op when chroma.sqlite3 is absent or the FTS5
table doesn't exist, so it is safe on every supported backend.

Four new tests cover the happy path, missing FTS5 table, missing file,
and call ordering (close must precede vacuum).

Closes #1516
Closes #1517
2026-05-18 16:10:16 -03:00
Ivan Dergachev e811b6d10a fix: avoid false HNSW metadata quarantine 2026-05-18 16:08:55 -03:00
3cac26fc65 fix(convo_miner): enforce CHUNK_SIZE in paragraph chunker (#1534)
`_chunk_by_paragraph` and its 25-line-group fallback appended whole
paragraphs and line groups as single drawers with no per-drawer size
cap, so a normalized transcript containing a single >CHUNK_SIZE
paragraph (for example a Claude Code session with pasted content as
one 135,600-char line) produced one giant chunk. ChromaDB upsert then
fed that chunk to the embedding model, blowing the O(seq_len^2)
attention budget with `RuntimeError: Invalid buffer size: 120.00 GiB`.

Introduce a single `_emit_bounded` helper that gates the whole stripped
content against `min_chunk_size` (noise filter) and emits every slice
verbatim via an index-based `range(0, len, chunk_size)` loop. The
helper preserves trailing remainders instead of silently dropping them
and avoids the O(N^2) substring-copy pattern. Both `_chunk_by_paragraph`
and `_chunk_by_exchange` now delegate slicing to the helper. Plumb the
config-resolved `chunk_size` through `_chunk_by_paragraph` so
`MempalaceConfig.chunk_size` governs this path too.

Co-Authored-By: David F Glidden <4116848+davidglidden@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 23:53:37 +05:00
sjhddh 25b918ee7e feat(normalize): add Continue.dev session parser
Add _try_continue_json() normalizer for Continue.dev AI assistant
sessions (~/.continue/sessions/*.json). Parses history array with
role/content pairs, handles tool calls, system messages, and metadata.

Closes #59 (partial — adds Continue.dev format support)

Includes comprehensive test coverage for valid sessions, edge cases,
malformed input, and unicode content.
2026-05-18 13:08:09 +00:00
fatkobra eee5f327a2 Write placeholder PID when claiming mine slot 2026-05-18 10:05:11 +00:00
Igor Lins e Silva 2cab6f5a5b style: reformat tree with ruff 0.15.9
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 .`.
2026-05-17 23:20:01 -03:00
Igor Lins e Silva 5c9a5e04b1 Merge pull request #1528 from therahul-yo/fix/1505-extract-mode-aware-skip
fix(convo_miner): scope skip-check and drawer ids by extract_mode (#1505)
2026-05-17 23:16:10 -03:00
Igor Lins e Silva 83e4711593 style(tests): apply ruff 0.4.x format to test_convo_miner (#1528)
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.
2026-05-17 22:52:01 -03:00
Igor Lins e Silva 18bda00304 Merge pull request #1438 from fatkobra/patch-1
Fix UTF-8 lock holder writes on Windows
2026-05-17 22:50:47 -03:00
yonefive71 3171a1b4c1 fix(graph): resolve tunnel file from palace_path config (#1467)
palace_graph._TUNNEL_FILE was a module-level constant initialised from
os.path.expanduser("~") + "/.mempalace/tunnels.json", ignoring the
MempalaceConfig.palace_path config (and MEMPALACE_PALACE_PATH env var)
that drawers, KG, and every other piece of palace state honour. Under
any setup where $HOME and the configured palace diverge — subagent
profiles, sandboxes, multi-tenant hosts, container mounts moving the
palace to /srv/ — drawers landed in the configured palace while
tunnels silently landed in a different file invisible to other
processes touching the same palace.

Replace the constant with _get_tunnel_file(config=None) deriving the
path from a new MempalaceConfig.tunnel_file property (sibling of
palace_path). Default install unchanged because default palace_path
is ~/.mempalace/palace whose sibling tunnels.json is the legacy path.

Add a _legacy_tunnel_file() helper and a one-line WARNING in
_load_tunnels for the case where the configured tunnel file is missing
but the pre-fix hardcoded path has one. No auto-migration — silently
merging tunnel state across two locations risks clobbering newer data.

fix(graph): validate explicit-tunnel endpoints exist (#1468)

create_tunnel previously only validated that wing/room names were
non-empty strings; nothing queried chroma to confirm at least one
drawer carried matching {wing, room} metadata. Pointing an explicit
tunnel at a phantom room silently succeeded. Combined with #1467's
read-bubble, an agent could create_tunnel → list_tunnels and have both
calls return its own bogus write, self-confirming a tunnel that didn't
exist in the shared palace.

create_tunnel now calls _check_room_exists(wing, room, col) for both
endpoints before persisting an explicit tunnel; zero rows raises
ValueError naming the endpoint. Three deliberate carve-outs:

- kind != "explicit" skips validation because topic tunnels use
  synthetic topic:<name> room ids that don't correspond to real rooms
- _get_collection returning None (palace not yet created, transient
  failure, tests without backend) skips validation rather than
  fail-closed — matches tolerance pattern used throughout palace_graph
- Query exceptions are logged and treated as 'can't verify, allow' so
  a flaky index doesn't block legitimate writes

Behaviour change: callers that previously created tunnels pointing at
empty rooms (scaffolding before mining) will now raise. File the
drawer first, then create the tunnel.

Tests:
- _use_tmp_tunnel_file helper now also neutralises _get_collection so
  existing tests don't accidentally trip the new validation path when
  test-order pollution leaves a real chroma backend bound
- test_closets.py::TestTunnels setup/teardown updated to monkeypatch
  resolver functions instead of the removed constant; also neutralises
  _get_collection for the same reason
- Three tests in test_miner.py exercising compute_topic_tunnels are
  unchanged in intent — they monkeypatch the new resolvers and pass
  without stubbing _get_collection because kind=topic skips validation
- New TestTunnelFileFollowsConfig and TestCreateTunnelEndpointValidation
  classes cover the regression surface for both fixes
2026-05-17 20:19:56 +00:00
Igor Lins e Silva cabc3afb6e Merge pull request #1445 from yonefive71/fix/1426-none-metadata-mcp-handler
fix(mcp): tolerate None metadata cells (#1426)
2026-05-17 16:24:17 -03:00
Igor Lins e Silva 3c74ba6493 style(tests): apply ruff 0.4.x format to test_mcp_server (#1445)
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.
2026-05-17 16:09:45 -03:00
Igor Lins e Silva 419a34c5c5 style(tests): restore ruff 0.4.x assert formatting in test_palace_locks (#1438)
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.
2026-05-17 15:01:14 -03:00
Igor Lins e Silva a62f8a95a4 Merge pull request #1532 from mvalentsev/fix/1498-stratified-palace-state-messages
fix(palace): stratify state messages for empty/missing palace (#1498)
2026-05-17 12:22:57 -03:00
Igor Lins e Silva 8199d7287f Merge pull request #1529 from mvalentsev/fix/1504-tunnel-preserve-hyphenated-wing
fix(tunnels): preserve hyphenated wing slugs in create_tunnel write-path (#1504)
2026-05-17 12:22:19 -03:00
Igor Lins e Silva fc4d06d0e6 Merge pull request #1441 from mvalentsev/fix/hooks-bash-3.2-compat-1440
fix(hooks): replace mapfile with sed for bash 3.2 compat (#1440)
2026-05-17 12:21:59 -03:00
Igor Lins e Silva d114a594d6 Merge pull request #1383 from mvalentsev/fix/mcp-kg-cache-realpath
fix(mcp): canonicalize KG cache key via realpath + normcase (#1372)
2026-05-17 12:21:10 -03:00
Igor Lins e Silva e6c06ef1c8 Merge pull request #1408 from arnoldwender/fix/entity-registry-tmp-cleanup-on-failure
fix(entity_registry): clean up .tmp sidecar on write or rename failure (#1373)
2026-05-17 12:20:48 -03:00
mvalentsev 990b155515 fix(palace): address Gemini review on #1532
- 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.
2026-05-17 04:13:42 +05:00
mvalentsev c933095a2f fix(palace): stratify state messages for empty/missing palace (#1498)
`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.
2026-05-17 03:57:19 +05:00
mvalentsevandStarshipSuperjam cf96e68edf fix(mcp): cold-start embedder diagnostics + opt-in warmup (#1495)
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>
2026-05-17 00:57:13 +05:00
mvalentsev fba6372f2c fix(tunnels): preserve hyphenated wing slugs in create_tunnel write-path (#1504)
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.
2026-05-16 20:48:23 +05:00
Rahul 92de001c20 fix(convo_miner): scope skip-check and drawer ids by extract_mode (#1505)
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.
2026-05-16 17:55:10 +05:30
mvalentsev c736a57078 test(hooks): force umask 022 in test subprocess (#1440)
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.
2026-05-15 22:51:28 +05:00
mvalentsev 2bdb1e8846 fix(hooks): apply post-review hardenings (#1440)
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).
2026-05-15 22:51:27 +05:00
mvalentsev e241aa38ba fix(hooks): replace mapfile with sed for bash 3.2 compat (#1440)
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.
2026-05-15 22:51:27 +05:00
mvalentsev 4dc3ccf26a fix(mcp): thread captured KG path through _get_kg to lock insert/evict keys
_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.
2026-05-15 22:51:14 +05:00
mvalentsev 3ee158ecdd test(mcp): tighten _canonicalize_kg_path normcase wiring assertion
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.
2026-05-15 22:51:14 +05:00
mvalentsev 6f9fe8055a fix(mcp): canonicalize KG cache key via realpath + normcase (#1372)
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.
2026-05-15 22:51:14 +05:00
Igor Lins e Silva bb313961f3 Merge pull request #1519 from MemPalace/fix/1024-convo-min-chunk-validation
fix(convo_miner): validate explicit min_chunk_size instead of raw config reach
2026-05-15 12:23:06 -03:00
Igor Lins e Silva 342cfa629b fix(config): catch OverflowError in coercion; correct "stricter" wording
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.
2026-05-15 11:01:48 -03:00
Igor Lins e Silva 78d57ddf64 fix(test): remove duplicate pytest import breaking lint on develop
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.
2026-05-15 10:46:41 -03:00
Igor Lins e Silva bea7cb1646 fix(convo_miner): validate explicit min_chunk_size instead of raw config reach
#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.
2026-05-15 10:42:21 -03:00