roam-research-mcp 6.1.1 → 6.3.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.
package/README.md CHANGED
@@ -20,6 +20,22 @@ Whether you want to give Claude superpowers over your knowledge base or just wan
20
20
 
21
21
  ![Before and after: copy-pasting notes into Roam by hand, versus Claude and your terminal reading and writing the graph directly — install with npm i -g roam-research-mcp, then `roam save "idea"` or pipe with `echo "Buy milk" | roam save --todo`](./roam-research-mcp-sketchnote.png)
22
22
 
23
+ ## What's New in v6.3
24
+
25
+ **The CLI and the MCP tools agree on tables, headings and nesting.** A `table` in `roam batch` was laid out column by column; it now uses the same row-by-row layout as `roam_create_table`. `roam save` nests what follows a heading by the same rule as `roam_import_markdown`, including when the content under the heading is an indented list. In `roam_create_outline`, `heading` and `children_view_type` now land on the item that asked for them at any depth, where a nested item's heading used to end up on a later top-level block.
26
+
27
+ **Text that only looks like markup is stored as you wrote it.** `2 * 3 * 4` used to be stored as `2 __ 3 __ 4`, and `if a == b and c == d` as `if a ^^ b and c ^^ d`, because any two markers on a line were read as emphasis or a highlight. A marker now counts only when it touches the text it wraps: `*word*` is emphasis, `* word *` is not.
28
+
29
+ **Upgrading:** a `table` row in `roam batch` needs a `label` and one cell for each header after the first, or the batch is refused before anything is written. Text that starts with `# `, `## ` or `### ` is now a heading in `roam_create_page` content and in a one-line `roam_import_markdown`. `roam save` of a file with a heading and indented content now nests that content under the heading; `--flatten` keeps the old result. See the [changelog](CHANGELOG.md) for the full list.
30
+
31
+ ## What's New in v6.2
32
+
33
+ **`roam batch` does what its help says.** Outline items can be plain strings (`"items": ["Goal 1", "Goal 2"]`) or `{text, level?}` objects. `--dry-run` writes nothing: a page that does not exist yet is listed in the plan, not created. `parent: "daily"` means today's daily page. A page created with `as` can be used as a parent, so the example in `roam batch --help` runs as written.
34
+
35
+ **Searches skip superseded block versions.** When you give a block a new version in Roam, the old text stays in the graph as a block of its own. Page reads never showed those, but searches did, so an old `{{[[TODO]]}}` could come back as an open task. Searches now return only the version in use. To see the others, fetch the block: `roam_fetch_block` and `roam get <uid>` list every version, oldest first, and mark the one in use.
36
+
37
+ **Upgrading:** search results can shrink, since superseded versions and the blocks under them are no longer returned. `parent: "daily"` no longer reaches a page titled "daily"; use that page's UID. An outline `level` of 0 is refused; use 1. See the [changelog](CHANGELOG.md) for the full list.
38
+
23
39
  ## What's New in v6.1
24
40
 
25
41
  **Deletes that delete nothing now say so.** Roam's API accepts a `delete-block` for a UID that does not exist and reports success, so a mistyped UID, a stale one, or the wrong graph used to look like a successful delete. `roam_process_batch_actions` and `roam batch` now check delete UIDs first and report missing ones as `BLOCK_NOT_FOUND`, with a `not_found` list naming each one. The rest of the batch still runs and is listed under `committed`.
@@ -46,6 +46,20 @@ export async function resolveDailyPageUid(graph) {
46
46
  const dailyTitle = getDailyPageTitle();
47
47
  return resolvePageUid(graph, dailyTitle);
48
48
  }
49
+ /**
50
+ * The `parent` value that means today's daily page. The help has always listed
51
+ * it, but nothing read it, so it was looked up, and created, as a page titled
52
+ * "daily" (issue #36).
53
+ */
54
+ export const DAILY_PARENT = 'daily';
55
+ /**
56
+ * What a plan shows in place of a page UID it does not have: `--simulate`
57
+ * looks nothing up, and `--dry-run` does not create a page that is missing.
58
+ * Never sent to Roam, and shaped so it cannot be read as a UID.
59
+ */
60
+ export function pageStandIn(title) {
61
+ return `<page: ${title}>`;
62
+ }
49
63
  /**
50
64
  * Check if a string looks like a valid Roam UID (not a page title)
51
65
  */
@@ -75,7 +89,10 @@ export function collectPageTitles(commands) {
75
89
  // Commands that can have 'parent' param — if it looks like a page title, resolve it
76
90
  if ('parent' in params && typeof params.parent === 'string') {
77
91
  const parent = params.parent;
78
- if (!isUidFormat(parent)) {
92
+ if (parent === DAILY_PARENT) {
93
+ titles.add(getDailyPageTitle());
94
+ }
95
+ else if (!isUidFormat(parent)) {
79
96
  titles.add(parent);
80
97
  }
81
98
  }
@@ -132,7 +149,8 @@ export function createResolutionContext() {
132
149
  placeholders: new Map(),
133
150
  levelStack: [],
134
151
  currentParent: null,
135
- dailyPageUid: null
152
+ dailyPageUid: null,
153
+ internalNames: 0
136
154
  };
137
155
  }
138
156
  /**
@@ -145,6 +163,10 @@ export function resolveParentRef(ref, context) {
145
163
  const name = placeholderMatch[1];
146
164
  return context.placeholders.get(name) || `{{uid:${name}}}`;
147
165
  }
166
+ // "daily" is today's daily page, never a page title
167
+ if (ref === DAILY_PARENT) {
168
+ return context.dailyPageUid ?? context.pageUids.get(getDailyPageTitle()) ?? null;
169
+ }
148
170
  // Check if it's a resolved page title
149
171
  if (context.pageUids.has(ref)) {
150
172
  return context.pageUids.get(ref);
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { resolveParentRef, generatePlaceholder } from './resolver.js';
5
5
  import { sanitizeTagName } from '../../utils/helpers.js';
6
+ import { buildTableActions } from '../../tools/operations/table.js';
6
7
  /**
7
8
  * Translate a single command to batch actions
8
9
  * May return multiple actions (e.g., table, outline)
@@ -16,7 +17,7 @@ export function translateCommand(command, context) {
16
17
  case 'delete':
17
18
  return translateDelete(command);
18
19
  case 'move':
19
- return translateMove(command);
20
+ return translateMove(command, context);
20
21
  case 'todo':
21
22
  return translateTodo(command, context);
22
23
  case 'table':
@@ -70,6 +71,18 @@ function registerPlaceholder(name, context) {
70
71
  context.placeholders.set(name, placeholder);
71
72
  return placeholder;
72
73
  }
74
+ /**
75
+ * A name for a block the caller did not name with `as`, unique in this batch.
76
+ *
77
+ * These were stamped with `Date.now()`. Commands are translated in one
78
+ * synchronous pass, so two of a kind got the same stamp and the same names,
79
+ * and the batch created the second command's blocks under the first one's
80
+ * UIDs. A count held by the batch cannot repeat.
81
+ */
82
+ function internalName(kind, context) {
83
+ context.internalNames += 1;
84
+ return `_${kind}_${context.internalNames}`;
85
+ }
73
86
  /**
74
87
  * Update level stack for hierarchy tracking
75
88
  */
@@ -168,13 +181,15 @@ function translateDelete(cmd) {
168
181
  uid: cmd.params.uid
169
182
  }];
