roam-research-mcp 4.0.1 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -369,46 +369,30 @@ This cheatsheet is syntax only. How to tag, when to use a page ref versus a hash
369
369
 
370
370
  ---
371
371
  <personalization_layer>
372
- # Roam: Nova operating notes (server-side supplement)
373
372
 
374
- Style conventions (voice, `#Nova` attribution, tagging, namespacing, formatting) live on the `[[roam/agent guidelines]]` page and arrive through `roam_get_guidelines`. This file carries only what that page deliberately leaves out: the mechanics behind the `#@Nova` handshake, so an interactive session produces the same artifacts as the nightly job and neither one answers a block twice.
373
+ # Roam Preferences — Personalization Layer
375
374
 
376
- ## The `#@Nova` handshake: mechanics
375
+ > This section contains YOUR specific conventions, tagging philosophy, and graph-specific rules. Customize to match your workflow.
376
+
377
+ ---
378
+
379
+ ## Graph-Level Behaviors
380
+
381
+
382
+ ## Tagging Philosophy
383
+
384
+
385
+ ## Formatting Conventions
377
386
 
378
- Ownership rules are on the guidelines page (`#@Nova` is Ian's, `#@Nova-DONE` is Nova's, never self-tag). What follows is the output shape the nightly job writes and checks for.
379
387
 
380
- ### Reading the request
381
- - The request is the tagged block's text with `#@Nova` removed, plus every child block that is not a `[NOVA]` reply, read as further instructions.
382
- - Context is the page title, the ancestor chain, and the sibling blocks under the same parent. Fetch any URL present before answering.
383
- - Empty tag line and no children means "review and respond to the surrounding context."
388
+ ## Constraints & Guardrails
384
389
 
385
- ### Writing the reply
386
- - First child of the tagged block: `[NOVA] <one-line summary, at most 150 characters>`.
387
- - The rest of the reply nests under that `[NOVA]` block as ordinary blocks. Headings and bullets become nesting.
388
- - Then flip the tag in place: `#@Nova` becomes `#@Nova-DONE`. Leave the rest of the block text untouched. A `{{[[TODO]]}}` on the block stays as-is; that checkbox is Ian's.
389
- - Then embed on today's daily page under a `## Nova Responses` heading: a block `Nova response on [[<origin page>]]` with the child `{{[[embed]]: ((<uid of the [NOVA] block>))}}`. The guidelines' root-level rule for daily pages applies to memories; Nova responses go under this heading.
390
390
 
391
- ### Idempotency
392
- - A block that already has a `[NOVA]` child is answered. Do not answer it again, even if the tag still reads `#@Nova`. The nightly cleanup pass removes stray duplicates; do not create them.
393
- - `#@Nova-DONE` is never a work queue. Search `@Nova` for open items and skip anything containing `-DONE`.
391
+ ## Custom Rules
394
392
 
395
- ### Who runs when (America/Los_Angeles)
396
- | When | Job | Scope |
397
- |---|---|---|
398
- | 03:00 nightly | AI Intel sweep, `Skills/AIIntel/Tools/ProcessTriage.ts` | `#@Nova` and `#Status/*` on the `AI Intel Report` and `PAI-Anthropic Report` pages |
399
- | 04:30 nightly | `Skills/Productivity/scripts/ProcessNovaTodos.ts`, EventBridge job `nova_todo_processing` | `#@Nova` on every other page |
400
- | Interactive | This session, when Ian points at a block or asks for a sweep | Same output shape as above |
401
393
 
402
- - Both nightly jobs post their own Telegram summary. An interactive answer does not need one.
403
- - Dry run by hand: `bun $PAI_DIR/Skills/Productivity/scripts/ProcessNovaTodos.ts --dry-run`. Add `--cleanup` to only remove duplicate `[NOVA]` blocks.
404
- - On AI Intel pages, `#Status/ExecSum`, `#Status/Explore`, `#Status/Backburner`, and `#Status/Reject` run unattended. `#Status/Implement`, `#Status/PRD`, and `#@Nova` wait for an interactive session. Processed items end as `#Status/Processed`.
394
+ ## Integration Notes
405
395
 
