memorix 1.10.4 → 1.10.5

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/cli/index.js +418 -74
  3. package/dist/index.js +227 -55
  4. package/dist/maintenance-runner.js +225 -53
  5. package/dist/media-audio-runner.js +225 -53
  6. package/dist/media-video-runner.js +225 -53
  7. package/dist/memcode-runtime/CHANGELOG.md +44 -0
  8. package/dist/sdk.js +242 -56
  9. package/dist/vector-backfill-runner.js +225 -53
  10. package/docs/AGENT_OPERATOR_PLAYBOOK.md +7 -0
  11. package/docs/ARCHITECTURE.md +19 -0
  12. package/docs/CONFIGURATION.md +2 -0
  13. package/docs/DEVELOPMENT.md +8 -1
  14. package/docs/MODULES.md +1 -1
  15. package/docs/PERFORMANCE.md +7 -0
  16. package/docs/README.md +3 -1
  17. package/docs/ROADMAP-1.9.12-2.0.md +1 -1
  18. package/package.json +1 -1
  19. package/plugins/antigravity/memorix/plugin.json +1 -1
  20. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  21. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  22. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  23. package/plugins/copilot/memorix/plugin.json +1 -1
  24. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  25. package/plugins/hermes/memorix/plugin.yaml +1 -1
  26. package/plugins/omp/memorix/package.json +1 -1
  27. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  28. package/plugins/pi/memorix/package.json +1 -1
  29. package/server.json +2 -2
  30. package/src/cli/command-guide.ts +3 -1
  31. package/src/cli/commands/http-session-stream-watch.ts +138 -0
  32. package/src/cli/commands/memory.ts +3 -1
  33. package/src/cli/commands/project-detection-cache.ts +61 -0
  34. package/src/cli/commands/serve-http.ts +63 -13
  35. package/src/cli/index.ts +1 -1
  36. package/src/core/derived-view-registry.ts +33 -0
  37. package/src/embedding/api-provider.ts +14 -2
  38. package/src/embedding/ollama-embed.ts +118 -0
  39. package/src/memory/observations.ts +28 -6
  40. package/src/search/semantic-index.ts +38 -6
  41. package/src/store/orama-store.ts +46 -30
@@ -333,6 +333,8 @@ ascii = "hybrid"
333
333
  - `hybrid`: the existing Orama hybrid ranker.
334
334
 
335
335
  `cjk` applies when more than 30% of the query characters are CJK. Everything else uses `ascii`. Defaults are `cjk = "vector"` and `ascii = "hybrid"`. `MEMORIX_RETRIEVAL_CJK` and `MEMORIX_RETRIEVAL_ASCII` override the files.
336
+
337
+ When an embeddings host answers `GET /api/version` with an Ollama version string, Memorix rewrites that origin's `/v1/embeddings` requests to `/api/embed` and sends `keep_alive: "5m"` unless the request already sets one. The port is irrelevant. Leave `base_url` on `/v1`; a native `/api/embed` base URL does not match the OpenAI parser. Hosts that do not serve Ollama's version endpoint stay on `/v1/embeddings`.
336
338
  `transformers` is no longer installed by default; install
337
339
  `@huggingface/transformers` explicitly in the project or global prefix where
338
340
  Memorix runs if you choose that provider. `fastembed` remains a supported local
@@ -13,7 +13,14 @@ Memorix is a TypeScript project built around:
13
13
 
14
14
  ## Current Development Baseline
15
15
 
16
- The current release line is **1.10.4** and package metadata is kept
16
+ For HTTP session lifecycle changes, build the CLI and run
17
+ `node scripts/http-session-lifecycle-smoke.mjs`. This uses an isolated home and
18
+ data directory and checks silent disconnect expiry, reconnection, idle SSE,
19
+ POST-only clients, continued POST activity after a stream close, and repeated
20
+ stateless discovery outside Git. CI runs the same smoke on all three desktop
21
+ platforms after the test suite.
22
+
23
+ The current release line is **1.10.5** and package metadata is kept
17
24
  synchronized with the root package and MCP Registry manifest. The next larger
18
25
  feature phase follows the 1.11 relay-preview plan.
19
26
 
package/docs/MODULES.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Memorix 模块详解
2
2
 
3
- > 最后更新: 2026-11-18(源码与 npm 发布版本 v1.10.4)
3
+ > 最后更新: 2026-11-26(源码版本 v1.10.5;npm 发布状态见 ACTIVE_WORK.md)
4
4
  > 本文档记录当前模块边界、关键算法和兼容层,不把历史实现误写成运行时主路径。
5
5
 
