@nhatnguyen9317/memory-mcp-server 1.3.3 → 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";
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 ?`)
@@ -233,7 +193,7 @@ function recallRelatedMemories(database, title, workspace) {
233
193
  type: row.type,
234
194
  importance: row.importance,
235
195
  tags: parseJsonArray(row.tags),
236
- snippet: compactSnippetText(row.content),
196
+ snippet: buildRecallSnippet(row.content, terms),
237
197
  ...(typeof sourceSessionId === "string" &&
238
198
  typeof sourceSessionTitle === "string"
239
199
  ? {
@@ -265,13 +225,13 @@ Args:
265
225
 
266
226
  Returns: JSON with the new session's id (pass it to reasoning_add_step and reasoning_complete_session), plus:
267
227
  - 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.
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.
269
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).
270
230
  - auto_abandoned_sessions: count of stale in_progress sessions the server just cleaned up, if any.
271
231
 
272
232
  Examples:
273
233
  - 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).`,
234
+ - Don't use when: the answer is a single simple lookup (use memory_search directly).`,
275
235
  inputSchema: ReasoningStartSessionInputSchema.shape,
276
236
  annotations: {
277
237
  readOnlyHint: false,
@@ -318,6 +278,16 @@ Examples:
318
278
  LIMIT 5`)
319
279
  .all(id);
320
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
+ }
321
291
  const output = {
322
292
  session_id: id,
323
293
  title: params.title,
@@ -325,7 +295,7 @@ Examples:
325
295
  workspace,
326
296
  ...(workspace === null
327
297
  ? {
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.",
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.",
329
299
  }
330
300
  : {}),
331
301
  related_memories: relatedMemories,
@@ -386,7 +356,7 @@ Args:
386
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.
387
357
 
388
358
  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).
359
+ - Returns an error if session_id does not exist (call reasoning_start_session first, or reasoning_find to look up an existing session).
390
360
  - Returns an error if the session is already 'completed' or 'abandoned'.`,
391
361
  inputSchema: ReasoningAddStepInputSchema.shape,
392
362
  annotations: {
@@ -487,7 +457,7 @@ Error Handling:
487
457
  content: [
488
458
  {
489
459
  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.`,
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.`,
491
461
  },
492
462
  ],
493
463
  isError: true,
@@ -509,7 +479,7 @@ Error Handling:
509
479
  .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
510
480
  .get(params.session_id);
511
481
  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.`);
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.`);
513
483
  }
514
484
  if (lockedSession.status !== "in_progress") {
515
485
  throw new Error(`Session '${params.session_id}' is already '${lockedSession.status}' and cannot accept new steps.`);
@@ -557,168 +527,18 @@ Error Handling:
557
527
  };
558
528
  }
559
529
  }));
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.
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.
566
533
 
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.
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.
637
535
 
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).
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.
642
539
 
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,
540
+ Find first, then read only the session that matters.`,
541
+ inputSchema: ReasoningFindInputSchema.shape,
722
542
  annotations: {
723
543
  readOnlyHint: true,
724
544
  destructiveHint: false,
@@ -727,224 +547,39 @@ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, titl
727
547
  },
728
548
  }, withTelemetry({
729
549
  database: databaseProvider,
730
- toolName: "reasoning_list_milestones",
550
+ toolName: "reasoning_find",
731
551
  operationType: "reasoning",
732
552
  accessType: "read",
733
553
  buildEvent: (params, result) => ({
734
- agentId: params.agent_id ?? null,
735
554
  sessionId: params.session_id ?? null,
736
555
  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,
556
+ mode: params.session_id !== undefined ? "read" : "find",
557
+ query_length: params.query?.length ?? 0,
558
+ limit: params.limit ?? FIND_DEFAULT_LIMIT,
858
559
  },
859
560
  outputShape: {
860
561
  result_count: Array.isArray(result.structuredContent?.results)
861
562
  ? result.structuredContent.results.length
862
563
  : 0,
564
+ step_count: Array.isArray(result.structuredContent?.steps)
565
+ ? result.structuredContent.steps.length
566
+ : 0,
863
567
  },
864
568
  }),
865
569
  }, 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 };
570
+ const activeDb = await resolveDatabase(database);
571
+ if ((params.query === undefined) === (params.session_id === undefined)) {
906
572
  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) }],
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
+ ],
914
579
  isError: true,
915
580
  };
916
581
  }
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);
582
+ if (params.session_id !== undefined) {
948
583
  const sessionRow = activeDb
949
584
  .prepare(`SELECT * FROM reasoning_sessions WHERE id = ?`)
950
585
  .get(params.session_id);
@@ -953,40 +588,22 @@ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, titl
953
588
  content: [
954
589
  {
955
590
  type: "text",
956
- 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.`,
957
592
  },
958
593
  ],
959
594
  isError: true,
960
595
  };
961
596
  }
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`)
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`)
982
600
  .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
601
  const output = {
988
- session,
989
- used_fallback: markedRows.length === 0,
602
+ mode: "read",
603
+ session: {
604
+ ...sessionRowToRecord(sessionRow, steps.length),
605
+ workspace: sessionRow.workspace,
606
+ },
990
607
  steps,
991
608
  };
992
609
  return {
@@ -994,89 +611,84 @@ Returns: JSON with { total_returned, has_more, next_offset, sessions: [{id, titl
994
611
  structuredContent: output,
995
612
  };
996
613
  }
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) {
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);
1039
668
  return {
1040
- content: [
1041
- {
1042
- type: "text",
1043
- text: `Error: Step '${params.step_id}' not found.`,
1044
- },
1045
- ],
1046
- 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
+ })),
1047
684
  };
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
- };
685
+ });
1079
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
+ };
1080
692
  }));
1081
693
  server.registerTool("reasoning_complete_session", {
1082
694
  title: "Complete Reasoning Session",