@nhatnguyen9317/memory-mcp-server 1.3.1 → 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 +37 -0
- package/GUIDELINES.md +78 -25
- 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 +6 -1
- package/dist/schemas/reasoning.js +5 -0
- package/dist/server.js +10 -0
- package/dist/tools/memory.js +57 -22
- package/dist/tools/reasoning.js +76 -31
- package/dist/utils.js +46 -4
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,42 @@
|
|
|
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
|
+
|
|
21
|
+
## 1.3.2 (2026-07-18)
|
|
22
|
+
|
|
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.
|
|
24
|
+
|
|
25
|
+
### Added
|
|
26
|
+
|
|
27
|
+
- **Server-level `instructions`**: `runServer()` now passes an `instructions` string to the `McpServer` constructor (`src/server.ts`) summarizing the core reasoning/memory loop (start session → log steps → complete with conclusion/`used_memory_ids`; `save_as_memory` is opt-in; never store secrets), so MCP clients that surface server instructions show this guidance without an extra tool call.
|
|
28
|
+
- **`src/__tests__/docs-consistency.test.ts`**: locks two invariants against drift — every registered tool name must appear in `GUIDELINES.md`, and the guide must not contradict specific schema contracts (`memory_mode='never'` requires `not_saved_reason`; the `session_id` vs `step_id` distinction between `reasoning_add_step`/`reasoning_complete_session` and `reasoning_mark_step`).
|
|
29
|
+
|
|
30
|
+
### Changed
|
|
31
|
+
|
|
32
|
+
- **`GUIDELINES.md` bumped `2026-07-12.v5` → `2026-07-17.v6` → `2026-07-18.v7`**. v6: added trivial-vs-multi-step examples, clarified that `open_sessions` belonging to other agents/runs should be left alone, documented the `thought`/`action`/`observation` step fields, made `conclusion` required even when abandoning a session, clarified `memory_record_usage_feedback`'s five usefulness values and its no-session use case, added `memory_type`/`memory_importance` selection guidance, documented `get_usage_guide` in the Tool Reference, and clarified the `MEMORY_TELEMETRY` env var's scope. v7 (this release): live-store telemetry showed the conflict-check and mark-step guidance were soft suggestions that never fired even though their preconditions occurred in most sessions — both are now concrete, explicit steps (an IF/THEN conflict check on `related_memories`, and a listed set of trigger conditions for `reasoning_mark_step`) instead of vague "when it seems useful" phrasing.
|
|
33
|
+
- **Tool description clarity pass** (`src/schemas/memory.ts`, `src/tools/memory.ts`, `src/tools/reasoning.ts`): `memory_save` documents that it returns the created id; `memory_search`/`memory_list` document their filters and pagination; `memory_update` documents partial-update semantics and the append/remove/patch fields; `memory_delete` warns it is a hard, unrecoverable delete; `memory_record_usage_feedback` documents its five usefulness values; tag guidance reworded to "topics, not workspace or project names."
|
|
34
|
+
- `src/__tests__/reasoning-audit-tools.test.ts`: `guide_version`/`guidance_version` assertions synced to `2026-07-18.v7`.
|
|
35
|
+
|
|
36
|
+
### Notes
|
|
37
|
+
|
|
38
|
+
- Live-store telemetry (`MEMORY_TELEMETRY=on`) showed the manual memory CRUD surface (`memory_save`/`search`/`list`/`delete`) and the entire reasoning audit tier (`reasoning_get_trace`/`list_sessions`/`search_steps`/`list_milestones`/`get_session_outline`/`mark_step`) at zero real-world calls, while the automatic recall → save → feedback pipeline shows a 63% memory reuse rate. Recorded as an owner monitoring decision in `docs/design/2026-07-12-spec-v1.3.5-recall-refinements.md` §8.1: keep observing with the tightened guide; remove the affected tools in a future release if usage stays near zero.
|
|
39
|
+
|
|
3
40
|
## 1.3.1 (2026-07-14)
|
|
4
41
|
|
|
5
42
|
Theme: contributor documentation catches up with the code, plus a one-command way to teach an agent to use this MCP.
|
package/GUIDELINES.md
CHANGED
|
@@ -1,81 +1,128 @@
|
|
|
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.
|
|
7
|
+
Tool schemas and descriptions are the source of truth for parameter contracts
|
|
8
|
+
(required fields, types, enums); this guide covers policy — when and why.
|
|
7
9
|
|
|
8
10
|
## Moment 1 — Task Start
|
|
9
11
|
|
|
10
12
|
1. Decide the task size first:
|
|
11
13
|
- Trivial one-step lookup: do NOT open a reasoning session and do NOT call
|
|
12
14
|
memory tools unless prior recall is genuinely needed. Stop here.
|
|
15
|
+
(Examples: read one config value, answer a question from context you
|
|
16
|
+
already have.)
|
|
13
17
|
- Anything multi-step, uncertain, or involving debugging, planning, review,
|
|
14
18
|
or trade-offs: call `reasoning_start_session` with a specific title.
|
|
19
|
+
(Examples: any bug hunt, any change touching more than one file.)
|
|
20
|
+
The title doubles as the recall query — favor concrete keywords
|
|
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`).
|
|
15
28
|
2. Read what the server hands back — this is free recall, act on it:
|
|
16
29
|
- `related_memories`: saved knowledge matched to your title, ranked by
|
|
17
|
-
|
|
18
|
-
|
|
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
|
|
19
35
|
the snippets before working; fetch full content
|
|
20
36
|
with `memory_get` if needed. Entries persisted from a past reasoning
|
|
21
37
|
session carry a `source` field (`{session_id, session_title, created_at}`)
|
|
22
38
|
— when you need to verify how a conclusion was reached, replay its origin
|
|
23
39
|
with `reasoning_get_trace(source.session_id)`. Remember which ones
|
|
24
40
|
actually help — you will report them at completion.
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
41
|
+
If `related_memories` has 2 or more entries, do not act on the first one
|
|
42
|
+
blindly: skim all the snippets for contradictions before proceeding.
|
|
43
|
+
- Agree or don't overlap → use the most relevant one(s) directly.
|
|
44
|
+
- Conflict, or you're unsure → call
|
|
45
|
+
`reasoning_get_trace(source.session_id)` on the newer, same-workspace
|
|
46
|
+
one *before* deciding, not after. Once resolved, clean up the losing
|
|
47
|
+
memory with `memory_update` or `memory_delete`.
|
|
48
|
+
- `open_sessions_warning` / `open_sessions`: sessions left in_progress.
|
|
49
|
+
Close the ones YOU opened and finished with
|
|
50
|
+
`reasoning_complete_session`. Leave sessions you don't recognize alone —
|
|
51
|
+
they may belong to another agent or a parallel run; stale ones are
|
|
52
|
+
auto-abandoned by the server. A completed or abandoned session cannot be
|
|
53
|
+
reopened: to resume interrupted work, start a new session and reference
|
|
54
|
+
the old one in the title or an early step.
|
|
28
55
|
3. Only call `memory_search` yourself when you need recall on a topic that is
|
|
29
56
|
NOT the session title (the server already searched the title for you).
|
|
30
57
|
|
|
31
58
|
## Moment 2 — During The Task
|
|
32
59
|
|
|
60
|
+
Every `reasoning_add_step` and `reasoning_complete_session` call requires the
|
|
61
|
+
`session_id` returned by `reasoning_start_session`; `reasoning_mark_step`
|
|
62
|
+
instead takes the `step_id` returned by `reasoning_add_step`.
|
|
63
|
+
|
|
33
64
|
- Log decisions, hypotheses, rejected options, conflicts, and meaningful
|
|
34
65
|
observations with `reasoning_add_step`. Routine mechanical actions do not
|
|
35
|
-
need steps.
|
|
66
|
+
need steps. Within a step: `thought` = your reasoning, `action` = what you
|
|
67
|
+
did, `observation` = what resulted — fill whichever apply (at least one).
|
|
36
68
|
- Prefer batch mode when it lowers friction: `reasoning_add_step` with
|
|
37
69
|
`steps: [{thought/action/observation}, ...]` logs up to 20 steps in one
|
|
38
70
|
call — ideal for recording a stretch of work you just finished instead of
|
|
39
71
|
pausing after every step. A post-hoc trace is far better than an empty one.
|
|
40
|
-
- Mark pivotal steps with `reasoning_mark_step`
|
|
41
|
-
|
|
42
|
-
|
|
72
|
+
- Mark pivotal steps with `reasoning_mark_step` in the same turn you log
|
|
73
|
+
them with `reasoning_add_step` — don't defer it, deferred marks get
|
|
74
|
+
forgotten. Call it whenever the step you just logged was any of: a choice
|
|
75
|
+
between alternatives (`decision`), an option you rejected (`decision`),
|
|
76
|
+
a genuine contradiction you found (`conflict`), an unverified guess you're
|
|
77
|
+
about to test (`hypothesis`), or a result that changed the direction of the
|
|
78
|
+
task (`milestone`). If none of these apply, skip it — not every step needs
|
|
79
|
+
a mark.
|
|
43
80
|
|
|
44
81
|
## Moment 3 — Task End
|
|
45
82
|
|
|
46
83
|
Always close the session with `reasoning_complete_session`:
|
|
47
84
|
|
|
48
|
-
- `conclusion`: the actual answer/decision, written to be reusable.
|
|
85
|
+
- `conclusion`: the actual answer/decision, written to be reusable. Required
|
|
86
|
+
even when abandoning — one line stating why the task was dropped is enough.
|
|
49
87
|
- `used_memory_ids`: ids of memories (e.g. from `related_memories`) that
|
|
50
|
-
genuinely helped. Report honestly, including reporting none.
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
88
|
+
genuinely helped. Report honestly, including reporting none. This is the
|
|
89
|
+
"used" feedback path when you have a session; call
|
|
90
|
+
`memory_record_usage_feedback` directly instead when there is no session to
|
|
91
|
+
close, or the moment you discover a recalled memory is stale or wrong. A
|
|
92
|
+
failed report (e.g. an unknown memory id) returns a warning and is not
|
|
93
|
+
recorded.
|
|
54
94
|
- Saving the conclusion as durable memory is opt-in: pass
|
|
55
95
|
`save_as_memory=true` or `memory_mode='always'`. The default (`auto`) does
|
|
56
96
|
NOT save on its own. Save when the conclusion would help a future task;
|
|
57
|
-
skip
|
|
97
|
+
skip with `memory_mode='never'` (requires `not_saved_reason`) when it is
|
|
58
98
|
one-off noise.
|
|
99
|
+
- When persisting, pick a `memory_type` (`fact`, `preference`, `episodic`,
|
|
100
|
+
`decision`, `reasoning_summary`) and a `memory_importance` (1–5 scale;
|
|
101
|
+
anchors: 5 = convention or decision affecting every task in the workspace,
|
|
102
|
+
3 = reusable pattern within one area, 1 = minor context note).
|
|
59
103
|
- If the task was dropped without a real conclusion, complete with
|
|
60
104
|
`status='abandoned'` instead of leaving the session open.
|
|
61
105
|
|
|
62
106
|
## Tool Reference
|
|
63
107
|
|
|
108
|
+
- `get_usage_guide`: returns this guide (with its version) at runtime
|
|
109
|
+
|
|
64
110
|
Durable memory:
|
|
65
111
|
|
|
66
112
|
- `memory_save`: store durable facts, decisions, preferences, or summaries.
|
|
67
113
|
Tags describe topics ('sqlite', 'auth', 'perf'), not locations — do not put
|
|
68
|
-
workspace or project names in tags
|
|
69
|
-
|
|
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
|
|
70
117
|
- `memory_search`: targeted recall by keyword, topic, or hypothesis
|
|
71
118
|
- `memory_list`: recent or filtered browsing (when browsing beats searching)
|
|
72
119
|
- `memory_get`: fetch one memory by exact id
|
|
73
120
|
- `memory_update`: correct an existing memory in place
|
|
74
121
|
- `memory_delete`: remove unsafe, duplicated, or wrong memory
|
|
75
|
-
- `memory_record_usage_feedback`: record
|
|
76
|
-
used
|
|
77
|
-
|
|
78
|
-
`
|
|
122
|
+
- `memory_record_usage_feedback`: record how a recalled memory turned out
|
|
123
|
+
(`used`, `ignored`, `irrelevant`, `stale`, `unsafe_to_use`) — prefer
|
|
124
|
+
`used_memory_ids` at completion for the common case; use this tool directly
|
|
125
|
+
for no-session tasks and for non-`used` reports
|
|
79
126
|
|
|
80
127
|
Reasoning traces:
|
|
81
128
|
|
|
@@ -90,12 +137,18 @@ Audit & reports (mostly for reviewers and operators, not everyday tasks):
|
|
|
90
137
|
`reasoning_get_session_outline`, `reasoning_search_steps`: navigate traces
|
|
91
138
|
by their pivotal moments
|
|
92
139
|
- `memory_usage_report`, `memory_adoption_report`, `memory_agent_scorecard`:
|
|
93
|
-
telemetry-backed views of how memory/reasoning is actually being used
|
|
94
|
-
|
|
95
|
-
|
|
140
|
+
telemetry-backed views of how memory/reasoning is actually being used
|
|
141
|
+
- Telemetry note: `MEMORY_TELEMETRY` is a server-side env var (`on`/`off`,
|
|
142
|
+
default `off`); agents cannot change it. Successful usage feedback and
|
|
143
|
+
session data are always recorded locally regardless of the setting — only
|
|
144
|
+
the full funnels and ratios in the reports above need `MEMORY_TELEMETRY=on`.
|
|
96
145
|
|
|
97
146
|
## Do Not Store
|
|
98
147
|
|
|
148
|
+
This list applies to durable memory — `memory_save` and conclusions persisted
|
|
149
|
+
via `save_as_memory`. Reasoning steps may summarize tool output briefly, but
|
|
150
|
+
secrets are banned everywhere.
|
|
151
|
+
|
|
99
152
|
- secrets, tokens, or credentials
|
|
100
153
|
- full hidden chain-of-thought
|
|
101
154
|
- transient debugging noise
|
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
|
@@ -30,7 +30,7 @@ export const MemorySaveInputSchema = z
|
|
|
30
30
|
.array(z.string().min(1).max(50))
|
|
31
31
|
.max(20)
|
|
32
32
|
.default([])
|
|
33
|
-
.describe("Short lowercase labels for filtering/search, e.g. ['
|
|
33
|
+
.describe("Short lowercase topic labels for filtering/search, e.g. ['sqlite','backend'] — topics, not workspace or project names."),
|
|
34
34
|
importance: z
|
|
35
35
|
.number()
|
|
36
36
|
.int()
|
|
@@ -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/server.js
CHANGED
|
@@ -5,10 +5,20 @@ import "./db.js"; // ensures schema is created before tools run
|
|
|
5
5
|
import { registerMemoryTools } from "./tools/memory.js";
|
|
6
6
|
import { registerReasoningTools } from "./tools/reasoning.js";
|
|
7
7
|
import { registerUsageGuideTool } from "./tools/usage-guide.js";
|
|
8
|
+
export const SERVER_INSTRUCTIONS = [
|
|
9
|
+
"Memory MCP: durable memory (memory_*) plus reasoning traces (reasoning_*).",
|
|
10
|
+
"Call get_usage_guide for the full policy guide before first use.",
|
|
11
|
+
"Core loop: reasoning_start_session at task start (skip for trivial one-step lookups); log pivotal steps with reasoning_add_step; always finish with reasoning_complete_session (conclusion + used_memory_ids).",
|
|
12
|
+
"Every reasoning_add_step/complete_session call requires the session_id returned by reasoning_start_session; reasoning_mark_step takes the step_id returned by reasoning_add_step.",
|
|
13
|
+
"Saving a conclusion as memory is opt-in (save_as_memory=true); memory_mode='never' requires not_saved_reason.",
|
|
14
|
+
"Tool schemas are the source of truth for parameter contracts. Never store secrets, tokens, or credentials.",
|
|
15
|
+
].join(" ");
|
|
8
16
|
export async function runServer() {
|
|
9
17
|
const server = new McpServer({
|
|
10
18
|
name: "memory-mcp-server",
|
|
11
19
|
version: MCP_VERSION,
|
|
20
|
+
}, {
|
|
21
|
+
instructions: SERVER_INSTRUCTIONS,
|
|
12
22
|
});
|
|
13
23
|
registerMemoryTools(server);
|
|
14
24
|
registerReasoningTools(server);
|
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. 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: [
|
|
@@ -287,7 +322,7 @@ export function registerMemoryTools(server, database) {
|
|
|
287
322
|
}));
|
|
288
323
|
server.registerTool("memory_list", {
|
|
289
324
|
title: "List Memories",
|
|
290
|
-
description: "List saved memories with optional filters, sorted
|
|
325
|
+
description: "List saved memories with optional filters (type, agent_id, tags, min_importance), sorted by created_at, updated_at (default, newest first), or importance.",
|
|
291
326
|
inputSchema: MemoryListInputSchema.shape,
|
|
292
327
|
annotations: {
|
|
293
328
|
readOnlyHint: true,
|
|
@@ -401,7 +436,7 @@ export function registerMemoryTools(server, database) {
|
|
|
401
436
|
}));
|
|
402
437
|
server.registerTool("memory_update", {
|
|
403
438
|
title: "Update Memory",
|
|
404
|
-
description: "Update one or more fields of an existing memory.",
|
|
439
|
+
description: "Update one or more fields of an existing memory. Partial update: only the fields you pass change; omitted fields are preserved. `tags`/`metadata` replace the whole value — use `tags_append`/`tags_remove`/`metadata_patch` for incremental changes. At least one updatable field is required.",
|
|
405
440
|
inputSchema: MemoryUpdateInputSchema.shape,
|
|
406
441
|
annotations: {
|
|
407
442
|
readOnlyHint: false,
|
|
@@ -514,7 +549,7 @@ export function registerMemoryTools(server, database) {
|
|
|
514
549
|
}));
|
|
515
550
|
server.registerTool("memory_delete", {
|
|
516
551
|
title: "Delete Memory",
|
|
517
|
-
description: "Permanently delete a memory by id.",
|
|
552
|
+
description: "Permanently delete a memory by id. Hard delete with no undo — prefer memory_update when the memory is merely wrong or outdated.",
|
|
518
553
|
inputSchema: MemoryDeleteInputSchema.shape,
|
|
519
554
|
annotations: {
|
|
520
555
|
readOnlyHint: false,
|
|
@@ -941,7 +976,7 @@ export function registerMemoryTools(server, database) {
|
|
|
941
976
|
}));
|
|
942
977
|
server.registerTool("memory_record_usage_feedback", {
|
|
943
978
|
title: "Record Memory Usage Feedback",
|
|
944
|
-
description: "Record
|
|
979
|
+
description: "Record how a recalled memory turned out — usefulness is one of: used, ignored, irrelevant, stale, unsafe_to_use. For the common 'used' case, prefer used_memory_ids on reasoning_complete_session; call this tool directly for tasks without a session, or the moment a recalled memory turns out stale or wrong. Feedback is a first-party learning signal for recall quality and is always persisted locally, regardless of the MEMORY_TELEMETRY setting.",
|
|
945
980
|
inputSchema: MemoryRecordUsageFeedbackInputSchema.shape,
|
|
946
981
|
annotations: {
|
|
947
982
|
readOnlyHint: false,
|
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,10 +261,12 @@ 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
|
-
-
|
|
231
|
-
-
|
|
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.
|
|
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
|
|
|
234
272
|
Examples:
|
|
@@ -268,25 +306,32 @@ 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
|
? {
|
|
289
|
-
open_sessions_warning: `You have ${openSessions.length} other in_progress session(s). Close
|
|
334
|
+
open_sessions_warning: `You have ${openSessions.length} other in_progress session(s). Close the ones you opened and finished with reasoning_complete_session; leave sessions you don't recognize alone.`,
|
|
290
335
|
open_sessions: openSessions,
|
|
291
336
|
}
|
|
292
337
|
: {}),
|
|
@@ -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))
|