406
- ## Retired conventions
407
- - `#PAI/do`, `#PAI/done`, `#PAI/hold`, `#PAI/ignore`: replaced by `#@Nova` and `#@Nova-DONE`. Nothing processes them and no block carried them as of September 6th, 2026. Never create them. If one turns up, treat it as `#@Nova`.
408
- - The `| [[Date]]` suffix once used to surface nested results on the daily page: replaced by the embed above.
396
+ <!-- CUSTOMIZE: Any rules about how Roam integrates with your other tools/systems -->
409
397
 
410
- ## Ian's capture tags (not Nova's queue)
411
- - `{{[[TODO]]}} #task <action>` on the daily page is Ian's capture inbox. ProcessFlow routes it to OmniFocus weekly. Do not convert `#task` to `#@Nova` unprompted; Ian decides what to delegate.
412
- - `#researchThis` means look into this later. It is not a task and not a delegation.
413
- - `#suggested-next-action` is a follow-up Nova proposes under a reply. Ian adds `#@Nova` to delegate it or checks it `{{[[DONE]]}}` to close it himself.
414
- </personalization_layer>
398
+ </personalization_layer>
@@ -8,6 +8,8 @@ import { parseMarkdown, generateBlockUid, parseMarkdownHeadingLevel } from '../.
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';
11
+ import { resolveParentRef, resolvePageRef } from '../utils/ref-resolver.js';
12
+ import { uidExists } from '../../shared/page-validator.js';
11
13
  import { formatRoamDate, sanitizeTagName } from '../../utils/helpers.js';
12
14
  import { q, createPage as roamCreatePage } from '@roam-research/roam-api-sdk';
13
15
  /**
@@ -77,16 +79,6 @@ function adjustLevelsForHeadingHierarchy(blocks) {
77
79
  }
78
80
  return result;
79
81
  }
80
- /**
81
- * Check if a string looks like a Roam block UID (9 alphanumeric chars with _ or -)
82
- */
83
- function isBlockUid(value) {
84
- // Strip (( )) wrapper if present
85
- const cleaned = value.replace(/^\(\(|\)\)$/g, '');
86
- // Require at least one digit — real Roam UIDs are randomly generated and
87
- // virtually always contain numbers, while page titles like "Learnings" don't.
88
- return /^[a-zA-Z0-9_-]{9}$/.test(cleaned) && /\d/.test(cleaned);
89
- }
90
82
  /**
91
83
  * Check if content looks like a JSON array
92
84
  */
@@ -125,7 +117,8 @@ async function getDailyPageUid(graph) {
125
117
  return findOrCreatePage(graph, dateStr);
126
118
  }
127
119
  /**
128
- * Find or create a heading block on a page
120
+ * Find or create a heading block on a page. `created` tells the caller whether
121
+ * a block was added, so it can say so: a created parent is otherwise invisible.
129
122
  */
