@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/dist/bm-client.js CHANGED
@@ -1,26 +1,42 @@
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";
4
5
  import { log } from "./logger.js";
5
6
  const DEFAULT_RETRY_DELAYS_MS = [500, 1000, 2000];
7
+ // Thrown for calls to the plugin's project after BM refused to create it.
8
+ // Deliberately not a BmToolError: note methods read a BmToolError's refusal
9
+ // payload as their own, and would report this ALREADY_EXISTS as an existing
10
+ // note.
11
+ export class ProjectUnavailableError extends Error {
12
+ project;
13
+ reason;
14
+ constructor(project, reason) {
15
+ super(`Basic Memory project "${project}" is unavailable: ${reason}`);
16
+ this.name = "ProjectUnavailableError";
17
+ this.project = project;
18
+ this.reason = reason;
19
+ }
20
+ }
6
21
  export class NoteAlreadyExistsError extends Error {
7
22
  permalink;
8
- constructor(title, permalink) {
9
- super(`Note already exists: "${title}" (${permalink})`);
23
+ constructor(title, permalink, message) {
24
+ super(message ?? `Note already exists: "${title}" (${permalink})`);
10
25
  this.name = "NoteAlreadyExistsError";
11
26
  this.permalink = permalink;
12
27
  }
13
28
  }
14
29
  /**
15
- * write_note refused a conditional overwrite: the note is no longer the
30
+ * bm_write refused a conditional overwrite: the note is no longer the
16
31
  * revision named by expected_checksum. Nothing was written; currentChecksum is
17
- * the revision to re-read and retry against (null once no note owns the path).
32
+ * available revision when supplied by a server. A null value means unknown;
33
+ * 1.0 puts revision details in the refusal message, not a checksum field.
18
34
  */
19
35
  export class NoteRevisionConflictError extends Error {
20
36
  permalink;
21
37
  currentChecksum;
22
- constructor(title, permalink, currentChecksum) {
23
- super(`Note revision conflict: "${title}" changed since it was read`);
38
+ constructor(title, permalink, currentChecksum, message) {
39
+ super(message ?? `Note revision conflict: "${title}" changed since it was read`);
24
40
  this.name = "NoteRevisionConflictError";
25
41
  this.permalink = permalink;
26
42
  this.currentChecksum = currentChecksum;
@@ -38,21 +54,28 @@ export class BmToolError extends Error {
38
54
  }
39
55
  }
40
56
  const REQUIRED_TOOLS = [
41
- "search_notes",
42
- "read_note",
43
- "write_note",
44
- "edit_note",
45
- "build_context",
46
- "recent_activity",
47
- "list_memory_projects",
48
- "list_workspaces",
49
- "create_memory_project",
50
- "delete_note",
51
- "move_note",
52
- "schema_validate",
53
- "schema_infer",
54
- "schema_diff",
57
+ "bm_search",
58
+ "bm_read",
59
+ "bm_write",
60
+ "bm_edit",
61
+ "bm_context",
62
+ "bm_project_list",
63
+ "bm_project_create",
64
+ "bm_recent",
65
+ "bm_delete",
66
+ "bm_move",
67
+ "bm_schema_validate",
68
+ "bm_schema_infer",
69
+ "bm_schema_diff",
55
70
  ];
71
+ /**
72
+ * The text to preview for a search hit. `content` is the start of the note,
73
+ * so for a long note (a day of captured conversation) the matching part can
74
+ * sit far below any preview cut-off; the matched chunk is the part that hit.
75
+ */
76
+ export function searchResultText(result) {
77
+ return result.matched_chunk?.trim() || result.content || "";
78
+ }
56
79
  function getErrorMessage(err) {
57
80
  return err instanceof Error ? err.message : String(err);
58
81
  }
@@ -80,19 +103,24 @@ function isRecoverableConnectionError(err) {
80
103
  msg.includes("failed to start bm mcp stdio") ||
81
104
  msg.includes("client is closed"));
82
105
  }
83
- function isNoteNotFoundError(err) {
84
- const msg = getErrorMessage(err).toLowerCase();
85
- return (msg.includes("entity not found") ||
86
- msg.includes("note not found") ||
87
- msg.includes("resource not found") ||
88
- msg.includes("could not find note matching") ||
89
- msg.includes("404"));
106
+ export function isNoteNotFoundError(err) {
107
+ return (err instanceof BmToolError &&
108
+ parseRefusalPayload(err.toolMessage)?.error === "NOT_FOUND");
109
+ }
110
+ function conversationDate(date) {
111
+ return date.toISOString().split("T")[0];
112
+ }
113
+ // Host advancement keys are opaque and may contain characters that would end
114
+ // an HTML comment, so the note stores a fixed-length digest instead.
115
+ function conversationTurnMarker(turnKey) {
116
+ const digest = createHash("sha256").update(turnKey).digest("hex").slice(0, 32);
117
+ return `<!-- openclaw-turn:${digest} -->`;
90
118
  }
91
119
  function asString(value) {
92
120
  return typeof value === "string" ? value : null;
93
121
  }
94
122
  // In JSON mode BM reports a refused write as a tool error whose text is the
95
- // refusal payload itself ({"error": "NOTE_ALREADY_EXISTS", ...}). Any other
123
+ // refusal payload itself ({"error": "ALREADY_EXISTS", ...}). Any other
96
124
  // error text (plain-text failures, older servers) is not a refusal payload.
97
125
  function parseRefusalPayload(text) {
98
126
  let parsed;
@@ -104,6 +132,24 @@ function parseRefusalPayload(text) {
104
132
  }
105
133
  return isRecord(parsed) && typeof parsed.error === "string" ? parsed : null;
106
134
  }
135
+ /**
136
+ * The server's own explanation of a failed tool call, for showing to an agent.
137
+ * A refusal payload becomes "CODE: message"; other tool text passes through.
138
+ */
139
+ export function describeToolError(err) {
140
+ if (!(err instanceof BmToolError))
141
+ return getErrorMessage(err);
142
+ const payload = parseRefusalPayload(err.toolMessage);
143
+ if (!payload)
144
+ return err.toolMessage || err.message;
145
+ const message = asString(payload.message);
146
+ return message ? `${payload.error}: ${message}` : String(payload.error);
147
+ }
148
+ /** describeToolError, but saying plainly when the note does not exist. */
149
+ export function describeNoteError(err) {
150
+ const reason = describeToolError(err);
151
+ return isNoteNotFoundError(err) ? `it does not exist. ${reason}` : reason;
152
+ }
107
153
  function projectMatchesWorkspace(project, workspace) {
108
154
  const requested = workspace.trim().toLowerCase();
109
155
  if (!requested)
@@ -114,32 +160,164 @@ function projectMatchesWorkspace(project, workspace) {
114
160
  project.workspace_tenant_id,
115
161
  ].some((value) => typeof value === "string" && value.toLowerCase() === requested);
116
162
  }
163
+ function parseProjectList(payload) {
164
+ if (isRecord(payload) && Array.isArray(payload.projects)) {
165
+ return payload.projects;
166
+ }
167
+ throw new Error("invalid bm_project_list response");
168
+ }
117
169
  export class BmClient {
118
170
  bmPath;
119
171
  project;
120
172
  cwd;
121
173
  env;
122
174
  shouldRun = false;
175
+ // True only between start() and stop(), i.e. while the plugin service owns
176
+ // the BM MCP session. A lazy connection opened by a tool or memory call in a
177
+ // one-shot CLI process leaves this false.
178
+ serviceRunning = false;
179
+ // Connect plus project creation, started by start(). Tool calls wait for
180
+ // it so none can reach a project that does not exist yet. Null when the
181
+ // client was never started (tests, one-shot CLI readers).
182
+ startup = null;
183
+ startupRetry = null;
184
+ projectPath;
185
+ adoptExistingProject = false;
186
+ // BM's refusal to create the plugin's project, kept so calls to that
187
+ // project report it while listing and other projects still work.
188
+ projectSetupError = null;
189
+ prepare;
123
190
  client = null;
124
191
  transport = null;
125
192
  connectPromise = null;
126
193
  retryDelaysMs = [...DEFAULT_RETRY_DELAYS_MS];
194
+ // Conversation captures run one at a time so a turn-key duplicate check
195
+ // and the append that follows it cannot interleave with another capture.
196
+ conversationWrites = Promise.resolve();
127
197
  constructor(bmPath, project) {
128
198
  this.bmPath = bmPath;
129
199
  this.project = project;
130
200
  }
131
- async start(options) {
201
+ /**
202
+ * Connect to BM and create the plugin's project.
203
+ *
204
+ * Returns the startup promise; callers that must not block (the plugin
205
+ * service, which OpenClaw gives only a few seconds) can leave it running.
206
+ * Tool calls made meanwhile wait for it. If it fails, the next tool call
207
+ * runs it again, so a transient failure does not leave the plugin dead.
208
+ */
209
+ start(options) {
132
210
  this.shouldRun = true;
211
+ this.serviceRunning = true;
133
212
  if (options?.cwd) {
134
213
  this.cwd = options.cwd;
135
214
  }
136
215
  if (options?.env) {
137
216
  this.env = options.env;
138
217
  }
218
+ if (options?.projectPath) {
219
+ this.projectPath = options.projectPath;
220
+ }
221
+ if (options?.adoptExistingProject !== undefined) {
222
+ this.adoptExistingProject = options.adoptExistingProject;
223
+ }
224
+ if (options?.prepare) {
225
+ this.prepare = options.prepare;
226
+ }
227
+ this.startup = this.runStartup();
228
+ return this.startup;
229
+ }
230
+ async runStartup() {
231
+ await this.prepare?.();
139
232
  await this.connectWithRetries();
233
+ if (!this.projectPath)
234
+ return;
235
+ this.projectSetupError = null;
236
+ const projectPath = await this.startupProjectPath(this.projectPath);
237
+ try {
238
+ await this.createProject(projectPath);
239
+ }
240
+ catch (err) {
241
+ // Trigger: BM refused the project, e.g. a configured projectPath that
242
+ // differs from where a project of this name is stored (#1846).
243
+ // Why: a refusal is deterministic, so retrying startup cannot fix it,
244
+ // and failing startup would also fail project listing, the call a
245
+ // user needs to see the stored path. Other failures still fail
246
+ // startup so the next tool call retries them.
247
+ // Outcome: calls to the plugin's project throw this refusal; listing
248
+ // and calls naming another project still work.
249
+ if (!(err instanceof BmToolError) ||
250
+ parseRefusalPayload(err.toolMessage) === null) {
251
+ throw err;
252
+ }
253
+ this.projectSetupError = new ProjectUnavailableError(this.project, describeToolError(err));
254
+ log.error(this.projectSetupError.message);
255
+ }
256
+ }
257
+ // The folder startup creates the project at. Since #1846, BM refuses a
258
+ // create whose path differs from the stored one instead of reusing the
259
+ // project by name.
260
+ async startupProjectPath(configured) {
261
+ // Trigger: projectPath was not configured.
262
+ // Why: its default has changed between plugin releases ("." and
263
+ // ~/.basic-memory/openclaw/), and users create projects by hand, so an
264
+ // existing project may sit somewhere other than the default.
265
+ // Outcome: create at the stored folder, which BM treats as idempotent.
266
+ if (!this.adoptExistingProject)
267
+ return configured;
268
+ // With cloud credentials the listing holds one row per workspace for a
269
+ // name, and only the row attached to the local project carries
270
+ // local_path; a cloud-only row's path is tenant-relative. BM compares a
271
+ // local create against the local project, so only local_path qualifies.
272
+ const name = this.project.toLowerCase();
273
+ const localPath = parseProjectList(await this.callStructured("bm_project_list", {
274
+ output_format: "json",
275
+ })).find((project) => project.name.toLowerCase() === name && project.local_path)?.local_path;
276
+ if (!localPath)
277
+ return configured;
278
+ if (localPath !== configured) {
279
+ log.info(`using existing project "${this.project}" at ${localPath}; set projectPath to use another folder`);
280
+ }
281
+ return localPath;
282
+ }
283
+ // The refusal from the last project setup, or null when the project is
284
+ // usable. Status checks report it, since listing projects still succeeds.
285
+ projectUnavailableReason() {
286
+ return this.projectSetupError?.reason ?? null;
287
+ }
288
+ async waitForStartup() {
289
+ if (!this.startup)
290
+ return;
291
+ try {
292
+ await this.startup;
293
+ }
294
+ catch (err) {
295
+ // Trigger: the startup this call was waiting on failed.
296
+ // Why: the service no longer fails on a slow or failed start, so the
297
+ // first tool call afterwards is the place to recover.
298
+ // Outcome: one fresh attempt, shared by concurrent callers; its error
299
+ // reaches the tool if it fails too.
300
+ if (!this.serviceRunning)
301
+ throw err;
302
+ if (this.startupRetry === null) {
303
+ this.startupRetry = this.runStartup().finally(() => {
304
+ this.startupRetry = null;
305
+ });
306
+ this.startup = this.startupRetry;
307
+ }
308
+ await this.startupRetry;
309
+ }
310
+ }
311
+ isServiceRunning() {
312
+ return this.serviceRunning;
140
313
  }
141
314
  async stop() {
142
315
  this.shouldRun = false;
316
+ this.serviceRunning = false;
317
+ // Let an in-flight startup settle first, so it cannot reconnect after
318
+ // the disconnect below.
319
+ await this.startup?.catch(() => undefined);
320
+ this.startup = null;
143
321
  await this.disconnectCurrent(this.client, this.transport);
144
322
  this.client = null;
145
323
  this.transport = null;
@@ -297,6 +475,18 @@ export class BmClient {
297
475
  throw new Error(`BM MCP unavailable: ${getErrorMessage(lastErr)}`);
298
476
  }
299
477
  async callTool(name, args) {
478
+ await this.waitForStartup();
479
+ // Trigger: BM refused the plugin's project at startup.
480
+ // Why: the refusal concerns that project only; a call that names another
481
+ // project by name or id must still reach BM.
482
+ // Outcome: only calls routed to the plugin's project report the refusal.
483
+ if (this.projectSetupError && this.targetsPluginProject(args)) {
484
+ throw this.projectSetupError;
485
+ }
486
+ return this.callStructured(name, args);
487
+ }
488
+ // Ungated: startup itself calls this to create the project.
489
+ async callStructured(name, args) {
300
490
  const result = await this.callToolRaw(name, args);
301
491
  if (!isRecord(result) || result.structuredContent === undefined) {
302
492
  throw new Error(`BM MCP tool ${name} returned no structured payload`);
@@ -307,49 +497,61 @@ export class BmClient {
307
497
  }
308
498
  return structuredPayload;
309
499
  }
500
+ // Project names match case-insensitively in BM, so "Test-Project" routes
501
+ // to the plugin's "test-project" too.
502
+ targetsPluginProject(args) {
503
+ return (typeof args.project === "string" &&
504
+ args.project.toLowerCase() === this.project.toLowerCase());
505
+ }
310
506
  routedProject(project) {
311
507
  return project ?? this.project;
312
508
  }
313
- // project_id names one exact project, so it is sent alone: pairing it with
314
- // a name (or the plugin's default project) would make routing depend on
315
- // server-side precedence rather than on what the caller asked for.
509
+ // The 1.0 project parameter accepts either a name or an exact project UUID.
316
510
  routing(project, projectId) {
317
511
  if (projectId !== undefined)
318
- return { project_id: projectId };
512
+ return { project: projectId };
319
513
  return { project: this.routedProject(project) };
320
514
  }
321
515
  async ensureProject(projectPath) {
322
- const payload = await this.callTool("create_memory_project", {
323
- project_name: this.project,
324
- project_path: projectPath,
516
+ await this.waitForStartup();
517
+ await this.createProject(projectPath);
518
+ }
519
+ async createProject(projectPath) {
520
+ const payload = await this.callStructured("bm_project_create", {
521
+ name: this.project,
522
+ path: projectPath,
325
523
  set_default: true,
326
524
  output_format: "json",
327
525
  });
328
526
  if (!isRecord(payload)) {
329
- throw new Error("invalid create_memory_project response");
527
+ throw new Error("invalid bm_project_create response");
330
528
  }
331
529
  }
332
530
  async listWorkspaces() {
333
- const payload = await this.callTool("list_workspaces", {
334
- output_format: "json",
335
- });
336
- if (isRecord(payload) && Array.isArray(payload.workspaces)) {
337
- return payload.workspaces;
531
+ const projects = await this.listProjects();
532
+ const workspaces = new Map();
533
+ for (const project of projects) {
534
+ if (project.workspace_tenant_id && project.workspace_name) {
535
+ workspaces.set(project.workspace_tenant_id, {
536
+ tenant_id: project.workspace_tenant_id,
537
+ name: project.workspace_name,
538
+ workspace_type: project.workspace_type ?? null,
539
+ });
540
+ }
338
541
  }
339
- throw new Error("invalid list_workspaces response");
542
+ return [...workspaces.values()];
340
543
  }
341
544
  async listProjects(workspace) {
342
- const payload = await this.callTool("list_memory_projects", {
545
+ // Waits for startup but not for the plugin's project: when BM refused
546
+ // it, the listing is how the user finds where it is actually stored.
547
+ await this.waitForStartup();
548
+ const projects = parseProjectList(await this.callStructured("bm_project_list", {
343
549
  output_format: "json",
344
- });
345
- if (isRecord(payload) && Array.isArray(payload.projects)) {
346
- const projects = payload.projects;
347
- if (workspace) {
348
- return projects.filter((project) => projectMatchesWorkspace(project, workspace));
349
- }
350
- return projects;
550
+ }));
551
+ if (workspace) {
552
+ return projects.filter((project) => projectMatchesWorkspace(project, workspace));
351
553
  }
352
- throw new Error("invalid list_memory_projects response");
554
+ return projects;
353
555
  }
354
556
  async search(query, limit = 10, project, metadata) {
355
557
  const args = {
@@ -360,19 +562,21 @@ export class BmClient {
360
562
  };
361
563
  if (query)
362
564
  args.query = query;
363
- if (metadata?.filters)
364
- args.metadata_filters = metadata.filters;
365
- if (metadata?.tags)
366
- args.tags = metadata.tags;
367
- if (metadata?.status)
368
- args.status = metadata.status;
565
+ const filters = { ...metadata?.filters };
566
+ // Explicit predicates take precedence over convenience shortcuts.
567
+ if (metadata?.tags?.length && !("tags" in filters))
568
+ filters.tags = { $contains: metadata.tags };
569
+ if (metadata?.status && !("status" in filters))
570
+ filters.status = metadata.status;
571
+ if (Object.keys(filters).length)
572
+ args.filters = filters;
369
573
  if (metadata?.note_types)
370
574
  args.note_types = metadata.note_types;
371
575
  if (metadata?.entity_types)
372
- args.entity_types = metadata.entity_types;
373
- const payload = await this.callTool("search_notes", args);
576
+ args.items = metadata.entity_types.map((item) => item === "entity" ? "note" : item);
577
+ const payload = await this.callTool("bm_search", args);
374
578
  if (!isRecord(payload) || !Array.isArray(payload.results)) {
375
- throw new Error("invalid search_notes response");
579
+ throw new Error("invalid bm_search response");
376
580
  }
377
581
  return payload.results;
378
582
  }
@@ -383,16 +587,16 @@ export class BmClient {
383
587
  output_format: "json",
384
588
  ...this.routing(project, options.projectId),
385
589
  };
386
- const payload = await this.callTool("read_note", args);
590
+ const payload = await this.callTool("bm_read", args);
387
591
  if (!isRecord(payload)) {
388
- throw new Error("invalid read_note response");
592
+ throw new Error("invalid bm_read response");
389
593
  }
390
594
  const title = asString(payload.title);
391
595
  const permalink = asString(payload.permalink);
392
596
  const content = asString(payload.content);
393
597
  const filePath = asString(payload.file_path);
394
598
  if (!title || !permalink || content === null || !filePath) {
395
- throw new Error("invalid read_note payload");
599
+ throw new Error("invalid bm_read payload");
396
600
  }
397
601
  return {
398
602
  title,
@@ -423,30 +627,26 @@ export class BmClient {
423
627
  args.expected_checksum = options.expectedChecksum;
424
628
  let payload;
425
629
  try {
426
- payload = await this.callTool("write_note", args);
630
+ payload = await this.callTool("bm_write", args);
427
631
  }
428
632
  catch (err) {
429
633
  const refusal = err instanceof BmToolError ? parseRefusalPayload(err.toolMessage) : null;
430
- if (refusal?.error === "NOTE_ALREADY_EXISTS") {
431
- throw new NoteAlreadyExistsError(asString(refusal.title) ?? title, asString(refusal.permalink) ?? "");
634
+ if (refusal?.error === "ALREADY_EXISTS") {
635
+ throw new NoteAlreadyExistsError(asString(refusal.title) ?? title, asString(refusal.permalink) ?? "", asString(refusal.message) ?? undefined);
432
636
  }
433
- if (refusal?.error === "NOTE_REVISION_CONFLICT") {
434
- throw new NoteRevisionConflictError(asString(refusal.title) ?? title, asString(refusal.permalink), asString(refusal.currentChecksum));
637
+ if (refusal?.error === "REVISION_CONFLICT") {
638
+ throw new NoteRevisionConflictError(asString(refusal.title) ?? title, asString(refusal.permalink), asString(refusal.currentChecksum), asString(refusal.message) ?? undefined);
435
639
  }
436
640
  throw err;
437
641
  }
438
642
  if (!isRecord(payload)) {
439
- throw new Error("invalid write_note response");
440
- }
441
- // Older servers returned the refusal as a successful payload.
442
- if (payload.error === "NOTE_ALREADY_EXISTS") {
443
- throw new NoteAlreadyExistsError(asString(payload.title) ?? title, asString(payload.permalink) ?? "");
643
+ throw new Error("invalid bm_write response");
444
644
  }
445
645
  const resultTitle = asString(payload.title);
446
646
  const permalink = asString(payload.permalink);
447
647
  const filePath = asString(payload.file_path);
448
648
  if (!resultTitle || !permalink || !filePath) {
449
- throw new Error("invalid write_note payload");
649
+ throw new Error("invalid bm_write payload");
450
650
  }
451
651
  return {
452
652
  title: resultTitle,
@@ -461,33 +661,33 @@ export class BmClient {
461
661
  }
462
662
  async buildContext(url, depth = 1, project) {
463
663
  const args = {
464
- url,
664
+ identifier: url,
465
665
  depth,
466
666
  output_format: "json",
467
667
  project: this.routedProject(project),
468
668
  };
469
- const payload = await this.callTool("build_context", args);
669
+ const payload = await this.callTool("bm_context", args);
470
670
  if (!isRecord(payload) || !Array.isArray(payload.results)) {
471
- throw new Error("invalid build_context response");
671
+ throw new Error("invalid bm_context response");
472
672
  }
473
673
  return payload;
474
674
  }
475
675
  async recentActivity(timeframe = "24h", project) {
476
676
  const args = {
477
- timeframe,
677
+ since: timeframe,
478
678
  output_format: "json",
479
679
  project: this.routedProject(project),
480
680
  };
481
- const payload = await this.callTool("recent_activity", args);
482
- if (Array.isArray(payload)) {
483
- return payload;
681
+ const payload = await this.callTool("bm_recent", args);
682
+ if (isRecord(payload) && Array.isArray(payload.results)) {
683
+ return payload.results;
484
684
  }
485
- throw new Error("invalid recent_activity response");
685
+ throw new Error("invalid bm_recent response");
486
686
  }
487
687
  async editNote(identifier, operation, content, options = {}, project) {
488
688
  const args = {
489
689
  identifier,
490
- operation,
690
+ command: operation,
491
691
  content,
492
692
  output_format: "json",
493
693
  project: this.routedProject(project),
@@ -500,15 +700,15 @@ export class BmClient {
500
700
  args.expected_replacements = options.expected_replacements;
501
701
  if (options.metadata !== undefined)
502
702
  args.metadata = options.metadata;
503
- const payload = await this.callTool("edit_note", args);
703
+ const payload = await this.callTool("bm_edit", args);
504
704
  if (!isRecord(payload)) {
505
- throw new Error("invalid edit_note response");
705
+ throw new Error("invalid bm_edit response");
506
706
  }
507
707
  const title = asString(payload.title);
508
708
  const permalink = asString(payload.permalink);
509
709
  const filePath = asString(payload.file_path);
510
710
  if (!title || !permalink || !filePath) {
511
- throw new Error("invalid edit_note payload");
711
+ throw new Error("invalid bm_edit payload");
512
712
  }
513
713
  return {
514
714
  title,
@@ -524,12 +724,12 @@ export class BmClient {
524
724
  output_format: "json",
525
725
  project: this.routedProject(project),
526
726
  };
527
- const payload = await this.callTool("delete_note", args);
727
+ const payload = await this.callTool("bm_delete", args);
528
728
  if (!isRecord(payload)) {
529
- throw new Error("invalid delete_note response");
729
+ throw new Error("invalid bm_delete response");
530
730
  }
531
- if (payload.deleted !== true) {
532
- throw new Error(`delete_note did not delete "${identifier}"`);
731
+ if (payload.action !== "deleted") {
732
+ throw new Error(`bm_delete did not delete "${identifier}"`);
533
733
  }
534
734
  return {
535
735
  title: asString(payload.title) ?? identifier,
@@ -540,17 +740,17 @@ export class BmClient {
540
740
  async moveNote(identifier, newFolder, project) {
541
741
  const args = {
542
742
  identifier,
543
- destination_folder: newFolder,
743
+ destination: `${newFolder.replace(/\/+$/, "")}/`,
544
744
  output_format: "json",
545
745
  project: this.routedProject(project),
546
746
  };
547
- const payload = await this.callTool("move_note", args);
747
+ const payload = await this.callTool("bm_move", args);
548
748
  if (!isRecord(payload)) {
549
- throw new Error("invalid move_note response");
749
+ throw new Error("invalid bm_move response");
550
750
  }
551
- if (payload.moved !== true) {
751
+ if (payload.action !== "moved") {
552
752
  throw new Error(asString(payload.error) ??
553
- `move_note did not move "${identifier}" to "${newFolder}"`);
753
+ `bm_move did not move "${identifier}" to "${newFolder}"`);
554
754
  }
555
755
  return {
556
756
  title: asString(payload.title) ?? identifier,
@@ -568,9 +768,9 @@ export class BmClient {
568
768
  args.note_type = noteType;
569
769
  if (identifier)
570
770
  args.identifier = identifier;
571
- const payload = await this.callTool("schema_validate", args);
771
+ const payload = await this.callTool("bm_schema_validate", args);
572
772
  if (!isRecord(payload)) {
573
- throw new Error("invalid schema_validate response");
773
+ throw new Error("invalid bm_schema_validate response");
574
774
  }
575
775
  return payload;
576
776
  }
@@ -581,9 +781,9 @@ export class BmClient {
581
781
  output_format: "json",
582
782
  project: this.routedProject(project),
583
783
  };
584
- const payload = await this.callTool("schema_infer", args);
784
+ const payload = await this.callTool("bm_schema_infer", args);
585
785
  if (!isRecord(payload)) {
586
- throw new Error("invalid schema_infer response");
786
+ throw new Error("invalid bm_schema_infer response");
587
787
  }
588
788
  return payload;
589
789
  }
@@ -593,19 +793,50 @@ export class BmClient {
593
793
  output_format: "json",
594
794
  project: this.routedProject(project),
595
795
  };
596
- const payload = await this.callTool("schema_diff", args);
796
+ const payload = await this.callTool("bm_schema_diff", args);
597
797
  if (!isRecord(payload)) {
598
- throw new Error("invalid schema_diff response");
798
+ throw new Error("invalid bm_schema_diff response");
599
799
  }
600
800
  return payload;
601
801
  }
602
- async indexConversation(userMessage, assistantResponse) {
802
+ /**
803
+ * Append one user/assistant exchange to today's conversation note.
804
+ *
805
+ * With a turnKey the capture is idempotent: the entry carries a marker
806
+ * derived from the key, and a key already present in today's or
807
+ * yesterday's note is reported as a duplicate instead of written again.
808
+ * Yesterday is checked because a host retry can cross midnight.
809
+ */
810
+ async indexConversation(userMessage, assistantResponse, options = {}) {
811
+ const write = this.conversationWrites.then(() => this.writeConversationEntry(userMessage, assistantResponse, options.turnKey));
812
+ this.conversationWrites = write.catch(() => undefined);
813
+ return write;
814
+ }
815
+ async writeConversationEntry(userMessage, assistantResponse, turnKey) {
603
816
  const now = new Date();
604
- const dateStr = now.toISOString().split("T")[0];
817
+ const dateStr = conversationDate(now);
605
818
  const timeStr = now.toTimeString().slice(0, 5);
606
819
  const title = `conversations-${dateStr}`;
820
+ const marker = turnKey ? conversationTurnMarker(turnKey) : null;
821
+ // Trigger: the host supplied an advancement key for this turn.
822
+ // Why: hosts retry commits after a crash, and a second append would
823
+ // duplicate the exchange in the note.
824
+ // Outcome: an already-recorded key short-circuits before any write.
825
+ if (marker) {
826
+ const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
827
+ for (const candidate of [
828
+ title,
829
+ `conversations-${conversationDate(yesterday)}`,
830
+ ]) {
831
+ if (await this.noteContains(candidate, marker)) {
832
+ log.debug(`conversation turn already recorded in: ${candidate}`);
833
+ return "duplicate";
834
+ }
835
+ }
836
+ }
607
837
  const entry = [
608
838
  `### ${timeStr}`,
839
+ ...(marker ? [marker] : []),
609
840
  "",
610
841
  "**User:**",
611
842
  userMessage,
@@ -618,7 +849,7 @@ export class BmClient {
618
849
  try {
619
850
  await this.editNote(title, "append", entry);
620
851
  log.debug(`appended conversation to: ${title}`);
621
- return;
852
+ return "committed";
622
853
  }
623
854
  catch (err) {
624
855
  if (!isNoteNotFoundError(err)) {
@@ -639,12 +870,19 @@ export class BmClient {
639
870
  "",
640
871
  entry,
641
872
  ].join("\n");
873
+ await this.writeNote(title, content, "conversations");
874
+ log.debug(`created conversation note: ${title}`);
875
+ return "committed";
876
+ }
877
+ async noteContains(identifier, text) {
642
878
  try {
643
- await this.writeNote(title, content, "conversations");
644
- log.debug(`created conversation note: ${title}`);
879
+ const note = await this.readNote(identifier);
880
+ return note.content.includes(text);
645
881
  }
646
882
  catch (err) {
647
- log.error("conversation index failed", err);
883
+ if (isNoteNotFoundError(err))
884
+ return false;
885
+ throw err;
648
886
  }
649
887
  }
650
888
  getProject() {