170
183
  }
171
- function translateMove(cmd) {
184
+ function translateMove(cmd, context) {
172
185
  const { params } = cmd;
173
186
  return [{
174
187
  action: 'move-block',
175
188
  uid: params.uid,
176
189
  location: {
177
- 'parent-uid': params.parent,
190
+ // Resolved like every other parent. Passed through raw, a page title or
191
+ // "daily" reached the batch as a "UID" and was refused there.
192
+ 'parent-uid': getParentUid({ parent: params.parent }, context),
178
193
  order: params.order ?? 'last'
179
194
  }
180
195
  }];
@@ -198,60 +213,53 @@ function translateTodo(cmd, context) {
198
213
  function translateTable(cmd, context) {
199
214
  const { params } = cmd;
200
215
  const parentUid = getParentUid(params, context);
201
- const actions = [];
202
- // Table container
203
- const tableContainerPlaceholder = params.as
204
- ? registerPlaceholder(params.as, context)
205
- : registerPlaceholder(`_table_${Date.now()}`, context);
206
- actions.push({
207
- action: 'create-block',
208
- uid: tableContainerPlaceholder,
209
- string: '{{[[table]]}}',
210
- location: {
211
- 'parent-uid': parentUid,
212
- order: params.order ?? 'last'
213
- }
214
- });
215
- // Create columns (headers)
216
- const columnPlaceholders = [];
217
- for (let i = 0; i < params.headers.length; i++) {
218
- const colPlaceholder = registerPlaceholder(`_col_${i}_${Date.now()}`, context);
219
- columnPlaceholders.push(colPlaceholder);
220
- actions.push({
221
- action: 'create-block',
222
- uid: colPlaceholder,
223
- string: params.headers[i] || ' ',
224
- location: {
225
- 'parent-uid': tableContainerPlaceholder,
226
- order: i
227
- }
228
- });
216
+ // The layout is roam_create_table's: one builder, so the CLI and the MCP
217
+ // tool cannot disagree about it. This used to hang every cell under its
218
+ // column's header, which Roam reads as a table turned on its side (#40).
219
+ const scope = internalName('table', context);
220
+ const tableName = params.as ?? scope;
221
+ registerPlaceholder(tableName, context);
222
+ return buildTableActions({
223
+ parent_uid: parentUid,
224
+ order: params.order,
225
+ headers: params.headers,
226
+ rows: params.rows
227
+ }, { table: tableName, cellPrefix: `${scope}_` });
228
+ }
229
+ /**
230
+ * Check an outline's `items` and bring each one to `{text, level, ...}`.
231
+ *
232
+ * A plain string is a level-1 block, which is what the help has always shown,
233
+ * and a missing `level` is 1. Anything else is refused by name: a level that
234
+ * is not a whole number of 1 or more used to reach `levelStack.length = level`
235
+ * and surface as a bare "Invalid array length" (issue #34).
236
+ *
237
+ * Throws with the item's position, e.g. `items[2].level must be ...`.
238
+ */
239
+ export function normalizeOutlineItems(items) {
240
+ if (!Array.isArray(items)) {
241
+ throw new Error(`'items' must be an array of strings or {text, level?} objects`);
229
242
  }
230
- // Create rows under each column
231
- for (let rowIdx = 0; rowIdx < params.rows.length; rowIdx++) {
232
- const row = params.rows[rowIdx];
233
- // First column gets the row label
234
- actions.push({
235
- action: 'create-block',
236
- string: row.label || ' ',
237
- location: {
238
- 'parent-uid': columnPlaceholders[0],
239
- order: rowIdx
240
- }
241
- });
242
- // Remaining columns get the cells
243
- for (let cellIdx = 0; cellIdx < row.cells.length; cellIdx++) {
244
- actions.push({
245
- action: 'create-block',
246
- string: row.cells[cellIdx] || ' ',
247
- location: {
248
- 'parent-uid': columnPlaceholders[cellIdx + 1],
249
- order: rowIdx
250
- }
251
- });
243
+ return items.map((item, i) => {
244
+ if (typeof item === 'string') {
245
+ return { text: item, level: 1 };
252
246
  }
253
- }
254
- return actions;
247
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
248
+ throw new Error(`items[${i}] must be a string or a {text, level?} object (got ${JSON.stringify(item)})`);
249
+ }
250
+ const { text, level: given } = item;
251
+ if (typeof text !== 'string') {
252
+ throw new Error(`items[${i}].text must be a string (got ${JSON.stringify(text)})`);
253
+ }
254
+ // "2" worked before by coercion, so it still does.
255
+ const level = given == null ? 1
256
+ : typeof given === 'string' && given.trim() !== '' ? Number(given)
257
+ : given;
258
+ if (typeof level !== 'number' || !Number.isInteger(level) || level < 1) {
259
+ throw new Error(`items[${i}].level must be a whole number, 1 or more (got ${JSON.stringify(given)})`);
260
+ }
261
+ return { ...item, text, level };
262
+ });
255
263
  }
256
264
  function translateOutline(cmd, context) {
257
265
  const { params } = cmd;
@@ -260,7 +268,7 @@ function translateOutline(cmd, context) {
260
268
  // Reset level stack with outline parent
261
269
  context.currentParent = parentUid;
262
270
  context.levelStack = [];
263
- for (const item of params.items) {
271
+ for (const item of normalizeOutlineItems(params.items)) {
264
272
  let itemParentUid;
265
273
  if (item.level === 1) {
266
274
  itemParentUid = parentUid;
@@ -281,7 +289,7 @@ function translateOutline(cmd, context) {
281
289
  }
282
290
  };
283
291
  // Register placeholder
284
- const placeholderName = item.as || `_outline_${actions.length}_${Date.now()}`;
292
+ const placeholderName = item.as || internalName('outline', context);
285
293
  action.uid = registerPlaceholder(placeholderName, context);
286
294
  if (item.heading) {
287
295
  action.heading = item.heading;
@@ -335,8 +343,9 @@ function translatePage(cmd, context) {
335
343
  function translateCodeblock(cmd, context) {
336
344
  const { params } = cmd;
337
345
  const parentUid = getParentUid(params, context);
338
- // Format code with triple backticks
339
- const codeContent = '```' + params.language + '\n' + params.code + '\n```';
346
+ // Format code with triple backticks. `language` is optional: left out, it
347
+ // used to be written into the fence as the word "undefined".
348
+ const codeContent = '```' + (params.language ?? '') + '\n' + params.code + '\n```';
340
349
  const action = {
341
350
  action: 'create-block',
342
351
  string: codeContent,
@@ -350,6 +359,25 @@ function translateCodeblock(cmd, context) {
350
359
  }
351
360
  return [action];
352
361
  }
362
+ /**
363
+ * Point actions at pages created by `page` commands.
364
+ *
365
+ * A `page` command's `as` name stands for a page UID, and that UID exists only
366
+ * once the page does, which is after translation. Until then a parent of
367
+ * `{{name}}` is carried as `{{uid:name}}`, the form block placeholders use;
368
+ * left like that, the batch takes it for a block nobody defined and refuses
369
+ * the whole run. Called with the UIDs once the pages exist.
370
+ */
371
+ export function bindPagePlaceholders(actions, pageUidsByName) {
372
+ const uidByPlaceholder = new Map(Array.from(pageUidsByName, ([name, uid]) => [generatePlaceholder(name), uid]));
373
+ return actions.map(action => {
374
+ const parent = action.location?.['parent-uid'];
375
+ const pageUid = parent === undefined ? undefined : uidByPlaceholder.get(parent);
376
+ if (!action.location || pageUid === undefined)
377
+ return action;
378
+ return { ...action, location: { ...action.location, 'parent-uid': pageUid } };
379
+ });
380
+ }
353
381
  /**
354
382
  * Translate all commands to batch actions
355
383
  */
@@ -4,9 +4,10 @@ import { BatchOperations } from '../../tools/operations/batch.js';
4
4
  import { PageOperations } from '../../tools/operations/pages.js';
5
5
  import { printDebug, exitWithError } from '../utils/output.js';
6
6
  import { resolveGraph } from '../utils/graph.js';
7
- import { collectPageTitles, resolveAllPages, resolveDailyPageUid, needsDailyPage, createResolutionContext, getDailyPageTitle } from '../batch/resolver.js';
8
- import { translateAllCommands } from '../batch/translator.js';
7
+ import { collectPageTitles, resolveAllPages, resolveDailyPageUid, needsDailyPage, createResolutionContext, getDailyPageTitle, pageStandIn } from '../batch/resolver.js';
8
+ import { translateAllCommands, normalizeOutlineItems, bindPagePlaceholders } from '../batch/translator.js';
9
9
  import { readStdin } from '../utils/input.js';
10
+ import { validateTableInput } from '../../tools/operations/table.js';
10
11
  // Required params per command type
11
12
  const REQUIRED_PARAMS = {
12
13
  todo: ['text'],
@@ -49,6 +50,29 @@ function validateCommands(commands) {
49
50
  throw new Error(`[${i}] ${cmdType}: missing required param '${param}'`);
50
51
  }
51
52
  }
53
+ // Outline items are checked here, with the command's position, rather
54
+ // than left to fail somewhere inside the translation.
55
+ if (cmdType === 'outline') {
56
+ try {
57
+ normalizeOutlineItems(params.items);
58
+ }
59
+ catch (err) {
60
+ throw new Error(`[${i}] outline: ${err instanceof Error ? err.message : String(err)}`);
61
+ }
62
+ }
63
+ // A table is checked the way roam_create_table checks it, so the two
64
+ // refuse the same tables, and here rather than partway through a write.
65
+ if (cmdType === 'table') {
66
+ const check = validateTableInput({
67
+ parent_uid: String(params.parent),
68
+ headers: params.headers,
69
+ rows: params.rows
70
+ });
71
+ if (!check.valid) {
72
+ const problems = check.errors.map(e => `${e.field}: ${e.message}`).join('; ');
73
+ throw new Error(`[${i}] table: ${problems}`);
74
+ }
75
+ }
52
76
  validated.push(cmd);
53
77
  }
54
78
  return validated;
@@ -148,12 +172,16 @@ Command schemas:
148
172
  delete: {uid}
149
173
  move: {uid, parent, order?}
150
174
  page: {title, as?, content?: [{text, level, heading?}...]}
151
- outline: {parent, items: [string...]}
175
+ outline: {parent, items: [string | {text, level?, heading?, as?}...]}
152
176
  table: {parent, headers: [string...], rows: [{label, cells: [string...]}...]}
153
177
  remember: {text, categories?: [string...]}
154
178
  codeblock: {parent, code, language?}
155
179
 
156
- Parent accepts: block UID, "daily", page title, or {{placeholder}}
180
+ Parent accepts: block UID, "daily" (today's daily page), page title, or {{placeholder}}
181
+
182
+ A page title that does not exist yet is created. Creating a page also writes
183
+ "Created page: [[Title]]" to today's daily page and "Processed: [[date]]" to
184
+ the new page. --dry-run lists such pages and creates nothing.
157
185
 
158
186
  Example:
159
187
  [
@@ -213,6 +241,13 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
213
241
  // Simulate mode: validate structure without connecting to Roam
214
242
  if (options.simulate) {
215
243
  const context = createResolutionContext();
244
+ // Nothing is looked up offline, so every page a command names gets a
245
+ // stand-in UID. Without one, a page title, "daily" or a bare todo
246
+ // could not be translated and failed as if the input were wrong.
247
+ for (const title of collectPageTitles(commands)) {
248
+ context.pageUids.set(title, pageStandIn(title));
249
+ }
250
+ context.dailyPageUid = pageStandIn(getDailyPageTitle());
216
251
  const { actions, pageCommands } = translateAllCommands(commands, context);
217
252
  console.log('\n[SIMULATE] Validation passed\n');
218
253
  console.log(`Commands: ${commands.length}`);
@@ -232,6 +267,8 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
232
267
  // Phase 1: Collect and resolve page titles (from 'page' AND 'parent' params)
233
268
  const context = createResolutionContext();
234
269
  const pageTitles = collectPageTitles(commands);
270
+ // Pages a dry run found missing: reported in the plan, never created.
271
+ const missingPages = [];
235
272
  if (pageTitles.size > 0) {
236
273
  if (options.debug) {
237
274
  printDebug('Pages to resolve', Array.from(pageTitles));
@@ -242,7 +279,15 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
242
279
  }
243
280
  // Auto-create unresolved pages (e.g., parent: "Page Title" for a page that doesn't exist yet)
244
281
  const unresolved = Array.from(pageTitles).filter(t => !context.pageUids.has(t));
245
- if (unresolved.length > 0) {
282
+ if (options.dryRun) {
283
+ // A dry run writes nothing. This creation used to run before the
284
+ // dry-run exit below, so previewing a batch created its pages.
285
+ for (const title of unresolved) {
286
+ context.pageUids.set(title, pageStandIn(title));
287
+ missingPages.push(title);
288
+ }
289
+ }
290
+ else if (unresolved.length > 0) {
246
291
  if (options.debug) {
247
292
  printDebug('Auto-creating pages', unresolved);
248
293
  }
@@ -266,7 +311,8 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
266
311
  }
267
312
  // Resolve daily page if needed
268
313
  if (needsDailyPage(commands)) {
269
- const dailyUid = await resolveDailyPageUid(graph);
314
+ // Phase 1 already has it: found, created, or a dry run's stand-in.
315
+ const dailyUid = context.pageUids.get(getDailyPageTitle()) ?? await resolveDailyPageUid(graph);
270
316
  if (!dailyUid) {
271
317
  exitWithError(`Daily page not found: "${getDailyPageTitle()}"`);
272
318
  }
@@ -285,19 +331,24 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
285
331
  // Dry run: show actions and exit
286
332
  if (options.dryRun) {
287
333
  console.log('\n[DRY RUN] Planned actions:\n');
288
- if (pageCommands.length > 0) {
334
+ // A page both named by a `page` command and used as a parent is one page.
335
+ const impliedPages = missingPages.filter(t => !pageCommands.some(pc => pc.params.title === t));
336
+ if (pageCommands.length + impliedPages.length > 0) {
289
337
  console.log('Page creations:');
290
338
  for (const pc of pageCommands) {
291
339
  const as = pc.params.as ? ` (as: {{${pc.params.as}}})` : '';
292
340
  console.log(` - "${pc.params.title}"${as}`);
293
341
  }
342
+ for (const title of impliedPages) {
343
+ console.log(` - "${title}" (does not exist yet)`);
344
+ }
294
345
  console.log('');
295
346
  }
296
347
  if (actions.length > 0) {
297
348
  console.log('Batch actions:');
298
349
  console.log(actions.map((a, i) => formatAction(a, i)).join('\n'));
299
350
  }
300
- console.log(`\nTotal: ${pageCommands.length} page(s), ${actions.length} action(s)`);
351
+ console.log(`\nTotal: ${pageCommands.length + impliedPages.length} page(s), ${actions.length} action(s)`);
301
352
  return;
302
353
  }
303
354
  // Phase 3: Execute page commands (in parallel where possible)
@@ -328,7 +379,12 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
328
379
  let batchResult = { success: true, actions_attempted: 0 };
329
380
  if (actions.length > 0) {
330
381
  const batchOps = new BatchOperations(graph);
331
- batchResult = await batchOps.processBatch(actions);
382
+ // The pages exist now, so a parent of {{name}} can become their UID.
383
+ const pagePlaceholders = new Map(pageCommands.flatMap(pc => {
384
+ const uid = pc.params.as ? context.placeholders.get(pc.params.as) : undefined;
385
+ return pc.params.as && uid ? [[pc.params.as, uid]] : [];
386
+ }));
387
+ batchResult = await batchOps.processBatch(bindPagePlaceholders(actions, pagePlaceholders));
332
388
  if (!batchResult.success) {
333
389
  const errorMsg = typeof batchResult.error === 'string'
334
390
  ? batchResult.error
@@ -4,7 +4,7 @@ import { basename } from 'path';
4
4
  import { PageOperations } from '../../tools/operations/pages.js';
5
5
  import { TodoOperations } from '../../tools/operations/todos.js';
6
6
  import { BatchOperations } from '../../tools/operations/batch.js';
7
- import { parseMarkdown, generateBlockUid, parseMarkdownHeadingLevel } from '../../markdown-utils.js';
7
+ import { parseMarkdown, nestUnderHeadings, generateBlockUid, parseMarkdownHeadingLevel } from '../../markdown-utils.js';
8
8
  import { printDebug, exitWithError } from '../utils/output.js';
9
9
  import { resolveGraph } from '../utils/graph.js';
10
10
  import { readStdin } from '../utils/input.js';
@@ -31,55 +31,6 @@ function flattenNodes(nodes, baseLevel = 1) {
31
31
  }
32
32
  return result;
33
33
  }
34
- /**
35
- * Infer hierarchy from heading levels when all blocks are at the same level.
36
- * This handles prose-style markdown where headings (# ## ###) define structure
37
- * without explicit indentation.
38
- *
39
- * Example: "# Title\n## Chapter\nContent" becomes:
40
- * - Title (level 1, H1)
41
- * - Chapter (level 2, H2)
42
- * - Content (level 3)
43
- */
44
- function adjustLevelsForHeadingHierarchy(blocks) {
45
- if (blocks.length === 0)
46
- return blocks;
47
- // Only apply heading-based adjustment when:
48
- // 1. All blocks are at the same level (no indentation-based hierarchy)
49
- // 2. There are headings present
50
- const allSameLevel = blocks.every(b => b.level === blocks[0].level);
51
- const hasHeadings = blocks.some(b => b.heading);
52
- if (!allSameLevel || !hasHeadings) {
53
- // Indentation-based hierarchy exists, preserve it
54
- return blocks;
55
- }
56
- const result = [];
57
- // Track heading stack: each entry is { headingLevel: 1|2|3, adjustedLevel: number }
58
- const headingStack = [];
59
- for (const block of blocks) {
60
- if (block.heading) {
61
- // Pop headings of same or lower priority (higher h-number)
62
- while (headingStack.length > 0 &&
63
- headingStack[headingStack.length - 1].headingLevel >= block.heading) {
64
- headingStack.pop();
65
- }
66
- // New heading level is one deeper than parent heading (or 1 if no parent)
67
- const adjustedLevel = headingStack.length > 0
68
- ? headingStack[headingStack.length - 1].adjustedLevel + 1
69
- : 1;
70
- headingStack.push({ headingLevel: block.heading, adjustedLevel });
71
- result.push({ ...block, level: adjustedLevel });
72
- }
73
- else {
74
- // Content: nest under current heading context
75
- const adjustedLevel = headingStack.length > 0
76
- ? headingStack[headingStack.length - 1].adjustedLevel + 1
77
- : 1;
78
- result.push({ ...block, level: adjustedLevel });
79
- }
80
- }
81
- return result;
82
- }
83
34
  /**
84
35
  * Check if content looks like a JSON array
85
36
  */
@@ -338,9 +289,11 @@ JSON format (--json):
338
289
  else if (isFile || content.includes('\n')) {
339
290
  // Multi-line content: parse as markdown
340
291
  const nodes = parseMarkdown(content);
341
- const flattened = flattenNodes(nodes);
342
- // Apply heading hierarchy unless --flatten is specified
343
- contentBlocks = options.flatten ? flattened : adjustLevelsForHeadingHierarchy(flattened);
292
+ // What follows a heading goes under it, unless --flatten asks for
293
+ // only the nesting the indentation gives. This is the rule
294
+ // roam_import_markdown uses. `save` had one of its own, which gave
295
+ // up as soon as any line in the file was indented.
296
+ contentBlocks = flattenNodes(options.flatten ? nodes : nestUnderHeadings(nodes));
344
297
  }
345
298
  else {
346
299
  // Single line text: detect heading syntax and strip hashes
@@ -82,9 +82,20 @@ export function formatBlockOutput(block, options) {
82
82
  }
83
83
  const displayBlocks = options.flat ? flattenBlocks([block]) : [block];
84
84
  const escape = needsNewlineEscaping(collectBlockStrings(displayBlocks));
85
- const body = blocksToMarkdown(displayBlocks, 0, escape);
85
+ const body = blocksToMarkdown(displayBlocks, 0, escape) + formatVersions(block);
86
86
  return escape ? `${ESCAPED_NEWLINES_MARKER}\n\n${body}` : body;
87
87
  }
88
+ /**
89
+ * The versions of a fetched block, for the markdown output: one line each,
90
+ * oldest first, with the UID a reader needs to fetch that version. Empty for a
91
+ * block that has none, so its output is unchanged.
92
+ */
93
+ function formatVersions(block) {
94
+ if (!block.versions?.length)
95
+ return '';
96
+ const lines = block.versions.map((v) => `${v.active ? '*' : ' '} ((${v.uid})) ${v.string.replace(/\n/g, '⏎')}`);
97
+ return `\n\nVersions (${lines.length}, oldest first, * marks the one in use):\n${lines.join('\n')}`;
98
+ }
88
99
  /**
89
100
  * Format search results for output
90
101
  */
@@ -82,13 +82,21 @@ function convertToRoamMarkdown(text) {
82
82
  // Handle double asterisks/underscores (bold)
83
83
  text = text.replace(/\*\*(.+?)\*\*/g, '**$1**'); // Preserve double asterisks
84
84
  // Handle single asterisks/underscores (italic)
85
- text = text.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, '__$1__'); // Single asterisk to double underscore
85
+ //
86
+ // A marker only opens emphasis when the text it wraps starts right after it,
87
+ // and only closes it when that text ends right before it: "*word*", never
88
+ // "* word *". Without that rule any two markers on a line were a pair, so
89
+ // "2 * 3 * 4" became "2 __ 3 __ 4", and a star bullet's own asterisk was
90
+ // paired with the emphasis later on its line. The same holds for highlights
91
+ // below ("if a == b and c == d").
92
+ text = text.replace(/(?<!\*)\*(?![\s*])(.+?)(?<![\s*])\*(?!\*)/g, '__$1__'); // Single asterisk to double underscore
86
93
  // Single underscore to italic, but only at word boundaries. Underscores flanked by
87
94
  // word chars (\w includes _) are literal per CommonMark, so snake_case filenames and
88
95
  // URLs like /wiki/Ning_Li_(physicist) are left intact instead of becoming __Li__.
89
- text = text.replace(/(?<!\w)_(?!_)(.+?)_(?!\w)/g, '__$1__');
90
- // Handle highlights
91
- text = text.replace(/==(.+?)==/g, '^^$1^^');
96
+ text = text.replace(/(?<!\w)_(?![\s_])(.+?)(?<!\s)_(?!\w)/g, '__$1__');
97
+ // Handle highlights. Exactly two equals signs make a marker: a longer run is
98
+ // a rule ("=====") or a comparison ("a === b"), not a highlight.
99
+ text = text.replace(/(?<!=)==(?![\s=])(.+?)(?<![\s=])==(?!=)/g, '^^$1^^');
92
100
  // Convert tasks
93
101
  text = text.replace(/- \[ \]/g, '- {{[[TODO]]}}');
94
102
  text = text.replace(/- \[x\]/g, '- {{[[DONE]]}}');
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Roam's block versions.
3
+ *
4
+ * Giving a block a new version does not edit it. The old text stays in the
5
+ * graph as a block of its own, with its own UID and its own children, and a
6
+ * container entity lists every version of the block under `:vc/blocks`.
7
+ *
8
+ * A superseded version is taken out of its parent's `:block/children`, and
9
+ * that is the only thing that marks it: it keeps `:block/string`,
10
+ * `:block/page`, `:block/parents`, `:block/refs` and its timestamps. So a read
11
+ * that walks `:block/children` (every page read) shows the version in use and
12
+ * nothing else, while a query that matches blocks by attribute (every search)
13
+ * matches the old text too, and the blocks nested under it, as if they were
14
+ * live. A superseded `{{[[TODO]]}}` comes back as an open task.
15
+ *
16
+ * This module is how the content-read paths tell the two apart. Like the hide
17
+ * filter beside it, it is not applied to `roam_datomic_query`, which reads the
18
+ * database as it is.
19
+ *
20
+ * Observed on a live graph on 2026-11-24; Roam does not document the model.
21
+ */
22
+ import { q } from '@roam-research/roam-api-sdk';
23
+ import { isHiddenBlockString } from './hidden.js';
24
+ /** Same trade-off, and the same 30 seconds, as the hidden-UID closure. */
25
+ const supersededUidCache = new WeakMap();
26
+ const TTL_MS = 30_000;
27
+ /** Test seam: drop the memoised set so a test can observe a fresh query. */
28
+ export function clearSupersededUidCache(graph) {
29
+ supersededUidCache.delete(graph);
30
+ }
31
+ /**
32
+ * Every UID a search should leave out because it belongs to a version no
33
+ * longer in use: the superseded versions themselves and everything nested
34
+ * under them.
35
+ *
36
+ * A version is superseded when it is in a `:vc/blocks` set and in nobody's
37
+ * `:block/children`. Its descendants are found through `:block/parents`, which
38
+ * Roam keeps for every level, so one clause covers the whole subtree.
39
+ *
40
+ * Returns an EMPTY set when the query fails, as `collectHiddenUids` does: a
41
+ * filter that takes every search down with it is worse than one that lets an
42
+ * old version through.
43
+ */
44
+ export async function collectSupersededUids(graph) {
45
+ const cached = supersededUidCache.get(graph);
46
+ if (cached && Date.now() - cached.at < TTL_MS)
47
+ return cached.uids;
48
+ const uids = new Set();
49
+ try {
50
+ const versions = (await q(graph, `[:find ?uid
51
+ :where [?vc :vc/blocks ?v]
52
+ (not [?p :block/children ?v])
53
+ [?v :block/uid ?uid]]`, []));
54
+ for (const [uid] of versions ?? [])
55
+ uids.add(uid);
56
+ // A graph that has never versioned a block stops here, one query in.
57
+ if (uids.size > 0) {
58
+ const nested = (await q(graph, `[:find ?uid
59
+ :where [?vc :vc/blocks ?v]
60
+ (not [?p :block/children ?v])
61
+ [?d :block/parents ?v]
62
+ [?d :block/uid ?uid]]`, []));
63
+ for (const [uid] of nested ?? [])
64
+ uids.add(uid);
65
+ }
66
+ }
67
+ catch {
68
+ // Fall through with whatever was collected; see the note above.
69
+ }
70
+ supersededUidCache.set(graph, { at: Date.now(), uids });
71
+ return uids;
72
+ }
73
+ /** Drop flat search matches that belong to a superseded version. */
74
+ export function filterSupersededMatches(matches, supersededUids) {
75
+ if (supersededUids.size === 0)
76
+ return matches;
77
+ return matches.filter((m) => !m.block_uid || !supersededUids.has(m.block_uid));
78
+ }
79
+ /**
80
+ * The versions of each of these blocks, oldest first, for the blocks that
81
+ * have more than one.
82
+ *
83
+ * Asked by UID and never cached: this answers "which version is in use" for a
84
+ * block someone is about to read or edit, where a 30-second-old answer could
85
+ * name the wrong one. A block with no versions costs the first query only.
86
+ *
87
+ * A version the user hid (`#.rm-hide` / `#.rm-private`, on it or above it) is
88
+ * left out, and a block left with a single visible version reports none, so
89
+ * the list never hints at what was withheld.
90
+ */
91
+ export async function fetchBlockVersions(graph, uids, hidden) {
92
+ const result = new Map();
93
+ if (uids.length === 0)
94
+ return result;
95
+ const rows = (await q(graph, `[:find ?rootUid ?versionUid ?string ?created
96
+ :in $ [?rootUid ...]
97
+ :where [?root :block/uid ?rootUid]
98
+ [?vc :vc/blocks ?root]
99
+ [?vc :vc/blocks ?v]
100
+ [?v :block/uid ?versionUid]
101
+ [?v :block/string ?string]
102
+ [(get-else $ ?v :create/time 0) ?created]]`, [[...new Set(uids)]]));
103
+ if (!rows || rows.length === 0)
104
+ return result;
105
+ const live = new Set(((await q(graph, `[:find ?versionUid
106
+ :in $ [?versionUid ...]
107
+ :where [?v :block/uid ?versionUid]
108
+ [?p :block/children ?v]]`, [[...new Set(rows.map(([, versionUid]) => versionUid))]])) ?? [])
109
+ .map(([uid]) => uid));
110
+ const byRoot = new Map();
111
+ for (const [rootUid, uid, string, created] of rows) {
112
+ if (hidden.has(uid) || isHiddenBlockString(string))
113
+ continue;
114
+ if (!byRoot.has(rootUid))
115
+ byRoot.set(rootUid, []);
116
+ byRoot.get(rootUid).push({ uid, string, active: live.has(uid), created });
117
+ }
118
+ for (const [rootUid, versions] of byRoot) {
119
+ if (versions.length < 2)
120
+ continue;
121
+ versions.sort((a, b) => a.created - b.created || a.uid.localeCompare(b.uid));
122
+ result.set(rootUid, versions.map(({ uid, string, active }) => ({ uid, string, active })));
123
+ }
124
+ return result;
125
+ }
@@ -4,6 +4,7 @@ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
4
4
  import { resolveBlockRefs } from '../helpers/refs.js';
5
5
  import { fetchChildrenByDepth } from '../helpers/fetch-children.js';
6
6
  import { collectHiddenUids, pruneHiddenBlocks, isHiddenBlockString } from '../helpers/hidden.js';
7
+ import { fetchBlockVersions } from '../helpers/versions.js';
7
8
  import { ednString } from '../../shared/datalog.js';
8
9
  export class BlockRetrievalOperations {
9
10
  constructor(graph) {
@@ -68,6 +69,10 @@ export class BlockRetrievalOperations {
68
69
  const visit = (block) => { allBlocks.push(block); block.children.forEach(visit); };
69
70
  roots.forEach(visit);
70
71
  await resolveBlockRefs(this.graph, allBlocks, 2, hidden);
72
+ // One query for all the roots; a set with no versioned block stops there.
73
+ for (const [uid, versions] of await fetchBlockVersions(this.graph, [...roots.keys()], hidden)) {
74
+ roots.get(uid).versions = versions;
75
+ }
71
76
  return requested.map(uid => roots.get(uid) ?? null);
72
77
  }
73
78
  async fetchBlock(block_uid_raw, depth = 4, include_ancestors = false) {
@@ -184,6 +189,11 @@ export class BlockRetrievalOperations {
184
189
  traverse(rootBlock);
185
190
  // Resolve references (max depth 2)
186
191
  await resolveBlockRefs(this.graph, allBlocks, 2);
192
+ // Nothing else in a fetch says a block has versions: the text above is
193
+ // the one in use if this UID is, and an old one if it is not.
194
+ const versions = (await fetchBlockVersions(this.graph, [block_uid], await collectHiddenUids(this.graph))).get(block_uid);
195
+ if (versions)
196
+ rootBlock.versions = versions;
187
197
  return rootBlock;
188
198
  }
189
199
  catch (error) {
@@ -4,6 +4,7 @@ import { getPageUid as getPageUidHelper } from '../helpers/page-resolution.js';
4
4
  import { resolveRefs } from '../helpers/refs.js';
5
5
  import { fetchChildrenByDepth } from '../helpers/fetch-children.js';
6
6
  import { collectHiddenUids, pruneHiddenBlocks, isHiddenBlockString } from '../helpers/hidden.js';
7
+ import { collectSupersededUids } from '../helpers/versions.js';
7
8
  import { escapeBlockString } from '../../shared/block-escaping.js';
8
9
  export class FullPageViewOperations {
9
10
  constructor(graph, pageOps) {
@@ -35,8 +36,13 @@ export class FullPageViewOperations {
35
36
  // elsewhere — hence the UID closure rather than a text check alone.
36
37
  // Filtered BEFORE the max_references cap so truncation counts what the
37
38
  // caller can actually see.
38
- const hiddenUids = await collectHiddenUids(this.graph);
39
- const allUniqueRefs = dedupedRefs.filter(r => !hiddenUids.has(r.block_uid) && !isHiddenBlockString(r.block_str));
39
+ // A superseded version keeps its `:block/refs`, so an old version of a
40
+ // block that links here is a backlink too. Only the version in use counts.
41
+ const [hiddenUids, supersededUids] = await Promise.all([
42
+ collectHiddenUids(this.graph),
43
+ collectSupersededUids(this.graph),
44
+ ]);
45
+ const allUniqueRefs = dedupedRefs.filter(r => !hiddenUids.has(r.block_uid) && !isHiddenBlockString(r.block_str) && !supersededUids.has(r.block_uid));
40
46
  const truncated = allUniqueRefs.length > max_references;
41
47
  const uniqueRefs = truncated ? allUniqueRefs.slice(0, max_references) : allUniqueRefs;
42
48
  const refBlockUids = uniqueRefs.map(r => r.block_uid);
@@ -4,7 +4,7 @@ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
4
4
  import { formatRoamDate } from '../../utils/helpers.js';
5
5
  import { findOrCreatePage, getPageUid, getOrCreateTodayPage } from '../helpers/page-resolution.js';
6
6
  import { executeBatch } from '../helpers/batch-utils.js';
7
- import { parseMarkdown, nestUnderHeadings, convertToRoamActions, convertToRoamActionsWithBlocks, convertToRoamMarkdown } from '../../markdown-utils.js';
7
+ import { parseMarkdown, nestUnderHeadings, convertToRoamActions, convertToRoamActionsWithBlocks, convertToRoamMarkdown, parseMarkdownHeadingLevel } from '../../markdown-utils.js';
8
8
  import { executeStagedBatch } from '../../shared/staged-batch.js';
9
9
  import { ednString } from '../../shared/datalog.js';
10
10
  // Threshold for skipping child fetch during verification
@@ -23,6 +23,10 @@ function blockInfoToNestedBlocks(blocks, level = 0) {
23
23
  children: block.children.length > 0 ? blockInfoToNestedBlocks(block.children, level + 1) : undefined
24
24
  }));
25
25
  }
26
+ /** A parsed markdown tree as a flat list, parents before their children. */
27
+ function inDocumentOrder(nodes) {
28
+ return nodes.flatMap(node => [node, ...inDocumentOrder(node.children)]);
29
+ }
26
30
  export class OutlineOperations {
27
31
  constructor(graph) {
28
32
  this.graph = graph;
@@ -243,30 +247,45 @@ export class OutlineOperations {
243
247
  }
244
248
  prevLevel = item.level;
245
249
  }
246
- // Convert outline items to markdown-like structure
247
- const markdownContent = validOutline
248
- .map(item => {
250
+ // Convert outline items to markdown-like structure, one chunk per item
251
+ const chunks = validOutline.map(item => {
249
252
  const indent = ' '.repeat(item.level - 1);
250
253
  // If the item text starts with a markdown heading (e.g., #, ##, ###),
251
254
  // treat it as a direct heading without adding a bullet or outline indentation.
252
255
  // NEW CHANGE: Handle standalone code blocks - do not prepend bullet
253
256
  const isCodeBlock = item.text?.startsWith('```') && item.text.endsWith('```') && item.text.includes('\n');
254
257
  return isCodeBlock ? `${indent}${item.text?.trim()}` : `${indent}- ${item.text?.trim()}`;
255
- })
256
- .join('\n');
258
+ });
257
259
  // Convert to Roam markdown format
258
- const convertedContent = convertToRoamMarkdown(markdownContent);
260
+ const convertedContent = convertToRoamMarkdown(chunks.join('\n'));
259
261
  // Parse markdown into hierarchical structure
260
- // We pass the original OutlineItem properties (heading, children_view_type)
261
- // along with the parsed content to the nodes.
262
- const nodes = parseMarkdown(convertedContent).map((node, index) => {
263
- const outlineItem = validOutline[index];
264
- return {
265
- ...node,
266
- ...(outlineItem?.heading && { heading_level: outlineItem.heading }),
267
- ...(outlineItem?.children_view_type && { children_view_type: outlineItem.children_view_type })
268
- };
269
- });
262
+ const nodes = parseMarkdown(convertedContent);
263
+ // Give each item's `heading` and `children_view_type` to the block that
264
+ // item became. The parser returns a tree, in the order the lines were
265
+ // written, so walking it depth-first meets the blocks in item order; an
266
+ // item is one block unless its text spans several lines, and parsing its
267
+ // chunk alone says how many. These used to be copied by position onto the
268
+ // top-level blocks only, which put a nested item's settings on a later
269
+ // top-level block and gave nested blocks none.
270
+ const blocksInOrder = inDocumentOrder(nodes);
271
+ const firstBlockOf = [];
272
+ let nextBlock = 0;
273
+ for (const chunk of chunks) {
274
+ firstBlockOf.push(nextBlock);
275
+ nextBlock += inDocumentOrder(parseMarkdown(chunk)).length;
276
+ }
277
+ // The counts can disagree when a code fence left open in one item takes
278
+ // in the items after it. No block can be traced to its item then, so
279
+ // none is given settings that may belong to another.
280
+ if (nextBlock === blocksInOrder.length) {
281
+ validOutline.forEach((item, index) => {
282
+ const node = blocksInOrder[firstBlockOf[index]];
283
+ if (item.heading)
284
+ node.heading_level = item.heading;
285
+ if (item.children_view_type)
286
+ node.children_view_type = item.children_view_type;
287
+ });
288
+ }
270
289
  // Convert nodes to batch actions (flat list)
271
290
  const resolvedOrder = order !== undefined ? order : 'last';
272
291
  const actions = convertToRoamActions(nodes, targetParentUid, resolvedOrder);
@@ -396,23 +415,27 @@ export class OutlineOperations {
396
415
  };
397
416
  }
398
417
  else {
399
- // Create a simple block for non-nested content
418
+ // Create a simple block for non-nested content. One line can still be a
419
+ // heading: "## Title" is one in longer content, and was written here as
420
+ // typed, hashes and all. Anything else is still written as typed.
421
+ const { heading_level, content: headingText } = parseMarkdownHeadingLevel(content);
422
+ const text = heading_level > 0 ? headingText : content;
400
423
  await executeBatch(this.graph, [{
401
424
  action: 'create-block',
402
425
  location: {
403
426
  "parent-uid": targetParentUid,
404
427
  "order": order
405
428
  },
406
- block: { string: content }
429
+ block: { string: text, ...(heading_level > 0 && { heading: heading_level }) }
407
430
  }], 'create content block');
408
431
  // For single-line content, we still need to fetch the UID and construct a NestedBlock
409
432
  const createdBlocks = [];
410
433
  try {
411
- const foundUid = await this.findBlockWithRetry(targetParentUid, content);
434
+ const foundUid = await this.findBlockWithRetry(targetParentUid, text);
412
435
  if (foundUid) {
413
436
  createdBlocks.push({
414
437
  uid: foundUid,
415
- text: content,
438
+ text,
416
439
  level: 0,
417
440
  order: 0,
418
441
  children: []
@@ -229,13 +229,21 @@ export class PageOperations {
229
229
  }
230
230
  }
231
231
  // Convert to node format with level info
232
- const nodes = normalizedContent.map(block => ({
233
- content: convertToRoamMarkdown(block.text.replace(/^#+\s+/, '')),
234
- level: block.level,
235
- ...(block.heading && { heading_level: block.heading }),
236
- ...(block.numbered_children && { children_view_type: 'numbered' }),
237
- children: []
238
- }));
232
+ const nodes = normalizedContent.map(block => {
233
+ // One to three hashes at the start of the text are a heading, as
234
+ // they are wherever else block text is written; `heading` decides
235
+ // when both are given. The hashes used to be removed and the
236
+ // heading with them, leaving a plain block.
237
+ const hashes = block.text.match(/^(#{1,3})\s+/);
238
+ const heading = block.heading || hashes?.[1].length;
239
+ return {
240
+ content: convertToRoamMarkdown(block.text.replace(/^#+\s+/, '')),
241
+ level: block.level,
242
+ ...(heading && { heading_level: heading }),
243
+ ...(block.numbered_children && { children_view_type: 'numbered' }),
244
+ children: []
245
+ };
246
+ });
239
247
  // Create hierarchical structure based on levels
240
248
  const rootNodes = [];
241
249
  const levelMap = {};
@@ -2,6 +2,7 @@ import { q } from '@roam-research/roam-api-sdk';
2
2
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
3
3
  import { TagSearchHandlerImpl, BlockRefSearchHandlerImpl, HierarchySearchHandlerImpl, TextSearchHandlerImpl, StatusSearchHandlerImpl, DatomicSearchHandlerImpl } from './handlers.js';
4
4
  import { collectHiddenUids, filterHiddenMatches } from '../../helpers/hidden.js';
5
+ import { collectSupersededUids, filterSupersededMatches } from '../../helpers/versions.js';
5
6
  import { resolveRefsMany } from '../../helpers/refs.js';
6
7
  export function validateSearchPage({ limit = -1, offset = 0 }) {
7
8
  if (!Number.isSafeInteger(limit) || limit < -1 || !Number.isSafeInteger(offset) || offset < 0) {
@@ -22,12 +23,20 @@ export class SearchOperations {
22
23
  * raw Datalog reads the database directly and stays raw, matching the
23
24
  * official Roam toolset. That is also why these tags are a convenience
24
25
  * filter, not a security boundary.
26
+ *
27
+ * Superseded block versions go the same way, for a different reason: they
28
+ * are not live content. Roam keeps a block's old versions as blocks of
29
+ * their own, which a search matches like any other; see
30
+ * `collectSupersededUids`.
25
31
  */
26
32
  async withoutHidden(result) {
27
33
  if (!result?.matches?.length)
28
34
  return result;
29
- const hidden = await collectHiddenUids(this.graph);
30
- const matches = filterHiddenMatches(result.matches, hidden);
35
+ const [hidden, superseded] = await Promise.all([
36
+ collectHiddenUids(this.graph),
37
+ collectSupersededUids(this.graph),
38
+ ]);
39
+ const matches = filterSupersededMatches(filterHiddenMatches(result.matches, hidden), superseded);
31
40
  const removed = result.matches.length - matches.length;
32
41
  if (removed === 0)
33
42
  return result;
@@ -167,8 +176,11 @@ export class SearchOperations {
167
176
  const rows = await q(this.graph, query, inputs);
168
177
  return rows.map(([block_uid, content, page_title, time]) => ({ block_uid, content, page_title, time, type }));
169
178
  }));
170
- const hidden = await collectHiddenUids(this.graph);
171
- const visible = filterHiddenMatches(results.flat(), hidden);
179
+ const [hidden, superseded] = await Promise.all([
180
+ collectHiddenUids(this.graph),
181
+ collectSupersededUids(this.graph),
182
+ ]);
183
+ const visible = filterSupersededMatches(filterHiddenMatches(results.flat(), hidden), superseded);
172
184
  const matchesByUid = new Map();
173
185
  for (const match of visible) {
174
186
  const previous = matchesByUid.get(match.block_uid);
@@ -42,6 +42,7 @@ export function validateTableInput(input) {
42
42
  }
43
43
  return { valid: errors.length === 0, errors };
44
44
  }
45
+ const SINGLE_TABLE_NAMES = { table: 'table', cellPrefix: '' };
45
46
  /**
46
47
  * Builds batch actions for creating a Roam table structure.
47
48
  *
@@ -49,21 +50,26 @@ export function validateTableInput(input) {
49
50
  * - The table container block contains {{[[table]]}}
50
51
  * - Header row is nested deeply (each column nested under the previous)
51
52
  * - Data rows follow the same nesting pattern
53
+ *
54
+ * This is the one place a table's layout is decided: `roam_create_table`,
55
+ * tables in `roam_create_page` content and `roam batch` all build through it.
52
56
  */
53
- export function buildTableActions(input) {
57
+ export function buildTableActions(input, names = SINGLE_TABLE_NAMES) {
54
58
  const actions = [];
59
+ const tableUid = `{{uid:${names.table}}}`;
60
+ const cellUid = (name) => `{{uid:${names.cellPrefix}${name}}}`;
55
61
  // Create table container
56
62
  actions.push({
57
63
  action: 'create-block',
58
- uid: '{{uid:table}}',
64
+ uid: tableUid,
59
65
  string: '{{[[table]]}}',
60
66
  location: { 'parent-uid': input.parent_uid, order: input.order ?? 'last' }
61
67
  });
62
68
  // Create header row with nested structure
63
69
  // In Roam tables, each column is nested under the previous column
64
- let headerParent = '{{uid:table}}';
70
+ let headerParent = tableUid;
65
71
  for (let i = 0; i < input.headers.length; i++) {
66
- const uid = `{{uid:header_${i}}}`;
72
+ const uid = cellUid(`header_${i}`);
67
73
  const headerText = input.headers[i] || ' '; // Convert empty to space
68
74
  actions.push({
69
75
  action: 'create-block',
@@ -78,26 +84,26 @@ export function buildTableActions(input) {
78
84
  for (let rowIdx = 0; rowIdx < input.rows.length; rowIdx++) {
79
85
  const row = input.rows[rowIdx];
80
86
  // Row label (first column) - child of table at position rowIdx + 1 (after header)
81
- const labelUid = `{{uid:row_${rowIdx}_label}}`;
87
+ const labelUid = cellUid(`row_${rowIdx}_label`);
82
88
  const labelText = row.label || ' '; // Convert empty to space
83
89
  actions.push({
84
90
  action: 'create-block',
85
91
  uid: labelUid,
86
92
  string: labelText,
87
- location: { 'parent-uid': '{{uid:table}}', order: rowIdx + 1 }
93
+ location: { 'parent-uid': tableUid, order: rowIdx + 1 }
88
94
  });
89
95
  // Row cells - each cell is nested under the previous
90
96
  let cellParent = labelUid;
91
97
  for (let cellIdx = 0; cellIdx < row.cells.length; cellIdx++) {
92
- const cellUid = `{{uid:row_${rowIdx}_cell_${cellIdx}}}`;
98
+ const uid = cellUid(`row_${rowIdx}_cell_${cellIdx}`);
93
99
  const cellText = row.cells[cellIdx] || ' '; // Convert empty to space
94
100
  actions.push({
95
101
  action: 'create-block',
96
- uid: cellUid,
102
+ uid,
97
103
  string: cellText,
98
104
  location: { 'parent-uid': cellParent, order: 0 }
99
105
  });
100
- cellParent = cellUid;
106
+ cellParent = uid;
101
107
  }
102
108
  }
103
109
  return actions;
@@ -799,7 +799,7 @@ export const toolSchemas = {
799
799
  roam_fetch_block: {
800
800
  name: 'roam_fetch_block',
801
801
  annotations: READ,
802
- description: 'Fetch a block by its UID with optional children (down to a specified depth) and/or ancestors (up to page root). Returns the block\'s UID, text, order, children array, and optionally an ancestors array with the chain to the page root.\n\nIMPORTANT: call roam_get_guidelines for this graph once per session before using this tool, reads included — conventions change how results are read, not just written.',
802
+ description: 'Fetch a block by its UID with optional children (down to a specified depth) and/or ancestors (up to page root). Returns the block\'s UID, text, order, children array, and optionally an ancestors array with the chain to the page root. A block that has Roam versions also returns `versions`: every version as {uid, string, active}, oldest first, where `active` marks the one in use (the one a page read shows). Searches return only the version in use; an older one is read by fetching its uid from this list.\n\nIMPORTANT: call roam_get_guidelines for this graph once per session before using this tool, reads included — conventions change how results are read, not just written.',
803
803
  inputSchema: {
804
804
  type: 'object',
805
805
  properties: withMultiGraphParams({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roam-research-mcp",
3
- "version": "6.1.1",
3
+ "version": "6.3.0",
4
4
  "description": "MCP server and CLI for Roam Research",
5
5
  "private": false,
6
6
  "repository": {