memoryintelligence-mcp 0.2.10__tar.gz → 0.2.13__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of memoryintelligence-mcp might be problematic. Click here for more details.

Files changed (23) hide show
  1. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/CHANGELOG.md +111 -0
  2. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/PKG-INFO +21 -6
  3. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/README.md +20 -5
  4. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/pyproject.toml +1 -1
  5. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/__init__.py +1 -1
  6. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/__main__.py +5 -3
  7. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/cli.py +158 -9
  8. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/local_index.py +37 -5
  9. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/.gitignore +0 -0
  10. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/CONTRIBUTING.md +0 -0
  11. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/LICENSE +0 -0
  12. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/client.py +0 -0
  13. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/config.py +0 -0
  14. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/embedder.py +0 -0
  15. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/indexer.py +0 -0
  16. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/keys.py +0 -0
  17. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/localreads.py +0 -0
  18. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/paths.py +0 -0
  19. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/recall_guard.py +0 -0
  20. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/scrub.py +0 -0
  21. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/server.py +0 -0
  22. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/umo_format.py +0 -0
  23. {memoryintelligence_mcp-0.2.10 → memoryintelligence_mcp-0.2.13}/src/mi_mcp/vault.py +0 -0
@@ -3,6 +3,117 @@
3
3
  All notable changes to `memoryintelligence-mcp` are documented here.
