@nhatnguyen9317/memory-mcp-server 1.3.2 → 1.3.3
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.
- package/CHANGELOG.md +18 -0
- package/GUIDELINES.md +15 -5
- package/README.md +8 -4
- package/dist/constants.js +45 -7
- package/dist/migrations/0006_workspace_identity.js +11 -0
- package/dist/migrations/index.js +2 -0
- package/dist/schemas/memory.js +5 -0
- package/dist/schemas/reasoning.js +5 -0
- package/dist/tools/memory.js +53 -18
- package/dist/tools/reasoning.js +74 -29
- package/dist/utils.js +46 -4
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.3.3 (2026-10-05)
|
|
4
|
+
|
|
5
|
+
Theme: recall that respects project identity — fixes `reasoning_start_session` recalling other projects' memories, stale memories, and near-zero-relevance memories from the same project — and brings `memory_search` onto the same blended ranking, so multi-term searches stop returning nothing. Design: [`docs/design/2026-10-05-spec-recall-workspace-identity.md`](docs/design/2026-10-05-spec-recall-workspace-identity.md), [`docs/design/2026-08-07-spec-zero-mem-inspired-recall.md`](docs/design/2026-08-07-spec-zero-mem-inspired-recall.md) §2 Option A′.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Optional `workspace` input on `reasoning_start_session` and `memory_save`; `reasoning_start_session` returns the resolved `workspace` and a `workspace_warning` when it is unknown.
|
|
10
|
+
- Migration `0006_workspace_identity`: `reasoning_sessions.workspace`; legacy `memories.workspace` values of `/` and the home directory are set to NULL (unknown).
|
|
11
|
+
- Recall eval base (WI-11): a labelled fixture (`src/__tests__/fixtures/recall-eval-cases.ts`) and suite (`src/__tests__/recall-eval.test.ts`) that drive the real `reasoning_start_session` and `memory_search` tools to lock auto-recall and search ranking behavior.
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- `getWorkspace` treats `/`, the home directory and empty as unknown instead of as a project.
|
|
16
|
+
- Auto-recall: other projects' non-preference memories need a near-complete title match; `preference` memories bypass that gate; one blended score (coverage 0.45, BM25 0.20, workspace 0.30, recency 0.05) replaces the lexicographic comparator; memories reported `stale`/`unsafe_to_use` are excluded; generic title words (fix, bug, update, …) no longer count as matches.
|
|
17
|
+
- **Behavior change:** `memory_search` matches with OR instead of implicit AND, with the same coverage floor as auto-recall (3+ distinct terms need at least 2 matches; fewer need 1; punctuation-only tokens such as `-` are ignored). Results are ranked by the blended score shared with auto-recall (coverage 0.45, BM25 0.20, recency 0.05, no workspace term), computed in SQL so `limit`/`offset` pagination is stable (ties break on importance, `updated_at`, then id). `RECALL_WEIGHTS` and `RECALL_RECENCY_DAYS` moved to `src/constants.ts`. Compatibility: multi-term queries that previously returned nothing because one term was absent now return partial matches, ranked below full matches.
|
|
18
|
+
- **Behavior change:** the "serendipity lifeline" is removed — when nothing is relevant, `related_memories` is `[]`.
|
|
19
|
+
- `GUIDELINES.md` `2026-07-18.v7` → `2026-10-05.v8`: agents are told to pass `workspace`, and an empty `related_memories` is described as normal.
|
|
20
|
+
|
|
3
21
|
## 1.3.2 (2026-07-18)
|
|
4
22
|
|
|
5
23
|
Theme: guide-contract alignment — `GUIDELINES.md`, tool descriptions, and server instructions now match what the code actually does, locked in by a new docs-consistency test; conflict-check and step-marking guidance tightened from soft suggestions into concrete triggers after live-store telemetry showed near-zero adoption.
|
package/GUIDELINES.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Memory MCP Guidelines
|
|
2
2
|
|
|
3
|
-
Version: 2026-
|
|
3
|
+
Version: 2026-10-05.v8
|
|
4
4
|
|
|
5
5
|
This file is the single source of truth for how an agent should use this MCP.
|
|
6
6
|
It is organized around the three moments of a task where this MCP matters.
|
|
@@ -19,10 +19,19 @@ Tool schemas and descriptions are the source of truth for parameter contracts
|
|
|
19
19
|
(Examples: any bug hunt, any change touching more than one file.)
|
|
20
20
|
The title doubles as the recall query — favor concrete keywords
|
|
21
21
|
(component, module, error names) over generic phrasing.
|
|
22
|
+
Also pass `workspace` — the absolute path of the project directory you
|
|
23
|
+
are working in. The server's own working directory is often `/` or your
|
|
24
|
+
home directory when a desktop app launched it; those count as "unknown
|
|
25
|
+
project" and turn project scoping off. If the response shows
|
|
26
|
+
`workspace: null` with a `workspace_warning`, pass `workspace` on this
|
|
27
|
+
and later calls (`reasoning_start_session`, `memory_save`).
|
|
22
28
|
2. Read what the server hands back — this is free recall, act on it:
|
|
23
29
|
- `related_memories`: saved knowledge matched to your title, ranked by
|
|
24
|
-
|
|
25
|
-
|
|
30
|
+
a blend of term coverage, text relevance, workspace and recency.
|
|
31
|
+
Memories from other projects appear only when they match nearly your
|
|
32
|
+
whole title (user `preference` memories are the exception). Weak matches
|
|
33
|
+
are filtered out, so an empty list is normal — do not pad the title just
|
|
34
|
+
to get results. Review
|
|
26
35
|
the snippets before working; fetch full content
|
|
27
36
|
with `memory_get` if needed. Entries persisted from a past reasoning
|
|
28
37
|
session carry a `source` field (`{session_id, session_title, created_at}`)
|
|
@@ -102,8 +111,9 @@ Durable memory:
|
|
|
102
111
|
|
|
103
112
|
- `memory_save`: store durable facts, decisions, preferences, or summaries.
|
|
104
113
|
Tags describe topics ('sqlite', 'auth', 'perf'), not locations — do not put
|
|
105
|
-
workspace or project names in tags
|
|
106
|
-
|
|
114
|
+
workspace or project names in tags. Pass `workspace` (your project
|
|
115
|
+
directory); if omitted the server records its own working directory (never
|
|
116
|
+
`/` or the home directory) and prefers same-workspace memories at recall time
|
|
107
117
|
- `memory_search`: targeted recall by keyword, topic, or hypothesis
|
|
108
118
|
- `memory_list`: recent or filtered browsing (when browsing beats searching)
|
|
109
119
|
- `memory_get`: fetch one memory by exact id
|
package/README.md
CHANGED
|
@@ -115,8 +115,9 @@ or `memory_list`.
|
|
|
115
115
|
|
|
116
116
|
1. **Task start** — the agent calls `reasoning_start_session`. The server
|
|
117
117
|
full-text-searches the title against saved memories and returns
|
|
118
|
-
`related_memories` in the response —
|
|
119
|
-
|
|
118
|
+
`related_memories` in the response — ranked by relevance, workspace and
|
|
119
|
+
recency; other projects' memories only when they match nearly the whole
|
|
120
|
+
title; nothing returned when nothing is relevant — warns about
|
|
120
121
|
still-open sessions, and auto-abandons stale ones
|
|
121
122
|
(`MEMORY_SESSION_TTL_HOURS`, default 24).
|
|
122
123
|
2. **During the task** — the agent logs decisions and observations with
|
|
@@ -142,7 +143,7 @@ the versioned [GUIDELINES.md](./GUIDELINES.md).
|
|
|
142
143
|
| `MEMORY_DB_PATH` | `~/.memory-mcp-server/memory.db` | SQLite database location |
|
|
143
144
|
| `MEMORY_SESSION_TTL_HOURS` | `24` | Auto-abandon in_progress sessions older than this (`0` disables) |
|
|
144
145
|
| `MEMORY_AUTO_RECALL_LIMIT` | `3` | Max related memories returned at session start (`0` disables) |
|
|
145
|
-
| `MEMORY_WORKSPACE` | current working directory |
|
|
146
|
+
| `MEMORY_WORKSPACE` | current working directory | Pins the workspace identity stamped on saved memories and used at recall time. Default: the server's working directory — but `/` and your home directory count as "unknown project". Agents should pass `workspace` (their project path) to `reasoning_start_session` / `memory_save`; that overrides this |
|
|
146
147
|
| `MEMORY_TELEMETRY` | `off` | Set `on` to record diagnostics events locally (searches, saves, recalls, latency) — required for full data in the report tools (`memory_usage_report`, `memory_adoption_report`, `memory_agent_scorecard`). Usage feedback (`used_memory_ids`, `memory_record_usage_feedback`) is a learning signal, not diagnostics: it is always recorded locally, with this flag on or off |
|
|
147
148
|
|
|
148
149
|
### Shared vs project-scoped memory
|
|
@@ -152,7 +153,10 @@ the versioned [GUIDELINES.md](./GUIDELINES.md).
|
|
|
152
153
|
memories are stamped with the workspace they were saved from, and recall
|
|
153
154
|
softly prefers the current workspace — cross-project memories still surface
|
|
154
155
|
when they match strongly (that's the point of a shared store), but they no
|
|
155
|
-
longer crowd out local ones.
|
|
156
|
+
longer crowd out local ones. Since v1.3.3 an explicit `workspace` argument
|
|
157
|
+
is honored, `/` and the home directory are treated as unknown, and
|
|
158
|
+
memories from other projects are recalled only on a near-complete title
|
|
159
|
+
match (user preferences excepted).
|
|
156
160
|
- **Project-scoped**: point `MEMORY_DB_PATH` at a file inside the project
|
|
157
161
|
(e.g. `.memory/project-memory.db`) for hard isolation per repository or
|
|
158
162
|
customer.
|
package/dist/constants.js
CHANGED
|
@@ -2,7 +2,7 @@ import path from "node:path";
|
|
|
2
2
|
import os from "node:os";
|
|
3
3
|
/** Max characters returned in a single tool response before truncation. */
|
|
4
4
|
export const CHARACTER_LIMIT = 25000;
|
|
5
|
-
export const MCP_VERSION = "1.3.
|
|
5
|
+
export const MCP_VERSION = "1.3.3";
|
|
6
6
|
/**
|
|
7
7
|
* Diagnostics-event recording is opt-in: set MEMORY_TELEMETRY=on to enable.
|
|
8
8
|
* Read at call time so tests and long-lived processes can toggle it.
|
|
@@ -30,15 +30,53 @@ export const AUTO_RECALL_LIMIT = Number(process.env.MEMORY_AUTO_RECALL_LIMIT ??
|
|
|
30
30
|
*/
|
|
31
31
|
export const DB_PATH = process.env.MEMORY_DB_PATH ??
|
|
32
32
|
path.join(os.homedir(), ".memory-mcp-server", "memory.db");
|
|
33
|
+
function stripTrailingSeparators(value) {
|
|
34
|
+
let result = value.trim();
|
|
35
|
+
while (result.length > 1 && /[\\/]$/.test(result)) {
|
|
36
|
+
result = result.slice(0, -1);
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Normalizes a workspace path: trims it and strips trailing separators.
|
|
42
|
+
* Returns null ("unknown") for values that cannot identify a project —
|
|
43
|
+
* empty, "/", and the home directory. Desktop clients launch the server
|
|
44
|
+
* from those, and treating them as a project merges unrelated projects.
|
|
45
|
+
*/
|
|
46
|
+
export function normalizeWorkspace(raw) {
|
|
47
|
+
if (!raw)
|
|
48
|
+
return null;
|
|
49
|
+
const value = stripTrailingSeparators(raw);
|
|
50
|
+
if (value === "" || value === "/")
|
|
51
|
+
return null;
|
|
52
|
+
if (value === stripTrailingSeparators(os.homedir()))
|
|
53
|
+
return null;
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
33
56
|
/**
|
|
34
|
-
* Workspace identity for memory scoping
|
|
35
|
-
*
|
|
36
|
-
* MEMORY_WORKSPACE
|
|
37
|
-
*
|
|
57
|
+
* Workspace identity for memory scoping, or null when unknown. Precedence:
|
|
58
|
+
* an explicit value passed by the agent (it always knows its project),
|
|
59
|
+
* then MEMORY_WORKSPACE, then process.cwd() — Claude Code/Codex launch the
|
|
60
|
+
* server inside the project, desktop apps often do not. Read at call time
|
|
61
|
+
* (same pattern as isTelemetryEnabled) for testability.
|
|
38
62
|
*/
|
|
39
|
-
export function getWorkspace() {
|
|
40
|
-
return process.env.MEMORY_WORKSPACE
|
|
63
|
+
export function getWorkspace(explicit) {
|
|
64
|
+
return normalizeWorkspace(explicit?.trim() || process.env.MEMORY_WORKSPACE || process.cwd());
|
|
41
65
|
}
|
|
42
66
|
export const DEFAULT_LIST_LIMIT = 20;
|
|
43
67
|
export const MAX_LIST_LIMIT = 200;
|
|
68
|
+
/**
|
|
69
|
+
* Blended auto-recall score weights — see
|
|
70
|
+
* docs/design/2026-10-05-spec-recall-workspace-identity.md §3.4.
|
|
71
|
+
* Relevance (coverage + bm25) is the largest block; workspace only orders
|
|
72
|
+
* candidates that already passed the cross-project gate.
|
|
73
|
+
*/
|
|
74
|
+
export const RECALL_WEIGHTS = {
|
|
75
|
+
coverage: 0.45,
|
|
76
|
+
bm25: 0.2,
|
|
77
|
+
workspace: 0.3,
|
|
78
|
+
recency: 0.05,
|
|
79
|
+
};
|
|
80
|
+
/** recency = 1 / (1 + age_days / RECALL_RECENCY_DAYS). */
|
|
81
|
+
export const RECALL_RECENCY_DAYS = 60;
|
|
44
82
|
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
export const migration0006WorkspaceIdentity = {
|
|
3
|
+
version: "0006_workspace_identity",
|
|
4
|
+
apply(db) {
|
|
5
|
+
db.exec(`ALTER TABLE reasoning_sessions ADD COLUMN workspace TEXT;`);
|
|
6
|
+
// '/' and the home directory never identified a project; they were the
|
|
7
|
+
// server's cwd when a desktop app launched it. NULL = unknown origin.
|
|
8
|
+
db.prepare(`UPDATE memories SET workspace = NULL WHERE workspace = '/' OR workspace = ?`).run(os.homedir());
|
|
9
|
+
},
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=0006_workspace_identity.js.map
|
package/dist/migrations/index.js
CHANGED
|
@@ -4,12 +4,14 @@ import { migration0002ReasoningStepMarks } from "./0002_reasoning_step_marks.js"
|
|
|
4
4
|
import { migration0003ReasoningStepsFts } from "./0003_reasoning_steps_fts.js";
|
|
5
5
|
import { migration0004ToolUsageEvents } from "./0004_tool_usage_events.js";
|
|
6
6
|
import { migration0005MemoryWorkspace } from "./0005_memory_workspace.js";
|
|
7
|
+
import { migration0006WorkspaceIdentity } from "./0006_workspace_identity.js";
|
|
7
8
|
const migrations = [
|
|
8
9
|
migration0001Initial,
|
|
9
10
|
migration0002ReasoningStepMarks,
|
|
10
11
|
migration0003ReasoningStepsFts,
|
|
11
12
|
migration0004ToolUsageEvents,
|
|
12
13
|
migration0005MemoryWorkspace,
|
|
14
|
+
migration0006WorkspaceIdentity,
|
|
13
15
|
];
|
|
14
16
|
export function runMigrations(db) {
|
|
15
17
|
db.exec(`
|
package/dist/schemas/memory.js
CHANGED
|
@@ -43,6 +43,11 @@ export const MemorySaveInputSchema = z
|
|
|
43
43
|
.max(100)
|
|
44
44
|
.optional()
|
|
45
45
|
.describe("Optional identifier for the agent/persona this memory belongs to, for multi-agent setups."),
|
|
46
|
+
workspace: z
|
|
47
|
+
.string()
|
|
48
|
+
.max(500)
|
|
49
|
+
.optional()
|
|
50
|
+
.describe("Absolute path of the project directory this memory belongs to. Pass your current working directory so recall can prefer this project's memories. If omitted the server uses its own working directory; '/' and the home directory count as unknown."),
|
|
46
51
|
metadata: z
|
|
47
52
|
.record(z.unknown())
|
|
48
53
|
.optional()
|
|
@@ -11,6 +11,11 @@ export const ReasoningStartSessionInputSchema = z
|
|
|
11
11
|
.max(100)
|
|
12
12
|
.optional()
|
|
13
13
|
.describe("Optional identifier for the agent/persona running this session."),
|
|
14
|
+
workspace: z
|
|
15
|
+
.string()
|
|
16
|
+
.max(500)
|
|
17
|
+
.optional()
|
|
18
|
+
.describe("Absolute path of the project directory you are working in. Pass it so recall prefers this project's memories and your conclusion is saved under it. If omitted the server uses its own working directory; '/' and the home directory count as unknown."),
|
|
14
19
|
})
|
|
15
20
|
.strict();
|
|
16
21
|
export const ReasoningStepEntrySchema = z
|
package/dist/tools/memory.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { MemoryAdoptionReportInputSchema, MemoryAgentScorecardInputSchema, MemoryDeleteInputSchema, MemoryGetInputSchema, MemoryListInputSchema, MemoryRecordUsageFeedbackInputSchema, MemorySaveInputSchema, MemorySearchInputSchema, MemoryUpdateInputSchema, MemoryUsageReportInputSchema, } from "../schemas/memory.js";
|
|
2
|
-
import { getWorkspace, isTelemetryEnabled } from "../constants.js";
|
|
3
|
-
import { newId, nowIso, parseJsonArray, parseJsonObject,
|
|
2
|
+
import { RECALL_RECENCY_DAYS, RECALL_WEIGHTS, getWorkspace, isTelemetryEnabled, } from "../constants.js";
|
|
3
|
+
import { newId, nowIso, parseJsonArray, parseJsonObject, toLimitedJson, toSearchTerms, } from "../utils.js";
|
|
4
4
|
import { withTelemetry, } from "./telemetry.js";
|
|
5
5
|
function rowToRecord(row) {
|
|
6
6
|
return {
|
|
@@ -141,7 +141,7 @@ export function registerMemoryTools(server, database) {
|
|
|
141
141
|
const databaseProvider = () => resolveDatabase(database);
|
|
142
142
|
server.registerTool("memory_save", {
|
|
143
143
|
title: "Save Memory",
|
|
144
|
-
description: "Persist a piece of long-term memory so it can be recalled in future sessions. Returns the created memory's id. Tags describe topics ('sqlite', 'auth', 'perf'), not locations — do not put workspace or project names in tags; the server records the
|
|
144
|
+
description: "Persist a piece of long-term memory so it can be recalled in future sessions. Returns the created memory's id. Tags describe topics ('sqlite', 'auth', 'perf'), not locations — do not put workspace or project names in tags. Pass workspace (your project directory) so the memory is scoped to this project; if omitted the server records its own working directory, and '/' or the home directory are stored as unknown.",
|
|
145
145
|
inputSchema: MemorySaveInputSchema.shape,
|
|
146
146
|
annotations: {
|
|
147
147
|
readOnlyHint: false,
|
|
@@ -189,7 +189,7 @@ export function registerMemoryTools(server, database) {
|
|
|
189
189
|
agent_id: params.agent_id ?? null,
|
|
190
190
|
importance: params.importance,
|
|
191
191
|
metadata: params.metadata ? JSON.stringify(params.metadata) : null,
|
|
192
|
-
workspace: getWorkspace(),
|
|
192
|
+
workspace: getWorkspace(params.workspace),
|
|
193
193
|
created_at: ts,
|
|
194
194
|
updated_at: ts,
|
|
195
195
|
});
|
|
@@ -209,7 +209,7 @@ export function registerMemoryTools(server, database) {
|
|
|
209
209
|
}));
|
|
210
210
|
server.registerTool("memory_search", {
|
|
211
211
|
title: "Search Memories",
|
|
212
|
-
description: "Full-text search over saved memories (content and tags)
|
|
212
|
+
description: "Full-text search over saved memories (content and tags). Any query term may match; results are ranked by term coverage, text relevance and recency (queries with 3+ terms need at least 2 to match). Optional filters: type, agent_id, tags (results must contain all); paginate with limit (default 20, max 200) and offset.",
|
|
213
213
|
inputSchema: MemorySearchInputSchema.shape,
|
|
214
214
|
annotations: {
|
|
215
215
|
readOnlyHint: true,
|
|
@@ -240,30 +240,65 @@ export function registerMemoryTools(server, database) {
|
|
|
240
240
|
}, async (params) => {
|
|
241
241
|
const activeDb = await resolveDatabase(database);
|
|
242
242
|
const { clause: tagClause, params: tagParams } = tagsFilterClauses(params.tags);
|
|
243
|
+
const terms = toSearchTerms(params.query);
|
|
243
244
|
const conditions = [];
|
|
244
|
-
const sqlParams = [toFtsQuery(params.query)];
|
|
245
245
|
if (params.type) {
|
|
246
246
|
conditions.push("m.type = ?");
|
|
247
|
-
sqlParams.push(params.type);
|
|
248
247
|
}
|
|
249
248
|
if (params.agent_id) {
|
|
250
249
|
conditions.push("m.agent_id = ?");
|
|
251
|
-
sqlParams.push(params.agent_id);
|
|
252
250
|
}
|
|
253
251
|
if (tagClause) {
|
|
254
252
|
// tagClause is " AND <clauses>"; strip the prefix to compose here.
|
|
255
253
|
conditions.push(tagClause.slice(" AND ".length));
|
|
256
254
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
.
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
255
|
+
const filterParams = [];
|
|
256
|
+
if (params.type)
|
|
257
|
+
filterParams.push(params.type);
|
|
258
|
+
if (params.agent_id)
|
|
259
|
+
filterParams.push(params.agent_id);
|
|
260
|
+
// Any term may match (OR). `hits` counts how many distinct terms each
|
|
261
|
+
// memory matches (one FTS query per term); the same floor as
|
|
262
|
+
// auto-recall applies: 3+ terms need >= 2 matches, otherwise >= 1.
|
|
263
|
+
// The blended score (same weights as auto-recall, minus the workspace
|
|
264
|
+
// term) is computed here, not in JS, so LIMIT/OFFSET paginate over a
|
|
265
|
+
// stable total order. Window aggregates normalize bm25 within the
|
|
266
|
+
// final eligible set; rank is negative (more negative = better) and
|
|
267
|
+
// all-equal counts as best.
|
|
268
|
+
const floor = terms.length >= 3 ? 2 : 1;
|
|
269
|
+
const rows = terms.length === 0
|
|
270
|
+
? []
|
|
271
|
+
: activeDb
|
|
272
|
+
.prepare(`WITH hits AS (
|
|
273
|
+
SELECT row_id, COUNT(*) AS matched FROM (
|
|
274
|
+
${terms
|
|
275
|
+
.map(() => "SELECT rowid AS row_id FROM memories_fts WHERE memories_fts MATCH ?")
|
|
276
|
+
.join(" UNION ALL ")}
|
|
277
|
+
) GROUP BY row_id
|
|
278
|
+
),
|
|
279
|
+
eligible AS (
|
|
280
|
+
SELECT m.*, f.rank AS fts_rank, h.matched AS matched_terms
|
|
281
|
+
FROM memories m
|
|
282
|
+
JOIN (
|
|
283
|
+
SELECT rowid, rank FROM memories_fts WHERE memories_fts MATCH ?
|
|
284
|
+
) f ON m.rowid = f.rowid
|
|
285
|
+
JOIN hits h ON h.row_id = m.rowid
|
|
286
|
+
WHERE h.matched >= ?${conditions.length > 0 ? ` AND ${conditions.join(" AND ")}` : ""}
|
|
287
|
+
)
|
|
288
|
+
SELECT * FROM eligible
|
|
289
|
+
ORDER BY
|
|
290
|
+
${RECALL_WEIGHTS.coverage} * (matched_terms * 1.0 / ${terms.length})
|
|
291
|
+
+ ${RECALL_WEIGHTS.bm25} * COALESCE(
|
|
292
|
+
(MAX(fts_rank) OVER () - fts_rank)
|
|
293
|
+
/ NULLIF(MAX(fts_rank) OVER () - MIN(fts_rank) OVER (), 0),
|
|
294
|
+
1.0)
|
|
295
|
+
+ ${RECALL_WEIGHTS.recency} * COALESCE(
|
|
296
|
+
1.0 / (1.0 + MAX(0.0, julianday('now') - julianday(updated_at))
|
|
297
|
+
/ ${RECALL_RECENCY_DAYS}),
|
|
298
|
+
0.0) DESC,
|
|
299
|
+
importance DESC, updated_at DESC, id ASC
|
|
300
|
+
LIMIT ? OFFSET ?`)
|
|
301
|
+
.all(...terms, terms.join(" OR "), floor, ...filterParams, ...tagParams, params.limit, params.offset);
|
|
267
302
|
if (rows.length === 0) {
|
|
268
303
|
return {
|
|
269
304
|
content: [
|
package/dist/tools/reasoning.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ReasoningAddStepInputSchema, ReasoningCompleteSessionInputSchema, ReasoningGetSessionOutlineInputSchema, ReasoningGetTraceInputSchema, ReasoningListMilestonesInputSchema, ReasoningListSessionsInputSchema, ReasoningMarkStepInputSchema, ReasoningSearchStepsInputSchema, ReasoningStartSessionInputSchema, } from "../schemas/reasoning.js";
|
|
2
|
-
import { AUTO_RECALL_LIMIT, SESSION_TTL_HOURS, getWorkspace } from "../constants.js";
|
|
2
|
+
import { AUTO_RECALL_LIMIT, RECALL_RECENCY_DAYS, RECALL_WEIGHTS, SESSION_TTL_HOURS, getWorkspace, } from "../constants.js";
|
|
3
3
|
import { handleToolError, newId, nowIso, parseJsonArray, parseJsonObject, toFtsQuery, toRecallTerms, toLimitedJson, } from "../utils.js";
|
|
4
4
|
import { recordToolUsageEvent, withTelemetry } from "./telemetry.js";
|
|
5
5
|
function sessionRowToRecord(row, stepCount) {
|
|
@@ -131,31 +131,42 @@ function abandonStaleSessions(database, now) {
|
|
|
131
131
|
.run(now, cutoff);
|
|
132
132
|
return Number(result.changes);
|
|
133
133
|
}
|
|
134
|
-
/** Candidate pool fetched by BM25 before the
|
|
134
|
+
/** Candidate pool fetched by BM25 before the gate/score pass. */
|
|
135
135
|
const RECALL_CANDIDATE_POOL = 50;
|
|
136
|
-
function recallRelatedMemories(database, title) {
|
|
136
|
+
function recallRelatedMemories(database, title, workspace) {
|
|
137
137
|
if (AUTO_RECALL_LIMIT <= 0)
|
|
138
138
|
return [];
|
|
139
139
|
try {
|
|
140
140
|
const terms = toRecallTerms(title);
|
|
141
141
|
if (terms.length === 0)
|
|
142
142
|
return [];
|
|
143
|
+
// workspace_priority: 2 = current workspace, 1 = unknown (NULL) or a
|
|
144
|
+
// user preference (cross-project by nature), 0 = another project. With
|
|
145
|
+
// a known workspace the pool is ordered by it first so home memories are
|
|
146
|
+
// never crowded out of the candidate pool by other projects' BM25 hits.
|
|
147
|
+
// Memories already reported stale/unsafe are excluded outright.
|
|
143
148
|
const candidates = database
|
|
144
149
|
.prepare(`SELECT m.rowid AS row_id, m.id, m.type, m.content, m.tags,
|
|
145
150
|
m.importance, m.metadata, m.created_at, m.updated_at,
|
|
146
151
|
f.rank AS fts_rank,
|
|
147
152
|
CASE
|
|
148
|
-
WHEN m.workspace = ?
|
|
149
|
-
WHEN m.workspace IS NULL THEN 1
|
|
153
|
+
WHEN m.workspace = ? THEN 2
|
|
154
|
+
WHEN m.workspace IS NULL OR m.type = 'preference' THEN 1
|
|
150
155
|
ELSE 0
|
|
151
156
|
END AS workspace_priority
|
|
152
157
|
FROM memories m
|
|
153
158
|
JOIN (
|
|
154
159
|
SELECT rowid, rank FROM memories_fts WHERE memories_fts MATCH ?
|
|
155
160
|
) f ON m.rowid = f.rowid
|
|
156
|
-
|
|
161
|
+
WHERE m.id NOT IN (
|
|
162
|
+
SELECT memory_id FROM tool_usage_events
|
|
163
|
+
WHERE operation_type = 'feedback' AND status = 'success'
|
|
164
|
+
AND memory_id IS NOT NULL
|
|
165
|
+
AND json_extract(metadata, '$.usefulness') IN ('stale', 'unsafe_to_use')
|
|
166
|
+
)
|
|
167
|
+
ORDER BY ${workspace === null ? "" : "workspace_priority DESC, "}f.rank ASC
|
|
157
168
|
LIMIT ?`)
|
|
158
|
-
.all(
|
|
169
|
+
.all(workspace, terms.join(" OR "), RECALL_CANDIDATE_POOL);
|
|
159
170
|
if (candidates.length === 0)
|
|
160
171
|
return [];
|
|
161
172
|
// Count how many title terms each candidate matches (one cheap FTS
|
|
@@ -169,26 +180,51 @@ function recallRelatedMemories(database, title) {
|
|
|
169
180
|
matchCounts.set(row.rowid, (matchCounts.get(row.rowid) ?? 0) + 1);
|
|
170
181
|
}
|
|
171
182
|
}
|
|
172
|
-
|
|
183
|
+
// Eligibility gate. Other projects' non-preference memories must match
|
|
184
|
+
// nearly the whole title; everyone else needs the base floor. Nothing
|
|
185
|
+
// eligible means nothing returned — no best-effort lifeline.
|
|
186
|
+
const total = terms.length;
|
|
187
|
+
const baseFloor = total >= 3 ? 2 : 1;
|
|
188
|
+
const crossProjectFloor = Math.max(2, Math.ceil(0.75 * total));
|
|
189
|
+
const eligible = candidates
|
|
190
|
+
.map((candidate) => ({
|
|
173
191
|
...candidate,
|
|
174
192
|
matched: matchCounts.get(candidate.row_id) ?? 1,
|
|
175
|
-
}))
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
193
|
+
}))
|
|
194
|
+
.filter((candidate) => {
|
|
195
|
+
const crossProject = workspace !== null && candidate.workspace_priority === 0;
|
|
196
|
+
return candidate.matched >= (crossProject ? crossProjectFloor : baseFloor);
|
|
197
|
+
});
|
|
198
|
+
if (eligible.length === 0)
|
|
199
|
+
return [];
|
|
200
|
+
// Blended score. bm25 rank is negative (more negative = better), so
|
|
201
|
+
// min-max normalize within the eligible set; all-equal counts as best.
|
|
202
|
+
const ranks = eligible.map((candidate) => candidate.fts_rank);
|
|
203
|
+
const bestRank = Math.min(...ranks);
|
|
204
|
+
const worstRank = Math.max(...ranks);
|
|
205
|
+
const now = Date.now();
|
|
206
|
+
const scored = eligible.map((candidate) => {
|
|
207
|
+
const bm25 = worstRank === bestRank
|
|
208
|
+
? 1
|
|
209
|
+
: (worstRank - candidate.fts_rank) / (worstRank - bestRank);
|
|
210
|
+
const workspaceTerm = workspace === null ? 0.5 : candidate.workspace_priority / 2;
|
|
211
|
+
const updatedMs = Date.parse(candidate.updated_at);
|
|
212
|
+
const ageDays = Number.isFinite(updatedMs)
|
|
213
|
+
? Math.max(0, (now - updatedMs) / 86_400_000)
|
|
214
|
+
: Infinity;
|
|
215
|
+
const recency = 1 / (1 + ageDays / RECALL_RECENCY_DAYS);
|
|
216
|
+
return {
|
|
217
|
+
...candidate,
|
|
218
|
+
score: RECALL_WEIGHTS.coverage * (candidate.matched / total) +
|
|
219
|
+
RECALL_WEIGHTS.bm25 * bm25 +
|
|
220
|
+
RECALL_WEIGHTS.workspace * workspaceTerm +
|
|
221
|
+
RECALL_WEIGHTS.recency * recency,
|
|
222
|
+
};
|
|
223
|
+
});
|
|
224
|
+
scored.sort((a, b) => b.score - a.score ||
|
|
189
225
|
b.importance - a.importance ||
|
|
190
226
|
(a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0));
|
|
191
|
-
return
|
|
227
|
+
return scored.slice(0, AUTO_RECALL_LIMIT).map((row) => {
|
|
192
228
|
const metadata = parseJsonObject(row.metadata);
|
|
193
229
|
const sourceSessionId = metadata?.source_session_id;
|
|
194
230
|
const sourceSessionTitle = metadata?.session_title;
|
|
@@ -225,9 +261,11 @@ export function registerReasoningTools(server, database) {
|
|
|
225
261
|
Args:
|
|
226
262
|
- title (string, required): Short description of the task/question, e.g. "Diagnose flaky checkout test".
|
|
227
263
|
- agent_id (string, optional): Identifier for the agent/persona running this session.
|
|
264
|
+
- workspace (string, optional): Absolute path of the project directory you are working in. Pass it: the server's own working directory is often "/" or your home directory, which counts as unknown.
|
|
228
265
|
|
|
229
266
|
Returns: JSON with the new session's id (pass it to reasoning_add_step and reasoning_complete_session), plus:
|
|
230
|
-
-
|
|
267
|
+
- workspace: the resolved project workspace for this session, or null when unknown (then workspace_warning explains how to fix it).
|
|
268
|
+
- related_memories: up to a few saved memories relevant to the title, auto-recalled by the server — ranked by a blend of term coverage, text relevance, workspace and recency; memories from other projects appear only when they match nearly the whole title (user preferences excepted); weak matches are filtered out, so a short or empty list is normal. Review them before starting work; if one helps, report it later via used_memory_ids on reasoning_complete_session. Memories persisted from a past reasoning session carry a 'source' field ({session_id, session_title, created_at}); pass source.session_id to reasoning_get_trace to replay how that conclusion was reached.
|
|
231
269
|
- open_sessions / open_sessions_warning: other in_progress sessions. Close the ones you opened and finished; leave sessions you don't recognize alone (they may belong to another agent or run).
|
|
232
270
|
- auto_abandoned_sessions: count of stale in_progress sessions the server just cleaned up, if any.
|
|
233
271
|
|
|
@@ -268,21 +306,28 @@ Examples:
|
|
|
268
306
|
const id = newId("sess");
|
|
269
307
|
const ts = nowIso();
|
|
270
308
|
const autoAbandoned = abandonStaleSessions(activeDb, ts);
|
|
309
|
+
const workspace = getWorkspace(params.workspace);
|
|
271
310
|
activeDb
|
|
272
|
-
.prepare(`INSERT INTO reasoning_sessions (id, title, agent_id, status, conclusion, created_at, updated_at)
|
|
273
|
-
VALUES (?, ?, ?, 'in_progress', NULL, ?, ?)`)
|
|
274
|
-
.run(id, params.title, params.agent_id ?? null, ts, ts);
|
|
311
|
+
.prepare(`INSERT INTO reasoning_sessions (id, title, agent_id, status, conclusion, workspace, created_at, updated_at)
|
|
312
|
+
VALUES (?, ?, ?, 'in_progress', NULL, ?, ?, ?)`)
|
|
313
|
+
.run(id, params.title, params.agent_id ?? null, workspace, ts, ts);
|
|
275
314
|
const openSessions = activeDb
|
|
276
315
|
.prepare(`SELECT id, title, updated_at FROM reasoning_sessions
|
|
277
316
|
WHERE status = 'in_progress' AND id != ?
|
|
278
317
|
ORDER BY updated_at DESC
|
|
279
318
|
LIMIT 5`)
|
|
280
319
|
.all(id);
|
|
281
|
-
const relatedMemories = recallRelatedMemories(activeDb, params.title);
|
|
320
|
+
const relatedMemories = recallRelatedMemories(activeDb, params.title, workspace);
|
|
282
321
|
const output = {
|
|
283
322
|
session_id: id,
|
|
284
323
|
title: params.title,
|
|
285
324
|
status: "in_progress",
|
|
325
|
+
workspace,
|
|
326
|
+
...(workspace === null
|
|
327
|
+
? {
|
|
328
|
+
workspace_warning: "Project workspace could not be determined (the server's working directory is '/', your home directory, or unset), so recall cannot prefer this project's memories. Pass workspace=<absolute project path> to reasoning_start_session and memory_save.",
|
|
329
|
+
}
|
|
330
|
+
: {}),
|
|
286
331
|
related_memories: relatedMemories,
|
|
287
332
|
...(openSessions.length > 0
|
|
288
333
|
? {
|
|
@@ -1164,7 +1209,7 @@ Error Handling:
|
|
|
1164
1209
|
session_title: session.title,
|
|
1165
1210
|
auto_saved: !(params.save_as_memory || params.memory_mode === "always"),
|
|
1166
1211
|
step_count: stepCount,
|
|
1167
|
-
}),
|
|
1212
|
+
}), session.workspace ?? null, ts, ts);
|
|
1168
1213
|
return nextMemoryId;
|
|
1169
1214
|
});
|
|
1170
1215
|
const usedMemoryWarnings = [];
|
package/dist/utils.js
CHANGED
|
@@ -40,19 +40,61 @@ function ftsTerms(raw) {
|
|
|
40
40
|
.filter(Boolean)
|
|
41
41
|
.map((t) => `"${t.replace(/"/g, '""')}"*`);
|
|
42
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* memory_search terms: the same quoted-prefix terms as toFtsQuery, deduped
|
|
45
|
+
* case-insensitively so a repeated word cannot inflate the coverage floor.
|
|
46
|
+
* Punctuation-only tokens ("-", "–", "/") never match anything, so they are
|
|
47
|
+
* dropped rather than counted toward the floor. No stopword or length
|
|
48
|
+
* filtering — an explicit query is the caller's intent.
|
|
49
|
+
*/
|
|
50
|
+
export function toSearchTerms(raw) {
|
|
51
|
+
const seen = new Set();
|
|
52
|
+
const words = raw
|
|
53
|
+
.trim()
|
|
54
|
+
.split(/\s+/)
|
|
55
|
+
.filter((token) => /[\p{L}\p{N}]/u.test(token))
|
|
56
|
+
.join(" ");
|
|
57
|
+
return ftsTerms(words).filter((term) => {
|
|
58
|
+
const key = term.toLowerCase();
|
|
59
|
+
if (seen.has(key))
|
|
60
|
+
return false;
|
|
61
|
+
seen.add(key);
|
|
62
|
+
return true;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Generic task words and function words. They match nearly every memory,
|
|
67
|
+
* so counting them toward the recall floor lets unrelated memories in.
|
|
68
|
+
* Includes a few common Vietnamese words (titles are often mixed-language).
|
|
69
|
+
*/
|
|
70
|
+
const RECALL_STOPWORDS = new Set([
|
|
71
|
+
"fix", "fixes", "fixing", "add", "adds", "adding", "update", "updates",
|
|
72
|
+
"updating", "improve", "improves", "improving", "implement",
|
|
73
|
+
"implementing", "review", "investigate", "investigating", "debug",
|
|
74
|
+
"debugging", "bug", "bugs", "issue", "issues", "task", "tasks",
|
|
75
|
+
"the", "and", "for", "with", "from", "into", "that", "this", "are", "not",
|
|
76
|
+
"không", "của", "cho", "với", "các", "những", "một", "cải", "tiến",
|
|
77
|
+
"sửa", "lỗi", "thêm",
|
|
78
|
+
]);
|
|
79
|
+
function bareToken(token) {
|
|
80
|
+
return token.toLowerCase().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");
|
|
81
|
+
}
|
|
43
82
|
/**
|
|
44
83
|
* Term preparation for auto-recall only. Drops noise tokens (<=2 chars,
|
|
45
|
-
* the main source of one-word junk matches) and
|
|
46
|
-
* titles stay cheap.
|
|
47
|
-
*
|
|
84
|
+
* the main source of one-word junk matches) and generic stopwords, and caps
|
|
85
|
+
* the count so long titles stay cheap. If filtering would leave nothing, it
|
|
86
|
+
* falls back to the unfiltered tokens. memory_search uses toSearchTerms (no
|
|
87
|
+
* filtering) — an explicit query is the caller's intent.
|
|
48
88
|
*/
|
|
49
89
|
export function toRecallTerms(raw) {
|
|
50
90
|
const tokens = raw.trim().split(/\s+/).filter(Boolean);
|
|
51
91
|
const significant = tokens.filter((token) => token.length > 2);
|
|
92
|
+
const topical = significant.filter((token) => !RECALL_STOPWORDS.has(bareToken(token)));
|
|
93
|
+
const base = topical.length > 0 ? topical : significant.length > 0 ? significant : tokens;
|
|
52
94
|
// Dedupe case-insensitively: a repeated word must not raise the
|
|
53
95
|
// match floor or double-count as two matched terms.
|
|
54
96
|
const seen = new Set();
|
|
55
|
-
const chosen =
|
|
97
|
+
const chosen = base
|
|
56
98
|
.filter((token) => {
|
|
57
99
|
const key = token.toLowerCase();
|
|
58
100
|
if (seen.has(key))
|