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.
The original sentence ('may distribute malware. Details and timeline:
docs/HISTORY.md') was split mid-sentence by the visibility reformat,
leaving a fragment 'malware. Details and timeline: ...' as an orphaned
blockquote outside the [!CAUTION] callout. Fold the link into the
malware line so the callout stays self-contained.
Co-Authored-By: Igor Lins e Silva <4753812+igorls@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two medium-priority gemini-code-assist comments on PR #1580 both
recommend more-idiomatic Python:
1. **Production code (``mempalace/hooks_cli.py::_mempalace_python``)** —
replace ``try/except IndexError`` with ``if len(parents) > N:``
look-before-you-leap checks. Exception handling for bounded-integer
index lookups is a code smell in Python; LBYL makes the depth check
explicit and removes exception overhead. Same behavior, clearer
intent.
Before (EAFP, ~12 lines + comment):
try:
venv_bin = resolved.parents[3] / "bin" / "python"
if venv_bin.is_file():
return str(venv_bin)
except IndexError:
pass
After (LBYL, ~5 lines):
if len(parents) > 3:
venv_bin = parents[3] / "bin" / "python"
if venv_bin.is_file():
return str(venv_bin)
2. **Test code (``tests/test_hooks_cli.py``)** — replace the lambda +
generator-throw hack with ``MagicMock.side_effect = get_item``,
where ``get_item`` is a normal function that returns the
editable-install path for index 1 and raises ``IndexError`` for
any other index (defensive against a future regression that drops
the LBYL length check). Standard ``side_effect`` mocking pattern.
Before:
fake_parents.__getitem__ = lambda self, idx: (
RealPath("/work/mempalace")
if idx == 1
else (_ for _ in ()).throw(IndexError(idx))
)
After:
def get_item(idx):
if idx == 1:
return RealPath("/work/mempalace")
raise IndexError(idx)
fake_parents.__len__.return_value = 3
fake_parents.__getitem__.side_effect = get_item
Also added ``__len__`` mock so the LBYL length check in production
sees the simulated shallow path correctly.
## Verification
pytest tests/test_hooks_cli.py
→ 110 passed, 1 skipped (same as PR #1580 baseline; regression
test for shallow-path crash still GREEN)
ruff check + ruff format --check (pinned 0.15.9)
→ All checks passed; 2 files already formatted
``_mempalace_python()`` in ``mempalace/hooks_cli.py`` uses
``Path(__file__).resolve().parents[3]`` to locate the venv Python
interpreter in the standard install layout
``<venv>/lib/pythonX.Y/site-packages/mempalace/hooks_cli.py``. When the
package lives at a shallow filesystem path — Docker containers
mounting at ``/work``, ``/opt/app``, minimal-prefix production
installs — ``parents`` has fewer than 4 elements and the index raises
``IndexError`` instead of falling through to the editable-install
branch.
The crash was caught by OrbStack-based triple-Python CI verification
on PR #1579: 16 tests in ``test_hooks_cli.py`` failed identically on
Linux 3.9 / 3.11 / 3.13 with the same ``IndexError: 3`` from
``pathlib._PathBase.parents.__getitem__`` — and verified pre-existing
on develop tip in the same container. The bug never surfaces in
GitHub Actions CI runners (their workdir at
``/home/runner/work/mempalace/mempalace`` has plenty of parent
directories) but it surfaces immediately for anyone:
- running mempalace in editable mode inside a Docker dev container
- shipping mempalace as part of an OCI image where the install
prefix is ``/app`` or ``/opt/<name>``
- using OrbStack / Colima / podman-machine for cross-version
verification
## The fix
Wrap each ``parents[N]`` access in ``try/except IndexError`` so the
helper falls through to the next strategy (editable-install →
``sys.executable``) instead of crashing the hook. Both ``parents[3]``
AND ``parents[1]`` are guarded — the latter is defensive against
extreme cases like a file at root (``/file.py``, parents=[/]) — same
class of bug.
## Test added (RED-first, then GREEN)
tests/test_hooks_cli.py::test_mempalace_python_handles_shallow_path_without_crashing
Mocks ``Path(__file__).resolve()`` so ``parents[3]`` raises
``IndexError`` and ``parents[1]`` returns a real shallow path
(``/work/mempalace``). Pre-commit: function raises ``IndexError: 3``.
Post-commit: function returns a valid Python interpreter path
(either editable-venv if present, otherwise ``sys.executable``).
## Verification
pytest tests/test_hooks_cli.py
→ 110 passed, 1 skipped on macOS (the existing run)
→ 110 passed, 1 skipped on Linux 3.9 / 3.11 / 3.13 (OrbStack)
— was 16 failed, 94 passed before this commit
ruff check + ruff format --check (pinned 0.15.9)
→ All checks passed; 2 files already formatted
Three medium-priority gemini-code-assist comments on PR #1579 all flagged
the same anti-pattern: slicing or splitting the entire ``content`` string
to inspect a small prefix. On a 500MB file with 50K chunks, the original
``content[:offset]`` and ``content.split("\n")`` calls produce O(N²) work
and severe memory churn. None of this was wrong semantically — it was
wrong about *cost*.
This commit replaces all three sites with bounded equivalents that read
the original string in place:
## Changes
1. **``mempalace/miner.py::chunk_text``** — replace
``content[:start].count("\n")`` with ``content.count("\n", 0, start)``.
The ``str.count`` method's bounds form counts on the original string
without allocating a slice. Same result, O(start) instead of
O(N) memory per chunk.
2. **``mempalace/miner.py::_try_frontmatter_date``** — replace the
``stripped.split("\n")`` + line-by-line scan with ``stripped.find("\n---", 3)``
to locate the closing delimiter, then slice the frontmatter region
directly. Frontmatter is always near the start of the file, so the
find walks at most a few KB even on huge files. The earlier
implementation produced a list of every line in the file.
3. **``mempalace/miner.py::_try_content_body_date``** — two-part fix:
(a) skip frontmatter via ``find("\n---", 3)`` (same pattern as #2);
(b) replace ``stripped.split("\n")[:10]`` with
``stripped.split("\n", 10)[:10]`` — the ``maxsplit`` form caps work
to scanning 10 newlines rather than splitting the entire file.
## Why no behavior change
All three transformations are equivalence-preserving:
- ``s[:n].count(ch) == s.count(ch, 0, n)`` — by definition.
- ``s.split("\n")[i].strip() == "---"`` for some i ≤ N is equivalent to
``s.find("\n---") != -1`` (both detect "a line consisting of exactly
---") for our use case where the opening fence is already validated by
``stripped.startswith("---")``.
- ``s.split("\n")[:10]`` produces the same first-10-elements as
``s.split("\n", 10)[:10]``; the difference is the latter stops after
10 newlines instead of scanning the rest.
## Verification
pytest tests/test_miner.py::TestChunkTextLineRanges
tests/test_miner.py::TestBuildDrawerMetadataLineRange
tests/test_miner.py::TestExtractContentDate
tests/test_closets.py::TestBuildClosetLines
→ 32 passed (same as PR #1579's baseline; no test changes needed
because behavior is identical, only memory/time profile changed)
ruff check + ruff format --check (pinned 0.15.9)
→ All checks passed; 1 file already formatted
Closet pointer lines gain a 4th pipe-separated segment of shape
``YYYY-MM-DD:Lstart-Lend`` so retrieval can jump straight to the right
span in the source file instead of opening the whole drawer. The date
is selected via a content-aware hierarchy so legacy ingests (where
``filed_at`` is misleading) still produce honest pointers when the
content itself carries a date.
The legacy 3-segment format remains the fallback for drawers without
the new metadata, so existing palaces keep working without a re-mine.
## Pointer shape
Before:
topic|entities|→drawer_ids
After (when drawer metadata carries line range + a date):
topic|entities|2024-11-08:L42-L78|→drawer_ids
Backward compat: when ``drawer_metas`` is not passed, or the first
meta lacks ``line_start`` / ``line_end``, ``build_closet_lines`` emits
the legacy 3-segment form unchanged.
## Date-source hierarchy (NEW)
A new helper ``mempalace.miner._extract_content_date(source_file, content)``
selects a date once per file and stores it as ``content_date`` on every
drawer mined from that file. Priority order, first match wins:
1. **Filename** — ISO regex on stem, then dateutil fuzzy parse for
natural-language formats. Handles ``2024-11-08.md``,
``April-6th-2011-notes.md``, ``Nov-8-2024.md``, etc.
2. **YAML frontmatter** — looks at ``date`` / ``created`` /
``published`` fields. yaml.safe_load already parses ISO dates as
``datetime.date`` objects; dateutil handles string values.
3. **Content body, first ~10 lines** —
a. ISO regex (``YYYY-MM-DD`` / ``YYYY/MM/DD`` / ``YYYY.MM.DD``)
b. Slash dates with locale auto-disambiguation: if any
first-number > 12 appears anywhere in the head, lock the
file's locale to DD/MM (the only consistent reading);
otherwise default to US MM/DD for two-digit-year compactness.
c. dateutil fuzzy parse for natural-language
(``November 8, 2024``, ``8th November 2024``, etc.)
4. **Filesystem mtime** — ``os.path.getmtime`` formatted as
``YYYY-MM-DD``.
5. **None** — caller (``_build_drawer_metadata``) leaves
``content_date`` absent; ``build_closet_lines`` falls back to the
``filed_at`` ingestion timestamp's date portion.
``_build_date_line_segment`` in ``palace.py`` now prefers ``content_date``
when present, otherwise uses ``filed_at[:10]``. This is the load-bearing
change that makes Tier 6a meaningful for legacy content — a Nov 8 2024
transcript mined today now emits ``2024-11-08:L42-L78`` instead of
``2026-05-22:L42-L78``.
## Changes
1. ``mempalace/miner.py::chunk_text`` — each chunk dict now also carries
``line_start`` / ``line_end`` (1-indexed line numbers in the stripped
source). Computed via ``content[:offset].count("\n") + 1`` —
approximate locator accurate to ±1 line at chunk boundaries.
2. ``mempalace/miner.py::_extract_content_date`` (NEW) + helpers
(``_try_filename_date``, ``_try_frontmatter_date``,
``_try_content_body_date``, ``_try_mtime_date``). Pure functions, no
I/O beyond what's named. Uses lazy imports of ``dateutil`` and
``yaml`` to keep top-level import surface unchanged.
3. ``mempalace/miner.py::_build_drawer_metadata`` — gains
``line_start`` / ``line_end`` / ``content_date`` optional kwargs.
When provided, stored in drawer metadata; when omitted, keys are
absent from the dict — backward compatible.
4. ``mempalace/miner.py`` batched-upsert path — calls
``_extract_content_date(source_file, content)`` ONCE per file (not
once per chunk) and passes the result through to every chunk's
``_build_drawer_metadata`` call.
5. ``mempalace/format_miner.py::_file_chunks_locked`` — gains a
``content`` param so the format-miner path can also run
``_extract_content_date`` on the full extracted text. Plumbs
``content_date`` into every batched drawer's metadata. Caller passes
``text`` (the full extracted markdown).
6. ``mempalace/palace.py::build_closet_lines`` — accepts optional
``drawer_metas`` (parallel to ``drawer_ids``). When present and the
first meta has both ``line_start`` and ``line_end``, the new
segment is spliced in; otherwise legacy 3-segment form. Helper
``_build_date_line_segment`` prefers ``content_date`` over
``filed_at`` for the date portion.
## Tests added (RED-first, then GREEN)
tests/test_miner.py::TestChunkTextLineRanges (4 tests)
tests/test_miner.py::TestBuildDrawerMetadataLineRange (2 tests)
tests/test_miner.py::TestExtractContentDate (15 tests)
- filename ISO / natural-language / compact
- YAML frontmatter date / created
- Claude session preamble
- ISO + natural-language content body
- Slash-date locale disambiguation (DD/MM lock vs default MM/DD)
- Priority order (filename > frontmatter > content > mtime)
- mtime fallback
- Graceful None returns for missing file / empty content
tests/test_closets.py::TestBuildClosetLines (5 new tests)
- includes_date_line_segment_when_metas_provided
- falls_back_to_3_segment_format_when_metas_missing (compat)
- falls_back_to_3_segment_format_when_metas_lack_line_keys (compat)
- date_segment_uses_filed_at_date_portion_only
- content_date_preferred_over_filed_at (new — Tier 6a hierarchy)
26 new tests total. All RED before this commit, all GREEN after.
## Verification
pytest tests/test_miner.py::TestChunkTextLineRanges
tests/test_miner.py::TestBuildDrawerMetadataLineRange
tests/test_miner.py::TestExtractContentDate
tests/test_closets.py::TestBuildClosetLines
→ 32 passed
pytest tests/test_miner.py tests/test_closets.py
tests/test_format_miner.py tests/test_palace.py
→ 230 passed, 2 skipped, 0 regressions in directly-affected files
ruff check + ruff format --check
→ All checks passed, 5 files already formatted
End-to-end smoke test on a YAML-frontmatter file (date: 2024-11-08,
mined "today"):
content_date extracted: 2024-11-08
chunks produced: 1
drawer meta: content_date=2024-11-08, filed_at='2026-05-22...', lines=1-15
closet pointer:
"conversation with lumi about brands of dog food|Filler;Lumi;Aya|2024-11-08:L1-L15|→drawer_a,drawer_b"
→ content_date correctly preferred over filed_at end-to-end.
OrbStack triple-Linux verify (Py 3.9 / 3.11 / 3.13)
→ 32 targeted Tier 6a + content-date tests pass on each.
## Out of scope (deliberate)
- No schema migration of existing drawers. Pre-Tier-6a drawers lack
``line_start`` / ``content_date`` and silently fall back to the
legacy 3-segment pointer shape.
- No re-mine required. Users keep existing palaces; new files mined
after this lands carry the new fields.
- No drawer ID change (Task #80, separate concern).
- No exact-quote line positioning within a chunk (future tier).
- No NLP-based date extraction (only regex + dateutil fuzzy).
- Linguistic-similarity / concept-recognition retrieval (L5 zettal
layer) is the natural next step but lives in its own PR family.
Addresses both inline comments left by gemini-code-assist on PR #1578.
## What this commit does
1. **HIGH PRIORITY (gemini, hallways.py:260) — canonicalize dynamics
preservation lookup key.** The previous code built the lookup key as
``(h.get("entity_a"), h.get("entity_b"))``, but the
``pair_counts`` dict and ``_hallway_id`` both use sorted entity pairs
for symmetric IDs. A persisted record with reversed entity order
(Lumi as entity_a, Aya as entity_b) would silently miss the lookup
and lose its accumulated dynamics on recompute. Now the lookup
canonicalizes the same way ID generation does:
key = tuple(sorted([h.get("entity_a"), h.get("entity_b")]))
Failure mode is rare in practice (the algorithm normally writes
sorted records), but any legacy data, manual JSON edit, or future
import path that violates the ordering would have silently broken
L7 preservation. Belt-and-suspenders fix.
2. **MEDIUM PRIORITY (gemini, palace_graph.py:512) — idiomatic field
preservation in tunnel dedup path.** Refactored the manual for-loop
into a dict-update with a comprehension. Field list lives in one
place; future schema expansion can't accidentally drop a field. No
behavior change.
## Test added (RED-first)
test_recompute_preserves_dynamics_when_existing_record_has_reversed_entity_order
Pre-populates the hallway store with a record whose ``entity_a`` /
``entity_b`` are in REVERSED (non-sorted) order, bumps its strength /
stability / access_count to non-default values, then runs
``compute_hallways_for_wing``. Asserts the recomputation preserves the
bumped values — proving the canonical lookup matches against
arbitrarily-ordered persisted entity pairs.
Reproduces the bug class gemini flagged: RED before this commit
(strength=1.0 instead of 4.2), GREEN after.
## Verification
pytest tests/test_hallways.py::TestHallwayDynamicsIntegration
tests/test_palace_graph_tunnels.py::TestTunnelDynamicsIntegration
tests/test_dynamics.py
→ 32 passed (was 31; added 1 new for the reverse-order case)
pytest -q (full mempalace suite)
→ 2112 passed, 3 skipped, 0 regressions
ruff check mempalace/dynamics.py mempalace/hallways.py mempalace/palace_graph.py tests/
→ All checks passed!
ruff format --check ...
→ 3 files already formatted (pinned 0.15.9)
Resolves conflicts from 60-commit divergence:
- tests/test_closets.py: assertion reformat — kept develop's ruff-format-
preferred multi-line shape (functionally identical).
- tests/test_palace_graph_tunnels.py: both branches added a new test
class at end-of-file (this PR's TestTunnelFileFollowsConfig + develop's
TestEntityTunnels from #1564). Kept both, no overlap.
Local: ruff check / format pass; full pytest suite passes
(2113 passed, 3 skipped).
Co-Authored-By: Igor Lins e Silva <4753812+igorls@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Resolves conflicts from 128-commit divergence:
- mempalace/convo_miner.py imports: kept both `mine_palace_lock` (this PR)
and `prefetch_mined_set` (develop).
- mempalace/convo_miner.py docstring: kept this PR's lock-wrapping
description, added a one-line pointer to the chunking-config section
whose body now lives in `_mine_convos_impl`.
- mempalace/convo_miner.py body: develop placed `cfg_chunk_size` /
`cfg_min_chunk_size` setup inline in `mine_convos`. This PR factored
the body into `_mine_convos_impl`, so the inline setup would have
left `cfg_chunk_size` referenced-but-undefined inside the impl.
Moved the `MempalaceConfig()` setup into `_mine_convos_impl` so the
variables are in scope where they're used.
- tests/test_convo_miner.py: kept both additive test sets (lock
concurrency from this PR + wing_api auto-routing from develop).
Local: ruff check / format pass; full pytest suite passes
(2103 passed, 3 skipped).
Co-Authored-By: Igor Lins e Silva <4753812+igorls@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds the L7 living-connection dynamics layer for the hallway primitive
(PR #1558) and the tunnel primitive (PR #1565). Connections now carry
strength, stability, last_activated, and access_count fields; pure-math
helpers in a new ``mempalace.dynamics`` module update these via Hebbian
potentiation (Hebb 1949) on co-access and Ebbinghaus exponential decay
(Ebbinghaus 1885) on time-since-use, with the Cepeda spacing effect
(Cepeda et al. 2006) growing stability when reinforcement is distributed
rather than massed.
Existing palaces continue to work unchanged — the new fields populate
via safe defaults (strength=1.0, stability=1.0, last_activated=created_at,
access_count=0) lazily on any potentiate/decay call. No migration step
required. No schema break. Old records work; new records ship with full
L7 state from creation.
## What this commit does
1. New module ``mempalace/dynamics.py`` — pure math, no I/O, no chromadb.
Three public helpers:
- ``initialize_dynamics_fields(connection, *, now=None)``
Backfill helper. Populates missing strength / stability /
last_activated / access_count fields. Existing fields are NOT
overwritten. Safe for pre-L7 records.
- ``potentiate(connection, *, increment=POTENTIATION_INCREMENT, now=None)``
Hebbian strengthening on a co-access event. Increments strength
(capped at MAX_STRENGTH), updates last_activated, increments
access_count. Grows stability by STABILITY_INCREMENT ONLY when
the gap since the prior activation is at least SPACED_INTERVAL_HOURS
— implements the Cepeda spacing effect (rapid bursts don't
build durability; distributed practice does).
- ``apply_decay(connection, *, now=None)``
Ebbinghaus exponential decay. New strength = old * exp(-days_since /
stability), floored at STRENGTH_FLOOR (0.05) so connections never
reach zero — only become dim. Idempotent at the same instant.
Higher stability = slower decay.
2. Integration in ``mempalace/hallways.py:compute_hallways_for_wing`` —
before persisting the new hallway list for a wing, looks up the
existing wing's hallways and builds a (entity_a, entity_b) → dynamics
lookup. Each new record gets the preserved dynamics if the entity
pair existed before, OR default dynamics via
``initialize_dynamics_fields`` if it's a brand-new pair. Without
this preservation, every mine would wipe accumulated connection
weights — defeating the whole L7 layer.
3. Integration in ``mempalace/palace_graph.py:create_tunnel`` — the
existing dedup-on-canonical-id path now also preserves the four
dynamics fields from the existing record onto the recreated tunnel
(in addition to the already-preserved ``created_at``). Brand-new
tunnels and legacy records (created before L7) get default dynamics
via ``initialize_dynamics_fields``.
## Tests (RED-first)
Twenty-five new tests in ``tests/test_dynamics.py`` covering the pure
math: field initialization defaults, potentiation strength increment +
cap, last_activated update, access_count increment, spaced vs. rapid
reinforcement (Cepeda spacing effect), decay rate (exp(-days/stability)),
floor clamping, idempotency at same instant, higher-stability slower-decay
behavior, no-time-passed no-op, backfill on missing fields, mutate-and-
return-same-dict chaining. Plus integration scenarios: potentiation
restoring decayed strength, repeated spaced reinforcement growing
stability monotonically, burst reinforcement not growing stability.
Six new integration tests:
test_new_hallway_record_carries_all_dynamics_fields
test_recompute_preserves_accumulated_strength
test_recompute_initializes_dynamics_for_brand_new_pairs
test_new_tunnel_carries_all_dynamics_fields
test_recreate_tunnel_preserves_accumulated_dynamics
test_recreate_tunnel_initializes_dynamics_for_legacy_records
All RED-first (KeyError: 'strength' before the integration commits).
All GREEN after.
## Backward compatibility
Pre-existing palaces work unchanged:
- Old hallway records with no dynamics fields are still readable; the
next ``compute_hallways_for_wing`` recompute populates the missing
fields via ``initialize_dynamics_fields``.
- Old tunnel records similarly; the next ``create_tunnel`` recreate (or
any future call passing the record through ``initialize_dynamics_fields``)
populates the missing fields.
- A ``test_recreate_tunnel_initializes_dynamics_for_legacy_records`` test
pins this contract explicitly.
No forced migration. No schema break. Old records work; new behavior
kicks in on first touch.
## What this does NOT do (intentionally scoped out)
- Spreading activation at search time — that's a search-layer change;
bigger PR; separate work.
- Lazy decay-on-read in ``list_hallways`` / ``list_tunnels`` — the math
is here; wiring it into the read path is a follow-up.
- Config exposure of the tunable constants — STRENGTH_FLOOR, MAX_STRENGTH,
POTENTIATION_INCREMENT etc. are hardcoded module-level for v1. If
empirical palace data shows the defaults need tuning, expose via
MempalaceConfig in a follow-up.
- Decay-aware ranking in search — the strength field is now there; the
search ranker doesn't yet use it. Follow-up.
## Verification
pytest tests/test_dynamics.py
→ 25 passed (RED before this commit; GREEN after)
pytest tests/test_hallways.py::TestHallwayDynamicsIntegration
→ 3 passed (RED before; GREEN after)
pytest tests/test_palace_graph_tunnels.py::TestTunnelDynamicsIntegration
→ 3 passed (RED before; GREEN after)
pytest -q (full mempalace suite)
→ 2111 passed, 3 skipped, 0 regressions
ruff check mempalace/dynamics.py mempalace/hallways.py mempalace/palace_graph.py tests/
→ All checks passed!
ruff format --check ...
→ 6 files already formatted (pinned 0.15.9)
## Research grounding
- Hebb, D. O. (1949). The Organization of Behavior. Wiley.
→ "Neurons that fire together, wire together" → potentiate()
- Ebbinghaus, H. (1885). Über das Gedächtnis.
→ Exponential forgetting curve → apply_decay()
- Cepeda, N. J., Pashler, H., Vul, E., Wixted, J. T., & Rohrer, D.
(2006). Distributed practice in verbal recall tasks: A review and
quantitative synthesis. Psychological Bulletin, 132(3), 354-380.
→ Spacing effect → stability growth on spaced reinforcement
Four sites passed content to `collection.upsert(documents=[...])` or
`collection.add(documents=[...])` without per-drawer size cap, hitting
the same `RuntimeError: Invalid buffer size` crash class from the
embedding model's attention buffer:
- `general_extractor.extract_memories`: post-classification slicer
that propagates `memory_type` to every slice. New `chunk_size`
parameter defaulting to `DEFAULT_CHUNK_SIZE` and resolved from
`MempalaceConfig.chunk_size` by the caller.
- `diary_ingest.ingest_diaries`: per-entry drawers via existing
`_split_entries`, with character-chunk fallback for any single
entry larger than `chunk_size`. New `_diary_drawer_id_entry`
helper carries (entry_idx, entry_chunk_idx). `chunk_index` in
metadata is a global counter across the file so
`searcher._expand_with_neighbors` stitches sibling chunks
regardless of entry boundary. Upsert is batched atomic per file
(one call carrying every entry/chunk) so a mid-pass embedding
failure cannot half-write the day. Auto-purge on full rebuild
deletes prior-pass drawers via `where={"source_file": ...}`,
which also migrates pre-#1539 legacy `drawer_diary_` IDs as a
side effect of normal use.
- `mcp_server.tool_diary_write`: split oversized entries into
bounded per-chunk drawers via a single batched `col.add` (atomic,
no half-write on embedding failure). `col.add` is intentional:
`entry_id` is timestamp-based with microsecond precision, so a
duplicate is a same-microsecond clash that should surface rather
than silently overwrite.
- `mcp_server.tool_add_drawer`: same crash class on the more common
add-drawer surface (100 KB sanitize cap, 125x `CHUNK_SIZE`).
Chunked path mirrors Site 3 with batched atomic `col.upsert`,
per-chunk `parent_drawer_id` + `chunk_index` metadata, and a
dual-id idempotency probe (last chunk for atomicity, legacy
`drawer_id` for pre-#1539 single-row backwards-compat). Return
shape additive: `chunks` always present, `chunk_ids` on the
chunked path. `tool_get_drawer` / `tool_delete_drawer` against
the logical handle report "not found" on the chunked path;
callers iterate `chunk_ids` or query `parent_drawer_id`.
Chunk id width is `:06d` so even a single-digit `chunk_size`
config cannot lex-sort chunks out of order.
PR #1555 (format coverage + virtual line numbering) merged with twelve
inline polish comments from Copilot + gemini-code-assist that weren't
load-bearing enough to block the original ship but are real cleanups.
This PR addresses them.
Twelve items in scope; one item (drawer ID delimiter — Copilot #13) is
deferred to its own dedicated PR because it's a breaking schema change
that requires migration design beyond the scope of a polish PR.
## Behavioral fixes (5 items, RED-tested first)
1. **FileNotFoundError vs broken symlink (Copilot #8).** ``extract_text``
previously mapped every ``FileNotFoundError`` from ``stat()`` to
``SKIP_BROKEN_SYMLINK``. That's misleading for the common case of a
regular file deleted between scan and extract. Now distinguishes:
``SKIP_BROKEN_SYMLINK`` only when ``p.is_symlink()`` is true;
``SKIP_UNREADABLE`` otherwise.
2. **``file_already_mined`` extract_mode scoping (Copilot #11, #12).**
Both call sites in ``mine_formats`` and ``_file_chunks_locked`` now
pass ``extract_mode="format"``. Previously the format miner could
falsely treat drawers from project / convo miner on the same source
file as "already mined" (and vice versa). Scopes idempotency to the
correct drawer subset.
3. **Sentinel skip for transient missing-dep statuses (Copilot #14).**
New ``_TRANSIENT_MISSING_DEP_STATUSES`` set + ``_register_skip_sentinel_if_appropriate``
helper. Skip variants like ``SKIP_NO_MARKITDOWN`` /
``SKIP_NO_STRIPRTF`` / ``SKIP_MISSING_FORMAT_DEPS`` /
``SKIP_NETWORK_TIMEOUT`` no longer write the "already-mined" sentinel.
Otherwise installing the missing extra later wouldn't trigger a re-mine.
4. **Outer ``except Exception`` in ``mine_formats`` (Gemini #5).** The
outer try around the loop previously caught only ``KeyboardInterrupt``,
leaving any setup-time error (e.g., ``scan_formats`` raising) to
propagate as a bare traceback. Now catches ``Exception`` defensively,
logs it, prints a partial-progress summary, and lets the ``finally``
PID-cleanup run. Mirrors miner.py's belt-and-suspenders pattern.
5. **Thread user's ``chunk_size`` / ``chunk_overlap`` / ``min_chunk_size``
through to ``chunk_text`` (Gemini #3).** ``MempalaceConfig`` was loaded
only to validate readability; users who tuned their config saw no
effect in format-mode mining. Now properly threaded.
## Trivial cleanups (5 items)
6. **Path expanduser in ``extract_text`` (Copilot #7).** ``Path(path)`` →
``Path(path).expanduser()`` so CLI inputs like ``~/docs/file.pdf``
resolve correctly.
7. **Path expanduser+resolve in ``scan_formats`` (Copilot #9).** Same
fix; ``~/docs`` and relative paths now work consistently.
8. **Use resolved ``format_path`` in ``mine_formats`` (Copilot #10).**
``scan_formats(format_dir)`` → ``scan_formats(format_path)`` so the
already-resolved path is used.
9. **``render_with_line_numbers`` type annotation (Copilot #15).**
``text: "str | None"`` reflects the documented + tested ``None``
handling.
10. **Test + docs claims (Copilot #16, #17, #18).** Stale framings
removed:
- ``docs/format-coverage.md`` — 14 fringe cases + "see the file for
the current test inventory" (no more frozen test count).
- ``tests/test_line_numbers.py`` — drops "proposed for mempalace
3.3.6" + "run from the proposal directory" references.
- ``tests/test_format_miner.py`` — drops "MarkItDown is mocked
throughout" (live integration tests exist) + proposal-directory
framing.
## Module-level hoists (enables clean test patching)
- ``MempalaceConfig`` (from ``.config``) hoisted from lazy local import
to module-level so tests can patch ``mempalace.format_miner.MempalaceConfig``.
- ``chunk_text`` (from ``.miner``) hoisted similarly.
Both follow the pattern PR #1565 used for ``compute_hallways_for_wing``.
## Complexity refactor
Extracted ``_print_mine_summary`` from ``mine_formats`` so the orchestrator
stays under the project's ``max-complexity = 25`` ceiling (per
``pyproject.toml [tool.ruff.lint.mccabe]``). Behavior unchanged; pure
extraction.
## Out of scope (intentionally deferred)
- **Drawer ID delimiter collision (Copilot #13)** — ``f"{source_file}{chunk_index}"``
can theoretically collide (``"/path/a1" + "23"`` == ``"/path/a" + "123"``).
Fixing this is a breaking schema change to drawer IDs and requires a
migration plan; will land as its own PR after design.
- The four bot comments that were ALREADY addressed by amendment #3
before the PR #1555 merge (``_SKIP_DIRS`` dedup, ``scan_formats``
symlink skip, ``source_mtime`` tracking, hall+entities metadata) —
no action needed; verified during audit.
## Tests (RED-first)
Six new RED-first tests in ``tests/test_format_miner.py``:
test_extract_text_nonexistent_regular_file_returns_unreadable_not_broken_symlink
test_mine_formats_passes_extract_mode_format_to_file_already_mined
test_mine_formats_does_not_write_sentinel_for_skip_no_markitdown
test_mine_formats_does_not_write_sentinel_for_skip_missing_format_deps
test_mine_formats_catches_unexpected_exception_and_prints_summary
test_mine_formats_threads_chunk_size_from_user_config
All six RED before this commit (failures correctly identified the bugs
they're targeting), all six GREEN after.
One existing test (``test_mine_formats_continues_after_per_file_error``)
updated to patch the new module-level binding
``mempalace.format_miner.chunk_text`` instead of the old
``mempalace.miner.chunk_text`` source location, and to accept the
``**kwargs`` the call now passes through. Behavior unchanged.
## Verification
pytest -q (full mempalace suite)
→ 2065 passed, 3 skipped, 0 regressions
ruff check mempalace/format_miner.py mempalace/searcher.py tests/
→ All checks passed!
ruff format --check ...
→ 4 files already formatted (pinned 0.15.9)
mine_formats complexity
→ ≤ 25 (under the project ceiling)
Addresses PR #1555 review (Igor) — two bugs that block this PR from
merging cleanly:
1. ``mempalace[extract]`` extras did not pull MarkItDown's per-format
sub-dependencies. A real PDF after ``pip install mempalace[extract]``
would raise ``MissingDependencyException`` asking for ``markitdown[pdf]``
— the code then routed that exception through the generic
``except Exception`` and surfaced it as ``SKIP_EXTRACTION_ERROR``,
stripping the actionable signal from the user.
2. ``test_fringe_broken_symlink`` and ``test_scan_formats_skips_symlinks``
called ``Path.symlink_to()`` unguarded, which raises ``OSError``
(``WinError 1314``) on Windows test environments without
``SeCreateSymbolicLinkPrivilege`` — surfacing as hard test failures
before any product code ran.
## What this commit does
1. ``mempalace/format_miner.py`` — adds a new
``ExtractionStatus.SKIP_MISSING_FORMAT_DEPS`` enum member and a
matching catch in ``extract_text`` that fires BEFORE the generic
``except Exception`` block. The catch matches by exception type name
(``type(exc).__name__ == "MissingDependencyException"``) so the static
import surface doesn't change — MarkItDown stays an optional
dependency.
2. ``pyproject.toml`` — changes ``[extract]`` to include MarkItDown's
per-format sub-extras:
"markitdown[docx,pdf,pptx,xlsx]>=0.1.5; python_version >= '3.10'"
These pull ``pdfminer-six``, ``pdfplumber``, ``mammoth``, ``lxml``,
``python-pptx``, ``openpyxl``, ``pandas`` — the deps each per-format
converter actually needs at runtime. Verified against MarkItDown
0.1.5's PyPI metadata (Provides-Extra includes ``pdf``, ``docx``,
``pptx``, ``xlsx`` among others). ``.epub`` is handled by base
markitdown (``EpubConverter`` uses ``beautifulsoup4``, a base
requirement, so no ``[epub]`` extra is needed — and none exists in
0.1.5). ``.rtf`` is covered by the existing ``striprtf`` entry.
``markitdown[all]`` was NOT used because it pulls audio
(``pydub``, ``speechrecognition``), YouTube, and Azure deps that
mempalace does not claim support for and that would bloat the
install for users.
3. ``tests/test_format_miner.py`` — adds a ``_make_symlink_or_skip``
helper near the top of the file that wraps ``Path.symlink_to()`` in
try/except ``OSError`` and calls ``pytest.skip(...)`` on failure.
Refactors both existing symlink tests
(``test_fringe_broken_symlink``, ``test_scan_formats_skips_symlinks``)
to use the helper. Behavior is unchanged on macOS/Linux; on Windows
without symlink privileges the tests skip cleanly instead of
spuriously failing.
## Tests (RED-first)
Two new RED-first tests:
test_extract_text_missing_format_dep_returns_distinct_status
Patches ``_extract_via_markitdown`` to raise a fake exception
with ``__name__ == "MissingDependencyException"``. Asserts the
dispatcher returns ``SKIP_MISSING_FORMAT_DEPS``, not
``SKIP_EXTRACTION_ERROR``.
test_pyproject_extract_extra_pulls_markitdown_format_subdeps
Parses ``pyproject.toml`` (via ``tomllib`` 3.11+ or ``tomli`` on
3.9/3.10 — the latter is already a base dependency under the
``python_version < '3.11'`` marker). Asserts ``[extract]``
includes ``pdf``, ``docx``, ``pptx``, ``xlsx`` inside SOME
``markitdown[...]`` bracketed group.
Both RED before this commit. Both GREEN after.
Also updates ``test_extraction_status_enum_has_all_documented_codes`` to
include the new ``SKIP_MISSING_FORMAT_DEPS`` code in the documented set,
so the enum-completeness doc-test stays honest.
## Verification
pytest tests/test_format_miner.py::test_extract_text_missing_format_dep_returns_distinct_status
tests/test_format_miner.py::test_pyproject_extract_extra_pulls_markitdown_format_subdeps
→ 2 passed (RED before, GREEN after)
pytest tests/test_format_miner.py::test_fringe_broken_symlink
tests/test_format_miner.py::test_scan_formats_skips_symlinks
→ 2 passed on macOS (Windows behaviour validated by CI test-windows)
pytest tests/test_format_miner.py
→ 64 passed, 2 skipped, 0 regressions
pytest -q (full mempalace suite)
→ 2002 passed, 3 skipped, 0 regressions
ruff check mempalace/format_miner.py tests/test_format_miner.py
→ All checks passed!
ruff format --check ...
→ 2 files already formatted (pinned 0.15.9)
## Why no OrbStack run this time
OrbStack runs Linux containers, which have unprivileged symlinks. It
cannot reproduce the Windows ``WinError 1314`` failure mode this
amendment fixes. The only authoritative gate for the symlink fix is
GitHub CI's ``test-windows`` job. For the enum + extras changes, both
are pure-Python / install-time concerns the CI test-linux matrix covers
identically to OrbStack. The ``tomli`` fallback in the new pyproject
test was verified against the base dependency declaration in
``pyproject.toml:32``.
Adds the architectural counterpart to ``compute_topic_tunnels`` that
materializes cross-wing tunnels from the within-wing hallway records
introduced in PR #1558. When an entity (person, project, concept,
interest) has hallways in two wings, an entity tunnel bridges them —
anchored on the entity. This completes the v4 sequence: Wing →
Drawer-entities → Hallway → Tunnel.
Topic tunnels are NOT replaced. Both systems coexist for one release
cycle so existing palaces don't lose tunnels between mines. Deprecation
of topic tunnels is a separate follow-up PR after entity tunnels prove
out in real use.
## What this commit does
1. Adds ``entity_tunnels_for_wing(wing, hallways, label_prefix)`` to
``mempalace/palace_graph.py``. Pure function: groups hallway records
by entity-and-wing, finds entities present in ``wing`` AND ≥1 other
wing, and emits one ``create_tunnel`` call per (entity, other_wing)
pair. Uses ``kind="entity"`` and synthetic endpoint room
``entity:<name>`` so the new tunnels are distinguishable from
explicit/topic tunnels at read time but interchangeable with them
via the standard ``list_tunnels`` / ``follow_tunnels`` API.
2. Adds ``_compute_entity_tunnels_for_wing(wing)`` wrapper to
``mempalace/miner.py``. Loads hallway records via
``hallways.list_hallways()`` and calls the algorithm. Module-level
so tests can patch it as ``mempalace.miner._compute_entity_tunnels_for_wing``.
3. Wires the wrapper into ``_mine_impl`` immediately after the existing
hallway-compute block. Same try/except fault-tolerance pattern as
the topic-tunnel and hallway blocks — entity-tunnel computation is
a derived analytic and must never fail a mine.
## Tests (RED-first)
Nine algorithm tests in ``tests/test_palace_graph_tunnels.py``
(new ``TestEntityTunnels`` class):
test_entity_tunnels_creates_cross_wing_tunnel_for_shared_entity
test_entity_tunnels_skips_entities_in_only_one_wing
test_entity_tunnels_counts_entity_in_either_pair_position
test_entity_tunnels_three_wings_pairwise_from_focus_wing
test_entity_tunnels_idempotent_on_rerun
test_entity_tunnels_retrievable_via_list_tunnels
test_entity_tunnels_empty_hallways_is_noop
test_entity_tunnels_unknown_wing_is_noop
test_entity_tunnel_room_does_not_collide_with_literal_room
Two integration tests in ``tests/test_miner.py``:
test_mine_computes_entity_tunnels_for_wing_post_mine
test_mine_entity_tunnel_failure_does_not_crash_mine
All 11 RED before this commit (AttributeError on the missing names).
All 11 GREEN after.
## Out of scope (deferred to follow-up PRs)
- ``format_miner.py`` and ``convo_miner.py`` integration: separate PRs
per the scope discipline used for #1560.
- Deprecating ``_compute_topic_tunnels_for_wing``: separate PR after
entity tunnels prove out in real use.
- Surfacing ``kind="entity"`` in MCP / search-result UI: not yet
required by any reader; behaviorally interchangeable with the other
tunnel kinds today.
## Stacking
This PR stacks on PR #1558 (which introduces the hallway primitive and
its miner integration). Base branch is
``feat/hallways-within-wing-connectors``. When #1558 merges to develop,
GitHub auto-updates this PR's base to ``develop`` and the diff reduces
to just the entity-tunnel additions.
## Verification
pytest tests/test_palace_graph_tunnels.py::TestEntityTunnels
→ 9 passed (RED before, GREEN after)
pytest tests/test_miner.py::test_mine_computes_entity_tunnels_for_wing_post_mine
tests/test_miner.py::test_mine_entity_tunnel_failure_does_not_crash_mine
→ 2 passed (RED before, GREEN after)
pytest tests/test_palace_graph_tunnels.py
→ 39 passed (no regressions)
pytest tests/test_miner.py
→ 49 passed (no regressions)
pytest -q (full mempalace suite)
→ 1949 passed, 1 skipped, 0 regressions
ruff check mempalace/palace_graph.py mempalace/miner.py tests/
→ All checks passed!
ruff format --check ...
→ 4 files already formatted (pinned 0.15.9)
- Disable mine and MCP idle timeouts when env values are invalid.
- Use bare-PID slot file mtime as the compatibility timestamp instead of treating old slots as infinitely stale.
- Treat malformed PID-slot timestamps as stale without crashing hook execution.
- Use process-level idle watchdog termination so stale MCP servers actually release file handles.
- Restore tenant-isolation assertions accidentally removed from the KG cache test.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Add MEMPALACE_MINE_TIMEOUT_HOURS (default 2h): PID files now record
'{pid} {unix_timestamp}'; _mine_already_running() treats alive-but-old
processes as stale, unblocking queued mines after a ChromaDB hang.
Backward-compatible: bare-PID files (old format) treated as stale.
- Add MEMPALACE_MCP_IDLE_HOURS (default 8h): daemon watchdog thread in
mcp_server calls sys.exit(0) after the configured idle period, preventing
accumulation of stale server processes holding ChromaDB/HNSW file handles.
Set to 0 to disable.
- Enrich _internal_tool_error() with optional exc parameter: adds
data: {error_class, message} to JSON-RPC error body so callers can
distinguish lock contention, ChromaDB transients, and segfaults without
scraping the message string. MineAlreadyRunning handler in tool_sync()
adds error_class: 'LockHeldByOtherProcess' to the result dict.
- Update miner._cleanup_mine_pid_file() to parse first whitespace token
as PID (handles both old and new PID file formats).
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>