@basicmemory/openclaw-basic-memory 0.24.1 → 1.1.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.
Files changed (93) hide show
  1. package/README.md +28 -16
  2. package/bm-client.ts +461 -140
  3. package/commands/cli.ts +5 -6
  4. package/commands/slash.ts +4 -4
  5. package/config.ts +5 -0
  6. package/context-engine/basic-memory-context-engine.ts +74 -9
  7. package/context-engine/types.ts +21 -0
  8. package/dist/bm-client.d.ts +101 -32
  9. package/dist/bm-client.js +346 -108
  10. package/dist/commands/cli.d.ts +1 -1
  11. package/dist/commands/cli.js +5 -5
  12. package/dist/commands/slash.d.ts +1 -1
  13. package/dist/commands/slash.js +4 -3
  14. package/dist/config.d.ts +1 -0
  15. package/dist/config.js +1 -0
  16. package/dist/context-engine/basic-memory-context-engine.d.ts +20 -1
  17. package/dist/context-engine/basic-memory-context-engine.js +50 -2
  18. package/dist/context-engine/types.d.ts +9 -0
  19. package/dist/context-engine/types.js +1 -0
  20. package/dist/index.d.ts +10 -4
  21. package/dist/index.js +78 -69
  22. package/dist/memory/basic-memory-capability.d.ts +19 -0
  23. package/dist/memory/basic-memory-capability.js +196 -0
  24. package/dist/tools/build-context.d.ts +1 -1
  25. package/dist/tools/build-context.js +12 -4
  26. package/dist/tools/delete-note.d.ts +1 -1
  27. package/dist/tools/delete-note.js +2 -1
  28. package/dist/tools/edit-note.d.ts +1 -1
  29. package/dist/tools/edit-note.js +22 -12
  30. package/dist/tools/list-memory-projects.d.ts +1 -1
  31. package/dist/tools/list-memory-projects.js +2 -1
  32. package/dist/tools/list-workspaces.d.ts +1 -1
  33. package/dist/tools/list-workspaces.js +4 -4
  34. package/dist/tools/move-note.d.ts +1 -1
  35. package/dist/tools/move-note.js +2 -1
  36. package/dist/tools/read-note.d.ts +1 -1
  37. package/dist/tools/read-note.js +2 -1
  38. package/dist/tools/schema-diff.d.ts +1 -1
  39. package/dist/tools/schema-diff.js +7 -4
  40. package/dist/tools/schema-infer.d.ts +1 -1
  41. package/dist/tools/schema-infer.js +3 -2
  42. package/dist/tools/schema-validate.d.ts +1 -1
  43. package/dist/tools/schema-validate.js +7 -5
  44. package/dist/tools/search-notes.d.ts +1 -1
  45. package/dist/tools/search-notes.js +13 -6
  46. package/dist/tools/write-note.d.ts +1 -1
  47. package/dist/tools/write-note.js +11 -12
  48. package/index.ts +92 -84
  49. package/memory/basic-memory-capability.ts +259 -0
  50. package/openclaw.plugin.json +1 -3
  51. package/package.json +6 -5
  52. package/scripts/setup-bm.sh +1 -4
  53. package/skills/manifest.json +10 -5
  54. package/skills/memory-agents/SKILL.md +23 -10
  55. package/skills/memory-capture/SKILL.md +29 -18
  56. package/skills/memory-comark/SKILL.md +17 -6
  57. package/skills/memory-continue/SKILL.md +47 -27
  58. package/skills/memory-curate/SKILL.md +40 -24
  59. package/skills/memory-defrag/SKILL.md +18 -7
  60. package/skills/memory-doctor/SKILL.md +93 -0
  61. package/skills/memory-ingest/SKILL.md +35 -18
  62. package/skills/memory-lifecycle/SKILL.md +35 -22
  63. package/skills/memory-literary-analysis/SKILL.md +112 -75
  64. package/skills/memory-metadata-search/SKILL.md +39 -28
  65. package/skills/memory-notes/SKILL.md +75 -50
  66. package/skills/memory-okf/SKILL.md +27 -15
  67. package/skills/memory-quest/SKILL.md +24 -8
  68. package/skills/memory-reflect/SKILL.md +25 -13
  69. package/skills/memory-research/SKILL.md +28 -13
  70. package/skills/memory-schema/SKILL.md +36 -24
  71. package/skills/memory-start/SKILL.md +116 -0
  72. package/skills/memory-tasks/SKILL.md +34 -22
  73. package/tools/build-context.ts +14 -5
  74. package/tools/delete-note.ts +2 -2
  75. package/tools/edit-note.ts +27 -14
  76. package/tools/list-memory-projects.ts +6 -2
  77. package/tools/list-workspaces.ts +8 -5
  78. package/tools/move-note.ts +2 -2
  79. package/tools/read-note.ts +2 -2
  80. package/tools/schema-diff.ts +9 -5
  81. package/tools/schema-infer.ts +3 -3
  82. package/tools/schema-validate.ts +7 -6
  83. package/tools/search-notes.ts +18 -7
  84. package/tools/write-note.ts +12 -12
  85. package/dist/tools/memory-provider.d.ts +0 -15
  86. package/dist/tools/memory-provider.js +0 -275
  87. package/skills/memory-onboarding/SKILL.md +0 -142
  88. package/skills/memory-onboarding/evals/evals.json +0 -29
  89. package/skills/memory-onboarding/references/assistant-setup.md +0 -72
  90. package/skills/memory-onboarding/references/conventions.md +0 -118
  91. package/skills/memory-onboarding/references/domain-playbooks.md +0 -159
  92. package/skills/memory-onboarding/references/schema-guide.md +0 -136
  93. package/tools/memory-provider.ts +0 -336
