roam-research-mcp 5.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.
Files changed (39) hide show
  1. package/README.md +58 -2
  2. package/build/cache/page-uid-cache.js +12 -3
  3. package/build/cli/batch/resolver.js +25 -4
  4. package/build/cli/batch/translator.js +60 -4
  5. package/build/cli/commands/batch.js +56 -13
  6. package/build/cli/commands/get.js +11 -30
  7. package/build/cli/commands/refs.js +1 -2
  8. package/build/cli/commands/rename.js +19 -21
  9. package/build/cli/commands/save.js +1 -2
  10. package/build/cli/commands/search.js +31 -66
  11. package/build/cli/commands/update.js +1 -2
  12. package/build/cli/utils/output.js +19 -2
  13. package/build/config/graph-registry.js +2 -0
  14. package/build/search/datomic-search.js +2 -0
  15. package/build/search/tag-search.js +4 -19
  16. package/build/search/text-search.js +11 -47
  17. package/build/search/types.js +3 -6
  18. package/build/server/roam-server.js +2 -2
  19. package/build/shared/errors.js +7 -0
  20. package/build/shared/page-validator.js +24 -72
  21. package/build/shared/retry.js +12 -2
  22. package/build/shared/staged-batch.js +12 -1
  23. package/build/tools/helpers/batch-utils.js +2 -0
  24. package/build/tools/helpers/fetch-children.js +7 -4
  25. package/build/tools/helpers/page-resolution.js +9 -9
  26. package/build/tools/helpers/refs.js +71 -40
  27. package/build/tools/helpers/versions.js +125 -0
  28. package/build/tools/operations/batch.js +115 -20
  29. package/build/tools/operations/block-retrieval.js +74 -1
  30. package/build/tools/operations/blocks.js +2 -0
  31. package/build/tools/operations/full-page-view.js +8 -2
  32. package/build/tools/operations/memory.js +2 -0
  33. package/build/tools/operations/outline.js +6 -0
  34. package/build/tools/operations/pages.js +42 -14
  35. package/build/tools/operations/search/index.js +60 -21
  36. package/build/tools/schemas.js +11 -3
  37. package/build/tools/tool-handlers.js +3 -3
  38. package/build/utils/roam-http-client.js +41 -0
  39. package/package.json +1 -1
