@nhatnguyen9317/memory-mcp-server 1.3.2 → 1.4.0

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.
@@ -1,6 +1,6 @@
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";
3
- import { handleToolError, newId, nowIso, parseJsonArray, parseJsonObject, toFtsQuery, toRecallTerms, toLimitedJson, } from "../utils.js";
1
+ import { ReasoningAddStepInputSchema, ReasoningCompleteSessionInputSchema, ReasoningFindInputSchema, ReasoningStartSessionInputSchema, } from "../schemas/reasoning.js";
2
+ import { AUTO_RECALL_LIMIT, RECALL_RECENCY_DAYS, RECALL_WEIGHTS, SESSION_TTL_HOURS, getWorkspace, } from "../constants.js";
3
+ import { buildMatchExcerpt, buildRecallSnippet, compactSnippetText, handleToolError, newId, nowIso, parseJsonArray, parseJsonObject, toRecallTerms, toLimitedJson, unquoteFtsTerm, wordPrefixPattern, } from "../utils.js";
4
4
  import { recordToolUsageEvent, withTelemetry } from "./telemetry.js";
5
5
  function sessionRowToRecord(row, stepCount) {
6
6
  return {
@@ -64,53 +64,6 @@ function runInTransaction(database, work) {
64
64
  throw error;
65
65
  }
66
66
  }
67
- function compactSnippetText(text) {
68
- const compact = text.replace(/\s+/g, " ").trim();
69
- return compact.length > 160 ? `${compact.slice(0, 157)}...` : compact;
70
- }
71
- function queryTokens(query) {
72
- return query
73
- .trim()
74
- .split(/\s+/)
75
- .filter(Boolean)
76
- .map((token) => token.toLowerCase());
77
- }
78
- function buildReasoningSnippet(step, query) {
79
- const fields = [step.thought, step.action, step.observation];
80
- const tokens = queryTokens(query);
81
- if (tokens.length > 0) {
82
- const matchingField = fields.find((field) => {
83
- if (!field)
84
- return false;
85
- const lower = field.toLowerCase();
86
- return tokens.some((token) => lower.includes(token));
87
- });
88
- if (matchingField)
89
- return compactSnippetText(matchingField);
90
- }
91
- const source = step.thought ?? step.action ?? step.observation ?? "";
92
- return compactSnippetText(source);
93
- }
94
- function stepToOutlineRecord(step, mark_type = null, note = null) {
95
- const { id, session_id, step_number, thought, action, observation, created_at, } = step;
96
- return {
97
- id,
98
- session_id,
99
- step_number,
100
- thought,
101
- action,
102
- observation,
103
- created_at,
104
- mark_type,
105
- note,
106
- };
107
- }
108
- function selectFallbackOutlineSteps(steps) {
109
- if (steps.length <= 2)
110
- return steps;
111
- const middleIndex = Math.floor((steps.length - 1) / 2);
112
- return [steps[0], steps[middleIndex], steps[steps.length - 1]];
113
- }
114
67
  let defaultDatabasePromise = null;
115
68
  async function resolveDatabase(database) {
116
69
  if (database)
@@ -118,6 +71,8 @@ async function resolveDatabase(database) {
118
71
  defaultDatabasePromise ??= import("../db.js").then((module) => module.db);
119
72
  return defaultDatabasePromise;
120
73
  }
74
+ /** Conclusion written by abandonStaleSessions; carries no searchable content. */
75
+ const AUTO_ABANDONED_CONCLUSION = "auto-abandoned: stale session";
121
76
  function abandonStaleSessions(database, now) {
122
77
  if (SESSION_TTL_HOURS <= 0)
123
78
  return 0;
@@ -125,37 +80,53 @@ function abandonStaleSessions(database, now) {
125
80
  const result = database
126
81
  .prepare(`UPDATE reasoning_sessions
127
82
  SET status = 'abandoned',
128
- conclusion = COALESCE(conclusion, 'auto-abandoned: stale session'),
83
+ conclusion = COALESCE(conclusion, ?),
129
84
  updated_at = ?
130
85
  WHERE status = 'in_progress' AND updated_at < ?`)
131
- .run(now, cutoff);
86
+ .run(AUTO_ABANDONED_CONCLUSION, now, cutoff);
132
87
  return Number(result.changes);
133
88
  }
134
- /** Candidate pool fetched by BM25 before the floor/re-rank pass. */
89
+ const FIND_DEFAULT_LIMIT = 5;
90
+ const FIND_CONCLUSION_CHARS = 300;
91
+ const FIND_EXCERPTS_PER_SESSION = 2;
92
+ /** Candidate pool fetched by BM25 before the gate/score pass. */
135
93
  const RECALL_CANDIDATE_POOL = 50;
136
- function recallRelatedMemories(database, title) {
94
+ function recallRelatedMemories(database, title, workspace) {
137
95
  if (AUTO_RECALL_LIMIT <= 0)
138
96
  return [];
139
97
  try {
140
98
  const terms = toRecallTerms(title);
141
99
  if (terms.length === 0)
142
100
  return [];
101
+ // workspace_priority: 2 = current workspace, 1 = unknown (NULL) or a
102
+ // user preference (cross-project by nature), 0 = another project. With
103
+ // a known workspace the pool is ordered by it first so home memories are
104
+ // never crowded out of the candidate pool by other projects' BM25 hits.
105
+ // Memories reported stale/unsafe are excluded until they are updated
106
+ // after the report.
143
107
  const candidates = database
144
108
  .prepare(`SELECT m.rowid AS row_id, m.id, m.type, m.content, m.tags,
145
109
  m.importance, m.metadata, m.created_at, m.updated_at,
146
110
  f.rank AS fts_rank,
147
111
  CASE
148
- WHEN m.workspace = ? THEN 2
149
- WHEN m.workspace IS NULL THEN 1
112
+ WHEN m.workspace = ? THEN 2
113
+ WHEN m.workspace IS NULL OR m.type = 'preference' THEN 1
150
114
  ELSE 0
151
115
  END AS workspace_priority
152
116
  FROM memories m
153
117
  JOIN (
154
118
  SELECT rowid, rank FROM memories_fts WHERE memories_fts MATCH ?
155
119
  ) f ON m.rowid = f.rowid
156
- ORDER BY f.rank ASC
120
+ WHERE NOT EXISTS (
121
+ SELECT 1 FROM tool_usage_events e
122
+ WHERE e.memory_id = m.id
123
+ AND e.operation_type = 'feedback' AND e.status = 'success'
124
+ AND json_extract(e.metadata, '$.usefulness') IN ('stale', 'unsafe_to_use')
125
+ AND e.created_at >= m.updated_at
126
+ )
127
+ ORDER BY ${workspace === null ? "" : "workspace_priority DESC, "}f.rank ASC
157
128
  LIMIT ?`)
158
- .all(getWorkspace(), terms.join(" OR "), RECALL_CANDIDATE_POOL);
129
+ .all(workspace, terms.join(" OR "), RECALL_CANDIDATE_POOL);
159
130
  if (candidates.length === 0)
160
131
  return [];
161
132
  // Count how many title terms each candidate matches (one cheap FTS
@@ -169,26 +140,51 @@ function recallRelatedMemories(database, title) {
169
140
  matchCounts.set(row.rowid, (matchCounts.get(row.rowid) ?? 0) + 1);
170
141
  }
171
142
  }
172
- const scored = candidates.map((candidate) => ({
143
+ // Eligibility gate. Other projects' non-preference memories must match
144
+ // nearly the whole title; everyone else needs the base floor. Nothing
145
+ // eligible means nothing returned — no best-effort lifeline.
146
+ const total = terms.length;
147
+ const baseFloor = total >= 3 ? 2 : 1;
148
+ const crossProjectFloor = Math.max(2, Math.ceil(0.75 * total));
149
+ const eligible = candidates
150
+ .map((candidate) => ({
173
151
  ...candidate,
174
152
  matched: matchCounts.get(candidate.row_id) ?? 1,
175
- }));
176
- // Quality floor: multi-term titles require at least two matched terms.
177
- // When nothing clears it, fall back to the single best-ranked match
178
- // (serendipity lifeline) instead of padding every slot with junk.
179
- const required = terms.length >= 3 ? 2 : 1;
180
- let pool = scored.filter((candidate) => candidate.matched >= required);
181
- let limit = AUTO_RECALL_LIMIT;
182
- if (pool.length === 0) {
183
- pool = scored;
184
- limit = Math.min(1, AUTO_RECALL_LIMIT);
185
- }
186
- pool.sort((a, b) => b.matched - a.matched ||
187
- b.workspace_priority - a.workspace_priority ||
188
- a.fts_rank - b.fts_rank ||
153
+ }))
154
+ .filter((candidate) => {
155
+ const crossProject = workspace !== null && candidate.workspace_priority === 0;
156
+ return candidate.matched >= (crossProject ? crossProjectFloor : baseFloor);
157
+ });
158
+ if (eligible.length === 0)
159
+ return [];
160
+ // Blended score. bm25 rank is negative (more negative = better), so
161
+ // min-max normalize within the eligible set; all-equal counts as best.
162
+ const ranks = eligible.map((candidate) => candidate.fts_rank);
163
+ const bestRank = Math.min(...ranks);
164
+ const worstRank = Math.max(...ranks);
165
+ const now = Date.now();
166
+ const scored = eligible.map((candidate) => {
167
+ const bm25 = worstRank === bestRank
168
+ ? 1
169
+ : (worstRank - candidate.fts_rank) / (worstRank - bestRank);
170
+ const workspaceTerm = workspace === null ? 0.5 : candidate.workspace_priority / 2;
171
+ const updatedMs = Date.parse(candidate.updated_at);
172
+ const ageDays = Number.isFinite(updatedMs)
173
+ ? Math.max(0, (now - updatedMs) / 86_400_000)
174
+ : Infinity;
175
+ const recency = 1 / (1 + ageDays / RECALL_RECENCY_DAYS);
176
+ return {
177
+ ...candidate,
178
+ score: RECALL_WEIGHTS.coverage * (candidate.matched / total) +
179
+ RECALL_WEIGHTS.bm25 * bm25 +
180
+ RECALL_WEIGHTS.workspace * workspaceTerm +
181
+ RECALL_WEIGHTS.recency * recency,
182
+ };
183
+ });
184
+ scored.sort((a, b) => b.score - a.score ||
189
185
  b.importance - a.importance ||
190
186
  (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0));
191
- return pool.slice(0, limit).map((row) => {
187
+ return scored.slice(0, AUTO_RECALL_LIMIT).map((row) => {
192
188
  const metadata = parseJsonObject(row.metadata);
193
189
  const sourceSessionId = metadata?.source_session_id;
194
190
  const sourceSessionTitle = metadata?.session_title;
@@ -197,7 +193,7 @@ function recallRelatedMemories(database, title) {
197
193
  type: row.type,
198
194
  importance: row.importance,
199
195
  tags: parseJsonArray(row.tags),
200
- snippet: compactSnippetText(row.content),
196
+ snippet: buildRecallSnippet(row.content, terms),
201
197
  ...(typeof sourceSessionId === "string" &&
202
198
  typeof sourceSessionTitle === "string"
203
199
  ? {
@@ -225,15 +221,17 @@ export function registerReasoningTools(server, database) {
225
221
  Args:
226
222
  - title (string, required): Short description of the task/question, e.g. "Diagnose flaky checkout test".
227
223
  - agent_id (string, optional): Identifier for the agent/persona running this session.
224
+ - 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
225
 
229
226
  Returns: JSON with the new session's id (pass it to reasoning_add_step and reasoning_complete_session), plus:
230
- - related_memories: up to a few saved memories relevant to the title, auto-recalled by the server — ranked by text relevance, softly preferring the current workspace; weak one-word 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.
227
+ - workspace: the resolved project workspace for this session, or null when unknown (then workspace_warning explains how to fix it).
228
+ - 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}); the source says which session produced the memory and when; read that session with reasoning_find(session_id) when the snippet is not enough.
231
229
  - 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
230
  - auto_abandoned_sessions: count of stale in_progress sessions the server just cleaned up, if any.
233
231
 
234
232
  Examples:
235
233
  - Use when: starting to debug a complex issue, plan a multi-step task, or work through a decision with tradeoffs.
236
- - Don't use when: the answer is a single simple lookup (just use memory_save/memory_search directly).`,
234
+ - Don't use when: the answer is a single simple lookup (use memory_search directly).`,
237
235
  inputSchema: ReasoningStartSessionInputSchema.shape,
238
236
  annotations: {
239
237
  readOnlyHint: false,
@@ -268,21 +266,38 @@ Examples:
268
266
  const id = newId("sess");
269
267
  const ts = nowIso();
270
268
  const autoAbandoned = abandonStaleSessions(activeDb, ts);
269
+ const workspace = getWorkspace(params.workspace);
271
270
  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);
271
+ .prepare(`INSERT INTO reasoning_sessions (id, title, agent_id, status, conclusion, workspace, created_at, updated_at)
272
+ VALUES (?, ?, ?, 'in_progress', NULL, ?, ?, ?)`)
273
+ .run(id, params.title, params.agent_id ?? null, workspace, ts, ts);
275
274
  const openSessions = activeDb
276
275
  .prepare(`SELECT id, title, updated_at FROM reasoning_sessions
277
276
  WHERE status = 'in_progress' AND id != ?
278
277
  ORDER BY updated_at DESC
279
278
  LIMIT 5`)
280
279
  .all(id);
281
- const relatedMemories = recallRelatedMemories(activeDb, params.title);
280
+ const relatedMemories = recallRelatedMemories(activeDb, params.title, workspace);
281
+ if (relatedMemories.length > 0) {
282
+ try {
283
+ activeDb
284
+ .prepare(`UPDATE reasoning_sessions SET recalled_memory_ids = ? WHERE id = ?`)
285
+ .run(JSON.stringify(relatedMemories.map((memory) => memory.id)), id);
286
+ }
287
+ catch {
288
+ // Measurement is best-effort; it must never block session creation.
289
+ }
290
+ }
282
291
  const output = {
283
292
  session_id: id,
284
293
  title: params.title,
285
294
  status: "in_progress",
295
+ workspace,
296
+ ...(workspace === null
297
+ ? {
298
+ 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.",
299
+ }
300
+ : {}),
286
301
  related_memories: relatedMemories,
287
302
  ...(openSessions.length > 0
288
303
  ? {
@@ -341,7 +356,7 @@ Args:
341
356
  Returns: single mode — JSON with the new step's id and step_number; batch mode — JSON with steps: [{step_id, step_number}, ...] in insertion order.
342
357
 
343
358
  Error Handling:
344
- - Returns an error if session_id does not exist (call reasoning_start_session first, or reasoning_list_sessions to find the right id).
359
+ - Returns an error if session_id does not exist (call reasoning_start_session first, or reasoning_find to look up an existing session).
345
360
  - Returns an error if the session is already 'completed' or 'abandoned'.`,
346
361
  inputSchema: ReasoningAddStepInputSchema.shape,
347
362
  annotations: {
@@ -442,7 +457,7 @@ Error Handling:
442
457
  content: [
443
458
  {
444
459
  type: "text",
445
- text: `Error: Session '${params.session_id}' not found. Use reasoning_start_session to create one, or reasoning_list_sessions to find existing ids.`,
460
+ text: `Error: Session '${params.session_id}' not found. Use reasoning_start_session to create one, or reasoning_find to look up an existing session.`,
446
461
  },
447
462
  ],
448
463
  isError: true,
@@ -464,7 +479,7 @@ Error Handling:
464
479
  .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
465
480
  .get(params.session_id);
466
481
  if (!lockedSession) {
467
- throw new Error(`Session '${params.session_id}' not found. Use reasoning_start_session to create one, or reasoning_list_sessions to find existing ids.`);
482
+ throw new Error(`Session '${params.session_id}' not found. Use reasoning_start_session to create one, or reasoning_find to look up an existing session.`);
468
483
  }
469
484
  if (lockedSession.status !== "in_progress") {
470
485
  throw new Error(`Session '${params.session_id}' is already '${lockedSession.status}' and cannot accept new steps.`);
@@ -512,282 +527,18 @@ Error Handling:
512
527
  };
513
528
  }
514
529
  }));
515
- server.registerTool("reasoning_get_trace", {
516
- title: "Get Reasoning Trace",
517
- description: `Retrieve the full ordered trace of steps for a reasoning session, plus its status and conclusion (if completed).
518
-
519
- Args:
520
- - session_id (string, required): The session id.
521
-
522
- Returns: JSON with { session: {...}, steps: [{step_number, thought, action, observation, created_at}, ...] }.
530
+ server.registerTool("reasoning_find", {
531
+ title: "Find Past Reasoning",
532
+ description: `Find past work that your current context does not contain, then read it.
523
533
 
524
- Error Handling:
525
- - Returns "Error: Session '<id>' not found" if the id does not exist.`,
526
- inputSchema: ReasoningGetTraceInputSchema.shape,
527
- annotations: {
528
- readOnlyHint: true,
529
- destructiveHint: false,
530
- idempotentHint: true,
531
- openWorldHint: false,
532
- },
533
- }, withTelemetry({
534
- database: databaseProvider,
535
- toolName: "reasoning_get_trace",
536
- operationType: "reasoning",
537
- accessType: "read",
538
- buildEvent: (params, result) => ({
539
- sessionId: params.session_id,
540
- outputShape: {
541
- step_count: Array.isArray(result.structuredContent?.steps)
542
- ? result.structuredContent.steps.length
543
- : 0,
544
- },
545
- }),
546
- }, async (params) => {
547
- try {
548
- const activeDb = await resolveDatabase(database);
549
- const sessionRow = activeDb
550
- .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
551
- .get(params.session_id);
552
- if (!sessionRow) {
553
- return {
554
- content: [
555
- {
556
- type: "text",
557
- text: `Error: Session '${params.session_id}' not found.`,
558
- },
559
- ],
560
- isError: true,
561
- };
562
- }
563
- const stepRows = activeDb
564
- .prepare(`SELECT * FROM reasoning_steps WHERE session_id = ? ORDER BY step_number ASC`)
565
- .all(params.session_id);
566
- const steps = stepRows.map((row) => ({
567
- id: row.id,
568
- session_id: row.session_id,
569
- step_number: row.step_number,
570
- thought: row.thought,
571
- action: row.action,
572
- observation: row.observation,
573
- created_at: row.created_at,
574
- }));
575
- const session = sessionRowToRecord(sessionRow, steps.length);
576
- const output = { session, steps };
577
- return {
578
- content: [{ type: "text", text: toLimitedJson(output) }],
579
- structuredContent: output,
580
- };
581
- }
582
- catch (error) {
583
- return {
584
- content: [{ type: "text", text: handleToolError(error) }],
585
- isError: true,
586
- };
587
- }
588
- }));
589
- server.registerTool("reasoning_list_sessions", {
590
- title: "List Reasoning Sessions",
591
- description: `List reasoning sessions with optional filters, most recently updated first. Use this to find past sessions (e.g. to check if a similar task was already worked through) before retrieving a full trace.
534
+ Call it when the user refers to earlier work, a past decision or a previous conversation you don't have ("last time…", "continue the unfinished…", "I already discussed…"), or when a recalled memory's source is not enough to know why that conclusion was reached.
592
535
 
593
- Args:
594
- - agent_id (optional): Filter by agent.
595
- - status ('in_progress'|'completed'|'abandoned', optional): Filter by status.
596
- - limit (1-200, default 20), offset (default 0).
536
+ Pass exactly one of:
537
+ - query: searches past sessions' titles, conclusions and step text. Returns up to limit sessions (default 5), best match first, each with its conclusion and up to 2 matching step excerpts.
538
+ - session_id: returns that session's full ordered trace.
597
539
 
598
- Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, title, status, step_count, conclusion, ...}] }.`,
599
- inputSchema: ReasoningListSessionsInputSchema.shape,
600
- annotations: {
601
- readOnlyHint: true,
602
- destructiveHint: false,
603
- idempotentHint: true,
604
- openWorldHint: false,
605
- },
606
- }, withTelemetry({
607
- database: databaseProvider,
608
- toolName: "reasoning_list_sessions",
609
- operationType: "reasoning",
610
- accessType: "read",
611
- buildEvent: (params, result) => ({
612
- agentId: params.agent_id ?? null,
613
- inputShape: {
614
- has_agent_id: params.agent_id !== undefined,
615
- status: params.status ?? null,
616
- limit: params.limit,
617
- offset: params.offset,
618
- },
619
- outputShape: {
620
- result_count: result.structuredContent?.total_returned ?? 0,
621
- total: result.structuredContent?.total ?? 0,
622
- },
623
- }),
624
- }, async (params) => {
625
- try {
626
- const activeDb = await resolveDatabase(database);
627
- const conditions = ["1=1"];
628
- const sqlParams = [];
629
- if (params.agent_id) {
630
- conditions.push("agent_id = ?");
631
- sqlParams.push(params.agent_id);
632
- }
633
- if (params.status) {
634
- conditions.push("status = ?");
635
- sqlParams.push(params.status);
636
- }
637
- const countRow = activeDb
638
- .prepare(`SELECT COUNT(*) as c FROM reasoning_sessions WHERE ${conditions.join(" AND ")}`)
639
- .get(...sqlParams);
640
- const rows = activeDb
641
- .prepare(`SELECT
642
- reasoning_sessions.*,
643
- COUNT(reasoning_steps.id) AS step_count
644
- FROM reasoning_sessions
645
- LEFT JOIN reasoning_steps
646
- ON reasoning_steps.session_id = reasoning_sessions.id
647
- WHERE ${conditions.join(" AND ")}
648
- GROUP BY reasoning_sessions.id
649
- ORDER BY updated_at DESC LIMIT ? OFFSET ?`)
650
- .all(...sqlParams, params.limit, params.offset);
651
- const sessions = rows.map((row) => sessionRowToRecord(row, row.step_count));
652
- const hasMore = countRow.c > params.offset + sessions.length;
653
- const output = {
654
- total: countRow.c,
655
- total_returned: sessions.length,
656
- offset: params.offset,
657
- has_more: hasMore,
658
- ...(hasMore ? { next_offset: params.offset + sessions.length } : {}),
659
- sessions,
660
- };
661
- return {
662
- content: [{ type: "text", text: toLimitedJson(output) }],
663
- structuredContent: output,
664
- };
665
- }
666
- catch (error) {
667
- return {
668
- content: [{ type: "text", text: handleToolError(error) }],
669
- isError: true,
670
- };
671
- }
672
- }));
673
- server.registerTool("reasoning_list_milestones", {
674
- title: "List Reasoning Milestones",
675
- description: "List marked reasoning steps for audit review without loading full traces.",
676
- inputSchema: ReasoningListMilestonesInputSchema.shape,
677
- annotations: {
678
- readOnlyHint: true,
679
- destructiveHint: false,
680
- idempotentHint: true,
681
- openWorldHint: false,
682
- },
683
- }, withTelemetry({
684
- database: databaseProvider,
685
- toolName: "reasoning_list_milestones",
686
- operationType: "reasoning",
687
- accessType: "read",
688
- buildEvent: (params, result) => ({
689
- agentId: params.agent_id ?? null,
690
- sessionId: params.session_id ?? null,
691
- inputShape: {
692
- has_session_id: params.session_id !== undefined,
693
- has_agent_id: params.agent_id !== undefined,
694
- mark_type: params.mark_type ?? null,
695
- limit: params.limit,
696
- offset: params.offset,
697
- },
698
- outputShape: {
699
- result_count: result.structuredContent?.total_returned ?? 0,
700
- has_more: result.structuredContent?.has_more === true,
701
- },
702
- }),
703
- }, async (params) => {
704
- try {
705
- const activeDb = await resolveDatabase(database);
706
- const conditions = ["1=1"];
707
- const sqlParams = [];
708
- if (params.session_id) {
709
- conditions.push("reasoning_steps.session_id = ?");
710
- sqlParams.push(params.session_id);
711
- }
712
- if (params.agent_id) {
713
- conditions.push("reasoning_sessions.agent_id = ?");
714
- sqlParams.push(params.agent_id);
715
- }
716
- if (params.mark_type) {
717
- conditions.push("reasoning_step_marks.mark_type = ?");
718
- sqlParams.push(params.mark_type);
719
- }
720
- const countRow = activeDb
721
- .prepare(`SELECT COUNT(*) as c
722
- FROM reasoning_step_marks
723
- JOIN reasoning_steps
724
- ON reasoning_steps.id = reasoning_step_marks.step_id
725
- JOIN reasoning_sessions
726
- ON reasoning_sessions.id = reasoning_steps.session_id
727
- WHERE ${conditions.join(" AND ")}`)
728
- .get(...sqlParams);
729
- const rows = activeDb
730
- .prepare(`SELECT
731
- reasoning_steps.session_id,
732
- reasoning_steps.id AS step_id,
733
- reasoning_steps.step_number,
734
- reasoning_step_marks.mark_type,
735
- reasoning_step_marks.note,
736
- reasoning_step_marks.created_at,
737
- reasoning_steps.thought,
738
- reasoning_steps.action,
739
- reasoning_steps.observation
740
- FROM reasoning_step_marks
741
- JOIN reasoning_steps
742
- ON reasoning_steps.id = reasoning_step_marks.step_id
743
- JOIN reasoning_sessions
744
- ON reasoning_sessions.id = reasoning_steps.session_id
745
- WHERE ${conditions.join(" AND ")}
746
- ORDER BY reasoning_step_marks.created_at ASC, reasoning_steps.step_number ASC
747
- LIMIT ? OFFSET ?`)
748
- .all(...sqlParams, params.limit, params.offset);
749
- const results = rows.map((row) => ({
750
- session_id: row.session_id,
751
- step_id: row.step_id,
752
- step_number: row.step_number,
753
- mark_type: row.mark_type,
754
- note: row.note,
755
- created_at: row.created_at,
756
- snippet: buildReasoningSnippet({
757
- id: row.step_id,
758
- session_id: row.session_id,
759
- step_number: row.step_number,
760
- thought: row.thought,
761
- action: row.action,
762
- observation: row.observation,
763
- created_at: row.created_at,
764
- }, row.note ?? row.mark_type),
765
- }));
766
- const hasMore = countRow.c > params.offset + results.length;
767
- const output = {
768
- total: countRow.c,
769
- total_returned: results.length,
770
- offset: params.offset,
771
- has_more: hasMore,
772
- ...(hasMore ? { next_offset: params.offset + results.length } : {}),
773
- results,
774
- };
775
- return {
776
- content: [{ type: "text", text: toLimitedJson(output) }],
777
- structuredContent: output,
778
- };
779
- }
780
- catch (error) {
781
- return {
782
- content: [{ type: "text", text: handleToolError(error) }],
783
- isError: true,
784
- };
785
- }
786
- }));
787
- server.registerTool("reasoning_search_steps", {
788
- title: "Search Reasoning Steps",
789
- description: "Search reasoning steps across thought, action, and observation.",
790
- inputSchema: ReasoningSearchStepsInputSchema.shape,
540
+ Find first, then read only the session that matters.`,
541
+ inputSchema: ReasoningFindInputSchema.shape,
791
542
  annotations: {
792
543
  readOnlyHint: true,
793
544
  destructiveHint: false,
@@ -796,110 +547,39 @@ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, titl
796
547
  },
797
548
  }, withTelemetry({
798
549
  database: databaseProvider,
799
- toolName: "reasoning_search_steps",
550
+ toolName: "reasoning_find",
800
551
  operationType: "reasoning",
801
552
  accessType: "read",
802
553
  buildEvent: (params, result) => ({
803
- agentId: params.agent_id ?? null,
804
554
  sessionId: params.session_id ?? null,
805
555
  inputShape: {
806
- query_length: params.query.length,
807
- token_count: params.query.trim().split(/\s+/).filter(Boolean).length,
808
- has_session_id: params.session_id !== undefined,
809
- has_agent_id: params.agent_id !== undefined,
810
- mark_type: params.mark_type ?? null,
811
- limit: params.limit,
812
- offset: params.offset,
556
+ mode: params.session_id !== undefined ? "read" : "find",
557
+ query_length: params.query?.length ?? 0,
558
+ limit: params.limit ?? FIND_DEFAULT_LIMIT,
813
559
  },
814
560
  outputShape: {
815
561
  result_count: Array.isArray(result.structuredContent?.results)
816
562
  ? result.structuredContent.results.length
817
563
  : 0,
564
+ step_count: Array.isArray(result.structuredContent?.steps)
565
+ ? result.structuredContent.steps.length
566
+ : 0,
818
567
  },
819
568
  }),
820
569
  }, async (params) => {
821
- try {
822
- const activeDb = await resolveDatabase(database);
823
- const conditions = [
824
- "reasoning_steps.rowid IN (SELECT rowid FROM reasoning_steps_fts WHERE reasoning_steps_fts MATCH ?)",
825
- ];
826
- const sqlParams = [toFtsQuery(params.query)];
827
- if (params.session_id) {
828
- conditions.push("reasoning_steps.session_id = ?");
829
- sqlParams.push(params.session_id);
830
- }
831
- if (params.agent_id) {
832
- conditions.push("reasoning_sessions.agent_id = ?");
833
- sqlParams.push(params.agent_id);
834
- }
835
- if (params.mark_type) {
836
- conditions.push("EXISTS (SELECT 1 FROM reasoning_step_marks WHERE reasoning_step_marks.step_id = reasoning_steps.id AND reasoning_step_marks.mark_type = ?)");
837
- sqlParams.push(params.mark_type);
838
- }
839
- const rows = activeDb
840
- .prepare(`SELECT
841
- reasoning_steps.id,
842
- reasoning_steps.session_id,
843
- reasoning_steps.step_number,
844
- reasoning_steps.thought,
845
- reasoning_steps.action,
846
- reasoning_steps.observation,
847
- reasoning_steps.created_at,
848
- reasoning_sessions.agent_id
849
- FROM reasoning_steps
850
- JOIN reasoning_sessions
851
- ON reasoning_sessions.id = reasoning_steps.session_id
852
- WHERE ${conditions.join(" AND ")}
853
- ORDER BY reasoning_steps.created_at DESC, reasoning_steps.step_number DESC
854
- LIMIT ? OFFSET ?`)
855
- .all(...sqlParams, params.limit, params.offset);
856
- const results = rows.map((row) => ({
857
- ...row,
858
- snippet: buildReasoningSnippet(row, params.query),
859
- }));
860
- const output = { results };
861
- return {
862
- content: [{ type: "text", text: toLimitedJson(output) }],
863
- structuredContent: output,
864
- };
865
- }
866
- catch (error) {
570
+ const activeDb = await resolveDatabase(database);
571
+ if ((params.query === undefined) === (params.session_id === undefined)) {
867
572
  return {
868
- content: [{ type: "text", text: handleToolError(error) }],
573
+ content: [
574
+ {
575
+ type: "text",
576
+ text: "Error: Pass exactly one of query (find past sessions) or session_id (read one session).",
577
+ },
578
+ ],
869
579
  isError: true,
870
580
  };
871
581
  }
872
- }));
873
- server.registerTool("reasoning_get_session_outline", {
874
- title: "Get Reasoning Session Outline",
875
- description: "Return an audit-oriented outline for a session, using marked steps when present and a deterministic fallback otherwise.",
876
- inputSchema: ReasoningGetSessionOutlineInputSchema.shape,
877
- annotations: {
878
- readOnlyHint: true,
879
- destructiveHint: false,
880
- idempotentHint: true,
881
- openWorldHint: false,
882
- },
883
- }, withTelemetry({
884
- database: databaseProvider,
885
- toolName: "reasoning_get_session_outline",
886
- operationType: "reasoning",
887
- accessType: "read",
888
- buildEvent: (params, result) => ({
889
- sessionId: params.session_id,
890
- inputShape: {
891
- session_id_present: true,
892
- },
893
- outputShape: {
894
- used_fallback: result.structuredContent?.used_fallback === true,
895
- step_count: Array.isArray(result.structuredContent?.steps)
896
- ? result.structuredContent.steps.length
897
- : 0,
898
- },
899
- }),
900
- }, async (params) => {
901
- try {
902
- const activeDb = await resolveDatabase(database);
582
+ if (params.session_id !== undefined) {
903
583
  const sessionRow = activeDb
904
584
  .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
905
585
  .get(params.session_id);
@@ -908,40 +588,22 @@ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, titl
908
588
  content: [
909
589
  {
910
590
  type: "text",
911
- text: `Error: Session '${params.session_id}' not found.`,
591
+ text: `Error: Session '${params.session_id}' not found. Call reasoning_find with a query to look sessions up.`,
912
592
  },
913
593
  ],
914
594
  isError: true,
915
595
  };
916
596
  }
917
- const stepRows = activeDb
918
- .prepare(`SELECT * FROM reasoning_steps WHERE session_id = ? ORDER BY step_number ASC`)
597
+ const steps = activeDb
598
+ .prepare(`SELECT id, session_id, step_number, thought, action, observation, created_at
599
+ FROM reasoning_steps WHERE session_id = ? ORDER BY step_number ASC`)
919
600
  .all(params.session_id);
920
- const markedRows = activeDb
921
- .prepare(`SELECT
922
- reasoning_steps.id,
923
- reasoning_steps.session_id,
924
- reasoning_steps.step_number,
925
- reasoning_steps.thought,
926
- reasoning_steps.action,
927
- reasoning_steps.observation,
928
- reasoning_steps.created_at,
929
- reasoning_step_marks.mark_type,
930
- reasoning_step_marks.note,
931
- reasoning_step_marks.created_at AS mark_created_at
932
- FROM reasoning_step_marks
933
- JOIN reasoning_steps
934
- ON reasoning_steps.id = reasoning_step_marks.step_id
935
- WHERE reasoning_steps.session_id = ?
936
- ORDER BY reasoning_step_marks.created_at ASC, reasoning_steps.step_number ASC`)
937
- .all(params.session_id);
938
- const session = sessionRowToRecord(sessionRow, stepRows.length);
939
- const steps = markedRows.length > 0
940
- ? markedRows.map((row) => stepToOutlineRecord(row, row.mark_type, row.note))
941
- : selectFallbackOutlineSteps(stepRows).map((row) => stepToOutlineRecord(row));
942
601
  const output = {
943
- session,
944
- used_fallback: markedRows.length === 0,
602
+ mode: "read",
603
+ session: {
604
+ ...sessionRowToRecord(sessionRow, steps.length),
605
+ workspace: sessionRow.workspace,
606
+ },
945
607
  steps,
946
608
  };
947
609
  return {
@@ -949,89 +611,84 @@ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, titl
949
611
  structuredContent: output,
950
612
  };
951
613
  }
952
- catch (error) {
953
- return {
954
- content: [{ type: "text", text: handleToolError(error) }],
955
- isError: true,
956
- };
957
- }
958
- }));
959
- server.registerTool("reasoning_mark_step", {
960
- title: "Mark Reasoning Step",
961
- description: "Attach an audit marker to an existing reasoning step. Repeating the same step_id + mark_type updates the note instead of creating a duplicate mark.",
962
- inputSchema: ReasoningMarkStepInputSchema.shape,
963
- annotations: {
964
- readOnlyHint: false,
965
- destructiveHint: false,
966
- idempotentHint: true,
967
- openWorldHint: false,
968
- },
969
- }, withTelemetry({
970
- database: databaseProvider,
971
- toolName: "reasoning_mark_step",
972
- operationType: "reasoning",
973
- accessType: "write",
974
- buildEvent: (params, result) => ({
975
- stepId: params.step_id,
976
- inputShape: {
977
- mark_type: params.mark_type,
978
- note_present: params.note !== undefined,
979
- note_length: params.note?.length ?? 0,
980
- },
981
- outputShape: {
982
- step_id: result.structuredContent?.step_id ?? null,
983
- mark_type: result.structuredContent?.mark_type ?? null,
984
- note_present: result.structuredContent?.note !== null,
985
- },
986
- }),
987
- }, async (params) => {
988
- try {
989
- const activeDb = await resolveDatabase(database);
990
- const step = activeDb
991
- .prepare(`SELECT id FROM reasoning_steps WHERE id = ?`)
992
- .get(params.step_id);
993
- if (!step) {
614
+ const query = params.query;
615
+ const terms = toRecallTerms(query);
616
+ const words = terms.map(unquoteFtsTerm);
617
+ const matched = new Map();
618
+ const markMatch = (sessionId, termIndex) => {
619
+ const set = matched.get(sessionId) ?? new Set();
620
+ set.add(termIndex);
621
+ matched.set(sessionId, set);
622
+ };
623
+ const stepMatches = activeDb.prepare(`SELECT DISTINCT session_id FROM reasoning_steps
624
+ WHERE rowid IN (SELECT rowid FROM reasoning_steps_fts WHERE reasoning_steps_fts MATCH ?)`);
625
+ const patterns = words.map(wordPrefixPattern);
626
+ const sessionTexts = activeDb
627
+ .prepare(`SELECT id, title, conclusion FROM reasoning_sessions`)
628
+ .all();
629
+ terms.forEach((term, index) => {
630
+ for (const row of stepMatches.all(term)) {
631
+ markMatch(row.session_id, index);
632
+ }
633
+ for (const row of sessionTexts) {
634
+ if (patterns[index].test(row.title) ||
635
+ (row.conclusion !== null &&
636
+ row.conclusion !== AUTO_ABANDONED_CONCLUSION &&
637
+ patterns[index].test(row.conclusion))) {
638
+ markMatch(row.id, index);
639
+ }
640
+ }
641
+ });
642
+ let results = [];
643
+ if (matched.size > 0) {
644
+ const ids = [...matched.keys()];
645
+ const rows = activeDb
646
+ .prepare(`SELECT reasoning_sessions.*, COUNT(reasoning_steps.id) AS step_count
647
+ FROM reasoning_sessions
648
+ LEFT JOIN reasoning_steps ON reasoning_steps.session_id = reasoning_sessions.id
649
+ WHERE reasoning_sessions.id IN (SELECT value FROM json_each(?))
650
+ GROUP BY reasoning_sessions.id`)
651
+ .all(JSON.stringify(ids));
652
+ const limit = params.limit ?? FIND_DEFAULT_LIMIT;
653
+ const excerptRows = activeDb.prepare(`SELECT step_number, thought, action, observation FROM reasoning_steps
654
+ WHERE session_id = ?
655
+ AND rowid IN (SELECT rowid FROM reasoning_steps_fts WHERE reasoning_steps_fts MATCH ?)
656
+ ORDER BY step_number ASC LIMIT ?`);
657
+ const anyTerm = terms.join(" OR ");
658
+ const isEmpty = (row) => Number(row.step_count === 0 &&
659
+ (!row.conclusion || row.conclusion === AUTO_ABANDONED_CONCLUSION));
660
+ results = rows
661
+ .sort((a, b) => isEmpty(a) - isEmpty(b) ||
662
+ matched.get(b.id).size - matched.get(a.id).size ||
663
+ (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0) ||
664
+ (a.id < b.id ? -1 : 1))
665
+ .slice(0, limit)
666
+ .map((row) => {
667
+ const steps = excerptRows.all(row.id, anyTerm, FIND_EXCERPTS_PER_SESSION);
994
668
  return {
995
- content: [
996
- {
997
- type: "text",
998
- text: `Error: Step '${params.step_id}' not found.`,
999
- },
1000
- ],
1001
- isError: true,
669
+ session_id: row.id,
670
+ title: row.title,
671
+ status: row.status,
672
+ workspace: row.workspace,
673
+ created_at: row.created_at,
674
+ updated_at: row.updated_at,
675
+ step_count: row.step_count,
676
+ matched_terms: matched.get(row.id).size,
677
+ conclusion: row.conclusion
678
+ ? compactSnippetText(row.conclusion, FIND_CONCLUSION_CHARS)
679
+ : null,
680
+ excerpts: steps.map((step) => ({
681
+ step_number: step.step_number,
682
+ excerpt: buildMatchExcerpt([step.thought, step.action, step.observation].filter(Boolean).join(" "), words),
683
+ })),
1002
684
  };
1003
- }
1004
- const ts = nowIso();
1005
- activeDb
1006
- .prepare(`INSERT INTO reasoning_step_marks (id, step_id, mark_type, note, created_at)
1007
- VALUES (?, ?, ?, ?, ?)
1008
- ON CONFLICT(step_id, mark_type)
1009
- DO UPDATE SET note = CASE
1010
- WHEN ? THEN excluded.note
1011
- ELSE reasoning_step_marks.note
1012
- END`)
1013
- .run(newId("mark"), params.step_id, params.mark_type, params.note ?? null, ts, params.note !== undefined ? 1 : 0);
1014
- const mark = activeDb
1015
- .prepare(`SELECT id, step_id, mark_type, note, created_at
1016
- FROM reasoning_step_marks
1017
- WHERE step_id = ? AND mark_type = ?`)
1018
- .get(params.step_id, params.mark_type);
1019
- const output = {
1020
- step_id: mark.step_id,
1021
- mark_type: mark.mark_type,
1022
- note: mark.note,
1023
- };
1024
- return {
1025
- content: [{ type: "text", text: toLimitedJson(output) }],
1026
- structuredContent: output,
1027
- };
1028
- }
1029
- catch (error) {
1030
- return {
1031
- content: [{ type: "text", text: handleToolError(error) }],
1032
- isError: true,
1033
- };
685
+ });
1034
686
  }
687
+ const output = { mode: "find", query, total_matched: matched.size, results };
688
+ return {
689
+ content: [{ type: "text", text: toLimitedJson(output) }],
690
+ structuredContent: output,
691
+ };
1035
692
  }));
1036
693
  server.registerTool("reasoning_complete_session", {
1037
694
  title: "Complete Reasoning Session",
@@ -1164,7 +821,7 @@ Error Handling:
1164
821
  session_title: session.title,
1165
822
  auto_saved: !(params.save_as_memory || params.memory_mode === "always"),
1166
823
  step_count: stepCount,
1167
- }), getWorkspace(), ts, ts);
824
+ }), session.workspace ?? null, ts, ts);
1168
825
  return nextMemoryId;
1169
826
  });
1170
827
  const usedMemoryWarnings = [];