4
4
  The format follows [Keep a Changelog](https://keepachangelog.com/); this project uses [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [0.2.13] — 2026-08-12
7
+
8
+ ### Fixed — `setup` could not be re-run without re-entering your API key (#1351)
9
+
10
+ `mi-mcp setup` is the most discoverable command for "my install is broken, fix it", but it
11
+ was written as the **first-run** path: it prompted for the API key unconditionally, so a
12
+ returning user got sent to the portal to dig out a credential they never needed to touch,
13
+ and a perfectly good stored key was overwritten.
14
+
15
+ `setup` now **keeps a key that is already in the Keychain or the keyfile**, printing only a
16
+ masked prefix. `--reset-key` replaces it deliberately. Resolution order, most explicit
17
+ first: `--api-key` → `MI_API_KEY` → already-stored → prompt.
18
+
19
+ It also names the command that user actually wanted. **`mi-mcp wire`** re-connects Claude
20
+ Desktop / Code / Cursor and never touches your key — `doctor` recommended it in five
21
+ places, but the failure is precisely for the user who does not run `doctor` first. The
22
+ `--help` epilog now says which of the two you need.
23
+
24
+ ## [0.2.12] — 2026-08-12
25
+
26
+ ### Fixed — local recency was corpus-relative, so importing one old memory reordered every result (#1253)
27
+
28
+ `LocalIndex.search` normalised recency against `max_age`, the age of the **oldest entry
29
+ currently in the index**. A document's score therefore depended on the whole corpus, not
30
+ on the query and the document: import one old memory and every existing result reorders,
31
+ with no change to the query and no change to the memories being ranked. Ranking stopped
32
+ being a function of `(query, document)`.
33
+
34
+ Recency is now an **absolute linear 30-day decay**, with semantics reused from the cloud
35
+ read path (`core/engines/rerank.py::recency_score`) rather than re-derived — floor to
36
+ whole days, decay over 30, floor at 0.0. One deliberate difference, stated rather than
37
+ silent: the result is also capped at **1.0**, so a future-dated entry from clock skew
38
+ cannot let recency out-rank every real signal.
39
+
40
+ `DEFAULT_WEIGHTS` carried the comment *"kept comparable to the cloud ranking."* The
41
+ numbers do match; the signals underneath do not all match. It now says so. Recency is
42
+ genuinely shared as of this release; keyword and entity remain locally derived.
43
+
44
+ ⚠️ **Ranking output changes for any vault whose oldest entry is not ~30 days old.** Under
45
+ the old formula the oldest entry always scored 0.0 recency and the newest always 1.0,
46
+ whatever the real span. Absolute decay means a vault where everything is a week old now
47
+ sees recency contribute ~equally across all entries — which is correct, and is the point.
48
+
49
+ ||||||| parent of 3fd5f209 (fix(mcp): setup keeps an already-stored key, and names `wire` as the repair command)
50
+ ## [0.2.11] — 2026-08-11
51
+
52
+ ### Fixed — `doctor` only ever asked PyPI, so a mirror install could not learn it was behind (#1347)
53
+
54
+ This package ships on **two** channels — PyPI and the public GitHub mirror — and doctor
55
+ consulted one. A user installed from the mirror could be **ahead of** PyPI and be told
56
+ they were current. Not hypothetical: 0.2.6 was tagged and installable from the mirror
57
+ while PyPI went 0.2.5 → 0.2.7, and for ~20 hours `mi-mcp doctor` answered
58
+ `0.2.6 (latest)` with a green tick.
59
+
60
+ The unreachable-PyPI branch already handled this class carefully — `latest unknown`,
61
+ never "up to date". The divergence branch never got the same care.
62
+
63
+ Doctor now reads **both** channels and reports the newest across them. When the channels
64
+ disagree it names them, **even when you are on the newest of the two**, because the
65
+ divergence itself is the defect and whoever runs `doctor` is the only person positioned
66
+ to see it. When you are current, any unreachable channel is disclosed rather than hidden:
67
+ one channel agreeing with you is weaker evidence than two. An unreachable channel is
68
+ treated as *unknown*, never as *different*, so being offline does not raise a false alarm.
69
+
70
+ `--no-version-check` / `MI_MCP_NO_VERSION_CHECK=1` still make **zero** network calls, now
71
+ to either channel.
72
+
73
+ ## [0.2.10] — 2026-08-11
74
+
75
+ ### Fixed — the local PII floor over-redacted digit runs and ate the following space (#1586)
76
+
77
+ ```
78
+ in : "the watermark is 1737654321 seconds"
79
+ out: "the watermark is <PHONE>seconds"
80
+ ```
81
+
82
+ `_PHONE_LONG_RE` was `(?:\+?\d[\s().-]?){10,15}` — **any** 10–15 digit run, each digit allowed
83
+ a trailing separator. Two defects compounded:
84
+
85
+ 1. it matched **UNIX epoch seconds**, the most common 10-digit run in MI's own corpus, so a
86
+ timestamp was redacted as a phone number;
87
+ 2. the final iteration's `[\s().-]?` **swallowed the following separator**, gluing the next
88
+ word to the marker.
89
+
90
+ **This was not a thin-install-only problem, as originally filed.** `scrub_text` applies the
91
+ `_HARD` floor on top of core's result **unconditionally** (`scrub.py:235`), so a floor looser
92
+ than core does not merely under-serve thin installs — it **overwrites a correct answer with a
93
+ wrong one on every MCP read**. Verified with core importable:
94
+
95
+ ```
96
+ core alone : "the watermark is 1737654321 seconds" (correct, untouched)
97
+ via floor : "the watermark is <PHONE>seconds" (degraded)
98
+ ```
99
+
100
+ One loose pattern split into three precise ones, mirroring `core/security/pii_detector.py`
101
+ rather than inventing a second design:
102
+
103
+ - **`_PHONE_SEP_RE`** — separated forms. The separators *are* the signal, so no digit-value
104
+ constraint is needed. Ends on a **digit**, which is defect 2's fix.
105
+ - **`_PHONE_E164_RE`** — the leading `+` is the signal (core measured 0 corpus matches for
106
+ this shape).
107
+ - **`_PHONE_BARE10_RE`** — defect 1's fix, and the dangerous one. NANP shape excludes epoch
108
+ seconds **structurally** (they start with `1` until 2033), and an alnum-aware boundary
109
+ excludes hex-hash digits (`"svo_hash": "914eb6579098371c"` contains a 10-digit run). Core
110
+ measured **360 → 48 → 1** as those are applied.
111
+
112
+ 21 RED-first cases in `tests/test_scrub_precision.py`, 8 failing before the fix. Every
113
+ precision case has a recall partner (#1456), so closing the over-redaction cannot reopen the
114
+ leak, and the suite is green in **both** install shapes — with core importable and without —
115
+ because the defect and the fix both live in the floor that runs either way.
116
+
6
117
  ## [0.2.9] — 2026-08-09
7
118
 
8
119
  ### Fixed — the thin-install PII floor had drifted behind core (#1464)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: memoryintelligence-mcp
3
- Version: 0.2.10
3
+ Version: 0.2.13
4
4
  Summary: MCP server for MemoryIntelligence — give Claude a memory you own, set up in one command
5
5
  Project-URL: Homepage, https://memoryintelligence.io
6
6
  Project-URL: Repository, https://github.com/somewhere11/memoryintelligence-mcp
@@ -227,17 +227,32 @@ mi-mcp status # wired surfaces + opt-in allowlist
227
227
  mi-mcp wire --dry-run # preview wiring changes
228
228
  ```
229
229
 
230
- **Staying current.** `doctor` compares your installed version against PyPI and
231
- prints the upgrade command for how you actually installed it:
230
+ **Staying current.** `doctor` compares your installed version against **both**
231
+ channels this package ships on — PyPI and the public GitHub mirror — and prints
232
+ the upgrade command for how you actually installed it:
232
233
 
233
234
  ```
234
235
  [✗] version 0.2.5 installed, 0.2.8 available — `uv tool upgrade memoryintelligence-mcp && mi-mcp wire`
235
236
  ```
236
237
 
238
+ Both channels are checked because they can diverge, and reading one alone told
239
+ mirror users they were current when they were not (0.2.6 was installable from the
240
+ mirror while PyPI went straight 0.2.5 → 0.2.7). When the channels disagree,
241
+ `doctor` names them — even if you are on the newest of the two — because that
242
+ divergence is worth knowing about:
243
+
244
+ ```
245
+ [✓] version 0.2.6 (latest) [channels differ: PyPI 0.2.5, mirror 0.2.6]
246
+ ```
247
+
248
+ An unreachable channel reads as *unknown*, never as up to date, and never as a
249
+ disagreement.
250
+
237
251
  Run `mi-mcp wire` after any upgrade — 0.2.6 renamed the server, and a config left
238
- pointing at the old id loses its tools silently. The check is an anonymous PyPI
239
- index fetch; skip it entirely with `--no-version-check` or
240
- `MI_MCP_NO_VERSION_CHECK=1`, and it fails quietly when you're offline.
252
+ pointing at the old id loses its tools silently. The checks are anonymous fetches
253
+ of the PyPI index and the mirror's `pyproject.toml`; skip them entirely with
254
+ `--no-version-check` or `MI_MCP_NO_VERSION_CHECK=1`, and they fail quietly when
255
+ you're offline.
241
256
 
242
257
  **Which server am I talking to?** The local server announces `mi-local`; the
243
258
  remote MCP surface announces `memoryintelligence-remote`. The local default
@@ -188,17 +188,32 @@ mi-mcp status # wired surfaces + opt-in allowlist
188
188
  mi-mcp wire --dry-run # preview wiring changes
189
189
  ```
190
190
 
191
- **Staying current.** `doctor` compares your installed version against PyPI and
192
- prints the upgrade command for how you actually installed it:
191
+ **Staying current.** `doctor` compares your installed version against **both**
192
+ channels this package ships on — PyPI and the public GitHub mirror — and prints
193
+ the upgrade command for how you actually installed it:
193
194
 
194
195
  ```
195
196
  [✗] version 0.2.5 installed, 0.2.8 available — `uv tool upgrade memoryintelligence-mcp && mi-mcp wire`
196
197
  ```
197
198
 
199
+ Both channels are checked because they can diverge, and reading one alone told
200
+ mirror users they were current when they were not (0.2.6 was installable from the
201
+ mirror while PyPI went straight 0.2.5 → 0.2.7). When the channels disagree,
202
+ `doctor` names them — even if you are on the newest of the two — because that
203
+ divergence is worth knowing about:
204
+
205
+ ```
206
+ [✓] version 0.2.6 (latest) [channels differ: PyPI 0.2.5, mirror 0.2.6]
207
+ ```
208
+
209
+ An unreachable channel reads as *unknown*, never as up to date, and never as a
210
+ disagreement.
211
+
198
212
  Run `mi-mcp wire` after any upgrade — 0.2.6 renamed the server, and a config left
199
- pointing at the old id loses its tools silently. The check is an anonymous PyPI
200
- index fetch; skip it entirely with `--no-version-check` or
201
- `MI_MCP_NO_VERSION_CHECK=1`, and it fails quietly when you're offline.
213
+ pointing at the old id loses its tools silently. The checks are anonymous fetches
214
+ of the PyPI index and the mirror's `pyproject.toml`; skip them entirely with
215
+ `--no-version-check` or `MI_MCP_NO_VERSION_CHECK=1`, and they fail quietly when
216
+ you're offline.
202
217
 
203
218
  **Which server am I talking to?** The local server announces `mi-local`; the
204
219
  remote MCP surface announces `memoryintelligence-remote`. The local default
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "memoryintelligence-mcp"
7
- version = "0.2.10"
7
+ version = "0.2.13"
8
8
  description = "MCP server for MemoryIntelligence — give Claude a memory you own, set up in one command"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -1,3 +1,3 @@
1
1
  """MI MCP Server — MemoryIntelligence tools for Claude."""
2
2
 
3
- __version__ = "0.2.10"
3
+ __version__ = "0.2.13"
@@ -43,9 +43,11 @@ def main():
43
43
  # user checking `--help` for `setup` shouldn't conclude the docs are stale.
44
44
  epilog=(
45
45
  "setup commands (run these first, not shown above):\n"
46
- " mi-mcp setup store your API key + wire + opt-in + verify (one command)\n"
47
- " mi-mcp wire wire into Claude Desktop / Code / Cursor\n"
48
- " mi-mcp doctor verify install, key resolution, and wiring\n"
46
+ " mi-mcp setup first run: store your API key + wire + opt-in + verify\n"
47
+ " mi-mcp wire ALREADY SET UP AND SOMETHING BROKE? start here —\n"
48
+ " re-connects Claude Desktop / Code / Cursor and\n"
49
+ " never touches your key\n"
50
+ " mi-mcp doctor tells you which of the two you need\n"
49
51
  " mi-mcp status show wired surfaces + opt-in allowlist\n"
50
52
  "\nGet a key at https://memoryintelligence.io/portal, then run `mi-mcp setup`."
51
53
  ),
@@ -455,6 +455,11 @@ def cmd_wire(argv: list[str]) -> int:
455
455
  #: PyPI project name — the package this CLI ships as.
456
456
  PYPI_PROJECT = "memoryintelligence-mcp"
457
457
 
458
+ #: The public GitHub mirror — the SECOND channel this package ships on (#1347).
459
+ #: A release reaches users through either, and they have diverged before.
460
+ MIRROR_REPO = "somewhere11/memoryintelligence-mcp"
461
+ MIRROR_BRANCH = "main"
462
+
458
463
  #: Set truthy to skip doctor's release check entirely (no network call at all).
459
464
  NO_VERSION_CHECK_ENV = "MI_MCP_NO_VERSION_CHECK"
460
465
 
@@ -500,6 +505,60 @@ def _latest_pypi_version(project: str = PYPI_PROJECT, timeout: float = 2.0) -> s
500
505
  return max(real, key=_version_tuple) if real else None
501
506
 
502
507
 
508
+ def _latest_mirror_version(repo: str = MIRROR_REPO, timeout: float = 2.0) -> str | None:
509
+ """Version the public GitHub mirror currently holds, or None if unknowable.
510
+
511
+ Reads the mirror's own ``pyproject.toml`` rather than its tags, because that is
512
+ what a mirror install actually gives you (``pip install git+…@main``). A tag
513
+ marks a release; the file is the thing you get.
514
+
515
+ Never raises: offline, DNS, 404, rate limit and a changed file layout are all
516
+ "unknown", the same contract as :func:`_latest_pypi_version`.
517
+ """
518
+ import urllib.request
519
+
520
+ url = f"https://raw.githubusercontent.com/{repo}/{MIRROR_BRANCH}/pyproject.toml"
521
+ req = urllib.request.Request(url, headers={"User-Agent": f"mi-mcp/{__version__}"})
522
+ try:
523
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 (fixed https URL)
524
+ text = resp.read().decode("utf-8", "replace")
525
+ except Exception:
526
+ return None
527
+ # Anchored to a line-leading `version`, so `requires-python = ">=3.10"` — which
528
+ # also holds a dotted number — cannot be mistaken for the package version.
529
+ m = re.search(r'(?m)^\s*version\s*=\s*["\']([^"\']+)["\']', text)
530
+ return m.group(1).strip() if m else None
531
+
532
+
533
+ def _latest_release(
534
+ pypi: str | None = None, mirror: str | None = None
535
+ ) -> tuple[str | None, dict]:
536
+ """(newest version across BOTH channels, {channel: version|None}).
537
+
538
+ "Latest" means newest *anywhere it ships*. Reading one channel and calling it
539
+ latest is what #1347 was filed about: for ~20 hours a mirror user on 0.2.6 was
540
+ told they were current because PyPI — which had never received 0.2.6 — was the
541
+ only thing consulted.
542
+ """
543
+ channels = {
544
+ "PyPI": _latest_pypi_version() if pypi is None else pypi,
545
+ "mirror": _latest_mirror_version() if mirror is None else mirror,
546
+ }
547
+ known = [v for v in channels.values() if v]
548
+ return (max(known, key=_version_tuple) if known else None), channels
549
+
550
+
551
+ def _channels_diverge(channels: dict) -> bool:
552
+ """True only when two channels are both KNOWN and disagree.
553
+
554
+ An unreachable channel is *unknown*, not *different* — reporting a divergence
555
+ because the network was down would train users to ignore the warning, which is
556
+ the same way the original green tick stopped meaning anything.
557
+ """
558
+ known = {v for v in channels.values() if v}
559
+ return len(known) > 1
560
+
561
+
503
562
  def _upgrade_command() -> str:
504
563
  """The upgrade command for THIS install, not a generic guess.
505
564
 
@@ -535,27 +594,48 @@ def cmd_doctor(argv: list[str]) -> int:
535
594
  # Release check FIRST — being two versions behind explains most "the tool
536
595
  # doesn't have X" reports, and it is the one thing nothing else surfaces.
537
596
  # Non-critical: out of date is not broken, so it never fails doctor's exit code.
538
- # Opt out with --no-version-check or MI_MCP_NO_VERSION_CHECK=1; the call is an
539
- # anonymous PyPI index fetch (same as any install) and is skipped entirely then.
597
+ # Opt out with --no-version-check or MI_MCP_NO_VERSION_CHECK=1; the calls are
598
+ # anonymous index/raw-file fetches (same as any install) and are skipped then.
599
+ #
600
+ # BOTH channels are consulted (#1347). This package ships on PyPI *and* the
601
+ # public GitHub mirror, and they have diverged in production: 0.2.6 was tagged
602
+ # and installable from the mirror while PyPI went straight 0.2.5 → 0.2.7. Asking
603
+ # PyPI alone told a mirror user on 0.2.6 they were on the latest, which is the
604
+ # false reassurance this whole check exists to prevent.
540
605
  skip_vc = args.no_version_check or os.environ.get(
541
606
  NO_VERSION_CHECK_ENV, ""
542
607
  ).strip().lower() in ("1", "true", "yes", "on")
543
608
  if skip_vc:
544
609
  check("version", True, f"{__version__} (release check skipped)", critical=False)
545
610
  else:
546
- latest = _latest_pypi_version()
611
+ latest, channels = _latest_release()
612
+ # Name the channels whenever they disagree — even when the user is already
613
+ # on the newest of the two. The divergence itself is the defect, and the
614
+ # person running doctor is the only one positioned to notice it.
615
+ where = ""
616
+ if _channels_diverge(channels):
617
+ where = " [channels differ: " + ", ".join(
618
+ f"{name} {v or 'unknown'}" for name, v in channels.items()
619
+ ) + "]"
620
+
547
621
  if latest is None:
548
622
  # Unknown is NOT "up to date" — say so rather than imply green.
549
623
  check("version", True,
550
- f"{__version__} installed — could not reach PyPI, latest unknown",
624
+ f"{__version__} installed — could not reach PyPI or the mirror, "
625
+ f"latest unknown",
551
626
  critical=False)
552
627
  elif _version_tuple(latest) > _version_tuple(__version__):
553
628
  check("version", False,
554
629
  f"{__version__} installed, {latest} available — "
555
- f"`{_upgrade_command()} && mi-mcp wire`",
630
+ f"`{_upgrade_command()} && mi-mcp wire`{where}",
556
631
  critical=False)
557
632
  else:
558
- check("version", True, f"{__version__} (latest)", critical=False)
633
+ # Current, but say which channels were actually readable. A lone
634
+ # reachable channel agreeing with you is weaker evidence than both.
635
+ unknown = [n for n, v in channels.items() if not v]
636
+ note = f" ({', '.join(unknown)} unreachable)" if unknown else ""
637
+ check("version", True, f"{__version__} (latest){note}{where}",
638
+ critical=False)
559
639
 
560
640
  bin_path = _mi_mcp_bin()
561
641
  check("mi-mcp binary", Path(bin_path).exists(), bin_path)
@@ -1002,6 +1082,36 @@ def cmd_backfill(argv: list[str]) -> int:
1002
1082
  # setup — the one-command front door (store key → wire → opt-in → verify)
1003
1083
  # ---------------------------------------------------------------------------
1004
1084
 
1085
+ def _stored_api_key(home: Path) -> str | None:
1086
+ """Return (key, where) for a key already on disk/Keychain, else (None, "").
1087
+
1088
+ Deliberately does NOT consult ``MI_API_KEY`` from the environment, unlike
1089
+ ``config.resolve_api_key``. Setup uses this to answer "do you already have a
1090
+ key I would be about to overwrite?", and an env var is neither stored nor
1091
+ overwritten — reporting it as "already stored" would be a lie the user
1092
+ cannot act on.
1093
+ """
1094
+ account = os.environ.get("MI_KEYCHAIN_ACCOUNT") or os.environ.get("USER") or ""
1095
+ try:
1096
+ r = subprocess.run(
1097
+ ["security", "find-generic-password", "-a", account, "-s", "MI_API_KEY", "-w"],
1098
+ capture_output=True, text=True, timeout=5,
1099
+ )
1100
+ if r.returncode == 0 and r.stdout.strip():
1101
+ return r.stdout.strip()
1102
+ except (OSError, subprocess.SubprocessError):
1103
+ pass # non-macOS or `security` unavailable — fall through to the keyfile
1104
+ envf = paths.resolve_keyfile(home)
1105
+ if envf is not None:
1106
+ for line in envf.read_text().splitlines():
1107
+ line = line.strip()
1108
+ if line.startswith("MI_API_KEY="):
1109
+ val = line.split("=", 1)[1].strip().strip('"').strip("'")
1110
+ if val:
1111
+ return val
1112
+ return None
1113
+
1114
+
1005
1115
  def _store_key_keychain(key: str, account: str) -> None:
1006
1116
  """Store the key in the macOS Keychain under service ``MI_API_KEY``.
1007
1117
 
@@ -1065,6 +1175,8 @@ def cmd_setup(argv: list[str]) -> int:
1065
1175
  )
1066
1176
  ap.add_argument("--api-key", default=None,
1067
1177
  help="provide the key non-interactively (else you're prompted, hidden)")
1178
+ ap.add_argument("--reset-key", action="store_true",
1179
+ help="replace a key that is already stored (default: keep it)")
1068
1180
  ap.add_argument("--store", choices=["auto", "keychain", "file"], default="auto",
1069
1181
  help="where to keep the key (auto: Keychain on macOS, ~/.memoryintelligence/.env elsewhere)")
1070
1182
  ap.add_argument("--surfaces", default="desktop,code",
@@ -1094,6 +1206,46 @@ def cmd_setup(argv: list[str]) -> int:
1094
1206
  if key:
1095
1207
  print(" ⚠ --api-key is visible in the process list (ps); on shared machines\n"
1096
1208
  " prefer the interactive prompt or the MI_API_KEY env var.", file=sys.stderr)
1209
+
1210
+ # #1351 — `setup` is the most discoverable command for "my install is
1211
+ # broken, fix it", but it was written as the FIRST-RUN path and prompted
1212
+ # for the key unconditionally. A returning user got sent to the portal to
1213
+ # dig out a credential they never needed to touch, and a perfectly good
1214
+ # stored key was overwritten.
1215
+ #
1216
+ # `mi-mcp wire` is the correct command for that user — it re-connects the
1217
+ # hosts and never touches the key — and nothing told them so. `doctor`
1218
+ # recommends `wire` in five places, but the whole failure is for the user
1219
+ # who does NOT run doctor first and goes straight for the command whose
1220
+ # name sounds like what they want.
1221
+ #
1222
+ # Resolution order, most explicit first:
1223
+ # --api-key → MI_API_KEY env → ALREADY-STORED key → prompt
1224
+ #
1225
+ # An env var set for this invocation is a deliberate per-run override and
1226
+ # outranks what is on disk; a stored key outranks the prompt, which is the
1227
+ # fix. Ordering matters and is asserted in test_cli_setup.py.
1228
+ if not key and os.environ.get("MI_API_KEY"):
1229
+ key = os.environ["MI_API_KEY"].strip()
1230
+ print(" using MI_API_KEY from the environment")
1231
+
1232
+ if not key and not args.reset_key:
1233
+ existing = _stored_api_key(home)
1234
+ if existing:
1235
+ key = existing
1236
+ # Nothing derived from the key is printed — not a masked slice, not
1237
+ # a hash. CodeQL taints the key value, so ANY derived value reaching
1238
+ # stdout is a clear-text-logging flow, and it is right to: the useful
1239
+ # fact here is that a key was kept and WHERE it lives, which needs no
1240
+ # part of the secret. Two earlier attempts got this wrong — a
1241
+ # `key[:11]…key[-4:]` mask (1 alert), then a SHA-256 fingerprint,
1242
+ # which kept that alert AND added a weak-hash-on-sensitive-data one
1243
+ # (2 alerts). `mi-mcp doctor` is where key identity belongs.
1244
+ print(" keeping the key already stored on this machine")
1245
+ print(" re-run with --reset-key to replace it\n")
1246
+ print(" \u2139 if you only need to re-connect the hosts, `mi-mcp wire` is\n"
1247
+ " the narrower command — it never touches your key.\n")
1248
+
1097
1249
  if not key:
1098
1250
  if sys.stdin.isatty():
1099
1251
  print("Get a free key at https://memoryintelligence.io/portal")
@@ -1102,9 +1254,6 @@ def cmd_setup(argv: list[str]) -> int:
1102
1254
  except (EOFError, KeyboardInterrupt):
1103
1255
  print("\naborted — nothing stored.", file=sys.stderr)
1104
1256
  return 130
1105
- elif os.environ.get("MI_API_KEY"):
1106
- key = os.environ["MI_API_KEY"].strip()
1107
- print(" using MI_API_KEY from the environment")
1108
1257
  else:
1109
1258
  print("error: no API key. Run in a terminal to be prompted, set MI_API_KEY,\n"
1110
1259
  " or pass --api-key. Get a free key at https://memoryintelligence.io/portal",
@@ -37,9 +37,44 @@ from typing import Optional, Sequence
37
37
  # module — for its dataclasses or JSON persistence — never requires numpy. Only
38
38
  # ranking does. Keeps `pip install memoryintelligence-mcp` numpy-free.
39
39
 
40
- # Local ranking weights, kept comparable to the cloud ranking.
40
+ # Local ranking weights. The NUMBERS match the cloud's
41
+ # (`core/engines/rerank.py`); the SIGNALS underneath are not all identical, so
42
+ # read this as "same blend, not the same function" rather than as a parity
43
+ # guarantee. Recency is now genuinely shared (see below); keyword and entity
44
+ # are still locally derived.
41
45
  DEFAULT_WEIGHTS = {"semantic": 0.60, "keyword": 0.15, "entity": 0.15, "recency": 0.10}
42
46
 
47
+ #: Days over which recency decays to zero. Mirrors `rerank.recency_score`,
48
+ #: which the cloud/sidecar read path uses.
49
+ RECENCY_HALFLIFE_DAYS = 30.0
50
+ _SECONDS_PER_DAY = 86_400.0
51
+
52
+
53
+ def _recency_score(created_at: float, now: float) -> float:
54
+ """Absolute linear 30-day decay — NOT normalized against the corpus (#1253).
55
+
56
+ This was ``1.0 - ((now - created_at) / max_age)`` where ``max_age`` was the
57
+ age of the oldest entry in the index. A document's score therefore depended
58
+ on the whole corpus: **importing one old memory reordered every existing
59
+ result**, with no change to the query and no change to the memories being
60
+ ranked. Ranking stopped being a function of ``(query, document)``, which is
61
+ wrong under any architecture we might pick for the local runtime — which is
62
+ why it is fixed here rather than folded into the local/cloud convergence
63
+ question.
64
+
65
+ Semantics are reused from ``core/engines/rerank.py::recency_score`` rather
66
+ than re-derived: floor to whole days ago, linear decay over
67
+ ``RECENCY_HALFLIFE_DAYS``, floor at 0.0.
68
+
69
+ One deliberate difference from the cloud function, stated rather than
70
+ silent: the result is also capped at **1.0**. A future-dated entry (clock
71
+ skew, a bad import) yields a negative ``days_ago`` there and a score above
72
+ 1.0, which would let recency out-rank every real signal. Capping cannot
73
+ hide a real difference — nothing legitimately scores above 1.0.
74
+ """
75
+ days_ago = (now - created_at) // _SECONDS_PER_DAY
76
+ return max(0.0, min(1.0, 1.0 - (days_ago / RECENCY_HALFLIFE_DAYS)))
77
+
43
78
  _TOKEN_RE = re.compile(r"[a-z0-9]+")
44
79
 
45
80
 
@@ -124,9 +159,6 @@ class LocalIndex:
124
159
  q_tokens = _tokens(query_text)
125
160
  q_ents = {e.lower() for e in (query_entities or [])}
126
161
 
127
- ages = [now - e.created_at for e in self._entries.values()]
128
- max_age = max(ages) or 1.0 # normalize recency against the oldest entry
129
-
130
162
  w = self._weights
131
163
  hits = []
132
164
  for e in self._entries.values():
@@ -135,7 +167,7 @@ class LocalIndex:
135
167
  semantic = max(0.0, cos) # similarity, never negative
136
168
  keyword = _overlap(q_tokens, _tokens(e.summary))
137
169
  entity = _overlap(q_ents, {x.lower() for x in e.entities}) if q_ents else 0.0
138
- recency = 1.0 - ((now - e.created_at) / max_age)
170
+ recency = _recency_score(e.created_at, now)
139
171
  score = (
140
172
  w["semantic"] * semantic
141
173
  + w["keyword"] * keyword