6
6
  > 当前真实主路径先看下面的模块总览,再看各模块的细节。早期 JSON/Orama
@@ -167,6 +167,7 @@ On the release development machine used for this check, the healthy HTTP service
167
167
  | Knob | Default | Use When |
168
168
  | --- | --- | --- |
169
169
  | `MEMORIX_SESSION_TIMEOUT_MS` | `43200000` (12 h) | Set a shorter GC window for supervised clients, or `0` to disable idle session GC |
170
+ | `MEMORIX_SESSION_DISCONNECT_GRACE_MS` | `120000` (2 min) | Release a legacy session after its last GET/SSE stream closes without reconnection or further requests; `0` disables this watch. Queued/running POST requests are protected. Values above Node's timer limit fall back to the default. |
170
171
  | `MEMORIX_MAX_HTTP_SESSIONS` | `64` (max `512`) | Bound concurrent stateful HTTP MCP sessions; excess initialization requests receive `429` |
171
172
  | `MEMORIX_FORMATION_TIMEOUT_MS` | `12000` (12 s) | Raise when LLM-backed formation should outlive slow proxy/provider hops |
172
173
  | `MEMORIX_LLM_API_KEY` / `OPENAI_API_KEY` | unset | Enable LLM-backed enrichment, extraction, rerank, or skill generation |
@@ -204,6 +205,12 @@ crash must be reconciled before a dangerous retry.
204
205
 
205
206
  - For memory-only use, prefer stdio MCP or a lightweight `memorix_session_start`; do not join orchestration coordination state by default.
206
207
  - HTTP sessions now default to 12 hours and return a fast `404` with a reinitialize hint after expiry. Set `MEMORIX_SESSION_TIMEOUT_MS=0` only when the host has its own reliable lifecycle cleanup; otherwise retain a bounded GC window.
208
+ - Legacy clients that opened a GET/SSE stream and then disconnected silently
209
+ are released after a two-minute grace period. Reconnection, further POST
210
+ activity, and queued/running requests prevent disconnect cleanup. Clients
211
+ that never opened a GET stream continue to use idle GC. Stateless project
212
+ detection caches positive and negative results for five minutes, up to 256
213
+ paths; explicit session binding continues to detect the project live.
207
214
  - If LLM-backed formation is timing out against a slow proxy/provider, raise `MEMORIX_FORMATION_TIMEOUT_MS` and keep it higher than `MEMORIX_LLM_TIMEOUT_MS`, because the full pipeline can include multiple LLM-backed stages.
208
215
  - For Docker, use it when you want a managed HTTP service. Do not use image size alone as the runtime memory estimate.
209
216
  - For orchestrated subagent work, expect CPU and disk activity proportional to the spawned agents and verification commands.
package/docs/README.md CHANGED
@@ -127,7 +127,9 @@ Historical/deep-reference documents may describe older designs. If they conflict
127
127
 
128
128
  ## Current Product Line
129
129
 
130
- The current product line is **1.10.4**; it includes the CodeGraph, lazy-vector,
130
+ The current product line is **1.10.5**; it adds scoped Lance vector identities,
131
+ HTTP disconnect cleanup, stateless project-detection caching, and clearer CLI
132
+ topic-key help. It includes the CodeGraph, lazy-vector,
131
133
  search-regression, browser-launch, and Runcrate updates on top of the LanceDB
132
134
  growth fix, derived-view receipts, and the optional Cheaper Inference preset.
133
135
  Multi-device store sync is opt-in and keeps local SQLite canonical; existing
@@ -47,7 +47,7 @@ Memorix 已经超过“给 coding agent 加一个记忆工具”的阶段。当
47
47
 
48
48
  ### 1.1 当前事实
49
49
 
50
- 当前发布基线是 `v1.10.4`。1.10.2 修复了 LanceDB 语义索引无限增长;1.10.3 继续修复 CodeGraph、lazy vector 和搜索回归;1.10.4 增加 embedding 传输恢复、启动缓存节流和 CJK 向量排序;1.9.12 的 CJK 搜索、搜索回退、大库 alias 迁移、
50
+ 当前维护版本是 `v1.10.5`,包含项目范围的向量身份、HTTP 断连回收和无状态项目检测缓存。1.10.2 修复了 LanceDB 语义索引无限增长;1.10.3 继续修复 CodeGraph、lazy vector 和搜索回归;1.10.4 增加 embedding 传输恢复、启动缓存节流和 CJK 向量排序;1.9.12 的 CJK 搜索、搜索回退、大库 alias 迁移、
51
51
  Node 26 Pi hooks、Qwen hooks、API Route provider、session label、发布
52
52
  provenance 收紧和后台更新脚本隔离,已经与 1.10 的可信上下文、检索收据、
