@nhatnguyen9317/memory-mcp-server 1.3.3 → 1.4.1

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";
1
+ import { ReasoningAddStepInputSchema, ReasoningCompleteSessionInputSchema, ReasoningFindInputSchema, ReasoningStartSessionInputSchema, } from "../schemas/reasoning.js";
2
2
  import { AUTO_RECALL_LIMIT, RECALL_RECENCY_DAYS, RECALL_WEIGHTS, SESSION_TTL_HOURS, getWorkspace, } from "../constants.js";
3
- import { handleToolError, newId, nowIso, parseJsonArray, parseJsonObject, toFtsQuery, toRecallTerms, toLimitedJson, } from "../utils.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,12 +80,15 @@ 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
  }
89
+ const FIND_DEFAULT_LIMIT = 5;
90
+ const FIND_CONCLUSION_CHARS = 300;
91
+ const FIND_EXCERPTS_PER_SESSION = 2;
134
92
  /** Candidate pool fetched by BM25 before the gate/score pass. */
135
93
  const RECALL_CANDIDATE_POOL = 50;
136
94
  function recallRelatedMemories(database, title, workspace) {
@@ -144,7 +102,8 @@ function recallRelatedMemories(database, title, workspace) {
144
102
  // user preference (cross-project by nature), 0 = another project. With
145
103
  // a known workspace the pool is ordered by it first so home memories are
146
104
  // never crowded out of the candidate pool by other projects' BM25 hits.
147
- // Memories already reported stale/unsafe are excluded outright.
105
+ // Memories reported stale/unsafe are excluded until they are updated
106
+ // after the report.
148
107
  const candidates = database
149
108
  .prepare(`SELECT m.rowid AS row_id, m.id, m.type, m.content, m.tags,
150
109
  m.importance, m.metadata, m.created_at, m.updated_at,
@@ -158,11 +117,12 @@ function recallRelatedMemories(database, title, workspace) {
158
117
  JOIN (
159
118
  SELECT rowid, rank FROM memories_fts WHERE memories_fts MATCH ?
160
119
  ) f ON m.rowid = f.rowid
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')
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
166
126
  )
167
127
  ORDER BY ${workspace === null ? "" : "workspace_priority DESC, "}f.rank ASC
168
128
  LIMIT ?`)
@@ -180,7 +140,7 @@ function recallRelatedMemories(database, title, workspace) {
180
140
  matchCounts.set(row.rowid, (matchCounts.get(row.rowid) ?? 0) + 1);
181
141
  }
182
142
  }
183
- // Eligibility gate. Other projects' non-preference memories must match
143
+ // Eligibility gate. Other/unknown projects' non-preference memories must match
184
144
  // nearly the whole title; everyone else needs the base floor. Nothing
185
145
  // eligible means nothing returned — no best-effort lifeline.
186
146
  const total = terms.length;
@@ -192,8 +152,10 @@ function recallRelatedMemories(database, title, workspace) {
192
152
  matched: matchCounts.get(candidate.row_id) ?? 1,
193
153
  }))
194
154
  .filter((candidate) => {
195
- const crossProject = workspace !== null && candidate.workspace_priority === 0;
196
- return candidate.matched >= (crossProject ? crossProjectFloor : baseFloor);
155
+ const needsStrongMatch = workspace !== null &&
156
+ candidate.workspace_priority !== 2 &&
157
+ candidate.type !== "preference";
158
+ return candidate.matched >= (needsStrongMatch ? crossProjectFloor : baseFloor);
197
159
  });
198
160
  if (eligible.length === 0)
199
161
  return [];