package/bm-client.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto"
1
2
  import { setTimeout as delay } from "node:timers/promises"
2
3
  import { Client } from "@modelcontextprotocol/sdk/client"
3
4
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
@@ -5,19 +6,35 @@ import { log } from "./logger.ts"
5
6
 
6
7
  const DEFAULT_RETRY_DELAYS_MS = [500, 1000, 2000]
7
8
 
9
+ // Thrown for calls to the plugin's project after BM refused to create it.
10
+ // Deliberately not a BmToolError: note methods read a BmToolError's refusal
11
+ // payload as their own, and would report this ALREADY_EXISTS as an existing
12
+ // note.
13
+ export class ProjectUnavailableError extends Error {
14
+ readonly project: string
15
+ readonly reason: string
16
+ constructor(project: string, reason: string) {
17
+ super(`Basic Memory project "${project}" is unavailable: ${reason}`)
18
+ this.name = "ProjectUnavailableError"
19
+ this.project = project
20
+ this.reason = reason
21
+ }
22
+ }
23
+
8
24
  export class NoteAlreadyExistsError extends Error {
9
25
  readonly permalink: string
10
- constructor(title: string, permalink: string) {
11
- super(`Note already exists: "${title}" (${permalink})`)
26
+ constructor(title: string, permalink: string, message?: string) {
27
+ super(message ?? `Note already exists: "${title}" (${permalink})`)
12
28
  this.name = "NoteAlreadyExistsError"
13
29
  this.permalink = permalink
14
30
  }
15
31
  }
16
32
 
17
33
  /**
18
- * write_note refused a conditional overwrite: the note is no longer the
34
+ * bm_write refused a conditional overwrite: the note is no longer the
19
35
  * revision named by expected_checksum. Nothing was written; currentChecksum is
20
- * the revision to re-read and retry against (null once no note owns the path).
36
+ * available revision when supplied by a server. A null value means unknown;
37
+ * 1.0 puts revision details in the refusal message, not a checksum field.
21
38
  */
22
39
  export class NoteRevisionConflictError extends Error {
23
40
  readonly permalink: string | null
@@ -26,8 +43,11 @@ export class NoteRevisionConflictError extends Error {
26
43
  title: string,
27
44
  permalink: string | null,
28
45
  currentChecksum: string | null,
46
+ message?: string,
29
47
  ) {
30
- super(`Note revision conflict: "${title}" changed since it was read`)
48
+ super(
49
+ message ?? `Note revision conflict: "${title}" changed since it was read`,
50
+ )
31
51
  this.name = "NoteRevisionConflictError"
32
52
  this.permalink = permalink
33
53
  this.currentChecksum = currentChecksum
@@ -49,20 +69,19 @@ export class BmToolError extends Error {
49
69
  }
50
70
 
51
71
  const REQUIRED_TOOLS = [
52
- "search_notes",
53
- "read_note",
54
- "write_note",
55
- "edit_note",
56
- "build_context",
57
- "recent_activity",
58
- "list_memory_projects",
59
- "list_workspaces",
60
- "create_memory_project",
61
- "delete_note",
62
- "move_note",
63
- "schema_validate",
64
- "schema_infer",
65
- "schema_diff",
72
+ "bm_search",
73
+ "bm_read",
74
+ "bm_write",
75
+ "bm_edit",
76
+ "bm_context",
77
+ "bm_project_list",
78
+ "bm_project_create",
79
+ "bm_recent",
80
+ "bm_delete",
81
+ "bm_move",
82
+ "bm_schema_validate",
83
+ "bm_schema_infer",
84
+ "bm_schema_diff",
66
85
  ]
67
86
 
68
87
  export interface SearchResult {
@@ -71,6 +90,17 @@ export interface SearchResult {
71
90
  content: string
72
91
  score?: number
73
92
  file_path: string
93
+ // The chunk of the note that matched, when the server ranked by chunk.
94
+ matched_chunk?: string | null
95
+ }
96
+
97
+ /**
98
+ * The text to preview for a search hit. `content` is the start of the note,
99
+ * so for a long note (a day of captured conversation) the matching part can
100
+ * sit far below any preview cut-off; the matched chunk is the part that hit.
101
+ */
102
+ export function searchResultText(result: SearchResult): string {
103
+ return result.matched_chunk?.trim() || result.content || ""
74
104
  }
75
105
 
76
106
  export interface NoteResult {
@@ -87,7 +117,7 @@ export interface EditNoteResult {
87
117
  title: string
88
118
  permalink: string
89
119
  file_path: string
90
- operation: "append" | "prepend" | "find_replace" | "replace_section"
120
+ operation: EditOperation
91
121
  checksum?: string | null
92
122
  }
93
123
 
@@ -107,6 +137,16 @@ interface WriteNoteOptions {
107
137
  expectedChecksum?: string
108
138
  }
109
139
 
140
+ // bm_edit commands the plugin exposes. set_metadata is left out: edit_note
141
+ // already merges `metadata` alongside any other operation.
142
+ export type EditOperation =
143
+ | "append"
144
+ | "prepend"
145
+ | "find_replace"
146
+ | "replace_section"
147
+ | "insert_before_section"
148
+ | "insert_after_section"
149
+
110
150
  interface EditNoteOptions {
111
151
  find_text?: string
112
152
  section?: string
@@ -127,7 +167,10 @@ export interface ContextResult {
127
167
  permalink: string
128
168
  relation_type?: string
129
169
  from_entity?: string
130
- to_entity?: string
170
+ // Null for a forward reference whose target note does not exist yet;
171
+ // to_name then carries the link text.
172
+ to_entity?: string | null
173
+ to_name?: string | null
131
174
  }>
132
175
  }>
133
176
  }
@@ -142,6 +185,8 @@ export interface RecentResult {
142
185
  export interface ProjectListResult {
143
186
  name: string
144
187
  path: string
188
+ // Set only on the row attached to a local project; null on cloud-only rows.
189
+ local_path?: string | null
145
190
  external_id?: string | null
146
191
  source?: string | null
147
192
  qualified_name?: string | null
@@ -158,29 +203,42 @@ export interface ProjectListResult {
158
203
  export interface WorkspaceResult {
159
204
  tenant_id: string
160
205
  name: string
161
- workspace_type: string
162
- role: string
163
- organization_id?: string | null
164
- has_active_subscription: boolean
206
+ workspace_type: string | null
207
+ }
208
+
209
+ // The schema tool response shapes. They mirror the backend models in
210
+ // src/basic_memory/schemas/schema.py (ValidationReport, InferenceReport,
211
+ // DriftReport); the client casts the payload without translating fields, so
212
+ // a name that drifts from the backend renders as undefined (#1997).
213
+ // JSON responses drop null fields, so nullable backend fields are optional.
214
+ export interface SchemaNoteValidation {
215
+ note_identifier: string
216
+ schema_entity: string
217
+ passed: boolean
218
+ warnings: string[]
219
+ errors: string[]
165
220
  }
166
221
 
167
222
  export interface SchemaValidationResult {
168
- entity_type: string | null
223
+ note_type?: string | null
169
224
  total_notes: number
170
225
  total_entities: number
171
226
  valid_count: number
172
227
  warning_count: number
173
228
  error_count: number
174
- results: Array<{
175
- identifier: string
176
- valid: boolean
177
- warnings: string[]
178
- errors: string[]
229
+ results: SchemaNoteValidation[]
230
+ type_summaries?: Array<{
231
+ note_type: string
232
+ total_notes: number
233
+ total_entities: number
234
+ valid_count: number
235
+ warning_count: number
236
+ error_count: number
179
237
  }>
180
238
  }
181
239
 
182
240
  export interface SchemaInferResult {
183
- entity_type: string
241
+ note_type: string
184
242
  notes_analyzed: number
185
243
  field_frequencies: Array<{
186
244
  name: string
@@ -198,18 +256,21 @@ export interface SchemaInferResult {
198
256
  excluded: string[]
199
257
  }
200
258
 
259
+ export interface SchemaDriftField {
260
+ name: string
261
+ source: string
262
+ count: number
263
+ total: number
264
+ percentage: number
265
+ }
266
+
201
267
  export interface SchemaDiffResult {
202
- entity_type: string
268
+ note_type: string
203
269
  schema_found: boolean
204
- new_fields: Array<{
205
- name: string
206
- source: string
207
- count: number
208
- total: number
209
- percentage: number
210
- }>
211
- dropped_fields: Array<{ name: string; source: string; declared_in?: string }>
270
+ new_fields: SchemaDriftField[]
271
+ dropped_fields: SchemaDriftField[]
212
272
  cardinality_changes: string[]
273
+ notes_compared?: number | null
213
274
  }
214
275
 
215
276
  function getErrorMessage(err: unknown): string {
@@ -249,23 +310,32 @@ function isRecoverableConnectionError(err: unknown): boolean {
249
310
  )
250
311
  }
251
312
 
252
- function isNoteNotFoundError(err: unknown): boolean {
253
- const msg = getErrorMessage(err).toLowerCase()
313
+ export function isNoteNotFoundError(err: unknown): boolean {
254
314
  return (
255
- msg.includes("entity not found") ||
256
- msg.includes("note not found") ||
257
- msg.includes("resource not found") ||
258
- msg.includes("could not find note matching") ||
259
- msg.includes("404")
315
+ err instanceof BmToolError &&
316
+ parseRefusalPayload(err.toolMessage)?.error === "NOT_FOUND"
260
317
  )
261
318
  }
262
319
 
320
+ export type ConversationCaptureStatus = "committed" | "duplicate"
321
+
322
+ function conversationDate(date: Date): string {
323
+ return date.toISOString().split("T")[0]
324
+ }
325
+
326
+ // Host advancement keys are opaque and may contain characters that would end
327
+ // an HTML comment, so the note stores a fixed-length digest instead.
328
+ function conversationTurnMarker(turnKey: string): string {
329
+ const digest = createHash("sha256").update(turnKey).digest("hex").slice(0, 32)
330
+ return `<!-- openclaw-turn:${digest} -->`
331
+ }
332
+
263
333
  function asString(value: unknown): string | null {
264
334
  return typeof value === "string" ? value : null
265
335
  }
266
336
 
267
337
  // In JSON mode BM reports a refused write as a tool error whose text is the
268
- // refusal payload itself ({"error": "NOTE_ALREADY_EXISTS", ...}). Any other
338
+ // refusal payload itself ({"error": "ALREADY_EXISTS", ...}). Any other
269
339
  // error text (plain-text failures, older servers) is not a refusal payload.
270
340
  function parseRefusalPayload(text: string): Record<string, unknown> | null {
271
341
  let parsed: unknown
@@ -277,6 +347,24 @@ function parseRefusalPayload(text: string): Record<string, unknown> | null {
277
347
  return isRecord(parsed) && typeof parsed.error === "string" ? parsed : null
278
348
  }
279
349
 
350
+ /**
351
+ * The server's own explanation of a failed tool call, for showing to an agent.
352
+ * A refusal payload becomes "CODE: message"; other tool text passes through.
353
+ */
354
+ export function describeToolError(err: unknown): string {
355
+ if (!(err instanceof BmToolError)) return getErrorMessage(err)
356
+ const payload = parseRefusalPayload(err.toolMessage)
357
+ if (!payload) return err.toolMessage || err.message
358
+ const message = asString(payload.message)
359
+ return message ? `${payload.error}: ${message}` : String(payload.error)
360
+ }
361
+
362
+ /** describeToolError, but saying plainly when the note does not exist. */
363
+ export function describeNoteError(err: unknown): string {
364
+ const reason = describeToolError(err)
365
+ return isNoteNotFoundError(err) ? `it does not exist. ${reason}` : reason
366
+ }
367
+
280
368
  function projectMatchesWorkspace(
281
369
  project: ProjectListResult,
282
370
  workspace: string,
@@ -293,40 +381,191 @@ function projectMatchesWorkspace(
293
381
  )
294
382
  }
295
383
 
384
+ function parseProjectList(payload: unknown): ProjectListResult[] {
385
+ if (isRecord(payload) && Array.isArray(payload.projects)) {
386
+ return payload.projects as ProjectListResult[]
387
+ }
388
+ throw new Error("invalid bm_project_list response")
389
+ }
390
+
296
391
  export class BmClient {
297
392
  private bmPath: string
298
393
  private project: string
299
394
  private cwd?: string
300
395
  private env?: Record<string, string>
301
396
  private shouldRun = false
397
+ // True only between start() and stop(), i.e. while the plugin service owns
398
+ // the BM MCP session. A lazy connection opened by a tool or memory call in a
399
+ // one-shot CLI process leaves this false.
400
+ private serviceRunning = false
401
+ // Connect plus project creation, started by start(). Tool calls wait for
402
+ // it so none can reach a project that does not exist yet. Null when the
403
+ // client was never started (tests, one-shot CLI readers).
404
+ private startup: Promise<void> | null = null
405
+ private startupRetry: Promise<void> | null = null
406
+ private projectPath?: string
407
+ private adoptExistingProject = false
408
+ // BM's refusal to create the plugin's project, kept so calls to that
409
+ // project report it while listing and other projects still work.
410
+ private projectSetupError: ProjectUnavailableError | null = null
411
+ private prepare?: () => Promise<void>
302
412
 
303
413
  private client: Client | null = null
304
414
  private transport: StdioClientTransport | null = null
305
415
  private connectPromise: Promise<void> | null = null
306
416
  private retryDelaysMs = [...DEFAULT_RETRY_DELAYS_MS]
417
+ // Conversation captures run one at a time so a turn-key duplicate check
418
+ // and the append that follows it cannot interleave with another capture.
419
+ private conversationWrites: Promise<unknown> = Promise.resolve()
307
420
 
308
421
  constructor(bmPath: string, project: string) {
309
422
  this.bmPath = bmPath
310
423
  this.project = project
311
424
  }
312
425
 
313
- async start(options?: {
426
+ /**
427
+ * Connect to BM and create the plugin's project.
428
+ *
429
+ * Returns the startup promise; callers that must not block (the plugin
430
+ * service, which OpenClaw gives only a few seconds) can leave it running.
431
+ * Tool calls made meanwhile wait for it. If it fails, the next tool call
432
+ * runs it again, so a transient failure does not leave the plugin dead.
433
+ */
434
+ start(options?: {
314
435
  cwd?: string
315
436
  env?: Record<string, string>
437
+ projectPath?: string
438
+ // True when projectPath is only the default: an existing project of the
439
+ // plugin's name is then used at its stored folder.
440
+ adoptExistingProject?: boolean
441
+ // Runs before each connect attempt, e.g. installing the bm CLI.
442
+ prepare?: () => Promise<void>
316
443
  }): Promise<void> {
317
444
  this.shouldRun = true
445
+ this.serviceRunning = true
318
446
  if (options?.cwd) {
319
447
  this.cwd = options.cwd
320
448
  }
321
449
  if (options?.env) {
322
450
  this.env = options.env
323
451
  }
452
+ if (options?.projectPath) {
453
+ this.projectPath = options.projectPath
454
+ }
455
+ if (options?.adoptExistingProject !== undefined) {
456
+ this.adoptExistingProject = options.adoptExistingProject
457
+ }
458
+ if (options?.prepare) {
459
+ this.prepare = options.prepare
460
+ }
324
461
 
462
+ this.startup = this.runStartup()
463
+ return this.startup
464
+ }
465
+
466
+ private async runStartup(): Promise<void> {
467
+ await this.prepare?.()
325
468
  await this.connectWithRetries()
469
+ if (!this.projectPath) return
470
+
471
+ this.projectSetupError = null
472
+ const projectPath = await this.startupProjectPath(this.projectPath)
473
+ try {
474
+ await this.createProject(projectPath)
475
+ } catch (err) {
476
+ // Trigger: BM refused the project, e.g. a configured projectPath that
477
+ // differs from where a project of this name is stored (#1846).
478
+ // Why: a refusal is deterministic, so retrying startup cannot fix it,
479
+ // and failing startup would also fail project listing, the call a
480
+ // user needs to see the stored path. Other failures still fail
481
+ // startup so the next tool call retries them.
482
+ // Outcome: calls to the plugin's project throw this refusal; listing
483
+ // and calls naming another project still work.
484
+ if (
485
+ !(err instanceof BmToolError) ||
486
+ parseRefusalPayload(err.toolMessage) === null
487
+ ) {
488
+ throw err
489
+ }
490
+ this.projectSetupError = new ProjectUnavailableError(
491
+ this.project,
492
+ describeToolError(err),
493
+ )
494
+ log.error(this.projectSetupError.message)
495
+ }
496
+ }
497
+
498
+ // The folder startup creates the project at. Since #1846, BM refuses a
499
+ // create whose path differs from the stored one instead of reusing the
500
+ // project by name.
501
+ private async startupProjectPath(configured: string): Promise<string> {
502
+ // Trigger: projectPath was not configured.
503
+ // Why: its default has changed between plugin releases ("." and
504
+ // ~/.basic-memory/openclaw/), and users create projects by hand, so an
505
+ // existing project may sit somewhere other than the default.
506
+ // Outcome: create at the stored folder, which BM treats as idempotent.
507
+ if (!this.adoptExistingProject) return configured
508
+
509
+ // With cloud credentials the listing holds one row per workspace for a
510
+ // name, and only the row attached to the local project carries
511
+ // local_path; a cloud-only row's path is tenant-relative. BM compares a
512
+ // local create against the local project, so only local_path qualifies.
513
+ const name = this.project.toLowerCase()
514
+ const localPath = parseProjectList(
515
+ await this.callStructured("bm_project_list", {
516
+ output_format: "json",
517
+ }),
518
+ ).find(
519
+ (project) => project.name.toLowerCase() === name && project.local_path,
520
+ )?.local_path
521
+ if (!localPath) return configured
522
+
523
+ if (localPath !== configured) {
524
+ log.info(
525
+ `using existing project "${this.project}" at ${localPath}; set projectPath to use another folder`,
526
+ )
527
+ }
528
+ return localPath
529
+ }
530
+
531
+ // The refusal from the last project setup, or null when the project is
532
+ // usable. Status checks report it, since listing projects still succeeds.
533
+ projectUnavailableReason(): string | null {
534
+ return this.projectSetupError?.reason ?? null
535
+ }
536
+
537
+ private async waitForStartup(): Promise<void> {
538
+ if (!this.startup) return
539
+ try {
540
+ await this.startup
541
+ } catch (err) {
542
+ // Trigger: the startup this call was waiting on failed.
543
+ // Why: the service no longer fails on a slow or failed start, so the
544
+ // first tool call afterwards is the place to recover.
545
+ // Outcome: one fresh attempt, shared by concurrent callers; its error
546
+ // reaches the tool if it fails too.
547
+ if (!this.serviceRunning) throw err
548
+ if (this.startupRetry === null) {
549
+ this.startupRetry = this.runStartup().finally(() => {
550
+ this.startupRetry = null
551
+ })
552
+ this.startup = this.startupRetry
553
+ }
554
+ await this.startupRetry
555
+ }
556
+ }
557
+
558
+ isServiceRunning(): boolean {
559
+ return this.serviceRunning
326
560
  }
327
561
 
328
562
  async stop(): Promise<void> {
329
563
  this.shouldRun = false
564
+ this.serviceRunning = false
565
+ // Let an in-flight startup settle first, so it cannot reconnect after
566
+ // the disconnect below.
567
+ await this.startup?.catch(() => undefined)
568
+ this.startup = null
330
569
  await this.disconnectCurrent(this.client, this.transport)
331
570
  this.client = null
332
571
  this.transport = null
@@ -527,6 +766,22 @@ export class BmClient {
527
766
  private async callTool(
528
767
  name: string,
529
768
  args: Record<string, unknown>,
769
+ ): Promise<unknown> {
770
+ await this.waitForStartup()
771
+ // Trigger: BM refused the plugin's project at startup.
772
+ // Why: the refusal concerns that project only; a call that names another
773
+ // project by name or id must still reach BM.
774
+ // Outcome: only calls routed to the plugin's project report the refusal.
775
+ if (this.projectSetupError && this.targetsPluginProject(args)) {
776
+ throw this.projectSetupError
777
+ }
778
+ return this.callStructured(name, args)
779
+ }
780
+
781
+ // Ungated: startup itself calls this to create the project.
782
+ private async callStructured(
783
+ name: string,
784
+ args: Record<string, unknown>,
530
785
  ): Promise<unknown> {
531
786
  const result = await this.callToolRaw(name, args)
532
787
 
@@ -542,62 +797,73 @@ export class BmClient {
542
797
  return structuredPayload
543
798
  }
544
799
 
800
+ // Project names match case-insensitively in BM, so "Test-Project" routes
801
+ // to the plugin's "test-project" too.
802
+ private targetsPluginProject(args: Record<string, unknown>): boolean {
803
+ return (
804
+ typeof args.project === "string" &&
805
+ args.project.toLowerCase() === this.project.toLowerCase()
806
+ )
807
+ }
808
+
545
809
  private routedProject(project?: string): string {
546
810
  return project ?? this.project
547
811
  }
548
812
 
549
- // project_id names one exact project, so it is sent alone: pairing it with
550
- // a name (or the plugin's default project) would make routing depend on
551
- // server-side precedence rather than on what the caller asked for.
552
- private routing(
553
- project?: string,
554
- projectId?: string,
555
- ): { project: string } | { project_id: string } {
556
- if (projectId !== undefined) return { project_id: projectId }
813
+ // The 1.0 project parameter accepts either a name or an exact project UUID.
814
+ private routing(project?: string, projectId?: string): { project: string } {
815
+ if (projectId !== undefined) return { project: projectId }
557
816
  return { project: this.routedProject(project) }
558
817
  }
559
818
 
560
819
  async ensureProject(projectPath: string): Promise<void> {
561
- const payload = await this.callTool("create_memory_project", {
562
- project_name: this.project,
563
- project_path: projectPath,
820
+ await this.waitForStartup()
821
+ await this.createProject(projectPath)
822
+ }
823
+
824
+ private async createProject(projectPath: string): Promise<void> {
825
+ const payload = await this.callStructured("bm_project_create", {
826
+ name: this.project,
827
+ path: projectPath,
564
828
  set_default: true,
565
829
  output_format: "json",
566
830
  })
567
831
 
568
832
  if (!isRecord(payload)) {
569
- throw new Error("invalid create_memory_project response")
833
+ throw new Error("invalid bm_project_create response")
570
834
  }
571
835
  }
572
836
 
573
837
  async listWorkspaces(): Promise<WorkspaceResult[]> {
574
- const payload = await this.callTool("list_workspaces", {
575
- output_format: "json",
576
- })
577
-
578
- if (isRecord(payload) && Array.isArray(payload.workspaces)) {
579
- return payload.workspaces as WorkspaceResult[]
838
+ const projects = await this.listProjects()
839
+ const workspaces = new Map<string, WorkspaceResult>()
840
+ for (const project of projects) {
841
+ if (project.workspace_tenant_id && project.workspace_name) {
842
+ workspaces.set(project.workspace_tenant_id, {
843
+ tenant_id: project.workspace_tenant_id,
844
+ name: project.workspace_name,
845
+ workspace_type: project.workspace_type ?? null,
846
+ })
847
+ }
580
848
  }
581
-
582
- throw new Error("invalid list_workspaces response")
849
+ return [...workspaces.values()]
583
850
  }
584
851
 
585
852
  async listProjects(workspace?: string): Promise<ProjectListResult[]> {
586
- const payload = await this.callTool("list_memory_projects", {
587
- output_format: "json",
588
- })
589
-
590
- if (isRecord(payload) && Array.isArray(payload.projects)) {
591
- const projects = payload.projects as ProjectListResult[]
592
- if (workspace) {
593
- return projects.filter((project) =>
594
- projectMatchesWorkspace(project, workspace),
595
- )
596
- }
597
- return projects
853
+ // Waits for startup but not for the plugin's project: when BM refused
854
+ // it, the listing is how the user finds where it is actually stored.
855
+ await this.waitForStartup()
856
+ const projects = parseProjectList(
857
+ await this.callStructured("bm_project_list", {
858
+ output_format: "json",
859
+ }),
860
+ )
861
+ if (workspace) {
862
+ return projects.filter((project) =>
863
+ projectMatchesWorkspace(project, workspace),
864
+ )
598
865
  }
599
-
600
- throw new Error("invalid list_memory_projects response")
866
+ return projects
601
867
  }
602
868
 
603
869
  async search(
@@ -619,16 +885,23 @@ export class BmClient {
619
885
  project: this.routedProject(project),
620
886
  }
621
887
  if (query) args.query = query
622
- if (metadata?.filters) args.metadata_filters = metadata.filters
623
- if (metadata?.tags) args.tags = metadata.tags
624
- if (metadata?.status) args.status = metadata.status
888
+ const filters = { ...metadata?.filters }
889
+ // Explicit predicates take precedence over convenience shortcuts.
890
+ if (metadata?.tags?.length && !("tags" in filters))
891
+ filters.tags = { $contains: metadata.tags }
892
+ if (metadata?.status && !("status" in filters))
893
+ filters.status = metadata.status
894
+ if (Object.keys(filters).length) args.filters = filters
625
895
  if (metadata?.note_types) args.note_types = metadata.note_types
626
- if (metadata?.entity_types) args.entity_types = metadata.entity_types
896
+ if (metadata?.entity_types)
897
+ args.items = metadata.entity_types.map((item) =>
898
+ item === "entity" ? "note" : item,
899
+ )
627
900
 
628
- const payload = await this.callTool("search_notes", args)
901
+ const payload = await this.callTool("bm_search", args)
629
902
 
630
903
  if (!isRecord(payload) || !Array.isArray(payload.results)) {
631
- throw new Error("invalid search_notes response")
904
+ throw new Error("invalid bm_search response")
632
905
  }
633
906
 
634
907
  return payload.results as SearchResult[]
@@ -646,10 +919,10 @@ export class BmClient {
646
919
  ...this.routing(project, options.projectId),
647
920
  }
648
921
 
649
- const payload = await this.callTool("read_note", args)
922
+ const payload = await this.callTool("bm_read", args)
650
923
 
651
924
  if (!isRecord(payload)) {
652
- throw new Error("invalid read_note response")
925
+ throw new Error("invalid bm_read response")
653
926
  }
654
927
 
655
928
  const title = asString(payload.title)
@@ -658,7 +931,7 @@ export class BmClient {
658
931
  const filePath = asString(payload.file_path)
659
932
 
660
933
  if (!title || !permalink || content === null || !filePath) {
661
- throw new Error("invalid read_note payload")
934
+ throw new Error("invalid bm_read payload")
662
935
  }
663
936
 
664
937
  return {
@@ -695,36 +968,30 @@ export class BmClient {
695
968
 
696
969
  let payload: unknown
697
970
  try {
698
- payload = await this.callTool("write_note", args)
971
+ payload = await this.callTool("bm_write", args)
699
972
  } catch (err) {
700
973
  const refusal =
701
974
  err instanceof BmToolError ? parseRefusalPayload(err.toolMessage) : null
702
- if (refusal?.error === "NOTE_ALREADY_EXISTS") {
975
+ if (refusal?.error === "ALREADY_EXISTS") {
703
976
  throw new NoteAlreadyExistsError(
704
977
  asString(refusal.title) ?? title,
705
978
  asString(refusal.permalink) ?? "",
979
+ asString(refusal.message) ?? undefined,
706
980
  )
707
981
  }
708
- if (refusal?.error === "NOTE_REVISION_CONFLICT") {
982
+ if (refusal?.error === "REVISION_CONFLICT") {
709
983
  throw new NoteRevisionConflictError(
710
984
  asString(refusal.title) ?? title,
711
985
  asString(refusal.permalink),
712
986
  asString(refusal.currentChecksum),
987
+ asString(refusal.message) ?? undefined,
713
988
  )
714
989
  }
715
990
  throw err
716
991
  }
717
992
 
718
993
  if (!isRecord(payload)) {
719
- throw new Error("invalid write_note response")
720
- }
721
-
722
- // Older servers returned the refusal as a successful payload.
723
- if (payload.error === "NOTE_ALREADY_EXISTS") {
724
- throw new NoteAlreadyExistsError(
725
- asString(payload.title) ?? title,
726
- asString(payload.permalink) ?? "",
727
- )
994
+ throw new Error("invalid bm_write response")
728
995
  }
729
996
 
730
997
  const resultTitle = asString(payload.title)
@@ -732,7 +999,7 @@ export class BmClient {
732
999
  const filePath = asString(payload.file_path)
733
1000
 
734
1001
  if (!resultTitle || !permalink || !filePath) {
735
- throw new Error("invalid write_note payload")
1002
+ throw new Error("invalid bm_write payload")
736
1003
  }
737
1004
 
738
1005
  return {
@@ -754,16 +1021,16 @@ export class BmClient {
754
1021
  project?: string,
755
1022
  ): Promise<ContextResult> {
756
1023
  const args: Record<string, unknown> = {
757
- url,
1024
+ identifier: url,
758
1025
  depth,
759
1026
  output_format: "json",
760
1027
  project: this.routedProject(project),
761
1028
  }
762
1029
 
763
- const payload = await this.callTool("build_context", args)
1030
+ const payload = await this.callTool("bm_context", args)
764
1031
 
765
1032
  if (!isRecord(payload) || !Array.isArray(payload.results)) {
766
- throw new Error("invalid build_context response")
1033
+ throw new Error("invalid bm_context response")
767
1034
  }
768
1035
 
769
1036
  return payload as unknown as ContextResult
@@ -774,30 +1041,30 @@ export class BmClient {
774
1041
  project?: string,
775
1042
  ): Promise<RecentResult[]> {
776
1043
  const args: Record<string, unknown> = {
777
- timeframe,
1044
+ since: timeframe,
778
1045
  output_format: "json",
779
1046
  project: this.routedProject(project),
780
1047
  }
781
1048
 
782
- const payload = await this.callTool("recent_activity", args)
1049
+ const payload = await this.callTool("bm_recent", args)
783
1050
 
784
- if (Array.isArray(payload)) {
785
- return payload as RecentResult[]
1051
+ if (isRecord(payload) && Array.isArray(payload.results)) {
1052
+ return payload.results as RecentResult[]
786
1053
  }
787
1054
 
788
- throw new Error("invalid recent_activity response")
1055
+ throw new Error("invalid bm_recent response")
789
1056
  }
790
1057
 
791
1058
  async editNote(
792
1059
  identifier: string,
793
- operation: "append" | "prepend" | "find_replace" | "replace_section",
1060
+ operation: EditOperation,
794
1061
  content: string,
795
1062
  options: EditNoteOptions = {},
796
1063
  project?: string,
797
1064
  ): Promise<EditNoteResult> {
798
1065
  const args: Record<string, unknown> = {
799
1066
  identifier,
800
- operation,
1067
+ command: operation,
801
1068
  content,
802
1069
  output_format: "json",
803
1070
  project: this.routedProject(project),
@@ -808,10 +1075,10 @@ export class BmClient {
808
1075
  args.expected_replacements = options.expected_replacements
809
1076
  if (options.metadata !== undefined) args.metadata = options.metadata
810
1077
 
811
- const payload = await this.callTool("edit_note", args)
1078
+ const payload = await this.callTool("bm_edit", args)
812
1079
 
813
1080
  if (!isRecord(payload)) {
814
- throw new Error("invalid edit_note response")
1081
+ throw new Error("invalid bm_edit response")
815
1082
  }
816
1083
 
817
1084
  const title = asString(payload.title)
@@ -819,7 +1086,7 @@ export class BmClient {
819
1086
  const filePath = asString(payload.file_path)
820
1087
 
821
1088
  if (!title || !permalink || !filePath) {
822
- throw new Error("invalid edit_note payload")
1089
+ throw new Error("invalid bm_edit payload")
823
1090
  }
824
1091
 
825
1092
  return {
@@ -841,14 +1108,14 @@ export class BmClient {
841
1108
  project: this.routedProject(project),
842
1109
  }
843
1110
 
844
- const payload = await this.callTool("delete_note", args)
1111
+ const payload = await this.callTool("bm_delete", args)
845
1112
 
846
1113
  if (!isRecord(payload)) {
847
- throw new Error("invalid delete_note response")
1114
+ throw new Error("invalid bm_delete response")
848
1115
  }
849
1116
 
850
- if (payload.deleted !== true) {
851
- throw new Error(`delete_note did not delete "${identifier}"`)
1117
+ if (payload.action !== "deleted") {
1118
+ throw new Error(`bm_delete did not delete "${identifier}"`)
852
1119
  }
853
1120
 
854
1121
  return {
@@ -865,21 +1132,21 @@ export class BmClient {
865
1132
  ): Promise<NoteResult> {
866
1133
  const args: Record<string, unknown> = {
867
1134
  identifier,
868
- destination_folder: newFolder,
1135
+ destination: `${newFolder.replace(/\/+$/, "")}/`,
869
1136
  output_format: "json",
870
1137
  project: this.routedProject(project),
871
1138
  }
872
1139
 
873
- const payload = await this.callTool("move_note", args)
1140
+ const payload = await this.callTool("bm_move", args)
874
1141
 
875
1142
  if (!isRecord(payload)) {
876
- throw new Error("invalid move_note response")
1143
+ throw new Error("invalid bm_move response")
877
1144
  }
878
1145
 
879
- if (payload.moved !== true) {
1146
+ if (payload.action !== "moved") {
880
1147
  throw new Error(
881
1148
  asString(payload.error) ??
882
- `move_note did not move "${identifier}" to "${newFolder}"`,
1149
+ `bm_move did not move "${identifier}" to "${newFolder}"`,
883
1150
  )
884
1151
  }
885
1152
 
@@ -903,10 +1170,10 @@ export class BmClient {
903
1170
  if (noteType) args.note_type = noteType
904
1171
  if (identifier) args.identifier = identifier
905
1172
 
906
- const payload = await this.callTool("schema_validate", args)
1173
+ const payload = await this.callTool("bm_schema_validate", args)
907
1174
 
908
1175
  if (!isRecord(payload)) {
909
- throw new Error("invalid schema_validate response")
1176
+ throw new Error("invalid bm_schema_validate response")
910
1177
  }
911
1178
 
912
1179
  return payload as unknown as SchemaValidationResult
@@ -924,10 +1191,10 @@ export class BmClient {
924
1191
  project: this.routedProject(project),
925
1192
  }
926
1193
 
927
- const payload = await this.callTool("schema_infer", args)
1194
+ const payload = await this.callTool("bm_schema_infer", args)
928
1195
 
929
1196
  if (!isRecord(payload)) {
930
- throw new Error("invalid schema_infer response")
1197
+ throw new Error("invalid bm_schema_infer response")
931
1198
  }
932
1199
 
933
1200
  return payload as unknown as SchemaInferResult
@@ -943,26 +1210,70 @@ export class BmClient {
943
1210
  project: this.routedProject(project),
944
1211
  }
945
1212
 
946
- const payload = await this.callTool("schema_diff", args)
1213
+ const payload = await this.callTool("bm_schema_diff", args)
947
1214
 
948
1215
  if (!isRecord(payload)) {
949
- throw new Error("invalid schema_diff response")
1216
+ throw new Error("invalid bm_schema_diff response")
950
1217
  }
951
1218
 
952
1219
  return payload as unknown as SchemaDiffResult
953
1220
  }
954
1221
 
1222
+ /**
1223
+ * Append one user/assistant exchange to today's conversation note.
1224
+ *
1225
+ * With a turnKey the capture is idempotent: the entry carries a marker
1226
+ * derived from the key, and a key already present in today's or
1227
+ * yesterday's note is reported as a duplicate instead of written again.
1228
+ * Yesterday is checked because a host retry can cross midnight.
1229
+ */
955
1230
  async indexConversation(
956
1231
  userMessage: string,
957
1232
  assistantResponse: string,
958
- ): Promise<void> {
1233
+ options: { turnKey?: string } = {},
1234
+ ): Promise<ConversationCaptureStatus> {
1235
+ const write = this.conversationWrites.then(() =>
1236
+ this.writeConversationEntry(
1237
+ userMessage,
1238
+ assistantResponse,
1239
+ options.turnKey,
1240
+ ),
1241
+ )
1242
+ this.conversationWrites = write.catch(() => undefined)
1243
+ return write
1244
+ }
1245
+
1246
+ private async writeConversationEntry(
1247
+ userMessage: string,
1248
+ assistantResponse: string,
1249
+ turnKey: string | undefined,
1250
+ ): Promise<ConversationCaptureStatus> {
959
1251
  const now = new Date()
960
- const dateStr = now.toISOString().split("T")[0]
1252
+ const dateStr = conversationDate(now)
961
1253
  const timeStr = now.toTimeString().slice(0, 5)
962
1254
  const title = `conversations-${dateStr}`
1255
+ const marker = turnKey ? conversationTurnMarker(turnKey) : null
1256
+
1257
+ // Trigger: the host supplied an advancement key for this turn.
1258
+ // Why: hosts retry commits after a crash, and a second append would
1259
+ // duplicate the exchange in the note.
1260
+ // Outcome: an already-recorded key short-circuits before any write.
1261
+ if (marker) {
1262
+ const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000)
1263
+ for (const candidate of [
1264
+ title,
1265
+ `conversations-${conversationDate(yesterday)}`,
1266
+ ]) {
1267
+ if (await this.noteContains(candidate, marker)) {
1268
+ log.debug(`conversation turn already recorded in: ${candidate}`)
1269
+ return "duplicate"
1270
+ }
1271
+ }
1272
+ }
963
1273
 
964
1274
  const entry = [
965
1275
  `### ${timeStr}`,
1276
+ ...(marker ? [marker] : []),
966
1277
  "",
967
1278
  "**User:**",
968
1279
  userMessage,
@@ -976,7 +1287,7 @@ export class BmClient {
976
1287
  try {
977
1288
  await this.editNote(title, "append", entry)
978
1289
  log.debug(`appended conversation to: ${title}`)
979
- return
1290
+ return "committed"
980
1291
  } catch (err) {
981
1292
  if (!isNoteNotFoundError(err)) {
982
1293
  log.error(`conversation append failed: ${getErrorMessage(err)}`, err)
@@ -1001,11 +1312,21 @@ export class BmClient {
1001
1312
  entry,
1002
1313
  ].join("\n")
1003
1314
 
1315
+ await this.writeNote(title, content, "conversations")
1316
+ log.debug(`created conversation note: ${title}`)
1317
+ return "committed"
1318
+ }
1319
+
1320
+ private async noteContains(
1321
+ identifier: string,
1322
+ text: string,
1323
+ ): Promise<boolean> {
1004
1324
  try {
1005
- await this.writeNote(title, content, "conversations")
1006
- log.debug(`created conversation note: ${title}`)
1325
+ const note = await this.readNote(identifier)
1326
+ return note.content.includes(text)
1007
1327
  } catch (err) {
1008
- log.error("conversation index failed", err)
1328
+ if (isNoteNotFoundError(err)) return false
1329
+ throw err
1009
1330
  }
1010
1331
  }
1011
1332