1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Re-export SDK modules so binary-internal modules can use crate::api:: and crate::error::
pub(crate) use roam_sdk::{api, error};
mod app;
mod commands;
mod config;
mod edit_buffer;
mod export;
mod highlight;
mod keys;
mod markdown;
mod mcp;
mod ui;
use std::path::PathBuf;
use clap::{Parser, Subcommand};
use config::AppConfig;
use roam_sdk::api::client::RoamClient;
#[derive(Parser)]
#[command(name = "roam", about = "Roam Research TUI and MCP server")]
struct Cli {
/// Run as MCP server (stdio transport)
#[arg(long, hide = true)]
mcp: bool,
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand)]
enum Commands {
/// Run as MCP server (stdio transport)
Mcp,
/// Journal — view or add to today's daily note (alias: j)
#[command(alias = "j")]
Journal {
#[command(subcommand)]
action: Option<JournalAction>,
},
/// Search pages or blocks
Search {
/// Search query string
query: String,
/// Search inside block content instead of page titles
#[arg(long, short)]
blocks: bool,
/// Maximum number of results
#[arg(long, short)]
limit: Option<usize>,
},
/// Get a resource (page, block, daily note, backlinks, refs, stats)
Get {
#[command(subcommand)]
resource: GetResource,
},
/// Run a raw Datalog query
Query {
/// Datalog query string
query: String,
/// JSON array of query arguments
#[arg(long)]
args: Option<String>,
},
/// Export daily notes or pages to JSON or Markdown
Export {
/// Date in YYYY-MM-DD format (default: today)
#[arg(long)]
date: Option<String>,
/// Page title to export (if set, exports a page instead of daily note)
#[arg(long)]
page: Option<String>,
/// Output format: "md" or "json" (default: md)
#[arg(long, default_value = "md")]
format: String,
/// Output file path (default: stdout)
#[arg(long, short)]
output: Option<String>,
},
/// Create a page or block
Create {
#[command(subcommand)]
resource: CreateResource,
},
/// Update a block's content
Update {
#[command(subcommand)]
resource: UpdateResource,
},
/// Delete a block or page
Delete {
#[command(subcommand)]
resource: DeleteResource,
},
/// Move a block to a new parent
Move {
#[command(subcommand)]
resource: MoveResource,
},
/// Execute batch write operations from a JSON file or stdin
Batch {
/// JSON file path (use "-" for stdin)
#[arg(default_value = "-")]
file: String,
},
}
#[derive(Subcommand)]
enum JournalAction {
/// View today's (or a specific date's) daily note
View {
/// Date in YYYY-MM-DD format (default: today)
#[arg(long)]
date: Option<String>,
},
/// Add a block to the daily note
Add {
/// Block content
text: String,
/// Date in YYYY-MM-DD format (default: today)
#[arg(long)]
date: Option<String>,
/// Position: "first", "last", or numeric index
#[arg(long)]
order: Option<String>,
/// JSON array of child block strings
#[arg(long)]
children: Option<String>,
},
}
#[derive(Subcommand)]
enum GetResource {
/// Get a page by title
Page {
/// Page title
title: String,
},
/// Get a block by UID
Block {
/// Block UID
uid: String,
},
/// Get a daily note
Daily {
/// Date in YYYY-MM-DD format (default: today)
#[arg(long)]
date: Option<String>,
},
/// Get backlinks for a page
Backlinks {
/// Page title
title: String,
},
/// Get outbound references from a block
Refs {
/// Block UID
uid: String,
},
/// Get graph statistics (page and block counts)
Stats,
}
#[derive(Subcommand)]
enum CreateResource {
/// Create a new page
Page {
/// Page title
title: String,
/// Optional page UID
#[arg(long)]
uid: Option<String>,
},
/// Create a new block
Block {
/// Parent block or page UID
#[arg(long)]
parent: String,
/// Block content
content: String,
/// Position: "first", "last", or numeric index
#[arg(long)]
order: Option<String>,
/// Optional block UID
#[arg(long)]
uid: Option<String>,
/// JSON array of child block strings
#[arg(long)]
children: Option<String>,
},
}
#[derive(Subcommand)]
enum UpdateResource {
/// Update a block's content
Block {
/// Block UID
uid: String,
/// New content
content: String,
},
}
#[derive(Subcommand)]
enum DeleteResource {
/// Delete a block by UID
Block {
/// Block UID
uid: String,
},
/// Delete a page by UID
Page {
/// Page UID
uid: String,
},
}
#[derive(Subcommand)]
enum MoveResource {
/// Move a block to a new parent
Block {
/// Block UID to move
uid: String,
/// New parent UID
#[arg(long)]
parent: String,
/// Position: "first", "last", or numeric index
#[arg(long)]
order: Option<String>,
},
}
fn config_path() -> PathBuf {
AppConfig::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("config.toml")
}
fn make_client(config: &AppConfig) -> RoamClient {
RoamClient::new(&config.graph.name, &config.graph.api_token)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli_args = Cli::parse();
let path = config_path();
if !path.exists() {
AppConfig::write_default(&path)?;
eprintln!(
"Created default config at: {}\nPlease edit it with your Roam graph name and API token, then run again.",
path.display()
);
return Ok(());
}
let config = match AppConfig::load_from_path(&path) {
Ok(c) => c,
Err(e) => {
eprintln!("Failed to load config from {}: {}", path.display(), e);
eprintln!("Fix the config file or delete it to regenerate defaults.");
return Ok(());
}
};
// Handle --mcp flag (backward compat, hidden)
if cli_args.mcp {
mcp::run(&config).await?;
return Ok(());
}
if let Some(command) = cli_args.command {
let client = make_client(&config);
let result = match command {
Commands::Mcp => {
mcp::run(&config).await?;
return Ok(());
}
Commands::Journal { action } => match action {
None => commands::journal_view(&client, None).await,
Some(JournalAction::View { date }) => {
commands::journal_view(&client, date.as_deref()).await
}
Some(JournalAction::Add {
text,
date,
order,
children,
}) => {
commands::journal_add(
&client,
&text,
date.as_deref(),
order.as_deref(),
children.as_deref(),
)
.await
}
},
Commands::Search {
query,
blocks,
limit,
} => commands::search(&client, &query, blocks, limit).await,
Commands::Get { resource } => match resource {
GetResource::Page { title } => commands::get_page(&client, &title).await,
GetResource::Block { uid } => commands::get_block(&client, &uid).await,
GetResource::Daily { date } => commands::get_daily(&client, date.as_deref()).await,
GetResource::Backlinks { title } => commands::get_backlinks(&client, &title).await,
GetResource::Refs { uid } => commands::get_refs(&client, &uid).await,
GetResource::Stats => commands::get_stats(&client).await,
},
Commands::Query { query, args } => {
commands::query(&client, &query, args.as_deref()).await
}
Commands::Export {
date,
page,
format,
output,
} => {
commands::run_export(
&client,
date.as_deref(),
page.as_deref(),
&format,
output.as_deref(),
)
.await?;
return Ok(());
}
Commands::Create { resource } => match resource {
CreateResource::Page { title, uid } => {
commands::create_page(&client, &title, uid.as_deref()).await
}
CreateResource::Block {
parent,
content,
order,
uid,
children,
} => {
commands::create_block(
&client,
&parent,
&content,
order.as_deref(),
uid.as_deref(),
children.as_deref(),
)
.await
}
},
Commands::Update { resource } => match resource {
UpdateResource::Block { uid, content } => {
commands::update_block(&client, &uid, &content).await
}
},
Commands::Delete { resource } => match resource {
DeleteResource::Block { uid } => commands::delete_block(&client, &uid).await,
DeleteResource::Page { uid } => commands::delete_page(&client, &uid).await,
},
Commands::Move { resource } => match resource {
MoveResource::Block { uid, parent, order } => {
commands::move_block(&client, &uid, &parent, order.as_deref()).await
}
},
Commands::Batch { file } => {
let input = if file == "-" {
use std::io::Read;
let mut buf = String::new();
std::io::stdin().read_to_string(&mut buf)?;
buf
} else {
std::fs::read_to_string(&file)?
};
commands::batch(&client, &input).await
}
};
match result {
Ok(output) => {
println!("{}", output);
}
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
return Ok(());
}
// No subcommand — launch TUI
let mut terminal = ratatui::init();
let _ = crossterm::execute!(
std::io::stdout(),
crossterm::event::PushKeyboardEnhancementFlags(
crossterm::event::KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES
)
);
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = crossterm::execute!(
std::io::stdout(),
crossterm::event::PopKeyboardEnhancementFlags
);
ratatui::restore();
hook(info);
}));
let result = app::run(&config, &mut terminal).await;
let _ = crossterm::execute!(
std::io::stdout(),
crossterm::event::PopKeyboardEnhancementFlags
);
ratatui::restore();
if let Err(e) = result {
eprintln!("Error: {}", e);
}
Ok(())
}