130
123
  async function findOrCreateHeading(graph, pageUid, heading, headingLevel) {
131
124
  // Search for existing heading block
@@ -138,7 +131,7 @@ async function findOrCreateHeading(graph, pageUid, heading, headingLevel) {
138
131
  [?block :block/uid ?uid]]`;
139
132
  const headingResults = await q(graph, headingQuery, [pageUid, heading]);
140
133
  if (headingResults && headingResults.length > 0) {
141
- return headingResults[0][0];
134
+ return { uid: headingResults[0][0], created: false };
142
135
  }
143
136
  // Create the heading block
144
137
  const batchOps = new BatchOperations(graph);
@@ -150,7 +143,7 @@ async function findOrCreateHeading(graph, pageUid, heading, headingLevel) {
150
143
  uid: headingUid,
151
144
  ...(headingLevel && { heading: headingLevel })
152
145
  }]);
153
- return headingUid;
146
+ return { uid: headingUid, created: true };
154
147
  }
155
148
  /**
156
149
  * Parse JSON content blocks
@@ -186,8 +179,9 @@ export function createSaveCommand() {
186
179
  .argument('[input]', 'Text, file path, or "-" for stdin (auto-detected)')
187
180
  .option('--title <title>', 'Create a new page with this title')
188
181
  .option('--update', 'Update existing page using smart diff (preserves block UIDs)')
189
- .option('-p, --page <ref>', 'Target page by title or UID (default: daily page, creates if missing)')
190
- .option('--parent <ref>', 'Nest under block UID ((uid)) or heading text (creates if missing). Use # prefix for heading level: "## Section"')
182
+ .option('-p, --page <ref>', 'Target page by title (creates if missing), or by UID as ((uid)) (must exist). Default: daily page')
183
+ .option('--parent <text>', 'Nest under the block with this text on the target page (creates if missing). Use # prefix for heading level: "## Section". Passing a UID here is deprecated: use --parent-uid')
184
+ .option('--parent-uid <uid>', 'Nest under the block with this UID (must exist). Accepts uid or ((uid))')
191
185
  .option('-c, --categories <tags>', 'Comma-separated tags appended to first block')
192
186
  .option('-t, --todo [text]', 'Add TODO item(s) to daily page. Accepts inline text or stdin')
193
187
  .option('--json', 'Force JSON array format: [{text, level, heading?}, ...]')
@@ -206,11 +200,11 @@ Examples:
206
200
 
207
201
  # Save under heading (creates if missing)
208
202
  roam save --parent "## Notes" "My note" # Under H2 "Notes" heading
209
- roam save --parent "((blockUid9))" "Child" # Under specific block
203
+ roam save --parent-uid blockUid9 "Child" # Under specific block, by UID
210
204
 
211
205
  # Target specific page
212
206
  roam save -p "Project X" "Status update" # By title (creates if missing)
213
- roam save -p "pageUid123" "Note" # By UID
207
+ roam save -p "((pageUid12))" "Note" # By UID (must exist)
214
208
 
215
209
  # File operations
216
210
  roam save notes.md --title "My Notes" # Create page from file
@@ -350,24 +344,6 @@ JSON format (--json):
350
344
  const categories = options.categories
351
345
  ? options.categories.split(',').map(c => c.trim()).filter(Boolean)
352
346
  : undefined;
353
- // Determine parent type if specified
354
- let parentUid;
355
- let parentHeading;
356
- let parentHeadingLevel;
357
- if (options.parent) {
358
- const cleanedParent = options.parent.replace(/^\(\(|\)\)$/g, '');
359
- if (isBlockUid(cleanedParent)) {
360
- parentUid = cleanedParent;
361
- }
362
- else {
363
- // Parse heading syntax from parent text
364
- const { heading_level, content } = parseMarkdownHeadingLevel(options.parent);
365
- parentHeading = content;
366
- if (heading_level > 0) {
367
- parentHeadingLevel = heading_level;
368
- }
369
- }
370
- }
371
347
  // Parse --order option
372
348
  let orderValue = 'last';
373
349
  if (options.order !== undefined) {
@@ -394,8 +370,7 @@ JSON format (--json):
394
370
  printDebug('Order', orderValue);
395
371
  printDebug('Graph', options.graph || 'default');
396
372
  printDebug('Content blocks', contentBlocks.length);
397
- printDebug('Parent UID', parentUid || 'none');
398
- printDebug('Parent heading', parentHeading || 'none');
373
+ printDebug('Parent', options.parentUid ?? options.parent ?? 'none');
399
374
  printDebug('Target page', options.page || 'daily page');
400
375
  printDebug('Categories', categories || 'none');
401
376
  printDebug('Title', options.title || 'none');
@@ -411,6 +386,33 @@ JSON format (--json):
411
386
  console.error('');
412
387
  }
413
388
  const graph = resolveGraph(options, true);
389
+ // Resolve the parent before any write. A UID is never guessed from its
390
+ // shape: --parent-uid and ((uid)) must exist, and a bare 9-character
391
+ // --parent value is a UID only if the graph has it.
392
+ const exists = (uid) => uidExists(graph, uid);
393
+ const parentTarget = await resolveParentRef({ parent: options.parent, parentUid: options.parentUid }, exists);
394
+ let parentUid;
395
+ let parentHeading;
396
+ let parentHeadingLevel;
397
+ if (parentTarget?.kind === 'uid') {
398
+ parentUid = parentTarget.uid;
399
+ if (parentTarget.deprecated) {
400
+ console.error(`Warning: passing a block UID to --parent is deprecated. In 5.0 --parent will always mean ` +
401
+ `the text of the parent block. Use: --parent-uid ${parentUid}`);
402
+ }
403
+ }
404
+ else if (parentTarget) {
405
+ // Parse heading syntax from parent text
406
+ const { heading_level, content } = parseMarkdownHeadingLevel(parentTarget.text);
407
+ parentHeading = content;
408
+ if (heading_level > 0) {
409
+ parentHeadingLevel = heading_level;
410
+ }
411
+ }
412
+ if (options.debug) {
413
+ printDebug('Parent UID', parentUid || 'none');
414
+ printDebug('Parent heading', parentHeading || 'none');
415
+ }
414
416
  // Determine operation mode based on options
415
417
  const hasParent = parentUid || parentHeading;
416
418
  const hasTitle = options.title;
@@ -515,14 +517,12 @@ JSON format (--json):
515
517
  // Parent heading or target page: get target page UID first
516
518
  let pageUid;
517
519
  if (options.page) {
518
- // Strip (( )) wrapper if UID, but NOT [[ ]] (that's valid page title syntax)
519
- const cleanedPage = options.page.replace(/^\(\(|\)\)$/g, '');
520
- if (isBlockUid(cleanedPage)) {
521
- pageUid = cleanedPage;
522
- }
523
- else {
524
- pageUid = await findOrCreatePage(graph, options.page);
525
- }
520
+ // ((uid)) must exist; a bare 9-character value is a UID only if the
521
+ // graph has it, otherwise a title ("Learnings"). [[ ]] is left alone.
522
+ const pageTarget = await resolvePageRef(options.page, exists);
523
+ pageUid = pageTarget.kind === 'uid'
524
+ ? pageTarget.uid
525
+ : await findOrCreatePage(graph, pageTarget.title);
526
526
  }
527
527
  else {
528
528
  pageUid = await getDailyPageUid(graph);
@@ -533,7 +533,11 @@ JSON format (--json):
533
533
  // Resolve heading to parent UID if specified
534
534
  let targetParentUid;
535
535
  if (parentHeading) {
536
- targetParentUid = await findOrCreateHeading(graph, pageUid, parentHeading, parentHeadingLevel);
536
+ const heading = await findOrCreateHeading(graph, pageUid, parentHeading, parentHeadingLevel);
537
+ targetParentUid = heading.uid;
538
+ if (heading.created) {
539
+ console.error(`Created parent block "${parentHeading}" (uid: ${heading.uid})`);
540
+ }
537
541
  }
538
542
  else {
539
543
  targetParentUid = pageUid;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Classify a `roam save` reference (`--parent`, `--page`) by what its shape can
3
+ * actually establish. Pure: no graph access.
4
+ *
5
+ * This replaces a heuristic that required a digit before believing a value was
6
+ * a UID. About one block UID in five has no digit, so `--parent "((uid))"`
7
+ * silently became heading text for those. Shape alone cannot tell a bare
8
+ * 9-character UID from a 9-character title like "Learnings"; that case is
9
+ * reported as `ambiguous` and the caller asks the graph.
10
+ */
11
+ const UID_SHAPE = /^[a-zA-Z0-9_-]{9}$/;
12
+ const WRAPPED = /^\(\((.*)\)\)$/s;
13
+ export function classifyRef(raw) {
14
+ const inner = raw.match(WRAPPED)?.[1];
15
+ if (inner !== undefined && UID_SHAPE.test(inner)) {
16
+ return { kind: 'uid', uid: inner };
17
+ }
18
+ if (UID_SHAPE.test(raw)) {
19
+ return { kind: 'ambiguous', value: raw };
20
+ }
21
+ return { kind: 'text', value: raw };
22
+ }
23
+ /**
24
+ * Parse the value of `--parent-uid`, which is never text. Accepts `uid` or
25
+ * `((uid))`; throws on anything else.
26
+ */
27
+ export function parseUidFlag(raw) {
28
+ const candidate = raw.match(WRAPPED)?.[1] ?? raw;
29
+ if (!UID_SHAPE.test(candidate)) {
30
+ throw new Error(`--parent-uid expects a 9-character block UID (uid or "((uid))"), got "${raw}". ` +
31
+ `To nest under a block by its text, use --parent.`);
32
+ }
33
+ return candidate;
34
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Resolve `roam save`'s `--parent-uid`, `--parent` and `--page` values to a
3
+ * target, asking the graph only where shape cannot decide.
4
+ *
5
+ * Nothing here writes. Callers resolve every reference before their first
6
+ * write, so a reference that cannot be resolved leaves the graph untouched.
7
+ */
8
+ import { classifyRef, parseUidFlag } from './ref-classifier.js';
9
+ async function requireUid(uid, flag, exists) {
10
+ if (!(await exists(uid))) {
11
+ throw new Error(`${flag}: no block or page with UID "${uid}" exists in this graph. Nothing was written.`);
12
+ }
13
+ return uid;
14
+ }
15
+ export async function resolveParentRef(options, exists) {
16
+ const { parent, parentUid } = options;
17
+ if (parent !== undefined && parentUid !== undefined) {
18
+ throw new Error('Use either --parent (the text of the parent block) or --parent-uid (its UID), not both.');
19
+ }
20
+ if (parentUid !== undefined) {
21
+ const uid = await requireUid(parseUidFlag(parentUid), '--parent-uid', exists);
22
+ return { kind: 'uid', uid, deprecated: false };
23
+ }
24
+ if (parent === undefined)
25
+ return undefined;
26
+ const ref = classifyRef(parent);
27
+ switch (ref.kind) {
28
+ case 'uid':
29
+ return { kind: 'uid', uid: await requireUid(ref.uid, '--parent', exists), deprecated: true };
30
+ case 'ambiguous':
31
+ return (await exists(ref.value))
32
+ ? { kind: 'uid', uid: ref.value, deprecated: true }
33
+ : { kind: 'heading', text: ref.value };
34
+ case 'text':
35
+ return { kind: 'heading', text: ref.value };
36
+ }
37
+ }
38
+ export async function resolvePageRef(page, exists) {
39
+ const ref = classifyRef(page);
40
+ switch (ref.kind) {
41
+ case 'uid':
42
+ return { kind: 'uid', uid: await requireUid(ref.uid, '--page', exists) };
43
+ case 'ambiguous':
44
+ return (await exists(ref.value))
45
+ ? { kind: 'uid', uid: ref.value }
46
+ : { kind: 'title', title: ref.value };
47
+ case 'text':
48
+ return { kind: 'title', title: ref.value };
49
+ }
50
+ }
@@ -106,6 +106,20 @@ async function batchCheckExistence(graph, uids, config = DEFAULT_RATE_LIMIT_CONF
106
106
  }
107
107
  throw new McpError(ErrorCode.InternalError, `Rate limit exceeded checking page existence after ${config.maxRetries} retries: ${lastError?.message || 'Unknown error'}`);
108
108
  }
109
+ /**
110
+ * Check whether a single UID names an existing entity (page or block).
111
+ * Shares the session cache with `ensurePagesExist`, so a UID confirmed here is
112
+ * not queried again when a batch then writes under it.
113
+ */
114
+ export async function uidExists(graph, uid) {
115
+ if (pageUidCache.hasUid(uid))
116
+ return true;
117
+ const existing = await batchCheckExistence(graph, [uid]);
118
+ if (!existing.has(uid))
119
+ return false;
120
+ pageUidCache.addUid(uid);
121
+ return true;
122
+ }
109
123
  /**
110
124
  * Batch create daily pages that don't exist.
111
125
  * Uses Roam's createPage API.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roam-research-mcp",
3
- "version": "4.0.1",
3
+ "version": "4.1.0",
4
4
  "description": "MCP server and CLI for Roam Research",
5
5
  "private": false,
6
6
  "repository": {
@@ -31,11 +31,10 @@
31
31
  "scripts": {
32
32
  "build": "echo \"Using custom instructions: .roam/${CUSTOM_INSTRUCTIONS_PREFIX}custom-instructions.md\" && tsc && cat Roam_Markdown_Cheatsheet.md .roam/${CUSTOM_INSTRUCTIONS_PREFIX}custom-instructions.md > build/Roam_Markdown_Cheatsheet.md && chmod 755 build/index.js build/cli/roam.js",
33
33
  "clean": "rm -rf build",
34
- "prepublishOnly": "node scripts/check-bundled-cheatsheet.mjs",
34
+ "prepublishOnly": "npm run clean && npm run build && node scripts/check-bundled-cheatsheet.mjs",
35
35
  "watch": "tsc --watch",
36
36
  "inspector": "npx @modelcontextprotocol/inspector build/index.js",
37
37
  "start": "node build/index.js",
38
- "prepublishOnly": "npm run clean && npm run build",
39
38
  "release": "standard-version",
40
39
  "release:patch": "standard-version --release-as patch",
41
40
  "release:minor": "standard-version --release-as minor",