@@ -233,7 +195,7 @@ function recallRelatedMemories(database, title, workspace) {
233
195
  type: row.type,
234
196
  importance: row.importance,
235
197
  tags: parseJsonArray(row.tags),
236
- snippet: compactSnippetText(row.content),
198
+ snippet: buildRecallSnippet(row.content, terms),
237
199
  ...(typeof sourceSessionId === "string" &&
238
200
  typeof sourceSessionTitle === "string"
239
201
  ? {
@@ -265,13 +227,13 @@ Args:
265
227
 
266
228
  Returns: JSON with the new session's id (pass it to reasoning_add_step and reasoning_complete_session), plus:
267
229
  - 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.
230
+ - 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.
269
231
  - 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).
270
232
  - auto_abandoned_sessions: count of stale in_progress sessions the server just cleaned up, if any.
271
233
 
272
234
  Examples:
273
235
  - Use when: starting to debug a complex issue, plan a multi-step task, or work through a decision with tradeoffs.
274
- - Don't use when: the answer is a single simple lookup (just use memory_save/memory_search directly).`,
236
+ - Don't use when: the answer is a single simple lookup (use memory_search directly).`,
275
237
  inputSchema: ReasoningStartSessionInputSchema.shape,
276
238
  annotations: {
277
239
  readOnlyHint: false,
@@ -318,6 +280,16 @@ Examples:
318
280
  LIMIT 5`)
319
281
  .all(id);
320
282
  const relatedMemories = recallRelatedMemories(activeDb, params.title, workspace);
283
+ if (relatedMemories.length > 0) {
284
+ try {
285
+ activeDb
286
+ .prepare(`UPDATE reasoning_sessions SET recalled_memory_ids = ? WHERE id = ?`)
287
+ .run(JSON.stringify(relatedMemories.map((memory) => memory.id)), id);
288
+ }
289
+ catch {
290
+ // Measurement is best-effort; it must never block session creation.
291
+ }
292
+ }
321
293
  const output = {
322
294
  session_id: id,
323
295
  title: params.title,
@@ -325,7 +297,7 @@ Examples:
325
297
  workspace,
326
298
  ...(workspace === null
327
299
  ? {
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.",
300
+ 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.",
329
301
  }
330
302
  : {}),
331
303
  related_memories: relatedMemories,
@@ -386,7 +358,7 @@ Args:
386
358
  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.
387
359
 
388
360
  Error Handling:
389
- - Returns an error if session_id does not exist (call reasoning_start_session first, or reasoning_list_sessions to find the right id).
361
+ - Returns an error if session_id does not exist (call reasoning_start_session first, or reasoning_find to look up an existing session).
390
362
  - Returns an error if the session is already 'completed' or 'abandoned'.`,
391
363
  inputSchema: ReasoningAddStepInputSchema.shape,
392
364
  annotations: {
@@ -487,7 +459,7 @@ Error Handling:
487
459
  content: [
488
460
  {
489
461
  type: "text",
490
- text: `Error: Session '${params.session_id}' not found. Use reasoning_start_session to create one, or reasoning_list_sessions to find existing ids.`,
462
+ text: `Error: Session '${params.session_id}' not found. Use reasoning_start_session to create one, or reasoning_find to look up an existing session.`,
491
463
  },
492
464
  ],
493
465
  isError: true,
@@ -509,7 +481,7 @@ Error Handling:
509
481
  .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
510
482
  .get(params.session_id);
511
483
  if (!lockedSession) {
512
- throw new Error(`Session '${params.session_id}' not found. Use reasoning_start_session to create one, or reasoning_list_sessions to find existing ids.`);
484
+ 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.`);
513
485
  }
514
486
  if (lockedSession.status !== "in_progress") {
515
487
  throw new Error(`Session '${params.session_id}' is already '${lockedSession.status}' and cannot accept new steps.`);
@@ -557,168 +529,18 @@ Error Handling:
557
529
  };
558
530
  }
559
531
  }));
560
- server.registerTool("reasoning_get_trace", {
561
- title: "Get Reasoning Trace",
562
- description: `Retrieve the full ordered trace of steps for a reasoning session, plus its status and conclusion (if completed).
563
-
564
- Args:
565
- - session_id (string, required): The session id.
532
+ server.registerTool("reasoning_find", {
533
+ title: "Find Past Reasoning",
534
+ description: `Find past work that your current context does not contain, then read it.
566
535
 
567
- Returns: JSON with { session: {...}, steps: [{step_number, thought, action, observation, created_at}, ...] }.
568
-
569
- Error Handling:
570
- - Returns "Error: Session '<id>' not found" if the id does not exist.`,
571
- inputSchema: ReasoningGetTraceInputSchema.shape,
572
- annotations: {
573
- readOnlyHint: true,
574
- destructiveHint: false,
575
- idempotentHint: true,
576
- openWorldHint: false,
577
- },
578
- }, withTelemetry({
579
- database: databaseProvider,
580
- toolName: "reasoning_get_trace",
581
- operationType: "reasoning",
582
- accessType: "read",
583
- buildEvent: (params, result) => ({
584
- sessionId: params.session_id,
585
- outputShape: {
586
- step_count: Array.isArray(result.structuredContent?.steps)
587
- ? result.structuredContent.steps.length
588
- : 0,
589
- },
590
- }),
591
- }, async (params) => {
592
- try {
593
- const activeDb = await resolveDatabase(database);
594
- const sessionRow = activeDb
595
- .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
596
- .get(params.session_id);
597
- if (!sessionRow) {
598
- return {
599
- content: [
600
- {
601
- type: "text",
602
- text: `Error: Session '${params.session_id}' not found.`,
603
- },
604
- ],
605
- isError: true,
606
- };
607
- }
608
- const stepRows = activeDb
609
- .prepare(`SELECT * FROM reasoning_steps WHERE session_id = ? ORDER BY step_number ASC`)
610
- .all(params.session_id);
611
- const steps = stepRows.map((row) => ({
612
- id: row.id,
613
- session_id: row.session_id,
614
- step_number: row.step_number,
615
- thought: row.thought,
616
- action: row.action,
617
- observation: row.observation,
618
- created_at: row.created_at,
619
- }));
620
- const session = sessionRowToRecord(sessionRow, steps.length);
621
- const output = { session, steps };
622
- return {
623
- content: [{ type: "text", text: toLimitedJson(output) }],
624
- structuredContent: output,
625
- };
626
- }
627
- catch (error) {
628
- return {
629
- content: [{ type: "text", text: handleToolError(error) }],
630
- isError: true,
631
- };
632
- }
633
- }));
634
- server.registerTool("reasoning_list_sessions", {
635
- title: "List Reasoning Sessions",
636
- 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.
536
+ 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.
637
537
 
638
- Args:
639
- - agent_id (optional): Filter by agent.
640
- - status ('in_progress'|'completed'|'abandoned', optional): Filter by status.
641
- - limit (1-200, default 20), offset (default 0).
538
+ Pass exactly one of:
539
+ - 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.
540
+ - session_id: returns that session's full ordered trace.
642
541
 
643
- Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, title, status, step_count, conclusion, ...}] }.`,
644
- inputSchema: ReasoningListSessionsInputSchema.shape,
645
- annotations: {
646
- readOnlyHint: true,
647
- destructiveHint: false,
648
- idempotentHint: true,
649
- openWorldHint: false,
650
- },
651
- }, withTelemetry({
652
- database: databaseProvider,
653
- toolName: "reasoning_list_sessions",
654
- operationType: "reasoning",
655
- accessType: "read",
656
- buildEvent: (params, result) => ({
657
- agentId: params.agent_id ?? null,
658
- inputShape: {
659
- has_agent_id: params.agent_id !== undefined,
660
- status: params.status ?? null,
661
- limit: params.limit,
662
- offset: params.offset,
663
- },
664
- outputShape: {
665
- result_count: result.structuredContent?.total_returned ?? 0,
666
- total: result.structuredContent?.total ?? 0,
667
- },
668
- }),
669
- }, async (params) => {
670
- try {
671
- const activeDb = await resolveDatabase(database);
672
- const conditions = ["1=1"];
673
- const sqlParams = [];
674
- if (params.agent_id) {
675
- conditions.push("agent_id = ?");
676
- sqlParams.push(params.agent_id);
677
- }
678
- if (params.status) {
679
- conditions.push("status = ?");
680
- sqlParams.push(params.status);
681
- }
682
- const countRow = activeDb
683
- .prepare(`SELECT COUNT(*) as c FROM reasoning_sessions WHERE ${conditions.join(" AND ")}`)
684
- .get(...sqlParams);
685
- const rows = activeDb
686
- .prepare(`SELECT
687
- reasoning_sessions.*,
688
- COUNT(reasoning_steps.id) AS step_count
689
- FROM reasoning_sessions
690
- LEFT JOIN reasoning_steps
691
- ON reasoning_steps.session_id = reasoning_sessions.id
692
- WHERE ${conditions.join(" AND ")}
693
- GROUP BY reasoning_sessions.id
694
- ORDER BY updated_at DESC LIMIT ? OFFSET ?`)
695
- .all(...sqlParams, params.limit, params.offset);
696
- const sessions = rows.map((row) => sessionRowToRecord(row, row.step_count));
697
- const hasMore = countRow.c > params.offset + sessions.length;
698
- const output = {
699
- total: countRow.c,
700
- total_returned: sessions.length,
701
- offset: params.offset,
702
- has_more: hasMore,
703
- ...(hasMore ? { next_offset: params.offset + sessions.length } : {}),
704
- sessions,
705
- };
706
- return {
707
- content: [{ type: "text", text: toLimitedJson(output) }],
708
- structuredContent: output,
709
- };
710
- }
711
- catch (error) {
712
- return {
713
- content: [{ type: "text", text: handleToolError(error) }],
714
- isError: true,
715
- };
716
- }
717
- }));
718
- server.registerTool("reasoning_list_milestones", {
719
- title: "List Reasoning Milestones",
720
- description: "List marked reasoning steps for audit review without loading full traces.",
721
- inputSchema: ReasoningListMilestonesInputSchema.shape,
542
+ Find first, then read only the session that matters.`,
543
+ inputSchema: ReasoningFindInputSchema.shape,
722
544
  annotations: {
723
545
  readOnlyHint: true,
724
546
  destructiveHint: false,
@@ -727,224 +549,39 @@ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, titl
727
549
  },
728
550
  }, withTelemetry({
729
551
  database: databaseProvider,
730
- toolName: "reasoning_list_milestones",
552
+ toolName: "reasoning_find",
731
553
  operationType: "reasoning",
732
554
  accessType: "read",
733
555
  buildEvent: (params, result) => ({
734
- agentId: params.agent_id ?? null,
735
556
  sessionId: params.session_id ?? null,
736
557
  inputShape: {
737
- has_session_id: params.session_id !== undefined,
738
- has_agent_id: params.agent_id !== undefined,
739
- mark_type: params.mark_type ?? null,
740
- limit: params.limit,
741
- offset: params.offset,
742
- },
743
- outputShape: {
744
- result_count: result.structuredContent?.total_returned ?? 0,
745
- has_more: result.structuredContent?.has_more === true,
746
- },
747
- }),
748
- }, async (params) => {
749
- try {
750
- const activeDb = await resolveDatabase(database);
751
- const conditions = ["1=1"];
752
- const sqlParams = [];
753
- if (params.session_id) {
754
- conditions.push("reasoning_steps.session_id = ?");
755
- sqlParams.push(params.session_id);
756
- }
757
- if (params.agent_id) {
758
- conditions.push("reasoning_sessions.agent_id = ?");
759
- sqlParams.push(params.agent_id);
760
- }
761
- if (params.mark_type) {
762
- conditions.push("reasoning_step_marks.mark_type = ?");
763
- sqlParams.push(params.mark_type);
764
- }
765
- const countRow = activeDb
766
- .prepare(`SELECT COUNT(*) as c
767
- FROM reasoning_step_marks
768
- JOIN reasoning_steps
769
- ON reasoning_steps.id = reasoning_step_marks.step_id
770
- JOIN reasoning_sessions
771
- ON reasoning_sessions.id = reasoning_steps.session_id
772
- WHERE ${conditions.join(" AND ")}`)
773
- .get(...sqlParams);
774
- const rows = activeDb
775
- .prepare(`SELECT
776
- reasoning_steps.session_id,
777
- reasoning_steps.id AS step_id,
778
- reasoning_steps.step_number,
779
- reasoning_step_marks.mark_type,
780
- reasoning_step_marks.note,
781
- reasoning_step_marks.created_at,
782
- reasoning_steps.thought,
783
- reasoning_steps.action,
784
- reasoning_steps.observation
785
- FROM reasoning_step_marks
786
- JOIN reasoning_steps
787
- ON reasoning_steps.id = reasoning_step_marks.step_id
788
- JOIN reasoning_sessions
789
- ON reasoning_sessions.id = reasoning_steps.session_id
790
- WHERE ${conditions.join(" AND ")}
791
- ORDER BY reasoning_step_marks.created_at ASC, reasoning_steps.step_number ASC
792
- LIMIT ? OFFSET ?`)
793
- .all(...sqlParams, params.limit, params.offset);
794
- const results = rows.map((row) => ({
795
- session_id: row.session_id,
796
- step_id: row.step_id,
797
- step_number: row.step_number,
798
- mark_type: row.mark_type,
799
- note: row.note,
800
- created_at: row.created_at,
801
- snippet: buildReasoningSnippet({
802
- id: row.step_id,
803
- session_id: row.session_id,
804
- step_number: row.step_number,
805
- thought: row.thought,
806
- action: row.action,
807
- observation: row.observation,
808
- created_at: row.created_at,
809
- }, row.note ?? row.mark_type),
810
- }));
811
- const hasMore = countRow.c > params.offset + results.length;
812
- const output = {
813
- total: countRow.c,
814
- total_returned: results.length,
815
- offset: params.offset,
816
- has_more: hasMore,
817
- ...(hasMore ? { next_offset: params.offset + results.length } : {}),
818
- results,
819
- };
820
- return {
821
- content: [{ type: "text", text: toLimitedJson(output) }],
822
- structuredContent: output,
823
- };
824
- }
825
- catch (error) {
826
- return {
827
- content: [{ type: "text", text: handleToolError(error) }],
828
- isError: true,
829
- };
830
- }
831
- }));
832
- server.registerTool("reasoning_search_steps", {
833
- title: "Search Reasoning Steps",
834
- description: "Search reasoning steps across thought, action, and observation.",
835
- inputSchema: ReasoningSearchStepsInputSchema.shape,
836
- annotations: {
837
- readOnlyHint: true,
838
- destructiveHint: false,
839
- idempotentHint: true,
840
- openWorldHint: false,
841
- },
842
- }, withTelemetry({
843
- database: databaseProvider,
844
- toolName: "reasoning_search_steps",
845
- operationType: "reasoning",
846
- accessType: "read",
847
- buildEvent: (params, result) => ({
848
- agentId: params.agent_id ?? null,
849
- sessionId: params.session_id ?? null,
850
- inputShape: {
851
- query_length: params.query.length,
852
- token_count: params.query.trim().split(/\s+/).filter(Boolean).length,
853
- has_session_id: params.session_id !== undefined,
854
- has_agent_id: params.agent_id !== undefined,
855
- mark_type: params.mark_type ?? null,
856
- limit: params.limit,
857
- offset: params.offset,
558
+ mode: params.session_id !== undefined ? "read" : "find",
559
+ query_length: params.query?.length ?? 0,
560
+ limit: params.limit ?? FIND_DEFAULT_LIMIT,
858
561
  },
859
562
  outputShape: {
860
563
  result_count: Array.isArray(result.structuredContent?.results)
861
564
  ? result.structuredContent.results.length
862
565
  : 0,
566
+ step_count: Array.isArray(result.structuredContent?.steps)
567
+ ? result.structuredContent.steps.length
568
+ : 0,
863
569
  },
864
570
  }),
865
571
  }, async (params) => {
866
- try {
867
- const activeDb = await resolveDatabase(database);
868
- const conditions = [
869
- "reasoning_steps.rowid IN (SELECT rowid FROM reasoning_steps_fts WHERE reasoning_steps_fts MATCH ?)",
870
- ];
871
- const sqlParams = [toFtsQuery(params.query)];
872
- if (params.session_id) {
873
- conditions.push("reasoning_steps.session_id = ?");
874
- sqlParams.push(params.session_id);
875
- }
876
- if (params.agent_id) {
877
- conditions.push("reasoning_sessions.agent_id = ?");
878
- sqlParams.push(params.agent_id);
879
- }
880
- if (params.mark_type) {
881
- conditions.push("EXISTS (SELECT 1 FROM reasoning_step_marks WHERE reasoning_step_marks.step_id = reasoning_steps.id AND reasoning_step_marks.mark_type = ?)");
882
- sqlParams.push(params.mark_type);
883
- }
884
- const rows = activeDb
885
- .prepare(`SELECT
886
- reasoning_steps.id,
887
- reasoning_steps.session_id,
888
- reasoning_steps.step_number,
889
- reasoning_steps.thought,
890
- reasoning_steps.action,
891
- reasoning_steps.observation,
892
- reasoning_steps.created_at,
893
- reasoning_sessions.agent_id
894
- FROM reasoning_steps
895
- JOIN reasoning_sessions
896
- ON reasoning_sessions.id = reasoning_steps.session_id
897
- WHERE ${conditions.join(" AND ")}
898
- ORDER BY reasoning_steps.created_at DESC, reasoning_steps.step_number DESC
899
- LIMIT ? OFFSET ?`)
900
- .all(...sqlParams, params.limit, params.offset);
901
- const results = rows.map((row) => ({
902
- ...row,
903
- snippet: buildReasoningSnippet(row, params.query),
904
- }));
905
- const output = { results };
572
+ const activeDb = await resolveDatabase(database);
573
+ if ((params.query === undefined) === (params.session_id === undefined)) {
906
574
  return {
907
- content: [{ type: "text", text: toLimitedJson(output) }],
908
- structuredContent: output,
909
- };
910
- }
911
- catch (error) {
912
- return {
913
- content: [{ type: "text", text: handleToolError(error) }],
575
+ content: [
576
+ {
577
+ type: "text",
578
+ text: "Error: Pass exactly one of query (find past sessions) or session_id (read one session).",
579
+ },
580
+ ],
914
581
  isError: true,
915
582
  };
916
583
  }
917
- }));
918
- server.registerTool("reasoning_get_session_outline", {
919
- title: "Get Reasoning Session Outline",
920
- description: "Return an audit-oriented outline for a session, using marked steps when present and a deterministic fallback otherwise.",
921
- inputSchema: ReasoningGetSessionOutlineInputSchema.shape,
922
- annotations: {
923
- readOnlyHint: true,
924
- destructiveHint: false,
925
- idempotentHint: true,
926
- openWorldHint: false,
927
- },
928
- }, withTelemetry({
929
- database: databaseProvider,
930
- toolName: "reasoning_get_session_outline",
931
- operationType: "reasoning",
932
- accessType: "read",
933
- buildEvent: (params, result) => ({
934
- sessionId: params.session_id,
935
- inputShape: {
936
- session_id_present: true,
937
- },
938
- outputShape: {
939
- used_fallback: result.structuredContent?.used_fallback === true,
940
- step_count: Array.isArray(result.structuredContent?.steps)
941
- ? result.structuredContent.steps.length
942
- : 0,
943
- },
944
- }),
945
- }, async (params) => {
946
- try {
947
- const activeDb = await resolveDatabase(database);
584
+ if (params.session_id !== undefined) {
948
585
  const sessionRow = activeDb
949
586
  .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
950
587
  .get(params.session_id);
@@ -953,40 +590,22 @@ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, titl
953
590
  content: [
954
591
  {
955
592
  type: "text",
956
- text: `Error: Session '${params.session_id}' not found.`,
593
+ text: `Error: Session '${params.session_id}' not found. Call reasoning_find with a query to look sessions up.`,
957
594
  },
958
595
  ],
959
596
  isError: true,
960
597
  };
961
598
  }
962
- const stepRows = activeDb
963
- .prepare(`SELECT * FROM reasoning_steps WHERE session_id = ? ORDER BY step_number ASC`)
964
- .all(params.session_id);
965
- const markedRows = activeDb
966
- .prepare(`SELECT
967
- reasoning_steps.id,
968
- reasoning_steps.session_id,
969
- reasoning_steps.step_number,
970
- reasoning_steps.thought,
971
- reasoning_steps.action,
972
- reasoning_steps.observation,
973
- reasoning_steps.created_at,
974
- reasoning_step_marks.mark_type,
975
- reasoning_step_marks.note,
976
- reasoning_step_marks.created_at AS mark_created_at
977
- FROM reasoning_step_marks
978
- JOIN reasoning_steps
979
- ON reasoning_steps.id = reasoning_step_marks.step_id
980
- WHERE reasoning_steps.session_id = ?
981
- ORDER BY reasoning_step_marks.created_at ASC, reasoning_steps.step_number ASC`)
599
+ const steps = activeDb
600
+ .prepare(`SELECT id, session_id, step_number, thought, action, observation, created_at
601
+ FROM reasoning_steps WHERE session_id = ? ORDER BY step_number ASC`)
982
602
  .all(params.session_id);
983
- const session = sessionRowToRecord(sessionRow, stepRows.length);
984
- const steps = markedRows.length > 0
985
- ? markedRows.map((row) => stepToOutlineRecord(row, row.mark_type, row.note))
986
- : selectFallbackOutlineSteps(stepRows).map((row) => stepToOutlineRecord(row));
987
603
  const output = {
988
- session,
989
- used_fallback: markedRows.length === 0,
604
+ mode: "read",
605
+ session: {
606
+ ...sessionRowToRecord(sessionRow, steps.length),
607
+ workspace: sessionRow.workspace,
608
+ },
990
609
  steps,
991
610
  };
992
611
  return {
@@ -994,89 +613,84 @@ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, titl
994
613
  structuredContent: output,
995
614
  };
996
615
  }
997
- catch (error) {
998
- return {
999
- content: [{ type: "text", text: handleToolError(error) }],
1000
- isError: true,
1001
- };
1002
- }
1003
- }));
1004
- server.registerTool("reasoning_mark_step", {
1005
- title: "Mark Reasoning Step",
1006
- 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.",
1007
- inputSchema: ReasoningMarkStepInputSchema.shape,
1008
- annotations: {
1009
- readOnlyHint: false,
1010
- destructiveHint: false,
1011
- idempotentHint: true,
1012
- openWorldHint: false,
1013
- },
1014
- }, withTelemetry({
1015
- database: databaseProvider,
1016
- toolName: "reasoning_mark_step",
1017
- operationType: "reasoning",
1018
- accessType: "write",
1019
- buildEvent: (params, result) => ({
1020
- stepId: params.step_id,
1021
- inputShape: {
1022
- mark_type: params.mark_type,
1023
- note_present: params.note !== undefined,
1024
- note_length: params.note?.length ?? 0,
1025
- },
1026
- outputShape: {
1027
- step_id: result.structuredContent?.step_id ?? null,
1028
- mark_type: result.structuredContent?.mark_type ?? null,
1029
- note_present: result.structuredContent?.note !== null,
1030
- },
1031
- }),
1032
- }, async (params) => {
1033
- try {
1034
- const activeDb = await resolveDatabase(database);
1035
- const step = activeDb
1036
- .prepare(`SELECT id FROM reasoning_steps WHERE id = ?`)
1037
- .get(params.step_id);
1038
- if (!step) {
616
+ const query = params.query;
617
+ const terms = toRecallTerms(query);
618
+ const words = terms.map(unquoteFtsTerm);
619
+ const matched = new Map();
620
+ const markMatch = (sessionId, termIndex) => {
621
+ const set = matched.get(sessionId) ?? new Set();
622
+ set.add(termIndex);
623
+ matched.set(sessionId, set);
624
+ };
625
+ const stepMatches = activeDb.prepare(`SELECT DISTINCT session_id FROM reasoning_steps
626
+ WHERE rowid IN (SELECT rowid FROM reasoning_steps_fts WHERE reasoning_steps_fts MATCH ?)`);
627
+ const patterns = words.map(wordPrefixPattern);
628
+ const sessionTexts = activeDb
629
+ .prepare(`SELECT id, title, conclusion FROM reasoning_sessions`)
630
+ .all();
631
+ terms.forEach((term, index) => {
632
+ for (const row of stepMatches.all(term)) {
633
+ markMatch(row.session_id, index);
634
+ }
635
+ for (const row of sessionTexts) {
636
+ if (patterns[index].test(row.title) ||
637
+ (row.conclusion !== null &&
638
+ row.conclusion !== AUTO_ABANDONED_CONCLUSION &&
639
+ patterns[index].test(row.conclusion))) {
640
+ markMatch(row.id, index);
641
+ }
642
+ }
643
+ });
644
+ let results = [];
645
+ if (matched.size > 0) {
646
+ const ids = [...matched.keys()];
647
+ const rows = activeDb
648
+ .prepare(`SELECT reasoning_sessions.*, COUNT(reasoning_steps.id) AS step_count
649
+ FROM reasoning_sessions
650
+ LEFT JOIN reasoning_steps ON reasoning_steps.session_id = reasoning_sessions.id
651
+ WHERE reasoning_sessions.id IN (SELECT value FROM json_each(?))
652
+ GROUP BY reasoning_sessions.id`)
653
+ .all(JSON.stringify(ids));
654
+ const limit = params.limit ?? FIND_DEFAULT_LIMIT;
655
+ const excerptRows = activeDb.prepare(`SELECT step_number, thought, action, observation FROM reasoning_steps
656
+ WHERE session_id = ?
657
+ AND rowid IN (SELECT rowid FROM reasoning_steps_fts WHERE reasoning_steps_fts MATCH ?)
658
+ ORDER BY step_number ASC LIMIT ?`);
659
+ const anyTerm = terms.join(" OR ");
660
+ const isEmpty = (row) => Number(row.step_count === 0 &&
661
+ (!row.conclusion || row.conclusion === AUTO_ABANDONED_CONCLUSION));
662
+ results = rows
663
+ .sort((a, b) => isEmpty(a) - isEmpty(b) ||
664
+ matched.get(b.id).size - matched.get(a.id).size ||
665
+ (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0) ||
666
+ (a.id < b.id ? -1 : 1))
667
+ .slice(0, limit)
668
+ .map((row) => {
669
+ const steps = excerptRows.all(row.id, anyTerm, FIND_EXCERPTS_PER_SESSION);
1039
670
  return {
1040
- content: [
1041
- {
1042
- type: "text",
1043
- text: `Error: Step '${params.step_id}' not found.`,
1044
- },
1045
- ],
1046
- isError: true,
671
+ session_id: row.id,
672
+ title: row.title,
673
+ status: row.status,
674
+ workspace: row.workspace,
675
+ created_at: row.created_at,
676
+ updated_at: row.updated_at,
677
+ step_count: row.step_count,
678
+ matched_terms: matched.get(row.id).size,
679
+ conclusion: row.conclusion
680
+ ? compactSnippetText(row.conclusion, FIND_CONCLUSION_CHARS)
681
+ : null,
682
+ excerpts: steps.map((step) => ({
683
+ step_number: step.step_number,
684
+ excerpt: buildMatchExcerpt([step.thought, step.action, step.observation].filter(Boolean).join(" "), words),
685
+ })),
1047
686
  };
1048
- }
1049
- const ts = nowIso();
1050
- activeDb
1051
- .prepare(`INSERT INTO reasoning_step_marks (id, step_id, mark_type, note, created_at)
1052
- VALUES (?, ?, ?, ?, ?)
1053
- ON CONFLICT(step_id, mark_type)
1054
- DO UPDATE SET note = CASE
1055
- WHEN ? THEN excluded.note
1056
- ELSE reasoning_step_marks.note
1057
- END`)
1058
- .run(newId("mark"), params.step_id, params.mark_type, params.note ?? null, ts, params.note !== undefined ? 1 : 0);
1059
- const mark = activeDb
1060
- .prepare(`SELECT id, step_id, mark_type, note, created_at
1061
- FROM reasoning_step_marks
1062
- WHERE step_id = ? AND mark_type = ?`)
1063
- .get(params.step_id, params.mark_type);
1064
- const output = {
1065
- step_id: mark.step_id,
1066
- mark_type: mark.mark_type,
1067
- note: mark.note,
1068
- };
1069
- return {
1070
- content: [{ type: "text", text: toLimitedJson(output) }],
1071
- structuredContent: output,
1072
- };
1073
- }
1074
- catch (error) {
1075
- return {
1076
- content: [{ type: "text", text: handleToolError(error) }],
1077
- isError: true,
1078
- };
687
+ });
1079
688
  }
689
+ const output = { mode: "find", query, total_matched: matched.size, results };
690
+ return {
691
+ content: [{ type: "text", text: toLimitedJson(output) }],
692
+ structuredContent: output,
693
+ };
1080
694
  }));
1081
695
  server.registerTool("reasoning_complete_session", {
1082
696
  title: "Complete Reasoning Session",