53
53
  真实矩阵评估和容量门禁一起发布。
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "memorix",
3
3
  "mcpName": "io.github.AVIDS2/memorix",
4
- "version": "1.10.4",
4
+ "version": "1.10.5",
5
5
  "description": "Local-first shared memory layer for AI coding agents across MCP clients, Git history, reasoning context, and project sessions.",
6
6
  "type": "module",
7
7
  "sideEffects": false,
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "name": "memorix",
3
- "version": "1.10.4"
3
+ "version": "1.10.5"
4
4
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://anthropic.com/claude-code/plugin.schema.json",
3
3
  "name": "memorix",
4
- "version": "1.10.4",
4
+ "version": "1.10.5",
5
5
  "description": "Shared workspace memory for Claude Code and other AI coding agents.",
6
6
  "author": {
7
7
  "name": "AVIDS2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memorix",
3
- "version": "1.10.4",
3
+ "version": "1.10.5",
4
4
  "description": "Local-first project memory for CodeBuddy Code and other coding agents.",
5
5
  "author": {
6
6
  "name": "AVIDS2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memorix",
3
- "version": "1.10.4",
3
+ "version": "1.10.5",
4
4
  "description": "Shared workspace memory for Codex and other AI coding agents.",
5
5
  "author": {
6
6
  "name": "AVIDS2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memorix",
3
- "version": "1.10.4",
3
+ "version": "1.10.5",
4
4
  "description": "Shared local workspace memory for GitHub Copilot CLI and other AI coding agents.",
5
5
  "author": {
6
6
  "name": "AVIDS2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memorix",
3
- "version": "1.10.4",
3
+ "version": "1.10.5",
4
4
  "mcpServers": {
5
5
  "memorix": {
6
6
  "command": "memorix",
@@ -1,5 +1,5 @@
1
1
  name: memorix
2
- version: "1.10.4"
2
+ version: "1.10.5"
3
3
  description: Shared workspace memory bridge for Hermes Agent.
4
4
  author: AVIDS2
5
5
  license: Apache-2.0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memorix-omp-package",
3
- "version": "1.10.4",
3
+ "version": "1.10.5",
4
4
  "description": "Memorix shared workspace memory package for Oh-my-Pi.",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memorix",
3
- "version": "1.10.4",
3
+ "version": "1.10.5",
4
4
  "description": "Shared workspace memory for OpenClaw and other AI coding agents.",
5
5
  "author": {
6
6
  "name": "AVIDS2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memorix-pi-package",
3
- "version": "1.10.4",
3
+ "version": "1.10.5",
4
4
  "description": "Memorix shared workspace memory package for Pi coding agent.",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
package/server.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "url": "https://github.com/AVIDS2/memorix",
8
8
  "source": "github"
9
9
  },
10
- "version": "1.10.4",
10
+ "version": "1.10.5",
11
11
  "websiteUrl": "https://mem.rglens.com",
12
12
  "icons": [
13
13
  {
@@ -22,7 +22,7 @@
22
22
  {
23
23
  "registryType": "npm",
24
24
  "identifier": "memorix",
25
- "version": "1.10.4",
25
+ "version": "1.10.5",
26
26
  "runtimeHint": "npx",
27
27
  "packageArguments": [
28
28
  {
@@ -9,7 +9,7 @@ const GUIDES: Record<string, CliCommandGuide> = {
9
9
  summary: 'Store, search, inspect, resolve, consolidate, and promote project memory.',
10
10
  usage: [
11
11
  'memorix memory search --query "timeout regression" [--limit 10]',
12
- 'memorix memory store --text "..." [--title "..."] [--visibility project|personal|team]',
12
+ 'memorix memory store --text "..." [--title "..."] [--type discovery] [--entity <name>] [--topic-key <key>] [--facts a,b] [--files a,b] [--concepts a,b] [--visibility project|personal|team]',
13
13
  'memorix memory detail --id 42',
14
14
  'memorix memory recent [--limit 10]',
15
15
  'memorix memory resolve --ids 42,43 [--status resolved|archived]',
@@ -23,6 +23,8 @@ const GUIDES: Record<string, CliCommandGuide> = {
23
23
  ],
24
24
  notes: [
25
25
  'Personal and team visibility require `memorix identity join` or `memorix identity use` first.',
26
+ 'The same project and the same --topic-key update the existing observation and return upserted: true. A missing key creates a new observation. Lookup uses only the project selected by --cwd.',
27
+ 'memorix remember does not forward --entity or --topic-key. Topic-key upsert uses memorix memory store.',
26
28
  'Candidates never enter a task Workset. Only manual or user-confirmed `user + portable` memory may cross local projects.',
27
29
  ],
28
30
  },
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Detects legacy Streamable HTTP sessions whose client has gone away.
3
+ *
4
+ * MCP clients built on the official SDK open a standalone GET/SSE stream right
5
+ * after `notifications/initialized` and keep it open (reconnecting on drops)
6
+ * for as long as the client lives. Many clients never send the optional
7
+ * `DELETE /mcp` when they exit, so without this watch their sessions linger
8
+ * until the idle timeout (12 hours by default) and count against the session
9
+ * limit.
10
+ *
11
+ * A session is reported as abandoned only when both conditions hold:
12
+ * 1. its last SSE stream closed and no new stream was opened within the grace
13
+ * window (an SDK client reconnects within a few seconds), and
14
+ * 2. the client sent no request after the stream closed.
15
+ *
16
+ * Sessions that never open a GET stream are never reported: the idle timeout
17
+ * remains their only cleanup path.
18
+ */
19
+
20
+ export const DEFAULT_SESSION_DISCONNECT_GRACE_MS = 2 * 60 * 1000;
21
+
22
+ /** `MEMORIX_SESSION_DISCONNECT_GRACE_MS`: `0` disables the watch; invalid values keep the default. */
23
+ export function parseSessionDisconnectGraceMs(raw: string | undefined): number {
24
+ const value = raw?.trim();
25
+ if (!value) return DEFAULT_SESSION_DISCONNECT_GRACE_MS;
26
+ const parsed = Number(value);
27
+ if (!Number.isFinite(parsed) || parsed < 0 || parsed > 2_147_483_647) return DEFAULT_SESSION_DISCONNECT_GRACE_MS;
28
+ return Math.floor(parsed);
29
+ }
30
+
31
+ type TimerHandle = { unref?: () => unknown };
32
+
33
+ export interface SessionStreamWatchOptions {
34
+ /** Grace window in milliseconds; `0` disables abandonment detection. */
35
+ graceMs: number;
36
+ /** Last request time of a live session, or `undefined` once the session is gone. */
37
+ getLastActivity: (sessionId: string) => number | undefined;
38
+ /** A queued or running request must finish before disconnect cleanup. */
39
+ isBusy?: (sessionId: string) => boolean;
40
+ /** Called once when a session is considered abandoned. */
41
+ onAbandoned: (sessionId: string) => void;
42
+ now?: () => number;
43
+ setTimer?: (callback: () => void, ms: number) => TimerHandle;
44
+ clearTimer?: (handle: TimerHandle) => void;
45
+ }
46
+
47
+ export interface SessionStreamWatch {
48
+ /** A GET request for this session started. */
49
+ streamOpened(sessionId: string): void;
50
+ /**
51
+ * That GET request ended. `wasStream` is false when the server refused the
52
+ * request (non-200), which must not arm abandonment on its own.
53
+ */
54
+ streamClosed(sessionId: string, wasStream: boolean): void;
55
+ /** The session closed for another reason; drop its state. */
56
+ forget(sessionId: string): void;
57
+ /** Cancel every pending timer (shutdown). */
58
+ dispose(): void;
59
+ /** Number of sessions with a pending abandonment timer (diagnostics/tests). */
60
+ pendingCount(): number;
61
+ }
62
+
63
+ export function createSessionStreamWatch(options: SessionStreamWatchOptions): SessionStreamWatch {
64
+ const now = options.now ?? Date.now;
65
+ const setTimer = options.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
66
+ const clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle as ReturnType<typeof setTimeout>));
67
+ const openStreams = new Map<string, number>();
68
+ const closedStreams = new Set<string>();
69
+ const pending = new Map<string, TimerHandle>();
70
+
71
+ function cancel(sessionId: string): void {
72
+ const handle = pending.get(sessionId);
73
+ if (!handle) return;
74
+ clearTimer(handle);
75
+ pending.delete(sessionId);
76
+ }
77
+
78
+ return {
79
+ streamOpened(sessionId) {
80
+ if (options.graceMs === 0) return;
81
+ cancel(sessionId);
82
+ openStreams.set(sessionId, (openStreams.get(sessionId) ?? 0) + 1);
83
+ },
84
+
85
+ streamClosed(sessionId, wasStream) {
86
+ if (!openStreams.has(sessionId)) return;
87
+ if (wasStream) closedStreams.add(sessionId);
88
+ const remaining = Math.max(0, (openStreams.get(sessionId) ?? 0) - 1);
89
+ if (remaining > 0) {
90
+ openStreams.set(sessionId, remaining);
91
+ return;
92
+ }
93
+ openStreams.delete(sessionId);
94
+ const hadStream = closedStreams.delete(sessionId);
95
+ if (!hadStream || options.graceMs === 0) return;
96
+ if (options.getLastActivity(sessionId) === undefined) return;
97
+
98
+ cancel(sessionId);
99
+ const closedAt = now();
100
+ const check = () => {
101
+ pending.delete(sessionId);
102
+ if ((openStreams.get(sessionId) ?? 0) > 0) return;
103
+ const lastActivity = options.getLastActivity(sessionId);
104
+ if (lastActivity === undefined) return;
105
+ // The client is still talking to us without its stream: leave the
106
+ // session to the idle timeout instead of cutting a live client.
107
+ if (lastActivity > closedAt) return;
108
+ if (options.isBusy?.(sessionId)) {
109
+ const next = setTimer(check, options.graceMs);
110
+ next.unref?.();
111
+ pending.set(sessionId, next);
112
+ return;
113
+ }
114
+ options.onAbandoned(sessionId);
115
+ };
116
+ const handle = setTimer(check, options.graceMs);
117
+ handle.unref?.();
118
+ pending.set(sessionId, handle);
119
+ },
120
+
121
+ forget(sessionId) {
122
+ cancel(sessionId);
123
+ openStreams.delete(sessionId);
124
+ closedStreams.delete(sessionId);
125
+ },
126
+
127
+ dispose() {
128
+ for (const handle of pending.values()) clearTimer(handle);
129
+ pending.clear();
130
+ openStreams.clear();
131
+ closedStreams.clear();
132
+ },
133
+
134
+ pendingCount() {
135
+ return pending.size;
136
+ },
137
+ };
138
+ }
@@ -670,7 +670,9 @@ function printMemoryUsage(): void {
670
670
  console.log('Usage:');
671
671
  console.log(' memorix memory search --query "timeout bug" [--limit 10] [--quality fast|balanced|thorough]');
672
672
  console.log(' memorix memory recent [--limit 10]');
673
- console.log(' memorix memory store --text "..." [--title "..."] [--type discovery] [--visibility project|personal|team]');
673
+ console.log(' memorix memory store --text "..." [--title "..."] [--type discovery] [--entity <name>] [--topic-key <key>] [--facts a,b] [--files a,b] [--concepts a,b] [--visibility project|personal|team]');
674
+ console.log(' The same project and the same --topic-key update the existing observation and return upserted: true.');
675
+ console.log(' memorix remember does not forward --entity or --topic-key.');
674
676
  console.log(' memorix memory suggest-topic-key --type decision --title "..."');
675
677
  console.log(' memorix memory detail --id 42');
676
678
  console.log(' memorix memory detail obs:42@org/project');
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Short-lived memo for project detection on the HTTP request path.
3
+ *
4
+ * Stateless (2026-07-28) MCP requests carry no session, so serve-http resolves
5
+ * the project root on every request, up to three times. When that root is not
6
+ * inside a Git repository, detection falls through to a synchronous
7
+ * `git rev-parse` subprocess, which blocks the event loop. On hosts where
8
+ * process creation is slow (endpoint security scanners on Windows routinely
9
+ * add one to several seconds), the stateless probe of clients such as Claude
10
+ * Code then exceeds its budget and the client falls back to legacy sessions.
11
+ *
12
+ * Results, including "not a project", are cached per path for a bounded time
13
+ * so the subprocess runs at most once per path per TTL.
14
+ */
15
+
16
+ import type { ProjectInfo } from '../../types.js';
17
+
18
+ export const DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS = 5 * 60 * 1000;
19
+ export const MAX_PROJECT_DETECTION_CACHE_ENTRIES = 256;
20
+
21
+ export interface ProjectDetectionCacheOptions {
22
+ ttlMs?: number;
23
+ maxEntries?: number;
24
+ now?: () => number;
25
+ }
26
+
27
+ export type CachedProjectDetector = ((root: string) => ProjectInfo | null) & {
28
+ /** Drop every cached result. */
29
+ clear(): void;
30
+ /** Number of cached paths (diagnostics/tests). */
31
+ size(): number;
32
+ };
33
+
34
+ export function createCachedProjectDetector(
35
+ detect: (root: string) => ProjectInfo | null,
36
+ options: ProjectDetectionCacheOptions = {},
37
+ ): CachedProjectDetector {
38
+ const ttlMs = options.ttlMs ?? DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS;
39
+ const maxEntries = options.maxEntries ?? MAX_PROJECT_DETECTION_CACHE_ENTRIES;
40
+ const now = options.now ?? Date.now;
41
+ const cache = new Map<string, { project: ProjectInfo | null; expiresAt: number }>();
42
+
43
+ const cached = ((root: string) => {
44
+ const at = now();
45
+ const hit = cache.get(root);
46
+ if (hit && hit.expiresAt > at) return hit.project;
47
+ const project = detect(root);
48
+ cache.delete(root);
49
+ cache.set(root, { project, expiresAt: at + ttlMs });
50
+ while (cache.size > maxEntries) {
51
+ const oldest = cache.keys().next().value as string | undefined;
52
+ if (oldest === undefined) break;
53
+ cache.delete(oldest);
54
+ }
55
+ return project;
56
+ }) as CachedProjectDetector;
57
+
58
+ cached.clear = () => cache.clear();
59
+ cached.size = () => cache.size;
60
+ return cached;
61
+ }
@@ -33,6 +33,12 @@ import { CURRENT_MCP_PROTOCOL_VERSION, MCP_SERVER_NAME, getMcpDiagnostics } from
33
33
  import { createMcpStartupDiscoverResult, getMcpServerInfo } from '../../server/mcp-discovery.js';
34
34
  import { parseTcpPortOrReport } from '../port.js';
35
35
  import { mcpFileUriToPath } from '../mcp-root-path.js';
36
+ import {
37
+ DEFAULT_SESSION_DISCONNECT_GRACE_MS,
38
+ createSessionStreamWatch,
39
+ parseSessionDisconnectGraceMs,
40
+ } from './http-session-stream-watch.js';
41
+ import { createCachedProjectDetector } from './project-detection-cache.js';
36
42
 
37
43
  /**
38
44
  * HTTP MCP is a shared control plane. A normal thinking break should not
@@ -297,6 +303,7 @@ export default defineCommand({
297
303
  console.error(`[memorix] HTTP transport starting on ${host}:${port}`);
298
304
  console.error(`[memorix] Project root: ${projectRoot}`);
299
305
  const sessionTimeoutMs = parseSessionTimeoutMs(process.env.MEMORIX_SESSION_TIMEOUT_MS);
306
+ const sessionDisconnectGraceMs = parseSessionDisconnectGraceMs(process.env.MEMORIX_SESSION_DISCONNECT_GRACE_MS);
300
307
  const httpBodyLimitBytes = parseHttpBodyLimit(process.env.MEMORIX_HTTP_MAX_BODY_BYTES);
301
308
  const maxHttpSessions = parseMaxHttpSessions(process.env.MEMORIX_MAX_HTTP_SESSIONS);
302
309
  const eventLoopDelay = monitorEventLoopDelay({ resolution: 20 });
@@ -306,6 +313,11 @@ export default defineCommand({
306
313
  ? '[memorix] HTTP session idle timeout: disabled'
307
314
  : `[memorix] HTTP session idle timeout: ${Math.round(sessionTimeoutMs / 60000)}min (${sessionTimeoutMs}ms)`,
308
315
  );
316
+ console.error(
317
+ sessionDisconnectGraceMs === 0
318
+ ? '[memorix] HTTP session disconnect cleanup: disabled'
319
+ : `[memorix] HTTP session disconnect cleanup: ${Math.round(sessionDisconnectGraceMs / 1000)}s after the client stream closes`,
320
+ );
309
321
  console.error(`[memorix] HTTP session limit: ${maxHttpSessions}`);
310
322
 
311
323
  // Per-project TeamStore cache (Option B) — each dataDir gets its own TeamStore instance.
@@ -363,10 +375,13 @@ export default defineCommand({
363
375
  const statelessBindingStore = new McpBindingStore();
364
376
  await statelessBindingStore.init(controlPlaneBaseDir);
365
377
  const modernRuntimePool = new ModernMcpRuntimePool(MAX_STORE_CACHE_ENTRIES);
378
+ // Stateless requests resolve their project on every call. Memoize it so a
379
+ // non-Git root does not spawn `git rev-parse` (synchronously) per request.
380
+ const detectRequestProject = createCachedProjectDetector(detectorMod.detectProject);
366
381
 
367
382
  async function resolveModernDataDir(root: string, persisted?: { dataDir?: string }): Promise<string> {
368
383
  if (persisted?.dataDir) return persisted.dataDir;
369
- const detected = detectorMod.detectProject(root);
384
+ const detected = detectRequestProject(root);
370
385
  return detected
371
386
  ? persistMod.getProjectDataDir(detected.id)
372
387
  : controlPlaneBaseDir;
@@ -383,7 +398,7 @@ export default defineCommand({
383
398
  const root = persisted?.projectRoot ?? requestedRoot ?? projectRoot;
384
399
  const dataDir = await resolveModernDataDir(root, persisted);
385
400
  const binding = persisted ?? (() => {
386
- const detected = detectorMod.detectProject(root);
401
+ const detected = detectRequestProject(root);
387
402
  if (!detected) return undefined;
388
403
  const existing = statelessBindingStore.findByProjectRoot(detected.rootPath);
389
404
  return existing ? statelessBindingStore.touch(existing.handleId) ?? existing : undefined;
@@ -459,10 +474,36 @@ export default defineCommand({
459
474
 
460
475
  // Session activity tracking (for GC timeout)
461
476
  const sessionLastActivity = new Map<string, number>();
477
+ const sessionActiveRequests = new Map<string, number>();
462
478
  // Keep a short-lived tombstone so an expired client gets an actionable
463
479
  // reinitialize response instead of a generic bad request.
464
480
  const expiredSessions = new Map<string, number>();
465
481
 
482
+ /** Close a session the server decided to release, leaving a reinitialize tombstone. */
483
+ function expireSession(sid: string, reason: string): void {
484
+ const state = sessions.get(sid);
485
+ if (!state) return;
486
+ console.error(`[memorix] Session ${sid.slice(0, 8)}… ${reason}, closing`);
487
+ expiredSessions.set(sid, Date.now() + EXPIRED_SESSION_TTL_MS);
488
+ sessionStreamWatch.forget(sid);
489
+ sessions.delete(sid);
490
+ sessionLastActivity.delete(sid);
491
+ state.transport.close().catch(() => {});
492
+ }
493
+
494
+ // Release sessions whose client left without sending DELETE /mcp: the SDK
495
+ // client keeps a GET/SSE stream open for its whole life, so a closed stream
496
+ // followed by silence means the client is gone.
497
+ const sessionStreamWatch = createSessionStreamWatch({
498
+ graceMs: sessionDisconnectGraceMs,
499
+ getLastActivity: (sid) => (sessions.has(sid) ? sessionLastActivity.get(sid) ?? 0 : undefined),
500
+ isBusy: (sid) => (sessionActiveRequests.get(sid) ?? 0) > 0,
501
+ onAbandoned: (sid) => expireSession(
502
+ sid,
503
+ `client stream closed ${Math.round(sessionDisconnectGraceMs / 1000)}s ago with no further request`,
504
+ ),
505
+ });
506
+
466
507
  // Probe session noise reduction: defer init logs, suppress short-lived sessions
467
508
  let suppressedProbeCount = 0;
468
509
  let lastProbeSummaryTime = Date.now();
@@ -706,7 +747,7 @@ export default defineCommand({
706
747
  const requestedRoot = typeof req.headers['mcp-project-root'] === 'string'
707
748
  ? req.headers['mcp-project-root']
708
749
  : projectRoot;
709
- const detected = detectorMod.detectProject(requestedRoot);
750
+ const detected = detectRequestProject(requestedRoot);
710
751
  if (detected) {
711
752
  const bindingDataDir = await persistMod.getProjectDataDir(detected.id);
712
753
  const binding = statelessBindingStore.findByProjectRoot(detected.rootPath)
@@ -727,10 +768,17 @@ export default defineCommand({
727
768
  sessionLastActivity.set(sessionId, Date.now());
728
769
  patchMcpResponse(res);
729
770
  const session = sessions.get(sessionId)!;
730
- await withBusinessRuntimeQueue(async () => {
731
- await session.activateProjectRuntime();
732
- await session.transport.handleRequest(req, res, body);
733
- });
771
+ sessionActiveRequests.set(sessionId, (sessionActiveRequests.get(sessionId) ?? 0) + 1);
772
+ try {
773
+ await withBusinessRuntimeQueue(async () => {
774
+ await session.activateProjectRuntime();
775
+ await session.transport.handleRequest(req, res, body);
776
+ });
777
+ } finally {
778
+ const remaining = (sessionActiveRequests.get(sessionId) ?? 1) - 1;
779
+ if (remaining > 0) sessionActiveRequests.set(sessionId, remaining);
780
+ else sessionActiveRequests.delete(sessionId);
781
+ }
734
782
  return;
735
783
  }
736
784
 
@@ -795,6 +843,7 @@ export default defineCommand({
795
843
  }
796
844
  sessions.delete(sid);
797
845
  sessionLastActivity.delete(sid);
846
+ sessionStreamWatch.forget(sid);
798
847
  }
799
848
  handleTransportClose();
800
849
  for (const lease of sessionLeases) lease.release();
@@ -938,6 +987,8 @@ export default defineCommand({
938
987
 
939
988
  // GET may keep an SSE stream open; it does not enter the business tool
940
989
  // layer and must not occupy the singleton runtime gate.
990
+ sessionStreamWatch.streamOpened(sessionId);
991
+ res.once('close', () => sessionStreamWatch.streamClosed(sessionId, res.statusCode === 200));
941
992
  await sessions.get(sessionId)!.transport.handleRequest(req, res);
942
993
  }
943
994
 
@@ -2205,14 +2256,10 @@ export default defineCommand({
2205
2256
  evictIdleDatabases(MAX_STORE_CACHE_ENTRIES);
2206
2257
  void modernRuntimePool.evictIdle();
2207
2258
  if (SESSION_TIMEOUT_MS === 0) return;
2208
- for (const [sid, state] of sessions) {
2259
+ for (const sid of sessions.keys()) {
2209
2260
  const lastActive = sessionLastActivity.get(sid) ?? 0;
2210
2261
  if (now - lastActive > SESSION_TIMEOUT_MS) {
2211
- console.error(`[memorix] Session ${sid.slice(0, 8)}… timed out (idle ${Math.round((now - lastActive) / 60000)}min), closing`);
2212
- expiredSessions.set(sid, now + EXPIRED_SESSION_TTL_MS);
2213
- state.transport.close().catch(() => {});
2214
- sessions.delete(sid);
2215
- sessionLastActivity.delete(sid);
2262
+ expireSession(sid, `timed out (idle ${Math.round((now - lastActive) / 60000)}min)`);
2216
2263
  }
2217
2264
  }
2218
2265
  }, 60_000); // Check every minute
@@ -2243,6 +2290,7 @@ export default defineCommand({
2243
2290
  dashboardStoreLeases.clear();
2244
2291
  for (const lease of teamStoreLeases.values()) lease.release();
2245
2292
  teamStoreLeases.clear();
2293
+ sessionStreamWatch.dispose();
2246
2294
  for (const [sid, state] of sessions) {
2247
2295
  try {
2248
2296
  await state.transport.close();
@@ -2316,6 +2364,8 @@ export default defineCommand({
2316
2364
  /** @internal */
2317
2365
  export const _testing = {
2318
2366
  DEFAULT_SESSION_TIMEOUT_MS,
2367
+ DEFAULT_SESSION_DISCONNECT_GRACE_MS,
2368
+ parseSessionDisconnectGraceMs,
2319
2369
  DEFAULT_HTTP_BODY_LIMIT_BYTES,
2320
2370
  MAX_HTTP_BODY_LIMIT_BYTES,
2321
2371
  MIN_HTTP_BODY_LIMIT_BYTES,
package/src/cli/index.ts CHANGED
@@ -195,7 +195,7 @@ const main = defineCommand({
195
195
  },
196
196
  })),
197
197
  remember: () => Promise.resolve(defineCommand({
198
- meta: { name: 'remember', description: 'Shortcut for `memorix memory store`' },
198
+ meta: { name: 'remember', description: 'Shortcut for `memorix memory store`. Does not forward --entity or --topic-key. Topic-key upsert: memorix memory store --entity <name> --topic-key <key> --title "..." --text "..."' },
199
199
  args: {
200
200
  text: { type: 'positional', description: 'Text to remember', required: true },
201
201
  title: { type: 'string', description: 'Optional observation title' },
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Small kernel registry for named derived-view health readers.
3
+ *
4
+ * The registry owns naming, replacement, and failure isolation. It does not
5
+ * own a view's storage or lifecycle; concrete adapters remain responsible for
6
+ * refresh, rebuild, compaction, and close.
7
+ */
8
+ export type DerivedViewReceiptReader<Receipt> = () => Receipt;
9
+
10
+ export class DerivedViewRegistry<Receipt extends object> {
11
+ private readonly readers = new Map<string, DerivedViewReceiptReader<Receipt>>();
12
+
13
+ register(name: string, reader: DerivedViewReceiptReader<Receipt>): () => void {
14
+ const normalized = name.trim();
15
+ if (!normalized) throw new Error('Derived view name must not be empty');
16
+ this.readers.set(normalized, reader);
17
+ return () => {
18
+ if (this.readers.get(normalized) === reader) this.readers.delete(normalized);
19
+ };
20
+ }
21
+
22
+ snapshot(): Record<string, Receipt> {
23
+ const result: Record<string, Receipt> = {};
24
+ for (const [name, reader] of this.readers) {
25
+ try {
26
+ result[name] = reader();
27
+ } catch {
28
+ result[name] = { state: 'degraded', reason: 'derived view reader failed' } as Receipt;
29
+ }
30
+ }
31
+ return result;
32
+ }
33
+ }