roam-research-mcp 5.1.0 → 6.1.1
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 +50 -2
- package/build/cache/page-uid-cache.js +12 -3
- package/build/cli/batch/resolver.js +3 -3
- package/build/cli/commands/batch.js +5 -4
- package/build/cli/commands/get.js +11 -30
- package/build/cli/commands/refs.js +1 -2
- package/build/cli/commands/rename.js +19 -21
- package/build/cli/commands/save.js +1 -2
- package/build/cli/commands/search.js +31 -66
- package/build/cli/commands/update.js +1 -2
- package/build/cli/utils/output.js +7 -1
- package/build/config/graph-registry.js +2 -0
- package/build/search/datomic-search.js +2 -0
- package/build/search/tag-search.js +4 -19
- package/build/search/text-search.js +11 -47
- package/build/search/types.js +3 -6
- package/build/search/utils.js +17 -32
- package/build/server/roam-server.js +2 -2
- package/build/shared/errors.js +7 -0
- package/build/shared/page-validator.js +24 -72
- package/build/shared/retry.js +12 -2
- package/build/shared/staged-batch.js +12 -1
- package/build/tools/helpers/batch-utils.js +2 -0
- package/build/tools/helpers/fetch-children.js +7 -4
- package/build/tools/helpers/page-resolution.js +9 -9
- package/build/tools/helpers/refs.js +71 -40
- package/build/tools/operations/batch.js +115 -20
- package/build/tools/operations/block-retrieval.js +64 -1
- package/build/tools/operations/blocks.js +2 -0
- package/build/tools/operations/memory.js +2 -0
- package/build/tools/operations/outline.js +6 -0
- package/build/tools/operations/pages.js +42 -14
- package/build/tools/operations/search/index.js +96 -37
- package/build/tools/schemas.js +16 -8
- package/build/tools/tool-handlers.js +3 -3
- package/build/utils/roam-http-client.js +41 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -20,6 +20,25 @@ Whether you want to give Claude superpowers over your knowledge base or just wan
|
|
|
20
20
|
|
|
21
21
|

