roam-research-mcp 6.1.1 → 6.2.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,14 @@ 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.2
24
+
25
+ **`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.
26
+
27
+ **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.
28
+
29
+ **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.
30
+
23
31
  ## What's New in v6.1
24
32
 
25
33
  **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
  }
@@ -145,6 +162,10 @@ export function resolveParentRef(ref, context) {
145
162
  const name = placeholderMatch[1];
146
163
  return context.placeholders.get(name) || `{{uid:${name}}}`;
147
164
  }
165
+ // "daily" is today's daily page, never a page title
166
+ if (ref === DAILY_PARENT) {
167
+ return context.dailyPageUid ?? context.pageUids.get(getDailyPageTitle()) ?? null;
168
+ }
148
169
  // Check if it's a resolved page title
149
170
  if (context.pageUids.has(ref)) {
150
171
  return context.pageUids.get(ref);
@@ -16,7 +16,7 @@ export function translateCommand(command, context) {
16
16
  case 'delete':
17
17
  return translateDelete(command);
18
18
  case 'move':
19
- return translateMove(command);
19
+ return translateMove(command, context);
20
20
  case 'todo':
21
21
  return translateTodo(command, context);
22
22
  case 'table':
@@ -168,13 +168,15 @@ function translateDelete(cmd) {
168
168
  uid: cmd.params.uid
169
169
  }];
170
170
  }
171
- function translateMove(cmd) {
171
+ function translateMove(cmd, context) {
172
172
  const { params } = cmd;
173
173
  return [{
174
174
  action: 'move-block',
175
175
  uid: params.uid,
176
176
  location: {
177
- 'parent-uid': params.parent,
177
+ // Resolved like every other parent. Passed through raw, a page title or
178
+ // "daily" reached the batch as a "UID" and was refused there.
179
+ 'parent-uid': getParentUid({ parent: params.parent }, context),
178
180
  order: params.order ?? 'last'
179
181
  }
180
182
  }];
@@ -253,6 +255,41 @@ function translateTable(cmd, context) {
253
255
  }
254
256
  return actions;
255
257
  }
258
+ /**
259
+ * Check an outline's `items` and bring each one to `{text, level, ...}`.
260
+ *
261
+ * A plain string is a level-1 block, which is what the help has always shown,
262
+ * and a missing `level` is 1. Anything else is refused by name: a level that
263
+ * is not a whole number of 1 or more used to reach `levelStack.length = level`
264
+ * and surface as a bare "Invalid array length" (issue #34).
265
+ *
266
+ * Throws with the item's position, e.g. `items[2].level must be ...`.
267
+ */
268
+ export function normalizeOutlineItems(items) {
269
+ if (!Array.isArray(items)) {
270
+ throw new Error(`'items' must be an array of strings or {text, level?} objects`);
271
+ }
272
+ return items.map((item, i) => {
273
+ if (typeof item === 'string') {
274
+ return { text: item, level: 1 };
275
+ }
276
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
277
+ throw new Error(`items[${i}] must be a string or a {text, level?} object (got ${JSON.stringify(item)})`);
278
+ }
279
+ const { text, level: given } = item;
280
+ if (typeof text !== 'string') {
281
+ throw new Error(`items[${i}].text must be a string (got ${JSON.stringify(text)})`);
282
+ }
283
+ // "2" worked before by coercion, so it still does.
284
+ const level = given == null ? 1
285
+ : typeof given === 'string' && given.trim() !== '' ? Number(given)
286
+ : given;
287
+ if (typeof level !== 'number' || !Number.isInteger(level) || level < 1) {
288
+ throw new Error(`items[${i}].level must be a whole number, 1 or more (got ${JSON.stringify(given)})`);
289
+ }
290
+ return { ...item, text, level };
291
+ });
292
+ }
256
293
  function translateOutline(cmd, context) {
257
294
  const { params } = cmd;
258
295
  const parentUid = getParentUid(params, context);
@@ -260,7 +297,7 @@ function translateOutline(cmd, context) {
260
297
  // Reset level stack with outline parent
261
298
  context.currentParent = parentUid;
262
299
  context.levelStack = [];
263
- for (const item of params.items) {
300
+ for (const item of normalizeOutlineItems(params.items)) {
264
301
  let itemParentUid;
265
302
  if (item.level === 1) {
266
303
  itemParentUid = parentUid;
@@ -350,6 +387,25 @@ function translateCodeblock(cmd, context) {
350
387
  }
351
388
  return [action];
352
389
  }
390
+ /**
391
+ * Point actions at pages created by `page` commands.
392
+ *
393
+ * A `page` command's `as` name stands for a page UID, and that UID exists only
394
+ * once the page does, which is after translation. Until then a parent of
395
+ * `{{name}}` is carried as `{{uid:name}}`, the form block placeholders use;
396
+ * left like that, the batch takes it for a block nobody defined and refuses
397
+ * the whole run. Called with the UIDs once the pages exist.
398
+ */
399
+ export function bindPagePlaceholders(actions, pageUidsByName) {
400
+ const uidByPlaceholder = new Map(Array.from(pageUidsByName, ([name, uid]) => [generatePlaceholder(name), uid]));
401
+ return actions.map(action => {
402
+ const parent = action.location?.['parent-uid'];
403
+ const pageUid = parent === undefined ? undefined : uidByPlaceholder.get(parent);
404
+ if (!action.location || pageUid === undefined)
405
+ return action;
406
+ return { ...action, location: { ...action.location, 'parent-uid': pageUid } };
407
+ });
408
+ }
353
409
  /**
354
410
  * Translate all commands to batch actions
355
411
  */
@@ -4,8 +4,8 @@ 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
10
  // Required params per command type
11
11
  const REQUIRED_PARAMS = {
@@ -49,6 +49,16 @@ function validateCommands(commands) {
49
49
  throw new Error(`[${i}] ${cmdType}: missing required param '${param}'`);
50
50
  }
51
51
  }
52
+ // Outline items are checked here, with the command's position, rather
53
+ // than left to fail somewhere inside the translation.
54
+ if (cmdType === 'outline') {
55
+ try {
56
+ normalizeOutlineItems(params.items);
57
+ }
58
+ catch (err) {
59
+ throw new Error(`[${i}] outline: ${err instanceof Error ? err.message : String(err)}`);
60
+ }
61
+ }
52
62
  validated.push(cmd);
53
63
  }
54
64
  return validated;
@@ -148,12 +158,16 @@ Command schemas:
148
158
  delete: {uid}
149
159
  move: {uid, parent, order?}
150
160
  page: {title, as?, content?: [{text, level, heading?}...]}
151
- outline: {parent, items: [string...]}
161
+ outline: {parent, items: [string | {text, level?, heading?, as?}...]}
152
162
  table: {parent, headers: [string...], rows: [{label, cells: [string...]}...]}
153
163
  remember: {text, categories?: [string...]}
154
164
  codeblock: {parent, code, language?}
155
165
 
156
- Parent accepts: block UID, "daily", page title, or {{placeholder}}
166
+ Parent accepts: block UID, "daily" (today's daily page), page title, or {{placeholder}}
167
+
168
+ A page title that does not exist yet is created. Creating a page also writes
169
+ "Created page: [[Title]]" to today's daily page and "Processed: [[date]]" to
170
+ the new page. --dry-run lists such pages and creates nothing.
157
171
 
158
172
  Example:
159
173
  [
@@ -213,6 +227,13 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
213
227
  // Simulate mode: validate structure without connecting to Roam
214
228
  if (options.simulate) {
215
229
  const context = createResolutionContext();
230
+ // Nothing is looked up offline, so every page a command names gets a
231
+ // stand-in UID. Without one, a page title, "daily" or a bare todo
232
+ // could not be translated and failed as if the input were wrong.
233
+ for (const title of collectPageTitles(commands)) {
234
+ context.pageUids.set(title, pageStandIn(title));
235
+ }
236
+ context.dailyPageUid = pageStandIn(getDailyPageTitle());
216
237
  const { actions, pageCommands } = translateAllCommands(commands, context);
217
238
  console.log('\n[SIMULATE] Validation passed\n');
218
239
  console.log(`Commands: ${commands.length}`);
@@ -232,6 +253,8 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
232
253
  // Phase 1: Collect and resolve page titles (from 'page' AND 'parent' params)
233
254
  const context = createResolutionContext();
234
255
  const pageTitles = collectPageTitles(commands);
256
+ // Pages a dry run found missing: reported in the plan, never created.
257
+ const missingPages = [];
235
258
  if (pageTitles.size > 0) {
236
259
  if (options.debug) {
237
260
  printDebug('Pages to resolve', Array.from(pageTitles));
@@ -242,7 +265,15 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
242
265
  }
243
266
  // Auto-create unresolved pages (e.g., parent: "Page Title" for a page that doesn't exist yet)
244
267
  const unresolved = Array.from(pageTitles).filter(t => !context.pageUids.has(t));
245
- if (unresolved.length > 0) {
268
+ if (options.dryRun) {
269
+ // A dry run writes nothing. This creation used to run before the
270
+ // dry-run exit below, so previewing a batch created its pages.
271
+ for (const title of unresolved) {
272
+ context.pageUids.set(title, pageStandIn(title));
273
+ missingPages.push(title);
274
+ }
275
+ }
276
+ else if (unresolved.length > 0) {
246
277
  if (options.debug) {
247
278
  printDebug('Auto-creating pages', unresolved);
248
279
  }
@@ -266,7 +297,8 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
266
297
  }
267
298
  // Resolve daily page if needed
268
299
  if (needsDailyPage(commands)) {
269
- const dailyUid = await resolveDailyPageUid(graph);
300
+ // Phase 1 already has it: found, created, or a dry run's stand-in.
301
+ const dailyUid = context.pageUids.get(getDailyPageTitle()) ?? await resolveDailyPageUid(graph);
270
302
  if (!dailyUid) {
271
303
  exitWithError(`Daily page not found: "${getDailyPageTitle()}"`);
272
304
  }
@@ -285,19 +317,24 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
285
317
  // Dry run: show actions and exit
286
318
  if (options.dryRun) {
287
319
  console.log('\n[DRY RUN] Planned actions:\n');
288
- if (pageCommands.length > 0) {
320
+ // A page both named by a `page` command and used as a parent is one page.
321
+ const impliedPages = missingPages.filter(t => !pageCommands.some(pc => pc.params.title === t));
322
+ if (pageCommands.length + impliedPages.length > 0) {
289
323
  console.log('Page creations:');
290
324
  for (const pc of pageCommands) {
291
325
  const as = pc.params.as ? ` (as: {{${pc.params.as}}})` : '';
292
326
  console.log(` - "${pc.params.title}"${as}`);
293
327
  }
328
+ for (const title of impliedPages) {
329
+ console.log(` - "${title}" (does not exist yet)`);
330
+ }
294
331
  console.log('');
295
332
  }
296
333
  if (actions.length > 0) {
297
334
  console.log('Batch actions:');
298
335
  console.log(actions.map((a, i) => formatAction(a, i)).join('\n'));
299
336
  }
300
- console.log(`\nTotal: ${pageCommands.length} page(s), ${actions.length} action(s)`);
337
+ console.log(`\nTotal: ${pageCommands.length + impliedPages.length} page(s), ${actions.length} action(s)`);
301
338
  return;
302
339
  }
303
340
  // Phase 3: Execute page commands (in parallel where possible)
@@ -328,7 +365,12 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
328
365
  let batchResult = { success: true, actions_attempted: 0 };
329
366
  if (actions.length > 0) {
330
367
  const batchOps = new BatchOperations(graph);
331
- batchResult = await batchOps.processBatch(actions);
368
+ // The pages exist now, so a parent of {{name}} can become their UID.
369
+ const pagePlaceholders = new Map(pageCommands.flatMap(pc => {
370
+ const uid = pc.params.as ? context.placeholders.get(pc.params.as) : undefined;
371
+ return pc.params.as && uid ? [[pc.params.as, uid]] : [];
372
+ }));
373
+ batchResult = await batchOps.processBatch(bindPagePlaceholders(actions, pagePlaceholders));
332
374
  if (!batchResult.success) {
333
375
  const errorMsg = typeof batchResult.error === 'string'
334
376
  ? batchResult.error
@@ -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
  */
@@ -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);
@@ -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);
@@ -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.2.0",
4
4
  "description": "MCP server and CLI for Roam Research",
5
5
  "private": false,
6
6
  "repository": {