package/README.md CHANGED
@@ -20,6 +20,33 @@ 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
+
31
+ ## What's New in v6.1
32
+
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`.
34
+
35
+ **Upgrading:** a batch that deletes an already-missing UID now returns `success: false`, and `roam batch` exits nonzero. Scripts that delete blocks idempotently ("remove it if it's there") should treat `BLOCK_NOT_FOUND` as done.
36
+
37
+ ## What's New in v6.0
38
+
39
+ Search pagination now works consistently across MCP and CLI, repeated reads use fewer API requests, and write failures carry the information needed to recover safely.
40
+
41
+ - **Predictable search pages.** MCP text and tag searches enforce the documented default of 50 results; `roam search` defaults to 20 and adds `--offset`. Hidden blocks and tag filters are applied before pagination, and block references are expanded only for the selected results. Block results use UID order; namespace results use title order. Use `limit: -1` in MCP or `--limit -1` in the CLI to return all remaining results after the offset; `0` returns none. The backend still retrieves matching candidates, so pagination bounds output and reference expansion, not the initial search query.
42
+ - **Fewer repeated reads.** Reference expansion batches unique UIDs and reuses content already fetched during that operation. CLI `roam get --tag` and `--text` fetch selected blocks, children, and ancestors in batches, preserving their order and context.
43
+ - **Caches stay with their graph connection.** Page UID lookups cannot leak between graph connections, and successful page renames clear that connection's cached lookups.
44
+ - **Useful failure details.** Transport errors preserve HTTP status, `Retry-After`, and the number of confirmed successful actions when the backend provides them. Failed batches can include `committed.action_indices` and `committed.uids` to identify confirmed work. Retries honor the server's delay and stop when a write may already have taken effect.
45
+
46
+ **Upgrading from v5:** searches that previously ignored their limit may now return fewer results; request more pages or use `-1` when you need everything. CLI transport failures now write a JSON `{ "error": { ... } }` envelope to stderr and exit nonzero, so update scripts that parse error text. If a write reports `outcome_unknown: true`, inspect the graph before resubmitting it; a throttled write without confirmed progress is no longer automatically replayed. These observable changes are why this is a major release.
47
+
48
+ See the [changelog](CHANGELOG.md) for the four merged changes and their regression coverage.
49
+
23
50
  ## What's New in v5.0
24
51
 
25
52
  **In one line:** `roam save` now has one flag for each way of naming a parent block, and neither one guesses. `--parent-uid` is always a UID; `--parent` is always text.
@@ -101,6 +128,10 @@ roam save -p "Changelog" --order first "v2.18.0 release"
101
128
  # Search your graph and pipe results to another tool
102
129
  roam search "important" --json | jq .
103
130
 
131
+ # Fetch the next 20 matching blocks, or all matches after the offset
132
+ roam search "important" --limit 20 --offset 20
133
+ roam search "important" --limit -1 --offset 20 --json
134
+
104
135
  # Search for pages by namespace prefix
105
136
  roam search --namespace "Convention" # Finds all Convention/* pages
106
137
 
@@ -163,10 +194,10 @@ The MCP server exposes these tools to AI assistants (like Claude), enabling them
163
194
  | `roam_create_page` | Create new pages, optionally with mixed text and table content. |
164
195
  | `roam_update_page_markdown` | Update a page using smart diff (preserves block UIDs). |
165
196
  | `roam_get_subpages` | List sub-pages under a namespace prefix (e.g. "Project/") with optional tag filter. |
166
- | `roam_search_by_text` | Full-text search across the graph or within specific pages. Supports namespace prefix search for page titles. |
197
+ | `roam_search_by_text` | Search stored block text by literal substring, across the graph or within specific pages. Supports namespace prefix search for page titles. See [note-taking tips](#writing-notes-for-better-retrieval). |
167
198
  | `roam_search_block_refs` | Find blocks that reference a page, tag, or block UID. |
168
199
  | `roam_search_by_status` | Find TODO or DONE items. |
169
- | `roam_search_for_tag` | Find blocks containing specific tags (supports exclusion). |
200
+ | `roam_search_for_tag` | Find blocks directly referencing a page or tag (supports exclusion). |
170
201
  | `roam_search_by_date` | Find blocks/pages by creation or modification date. |
171
202
  | `roam_find_pages_modified_today` | List pages modified since midnight. |
172
203
  | `roam_add_todo` | Add TODO items to today's daily page. |
@@ -203,6 +234,31 @@ Three things worth knowing:
203
234
 
204
235
  ---
205
236
 
237
+ ## Writing notes for better retrieval
238
+
239
+ These tools work with ordinary Roam notes. For information you want to find and reuse later, this optional pattern makes search results more useful: **put the subject, insight or decision, and its essential qualification in one block**, with supporting detail underneath. Quick captures can stay informal.
240
+
241
+ For example, a note about this project's search behavior could look like:
242
+
243
+ ```text
244
+ - A note containing only a [[block reference]] will not match a text search for the referenced block's wording. #retrieval
245
+ - Evidence:: The text-search handler selects matching blocks before expanding block references.
246
+ - Source:: [Text search implementation](https://github.com/2b3pro/roam-research-mcp/blob/main/src/search/text-search.ts)
247
+ - **Practical implication:** Keep useful wording on the original knowledge block, then reference that block where you reuse it.
248
+ ```
249
+
250
+ Adapt the children to the material: evidence, source location, limitations, steps, or an open question. Keep conditions that change the main claim's meaning in that main block too.
251
+
252
+ - **Choose useful retrieval handles.** Use a few meaningful concept links or topic tags, reusing existing page names. `[[topic]]` and `#topic` both create references that tag search can match. Put them on the takeaway block you want returned; add references to a supporting child when it deserves its own search result.
253
+ - **Use words you will remember searching for.** `roam_search_by_text` matches a literal, contiguous substring of stored block text, ignoring case by default. It resolves block references after matching; it does not search the expanded wording or automatically expand synonyms.
254
+ - **Keep provenance clear.** Record a real source and a timestamp, page, or section when available. Keep quotations exact and attributed, and label your own interpretation. Include reusable properties such as `Source::` or `Status::` when helpful; use plain prose or `**Label:**` for local organization. A TODO should represent a real commitment.
255
+
256
+ **Search, then expand:** use text or tag search to locate the takeaway, then fetch its subtree with `roam_fetch_block` to read the evidence and context. With the CLI, use `roam get <block-uid>`; add `-a` for ancestor context.
257
+
258
+ In this project's tag-search tool, a parent's tags do not make its children match. Page-level metadata can help locate the source, then you can fetch that page's outline. These details describe this project's tools; native Roam queries can behave differently.
259
+
260
+ ---
261
+
206
262
  ## Agent guidelines (per-graph)
207
263
 
208
264
  `roam_get_guidelines` reads a page **inside the graph** — `[[roam/agent guidelines]]` by default — holding your own conventions: how you tag, how you namespace pages, what an agent should never do. Roam's official MCP server reads the same page title, so one page serves both.
@@ -7,7 +7,7 @@
7
7
  * 1. Title -> UID mappings (for getPageUid lookups)
8
8
  * 2. Known existing UIDs (for existence validation before batch operations)
9
9
  */
10
- class PageUidCache {
10
+ export class PageUidCache {
11
11
  constructor() {
12
12
  this.cache = new Map(); // title (lowercase) -> UID
13
13
  this.knownUids = new Set(); // UIDs confirmed to exist
@@ -89,5 +89,14 @@ class PageUidCache {
89
89
  return this.knownUids.size;
90
90
  }
91
91
  }
92
- // Singleton instance - shared across all operations
93
- export const pageUidCache = new PageUidCache();
92
+ // Cache by connection, not graph name: two credentials or endpoints must never
93
+ // share lookup/existence evidence. Weak keys let retired connections be collected.
94
+ const caches = new WeakMap();
95
+ export function getPageUidCache(graph) {
96
+ let cache = caches.get(graph);
97
+ if (!cache) {
98
+ cache = new PageUidCache();
99
+ caches.set(graph, cache);
100
+ }
101
+ return cache;
102
+ }
@@ -4,14 +4,14 @@
4
4
  import { q } from '@roam-research/roam-api-sdk';
5
5
  import { capitalizeWords } from '../../tools/helpers/text.js';
6
6
  import { formatRoamDate } from '../../utils/helpers.js';
7
- import { pageUidCache } from '../../cache/page-uid-cache.js';
7
+ import { getPageUidCache } from '../../cache/page-uid-cache.js';
8
8
  import { ednString } from '../../shared/datalog.js';
9
9
  /**
10
10
  * Resolve a page title to its UID, trying multiple case variations
11
11
  */
12
12
  export async function resolvePageUid(graph, title) {
13
13
  // Check cache first
14
- const cachedUid = pageUidCache.get(title);
14
+ const cachedUid = getPageUidCache(graph).get(title);
15
15
  if (cachedUid) {
16
16
  return cachedUid;
17
17
  }
@@ -29,7 +29,7 @@ export async function resolvePageUid(graph, title) {
29
29
  const uid = (result === null || result === undefined) ? null : String(result);
30
30
  // Cache the result
31
31
  if (uid) {
32
- pageUidCache.set(title, uid);
32
+ getPageUidCache(graph).set(title, uid);
33
33
  }
34
34
  return uid;
35
35
  }
@@ -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;
@@ -84,9 +94,11 @@ function validatePlaceholders(commands) {
84
94
  * Output partial results when a failure occurs mid-batch
85
95
  * Helps user know what was created and may need manual cleanup
86
96
  */
87
- function outputPartialResults(pageResults, failedPage, batchError) {
97
+ function outputPartialResults(pageResults, failedPage, batchError, failure) {
88
98
  const output = {
89
99
  success: false,
100
+ ...(failure?.error && { error: failure.error }),
101
+ ...(failure?.committed && { committed: failure.committed }),
90
102
  partial: true,
91
103
  pages_created: pageResults.length,
92
104
  ...(failedPage && { failed_at: `page: ${failedPage}` }),
@@ -146,12 +158,16 @@ Command schemas:
146
158
  delete: {uid}
147
159
  move: {uid, parent, order?}
148
160
  page: {title, as?, content?: [{text, level, heading?}...]}
149
- outline: {parent, items: [string...]}
161
+ outline: {parent, items: [string | {text, level?, heading?, as?}...]}
150
162
  table: {parent, headers: [string...], rows: [{label, cells: [string...]}...]}
151
163
  remember: {text, categories?: [string...]}
152
164
  codeblock: {parent, code, language?}
153
165
 
154
- 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.
155
171
 
156
172
  Example:
157
173
  [
@@ -211,6 +227,13 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
211
227
  // Simulate mode: validate structure without connecting to Roam
212
228
  if (options.simulate) {
213
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());
214
237
  const { actions, pageCommands } = translateAllCommands(commands, context);
215
238
  console.log('\n[SIMULATE] Validation passed\n');
216
239
  console.log(`Commands: ${commands.length}`);
@@ -230,6 +253,8 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
230
253
  // Phase 1: Collect and resolve page titles (from 'page' AND 'parent' params)
231
254
  const context = createResolutionContext();
232
255
  const pageTitles = collectPageTitles(commands);
256
+ // Pages a dry run found missing: reported in the plan, never created.
257
+ const missingPages = [];
233
258
  if (pageTitles.size > 0) {
234
259
  if (options.debug) {
235
260
  printDebug('Pages to resolve', Array.from(pageTitles));
@@ -240,7 +265,15 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
240
265
  }
241
266
  // Auto-create unresolved pages (e.g., parent: "Page Title" for a page that doesn't exist yet)
242
267
  const unresolved = Array.from(pageTitles).filter(t => !context.pageUids.has(t));
243
- 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) {
244
277
  if (options.debug) {
245
278
  printDebug('Auto-creating pages', unresolved);
246
279
  }
@@ -264,7 +297,8 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
264
297
  }
265
298
  // Resolve daily page if needed
266
299
  if (needsDailyPage(commands)) {
267
- 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);
268
302
  if (!dailyUid) {
269
303
  exitWithError(`Daily page not found: "${getDailyPageTitle()}"`);
270
304
  }
@@ -283,19 +317,24 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
283
317
  // Dry run: show actions and exit
284
318
  if (options.dryRun) {
285
319
  console.log('\n[DRY RUN] Planned actions:\n');
286
- 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) {
287
323
  console.log('Page creations:');
288
324
  for (const pc of pageCommands) {
289
325
  const as = pc.params.as ? ` (as: {{${pc.params.as}}})` : '';
290
326
  console.log(` - "${pc.params.title}"${as}`);
291
327
  }
328
+ for (const title of impliedPages) {
329
+ console.log(` - "${title}" (does not exist yet)`);
330
+ }
292
331
  console.log('');
293
332
  }
294
333
  if (actions.length > 0) {
295
334
  console.log('Batch actions:');
296
335
  console.log(actions.map((a, i) => formatAction(a, i)).join('\n'));
297
336
  }
298
- 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)`);
299
338
  return;
300
339
  }
301
340
  // Phase 3: Execute page commands (in parallel where possible)
@@ -326,13 +365,18 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
326
365
  let batchResult = { success: true, actions_attempted: 0 };
327
366
  if (actions.length > 0) {
328
367
  const batchOps = new BatchOperations(graph);
329
- 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));
330
374
  if (!batchResult.success) {
331
375
  const errorMsg = typeof batchResult.error === 'string'
332
376
  ? batchResult.error
333
377
  : batchResult.error?.message || 'Unknown error';
334
378
  // Report partial results (pages created before batch failed)
335
- outputPartialResults(pageResults, undefined, errorMsg);
379
+ outputPartialResults(pageResults, undefined, errorMsg, batchResult);
336
380
  }
337
381
  }
338
382
  // Build output
@@ -355,8 +399,7 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
355
399
  console.log(JSON.stringify(output, null, 2));
356
400
  }
357
401
  catch (error) {
358
- const message = error instanceof Error ? error.message : String(error);
359
- exitWithError(message);
402
+ exitWithError(error);
360
403
  }
361
404
  });
362
405
  }
@@ -6,7 +6,7 @@ import { FullPageViewOperations } from '../../tools/operations/full-page-view.js
6
6
  import { formatPageOutput, formatBlockOutput, formatTodoOutput, formatGroupedOutput, flattenBlocks, blocksToMarkdown, printDebug, exitWithError } from '../utils/output.js';
7
7
  import { resolveGraph } from '../utils/graph.js';
8
8
  import { readStdin } from '../utils/input.js';
9
- import { resolveRefs } from '../../tools/helpers/refs.js';
9
+ import { resolveRefsInTrees } from '../../tools/helpers/refs.js';
10
10
  import { resolveRelativeDate, parseRoamUrl, isRoamUid } from '../../utils/helpers.js';
11
11
  import { SearchUtils } from '../../search/utils.js';
12
12
  import { sortResults, groupResults, getDefaultDirection } from '../utils/sort-group.js';
@@ -16,22 +16,13 @@ const BLOCK_UID_PATTERN = /^(?:\(\()?([a-zA-Z0-9_-]{9})(?:\)\))?$/;
16
16
  * Recursively resolve block references in a RoamBlock tree
17
17
  */
18
18
  async function resolveBlockRefsInTree(graph, block, maxDepth) {
19
- // Only resolve if string is valid
20
- const resolvedString = typeof block.string === 'string'
21
- ? await resolveRefs(graph, block.string, 0, maxDepth)
22
- : block.string || '';
23
- const resolvedChildren = await Promise.all((block.children || []).map(child => resolveBlockRefsInTree(graph, child, maxDepth)));
24
- return {
25
- ...block,
26
- string: resolvedString,
27
- children: resolvedChildren
28
- };
19
+ return (await resolveRefsInTrees(graph, [block], maxDepth))[0];
29
20
  }
30
21
  /**
31
22
  * Resolve refs in an array of blocks
32
23
  */
33
24
  async function resolveBlocksRefsInTree(graph, blocks, maxDepth) {
34
- return Promise.all(blocks.map(block => resolveBlockRefsInTree(graph, block, maxDepth)));
25
+ return resolveRefsInTrees(graph, blocks, maxDepth);
35
26
  }
36
27
  /**
37
28
  * Normalize a tag by stripping #, [[, ]] wrappers
@@ -175,8 +166,7 @@ Examples:
175
166
  console.log(formatPageOutput(displayTitle, blocks, outputOptions));
176
167
  }
177
168
  catch (error) {
178
- const message = error instanceof Error ? error.message : String(error);
179
- exitWithError(message);
169
+ exitWithError(error);
180
170
  }
181
171
  });
182
172
  }
@@ -215,8 +205,7 @@ Examples:
215
205
  console.log(result);
216
206
  }
217
207
  catch (error) {
218
- const message = error instanceof Error ? error.message : String(error);
219
- exitWithError(message);
208
+ exitWithError(error);
220
209
  }
221
210
  });
222
211
  }
@@ -252,8 +241,7 @@ Examples:
252
241
  console.log(result);
253
242
  }
254
243
  catch (error) {
255
- const message = error instanceof Error ? error.message : String(error);
256
- exitWithError(message);
244
+ exitWithError(error);
257
245
  }
258
246
  });
259
247
  }
@@ -552,16 +540,10 @@ Note: For flat results with UIDs, use 'roam search' instead.
552
540
  return;
553
541
  }
554
542
  // Standard output: fetch full blocks with children
555
- const blocks = [];
556
- for (const match of limitedMatches) {
557
- let block = await blockOps.fetchBlock(match.block_uid, depth, ancestors);
558
- if (block) {
559
- // Resolve refs if requested (default: enabled for tag/text search)
560
- const effectiveRefsDepth = refsDepth > 0 ? refsDepth : 1;
561
- block = await resolveBlockRefsInTree(graph, block, effectiveRefsDepth);
562
- blocks.push(block);
563
- }
564
- }
543
+ const fetched = await blockOps.fetchBlocks(limitedMatches.map(match => match.block_uid), depth, ancestors);
544
+ const visible = fetched.filter((block) => block !== null);
545
+ const effectiveRefsDepth = refsDepth > 0 ? refsDepth : 1;
546
+ const blocks = await resolveBlocksRefsInTree(graph, visible, effectiveRefsDepth);
565
547
  // Output
566
548
  if (options.json) {
567
549
  const data = options.flat
@@ -666,8 +648,7 @@ Note: For flat results with UIDs, use 'roam search' instead.
666
648
  }
667
649
  }
668
650
  catch (error) {
669
- const message = error instanceof Error ? error.message : String(error);
670
- exitWithError(message);
651
+ exitWithError(error);
671
652
  }
672
653
  });
673
654
  // Add subcommands
@@ -148,8 +148,7 @@ JSON output fields: uid, content, page
148
148
  }
149
149
  }
150
150
  catch (error) {
151
- const message = error instanceof Error ? error.message : String(error);
152
- exitWithError(message);
151
+ exitWithError(error);
153
152
  }
154
153
  });
155
154
  }
@@ -1,12 +1,12 @@
1
1
  import { Command } from 'commander';
2
- import { updatePage } from '@roam-research/roam-api-sdk';
2
+ import { PageOperations } from '../../tools/operations/pages.js';
3
3
  import { printDebug, exitWithError } from '../utils/output.js';
4
4
  import { resolveGraph } from '../utils/graph.js';
5
5
  export function createRenameCommand() {
6
6
  return new Command('rename')
7
7
  .description('Rename a page')
8
- .argument('<old-title>', 'Current page title (or use --uid for UID)')
9
- .argument('<new-title>', 'New page title')
8
+ .argument('<old-title>', 'Current page title (leave out when using --uid)')
9
+ .argument('[new-title]', 'New page title')
10
10
  .option('-u, --uid <uid>', 'Use page UID instead of title')
11
11
  .option('-g, --graph <name>', 'Target graph key (multi-graph mode)')
12
12
  .option('--write-key <key>', 'Write confirmation key (non-default graphs)')
@@ -22,37 +22,35 @@ Examples:
22
22
  # Multi-graph
23
23
  roam rename "Draft" "Published" -g work --write-key confirm
24
24
  `)
25
- .action(async (oldTitle, newTitle, options) => {
25
+ .action(async (first, second, options, command) => {
26
+ // --uid already names the page, so a lone argument is the new title.
27
+ const newTitle = second ?? (options.uid ? first : undefined);
28
+ if (newTitle === undefined) {
29
+ command.error("error: missing required argument 'new-title'");
30
+ }
31
+ const oldTitle = options.uid ? undefined : first;
26
32
  try {
27
33
  if (options.debug) {
28
- printDebug('Old title', oldTitle);
34
+ printDebug('Old title', oldTitle ?? 'none (using UID)');
29
35
  printDebug('New title', newTitle);
30
36
  printDebug('UID', options.uid || 'none (using title)');
31
37
  printDebug('Graph', options.graph || 'default');
32
38
  }
33
39
  const graph = resolveGraph(options, true); // Write operation
34
- // Build the page identifier
35
- const pageIdentifier = options.uid
36
- ? { uid: options.uid }
37
- : { title: oldTitle };
38
- if (options.debug) {
39
- printDebug('Page identifier', pageIdentifier);
40
- }
41
- const success = await updatePage(graph, {
42
- page: pageIdentifier,
43
- title: newTitle
40
+ const result = await new PageOperations(graph).renamePage({
41
+ old_title: oldTitle,
42
+ uid: options.uid,
43
+ new_title: newTitle
44
44
  });
45
- if (success) {
46
- const identifier = options.uid ? `((${options.uid}))` : `"${oldTitle}"`;
47
- console.log(`Renamed ${identifier} → "${newTitle}"`);
45
+ if (result.success) {
46
+ console.log(result.message);
48
47
  }
49
48
  else {
50
- exitWithError('Failed to rename page (API returned false)');
49
+ exitWithError(result.message);
51
50
  }
52
51
  }
53
52
  catch (error) {
54
- const message = error instanceof Error ? error.message : String(error);
55
- exitWithError(message);
53
+ exitWithError(error);
56
54
  }
57
55
  });
58
56
  }
@@ -630,8 +630,7 @@ JSON format (--json):
630
630
  }
631
631
  }
632
632
  catch (error) {
633
- const message = error instanceof Error ? error.message : String(error);
634
- exitWithError(message);
633
+ exitWithError(error);
635
634
  }
636
635
  });
637
636
  }