|
|
22
22
|
|
|
23
|
+
## What's New in v6.1
|
|
24
|
+
|
|
25
|
+
**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`.
|
|
26
|
+
|
|
27
|
+
**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.
|
|
28
|
+
|
|
29
|
+
## What's New in v6.0
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
33
|
+
- **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.
|
|
34
|
+
- **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.
|
|
35
|
+
- **Caches stay with their graph connection.** Page UID lookups cannot leak between graph connections, and successful page renames clear that connection's cached lookups.
|
|
36
|
+
- **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.
|
|
37
|
+
|
|
38
|
+
**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.
|
|
39
|
+
|
|
40
|
+
See the [changelog](CHANGELOG.md) for the four merged changes and their regression coverage.
|
|
41
|
+
|
|
23
42
|
## What's New in v5.0
|
|
24
43
|
|
|
25
44
|
**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 +120,10 @@ roam save -p "Changelog" --order first "v2.18.0 release"
|
|
|
101
120
|
# Search your graph and pipe results to another tool
|
|
102
121
|
roam search "important" --json | jq .
|
|
103
122
|
|
|
123
|
+
# Fetch the next 20 matching blocks, or all matches after the offset
|
|
124
|
+
roam search "important" --limit 20 --offset 20
|
|
125
|
+
roam search "important" --limit -1 --offset 20 --json
|
|
126
|
+
|
|
104
127
|
# Search for pages by namespace prefix
|
|
105
128
|
roam search --namespace "Convention" # Finds all Convention/* pages
|
|
106
129
|
|
|
@@ -163,10 +186,10 @@ The MCP server exposes these tools to AI assistants (like Claude), enabling them
|
|
|
163
186
|
| `roam_create_page` | Create new pages, optionally with mixed text and table content. |
|
|
164
187
|
| `roam_update_page_markdown` | Update a page using smart diff (preserves block UIDs). |
|
|
165
188
|
| `roam_get_subpages` | List sub-pages under a namespace prefix (e.g. "Project/") with optional tag filter. |
|
|
166
|
-
| `roam_search_by_text` |
|
|
189
|
+
| `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
190
|
| `roam_search_block_refs` | Find blocks that reference a page, tag, or block UID. |
|
|
168
191
|
| `roam_search_by_status` | Find TODO or DONE items. |
|
|
169
|
-
| `roam_search_for_tag` | Find blocks
|
|
192
|
+
| `roam_search_for_tag` | Find blocks directly referencing a page or tag (supports exclusion). |
|
|
170
193
|
| `roam_search_by_date` | Find blocks/pages by creation or modification date. |
|
|
171
194
|
| `roam_find_pages_modified_today` | List pages modified since midnight. |
|
|
172
195
|
| `roam_add_todo` | Add TODO items to today's daily page. |
|
|
@@ -203,6 +226,31 @@ Three things worth knowing:
|
|
|
203
226
|
|
|
204
227
|
---
|
|
205
228
|
|
|
229
|
+
## Writing notes for better retrieval
|
|
230
|
+
|
|
231
|
+
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.
|
|
232
|
+
|
|
233
|
+
For example, a note about this project's search behavior could look like:
|
|
234
|
+
|
|
235
|
+
```text
|
|
236
|
+
- A note containing only a [[block reference]] will not match a text search for the referenced block's wording. #retrieval
|
|
237
|
+
- Evidence:: The text-search handler selects matching blocks before expanding block references.
|
|
238
|
+
- Source:: [Text search implementation](https://github.com/2b3pro/roam-research-mcp/blob/main/src/search/text-search.ts)
|
|
239
|
+
- **Practical implication:** Keep useful wording on the original knowledge block, then reference that block where you reuse it.
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
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.
|
|
243
|
+
|
|
244
|
+
- **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.
|
|
245
|
+
- **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.
|
|
246
|
+
- **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.
|
|
247
|
+
|
|
248
|
+
**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.
|
|
249
|
+
|
|
250
|
+
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.
|
|
251
|
+
|
|
252
|
+
---
|
|
253
|
+
|
|
206
254
|
## Agent guidelines (per-graph)
|
|
207
255
|
|
|
208
256
|
`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
|
-
//
|
|
93
|
-
|
|
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 {
|
|
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 =
|
|
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
|
-
|
|
32
|
+
getPageUidCache(graph).set(title, uid);
|
|
33
33
|
}
|
|
34
34
|
return uid;
|
|
35
35
|
}
|
|
@@ -84,9 +84,11 @@ function validatePlaceholders(commands) {
|
|
|
84
84
|
* Output partial results when a failure occurs mid-batch
|
|
85
85
|
* Helps user know what was created and may need manual cleanup
|
|
86
86
|
*/
|
|
87
|
-
function outputPartialResults(pageResults, failedPage, batchError) {
|
|
87
|
+
function outputPartialResults(pageResults, failedPage, batchError, failure) {
|
|
88
88
|
const output = {
|
|
89
89
|
success: false,
|
|
90
|
+
...(failure?.error && { error: failure.error }),
|
|
91
|
+
...(failure?.committed && { committed: failure.committed }),
|
|
90
92
|
partial: true,
|
|
91
93
|
pages_created: pageResults.length,
|
|
92
94
|
...(failedPage && { failed_at: `page: ${failedPage}` }),
|
|
@@ -332,7 +334,7 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
|
|
|
332
334
|
? batchResult.error
|
|
333
335
|
: batchResult.error?.message || 'Unknown error';
|
|
334
336
|
// Report partial results (pages created before batch failed)
|
|
335
|
-
outputPartialResults(pageResults, undefined, errorMsg);
|
|
337
|
+
outputPartialResults(pageResults, undefined, errorMsg, batchResult);
|
|
336
338
|
}
|
|
337
339
|
}
|
|
338
340
|
// Build output
|
|
@@ -355,8 +357,7 @@ Output (JSON): { success, pages_created, actions_executed, uid_map? }
|
|
|
355
357
|
console.log(JSON.stringify(output, null, 2));
|
|
356
358
|
}
|
|
357
359
|
catch (error) {
|
|
358
|
-
|
|
359
|
-
exitWithError(message);
|
|
360
|
+
exitWithError(error);
|
|
360
361
|
}
|
|
361
362
|
});
|
|
362
363
|
}
|
|
@@ -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 {
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
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
|
-
|
|
670
|
-
exitWithError(message);
|
|
651
|
+
exitWithError(error);
|
|
671
652
|
}
|
|
672
653
|
});
|
|
673
654
|
// Add subcommands
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
|
-
import {
|
|
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 (
|
|
9
|
-
.argument('
|
|
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 (
|
|
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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
:
|
|
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
|
-
|
|
47
|
-
console.log(`Renamed ${identifier} → "${newTitle}"`);
|
|
45
|
+
if (result.success) {
|
|
46
|
+
console.log(result.message);
|
|
48
47
|
}
|
|
49
48
|
else {
|
|
50
|
-
exitWithError(
|
|
49
|
+
exitWithError(result.message);
|
|
51
50
|
}
|
|
52
51
|
}
|
|
53
52
|
catch (error) {
|
|
54
|
-
|
|
55
|
-
exitWithError(message);
|
|
53
|
+
exitWithError(error);
|
|
56
54
|
}
|
|
57
55
|
});
|
|
58
56
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
|
-
import { SearchOperations } from '../../tools/operations/search/index.js';
|
|
2
|
+
import { SearchOperations, validateSearchPage } from '../../tools/operations/search/index.js';
|
|
3
3
|
import { formatSearchResults, printDebug, exitWithError } from '../utils/output.js';
|
|
4
4
|
import { resolveGraph } from '../utils/graph.js';
|
|
5
5
|
import { readStdin } from '../utils/input.js';
|
|
@@ -14,9 +14,8 @@ function normalizeTag(tag) {
|
|
|
14
14
|
*/
|
|
15
15
|
function contentHasTag(content, tag) {
|
|
16
16
|
const normalized = normalizeTag(tag);
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
content.includes(`#[[${normalized}]]`));
|
|
17
|
+
const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
18
|
+
return new RegExp(`\\[\\[${escaped}\\]\\]|#${escaped}(?![\\p{L}\\p{N}_/-])`, 'iu').test(content);
|
|
20
19
|
}
|
|
21
20
|
export function createSearchCommand() {
|
|
22
21
|
return new Command('search')
|
|
@@ -34,7 +33,8 @@ export function createSearchCommand() {
|
|
|
34
33
|
}, [])
|
|
35
34
|
.option('--page <title>', 'Scope search to a specific page')
|
|
36
35
|
.option('-i, --case-insensitive', 'Case-insensitive search')
|
|
37
|
-
.option('-n, --limit <n>', 'Limit
|
|
36
|
+
.option('-n, --limit <n>', 'Limit results; -1 returns all (default: 20)', '20')
|
|
37
|
+
.option('--offset <n>', 'Skip matching results after filtering (default: 0)', '0')
|
|
38
38
|
.option('--json', 'Output as JSON')
|
|
39
39
|
.option('--debug', 'Show query metadata')
|
|
40
40
|
.option('-g, --graph <name>', 'Target graph key (for multi-graph mode)')
|
|
@@ -76,7 +76,9 @@ Note: For hierarchical output with children, use 'roam get --tag/--text' instead
|
|
|
76
76
|
.action(async (terms, options) => {
|
|
77
77
|
try {
|
|
78
78
|
const graph = resolveGraph(options, false);
|
|
79
|
-
const limit =
|
|
79
|
+
const limit = Number(options.limit ?? '20');
|
|
80
|
+
const offset = Number(options.offset ?? '0');
|
|
81
|
+
validateSearchPage({ limit, offset });
|
|
80
82
|
const outputOptions = {
|
|
81
83
|
json: options.json,
|
|
82
84
|
debug: options.debug
|
|
@@ -99,12 +101,12 @@ Note: For hierarchical output with children, use 'roam get --tag/--text' instead
|
|
|
99
101
|
if (options.namespace) {
|
|
100
102
|
const result = await searchOps.searchByText({
|
|
101
103
|
text: options.namespace,
|
|
102
|
-
scope: 'page_titles'
|
|
104
|
+
scope: 'page_titles', limit, offset
|
|
103
105
|
});
|
|
104
106
|
if (!result.success) {
|
|
105
107
|
exitWithError(result.message || 'Namespace search failed');
|
|
106
108
|
}
|
|
107
|
-
|
|
109
|
+
const matches = result.matches;
|
|
108
110
|
if (options.json) {
|
|
109
111
|
// For JSON output, return page_uid and page_title
|
|
110
112
|
const jsonMatches = matches.map(m => ({
|
|
@@ -118,7 +120,7 @@ Note: For hierarchical output with children, use 'roam get --tag/--text' instead
|
|
|
118
120
|
console.log('No pages found.');
|
|
119
121
|
}
|
|
120
122
|
else {
|
|
121
|
-
console.log(`Found ${result.matches.length} page(s)${
|
|
123
|
+
console.log(`Found ${result.total_count ?? matches.length} page(s) (showing ${matches.length}, offset ${offset}):\n`);
|
|
122
124
|
for (const match of matches) {
|
|
123
125
|
console.log(`- ${match.page_title} (${match.block_uid})`);
|
|
124
126
|
}
|
|
@@ -151,7 +153,7 @@ Note: For hierarchical output with children, use 'roam get --tag/--text' instead
|
|
|
151
153
|
exitWithError(result.message || 'Query failed');
|
|
152
154
|
}
|
|
153
155
|
// Apply limit and format output
|
|
154
|
-
const limitedMatches = result.matches.slice(
|
|
156
|
+
const limitedMatches = result.matches.slice(offset, limit === -1 ? undefined : offset + limit);
|
|
155
157
|
if (options.json) {
|
|
156
158
|
const parsed = limitedMatches.map(m => {
|
|
157
159
|
try {
|
|
@@ -168,7 +170,7 @@ Note: For hierarchical output with children, use 'roam get --tag/--text' instead
|
|
|
168
170
|
console.log('No results found.');
|
|
169
171
|
}
|
|
170
172
|
else {
|
|
171
|
-
console.log(`Found ${result.matches.length} results${
|
|
173
|
+
console.log(`Found ${result.matches.length} results (showing ${limitedMatches.length}, offset ${offset}):\n`);
|
|
172
174
|
for (const match of limitedMatches) {
|
|
173
175
|
console.log(match.content);
|
|
174
176
|
}
|
|
@@ -176,70 +178,33 @@ Note: For hierarchical output with children, use 'roam get --tag/--text' instead
|
|
|
176
178
|
}
|
|
177
179
|
return;
|
|
178
180
|
}
|
|
179
|
-
|
|
180
|
-
const
|
|
181
|
+
const tags = (options.tag || []).map(normalizeTag);
|
|
182
|
+
const negTags = (options.negtag || []).map(normalizeTag);
|
|
183
|
+
const page = {
|
|
184
|
+
limit, offset,
|
|
185
|
+
filter: (match) => (tags.length === 0 || (options.any
|
|
186
|
+
? tags.some(tag => contentHasTag(match.content, tag))
|
|
187
|
+
: tags.every(tag => contentHasTag(match.content, tag)))) &&
|
|
188
|
+
!negTags.some(tag => contentHasTag(match.content, tag)),
|
|
189
|
+
};
|
|
190
|
+
let result;
|
|
181
191
|
if (tags.length > 0 && searchTerms.length === 0) {
|
|
182
|
-
|
|
183
|
-
const normalizedTags = tags.map(normalizeTag);
|
|
184
|
-
const useOrLogic = options.any || false;
|
|
185
|
-
const result = await searchOps.searchForTag(normalizedTags[0], options.page);
|
|
186
|
-
let matches = result.matches;
|
|
187
|
-
if (normalizedTags.length > 1) {
|
|
188
|
-
matches = matches.filter(m => {
|
|
189
|
-
if (useOrLogic) {
|
|
190
|
-
return normalizedTags.some(tag => contentHasTag(m.content, tag));
|
|
191
|
-
}
|
|
192
|
-
else {
|
|
193
|
-
return normalizedTags.every(tag => contentHasTag(m.content, tag));
|
|
194
|
-
}
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
const negTags = options.negtag || [];
|
|
198
|
-
if (negTags.length > 0) {
|
|
199
|
-
const normalizedNegTags = negTags.map(normalizeTag);
|
|
200
|
-
matches = matches.filter(m => !normalizedNegTags.some(tag => contentHasTag(m.content, tag)));
|
|
201
|
-
}
|
|
202
|
-
const limitedMatches = matches.slice(0, limit);
|
|
203
|
-
console.log(formatSearchResults(limitedMatches, outputOptions));
|
|
192
|
+
result = await searchOps.searchForTags(tags, options.page, options.any || false, page);
|
|
204
193
|
}
|
|
205
194
|
else if (searchTerms.length > 0) {
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
text: searchText,
|
|
210
|
-
page_title_uid: options.page
|
|
211
|
-
});
|
|
212
|
-
let matches = result.matches;
|
|
213
|
-
if (options.caseInsensitive) {
|
|
214
|
-
const lowerSearchText = searchText.toLowerCase();
|
|
215
|
-
matches = matches.filter(m => m.content.toLowerCase().includes(lowerSearchText));
|
|
216
|
-
}
|
|
217
|
-
if (tags.length > 0) {
|
|
218
|
-
const normalizedTags = tags.map(normalizeTag);
|
|
219
|
-
const useOrLogic = options.any || false;
|
|
220
|
-
matches = matches.filter(m => {
|
|
221
|
-
if (useOrLogic) {
|
|
222
|
-
return normalizedTags.some(tag => contentHasTag(m.content, tag));
|
|
223
|
-
}
|
|
224
|
-
else {
|
|
225
|
-
return normalizedTags.every(tag => contentHasTag(m.content, tag));
|
|
226
|
-
}
|
|
227
|
-
});
|
|
228
|
-
}
|
|
229
|
-
const negTags = options.negtag || [];
|
|
230
|
-
if (negTags.length > 0) {
|
|
231
|
-
const normalizedNegTags = negTags.map(normalizeTag);
|
|
232
|
-
matches = matches.filter(m => !normalizedNegTags.some(tag => contentHasTag(m.content, tag)));
|
|
233
|
-
}
|
|
234
|
-
console.log(formatSearchResults(matches.slice(0, limit), outputOptions));
|
|
195
|
+
result = await searchOps.searchByText({
|
|
196
|
+
text: searchTerms.join(' '), page_title_uid: options.page,
|
|
197
|
+
}, page);
|
|
235
198
|
}
|
|
236
199
|
else {
|
|
237
200
|
exitWithError('Please provide search terms or use --tag to search by tag');
|
|
238
201
|
}
|
|
202
|
+
if (!result.success)
|
|
203
|
+
exitWithError(result.message || 'Search failed');
|
|
204
|
+
console.log(formatSearchResults(result.matches, outputOptions));
|
|
239
205
|
}
|
|
240
206
|
catch (error) {
|
|
241
|
-
|
|
242
|
-
exitWithError(message);
|
|
207
|
+
exitWithError(error);
|
|
243
208
|
}
|
|
244
209
|
});
|
|
245
210
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { RoamError } from '../../shared/errors.js';
|
|
1
2
|
import { escapeBlockString, needsNewlineEscaping, ESCAPED_NEWLINES_MARKER } from '../../shared/block-escaping.js';
|
|
2
3
|
/**
|
|
3
4
|
* Convert RoamBlock hierarchy to markdown with proper indentation.
|
|
@@ -169,6 +170,11 @@ export function printDebug(label, data) {
|
|
|
169
170
|
* Print error message and exit
|
|
170
171
|
*/
|
|
171
172
|
export function exitWithError(message, code = 1) {
|
|
172
|
-
|
|
173
|
+
if (message instanceof RoamError) {
|
|
174
|
+
console.error(JSON.stringify({ error: { ...message.context, code: message.code, message: message.message } }, null, 2));
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
console.error(`Error: ${message instanceof Error ? message.message : String(message)}`);
|
|
178
|
+
}
|
|
173
179
|
process.exit(code);
|
|
174
180
|
}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* - Lazy graph initialization (connects only when first accessed)
|
|
9
9
|
*/
|
|
10
10
|
import { initializeGraph } from '@roam-research/roam-api-sdk';
|
|
11
|
+
import { roamHttpClient } from '../utils/roam-http-client.js';
|
|
11
12
|
import { RoamError } from '../shared/errors.js';
|
|
12
13
|
import { DEFAULT_GUIDELINES_PAGE } from '../tools/operations/guidelines.js';
|
|
13
14
|
/** List of tool names that perform write operations */
|
|
@@ -115,6 +116,7 @@ export class GraphRegistry {
|
|
|
115
116
|
const graph = initializeGraph({
|
|
116
117
|
token: config.token,
|
|
117
118
|
graph: config.graph,
|
|
119
|
+
httpClient: roamHttpClient,
|
|
118
120
|
});
|
|
119
121
|
this.initialized.set(resolvedKey, graph);
|
|
120
122
|
return graph;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { rethrowRoamError } from '../shared/errors.js';
|
|
1
2
|
import { q } from '@roam-research/roam-api-sdk';
|
|
2
3
|
import { BaseSearchHandler } from './types.js';
|
|
3
4
|
export class DatomicSearchHandler extends BaseSearchHandler {
|
|
@@ -59,6 +60,7 @@ export class DatomicSearchHandler extends BaseSearchHandler {
|
|
|
59
60
|
};
|
|
60
61
|
}
|
|
61
62
|
catch (error) {
|
|
63
|
+
rethrowRoamError(error);
|
|
62
64
|
return {
|
|
63
65
|
success: false,
|
|
64
66
|
matches: [],
|
|
@@ -8,7 +8,7 @@ export class TagSearchHandler extends BaseSearchHandler {
|
|
|
8
8
|
this.params = params;
|
|
9
9
|
}
|
|
10
10
|
async execute() {
|
|
11
|
-
const { primary_tag, page_title_uid, near_tag, exclude_tag, case_sensitive = false
|
|
11
|
+
const { primary_tag, page_title_uid, near_tag, exclude_tag, case_sensitive = false } = this.params;
|
|
12
12
|
let nearTagUid;
|
|
13
13
|
if (near_tag) {
|
|
14
14
|
nearTagUid = await SearchUtils.findPageByTitleOrUid(this.graph, near_tag);
|
|
@@ -40,9 +40,6 @@ export class TagSearchHandler extends BaseSearchHandler {
|
|
|
40
40
|
}
|
|
41
41
|
const tagMatchClause = SearchUtils.buildTagMatchClause(primary_tag, '?ref-page', case_sensitive);
|
|
42
42
|
let inClause = `:in $`;
|
|
43
|
-
let queryLimit = limit === -1 ? '' : `:limit ${limit}`;
|
|
44
|
-
let queryOffset = offset === 0 ? '' : `:offset ${offset}`;
|
|
45
|
-
let queryOrder = `:order ?page-edit-time asc ?block-uid asc`; // Sort by page edit time, then block UID
|
|
46
43
|
let queryWhereClauses = `
|
|
47
44
|
${tagMatchClause}
|
|
48
45
|
[?b :block/refs ?ref-page]
|
|
@@ -50,9 +47,8 @@ export class TagSearchHandler extends BaseSearchHandler {
|
|
|
50
47
|
[?b :block/uid ?block-uid]
|
|
51
48
|
[?b :block/page ?p]
|
|
52
49
|
[?p :node/title ?page-title]
|
|
53
|
-
[?p :edit/time ?page-edit-time]
|
|
54
50
|
[(get-else $ ?b :create/time 0) ?block-create-time]
|
|
55
|
-
[(get-else $ ?b :edit/time 0) ?block-edit-time]`; //
|
|
51
|
+
[(get-else $ ?b :edit/time 0) ?block-edit-time]`; // Block timestamps for CLI sort/group
|
|
56
52
|
if (nearTagUid) {
|
|
57
53
|
queryWhereClauses += `
|
|
58
54
|
[?b :block/refs ?near-tag-page]
|
|
@@ -69,7 +65,7 @@ export class TagSearchHandler extends BaseSearchHandler {
|
|
|
69
65
|
[?p :block/uid ?target-page-uid]`;
|
|
70
66
|
}
|
|
71
67
|
const queryStr = `[:find ?block-uid ?block-str ?page-title ?block-create-time ?block-edit-time
|
|
72
|
-
${inClause}
|
|
68
|
+
${inClause}
|
|
73
69
|
:where
|
|
74
70
|
${queryWhereClauses}]`;
|
|
75
71
|
const queryArgs = [];
|
|
@@ -77,18 +73,7 @@ export class TagSearchHandler extends BaseSearchHandler {
|
|
|
77
73
|
queryArgs.push(targetPageUid);
|
|
78
74
|
}
|
|
79
75
|
const rawResults = await q(this.graph, queryStr, queryArgs);
|
|
80
|
-
|
|
81
|
-
const countQueryStr = `[:find (count ?b)
|
|
82
|
-
${inClause}
|
|
83
|
-
:where
|
|
84
|
-
${queryWhereClauses.replace(/\[\?p :edit\/time \?page-edit-time\]/, '')}]`; // Remove edit time for count query
|
|
85
|
-
const totalCountResults = await q(this.graph, countQueryStr, queryArgs);
|
|
86
|
-
const totalCount = totalCountResults[0] ? totalCountResults[0][0] : 0;
|
|
87
|
-
// Resolve block references in content
|
|
88
|
-
const resolvedResults = await this.resolveBlockRefs(rawResults);
|
|
89
|
-
const searchDescription = `referencing "${primary_tag}"`;
|
|
90
|
-
const formattedResults = SearchUtils.formatSearchResults(resolvedResults, searchDescription, !targetPageUid);
|
|
91
|
-
formattedResults.total_count = totalCount;
|
|
76
|
+
const formattedResults = SearchUtils.formatSearchResults(rawResults, `referencing "${primary_tag}"`, !targetPageUid);
|
|
92
77
|
return formattedResults;
|
|
93
78
|
}
|
|
94
79
|
}
|