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
//! /graph handler — query the entity/relation graph (#393).
//!
//! Subcommands:
//! /graph search <query> [--kind <kind>] [--compress] [--tier auto|sql|walk|llm]
//! /graph traverse <id> [--depth <n>] [--compress] [--tier auto|sql|walk|llm]
//!
//! The `--tier` flag forces a specific routing path; `auto` (default) uses
//! keyword-based heuristics in `entity_router::route_query`.
use std::path::Path;
use crate::extras::dirge_paths::ProjectPaths;
use crate::extras::session_db::SessionDb;
#[cfg(feature = "experimental-graph-search")]
use crate::ui::slash::c_result;
use crate::ui::slash::{SlashCtx, c_agent, c_error};
#[cfg(feature = "experimental-graph-search")]
/// Format a timestamp for display. Trims the date portion, keeps time.
fn short_time(ts: &str) -> &str {
ts.split_once(' ').map(|(_, rest)| rest).unwrap_or(ts)
}
#[cfg(feature = "experimental-graph-search")]
/// Extract `--tier <value>` from a slice of parts. Returns the tier string if present.
fn extract_tier<'a>(parts: &[&'a str]) -> Option<&'a str> {
parts
.iter()
.position(|s| *s == "--tier")
.and_then(|i| parts.get(i + 1))
.copied()
}
pub(crate) async fn cmd_graph(ctx: &mut SlashCtx<'_>, parts: &[&str]) -> anyhow::Result<()> {
let sub = parts.get(1).copied().unwrap_or("").trim();
match sub {
"search" => {
let remainder = &parts[2..];
let query = remainder
.iter()
.take_while(|s| **s != "--kind" && **s != "--tier")
.copied()
.collect::<Vec<_>>()
.join(" ");
if query.is_empty() {
ctx.renderer.write_line(
"/graph search <query> [--kind <kind>] [--compress] [--tier auto|sql|walk|llm]",
c_agent(),
)?;
return Ok(());
}
let kind = remainder
.iter()
.position(|s| *s == "--kind")
.and_then(|i| remainder.get(i + 1))
.copied();
let paths = ProjectPaths::new(Path::new(ctx.session.working_dir.as_str()));
let db = match SessionDb::open(&paths.session_db_path()) {
Ok(d) => d,
Err(e) => {
ctx.renderer
.write_line(&format!("session db open failed: {e}"), c_error())?;
return Ok(());
}
};
#[cfg(feature = "experimental-graph-search")]
{
let compress = remainder.contains(&"--compress");
let tier = extract_tier(parts);
let resolved_tier = match tier {
Some("sql") => crate::extras::entity_router::QueryTier::DirectSql,
Some("walk") => crate::extras::entity_router::QueryTier::GraphWalk,
Some("llm") => crate::extras::entity_router::QueryTier::Llm,
_ => crate::extras::entity_router::route_query(&query),
};
if matches!(resolved_tier, crate::extras::entity_router::QueryTier::Llm) {
ctx.renderer.write_line(
"LLM tier not yet implemented — use --tier sql or --tier walk",
c_error(),
)?;
return Ok(());
}
if matches!(
resolved_tier,
crate::extras::entity_router::QueryTier::GraphWalk
) {
// FTS5 search first, then traverse from each result
let _ = kind;
let rows = match crate::extras::entity_db::search_entities(
&db.conn, &query, kind, None, 20,
) {
Ok(r) => r,
Err(e) => {
ctx.renderer
.write_line(&format!("search error: {e}"), c_error())?;
return Ok(());
}
};
if rows.is_empty() {
ctx.renderer.write_line("no entities found", c_agent())?;
return Ok(());
}
let seed_ids: Vec<i64> = rows.iter().map(|(id, ..)| *id).collect();
let depth: u32 = parts
.iter()
.position(|s| *s == "--depth")
.and_then(|i| parts.get(i + 1))
.and_then(|s| s.parse().ok())
.unwrap_or(3);
match crate::extras::entity_search::traverse_from(
&db.conn, &seed_ids, depth, None,
) {
Ok(trace) if trace.is_empty() => {
ctx.renderer
.write_line("no edges from results", c_agent())?;
}
Ok(trace) => {
if compress {
match crate::extras::entity_compress::compress_bundle(
&db.conn, &trace, &query,
) {
Ok(summary) => {
for line in summary.lines() {
ctx.renderer.write_line(line, c_result())?;
}
}
Err(e) => {
ctx.renderer.write_line(
&format!("compress error: {e}"),
c_error(),
)?;
}
}
} else {
for (_id, path, d) in &trace {
ctx.renderer
.write_line(&format!(" d={d} {path}"), c_result())?;
}
ctx.renderer
.write_line(&format!("{} nodes", trace.len()), c_agent())?;
}
}
Err(e) => {
ctx.renderer
.write_line(&format!("traverse error: {e}"), c_error())?;
}
}
} else {
// DirectSql: FTS5 only
let _ = kind;
match crate::extras::entity_db::search_entities(
&db.conn, &query, kind, None, 20,
) {
Ok(rows) if rows.is_empty() => {
ctx.renderer.write_line("no entities found", c_agent())?;
}
Ok(rows) => {
if compress {
match crate::extras::entity_compress::compress_search_results(
&db.conn, &rows, &query,
) {
Ok(summary) => {
for line in summary.lines() {
ctx.renderer.write_line(line, c_result())?;
}
}
Err(e) => {
ctx.renderer.write_line(
&format!("compress error: {e}"),
c_error(),
)?;
}
}
} else {
for (id, _sid, ek, ename, extra, ts) in &rows {
let extra_str = extra
.as_deref()
.map(|e| format!(" {}", e))
.unwrap_or_default();
ctx.renderer.write_line(
&format!(
"#{id} {short} {ek}/{ename}{extra_str}",
short = short_time(ts),
),
c_result(),
)?;
}
ctx.renderer
.write_line(&format!("{} results", rows.len()), c_agent())?;
}
}
Err(e) => {
ctx.renderer
.write_line(&format!("search error: {e}"), c_error())?;
}
}
}
}
#[cfg(not(feature = "experimental-graph-search"))]
{
let _ = (db, query, kind);
ctx.renderer
.write_line("experimental-graph-search feature not enabled", c_error())?;
}
}
"traverse" => {
let seed_str = parts.get(2).copied().unwrap_or("");
let seed_id: i64 = match seed_str.parse() {
Ok(id) => id,
Err(_) => {
ctx.renderer.write_line(
"/graph traverse <entity-id> [--depth <n>] [--compress] [--tier auto|sql|walk|llm]",
c_agent(),
)?;
return Ok(());
}
};
let depth: u32 = parts
.iter()
.position(|s| *s == "--depth")
.and_then(|i| parts.get(i + 1))
.and_then(|s| s.parse().ok())
.unwrap_or(3);
let paths = ProjectPaths::new(Path::new(ctx.session.working_dir.as_str()));
let db = match SessionDb::open(&paths.session_db_path()) {
Ok(d) => d,
Err(e) => {
ctx.renderer
.write_line(&format!("session db open failed: {e}"), c_error())?;
return Ok(());
}
};
#[cfg(feature = "experimental-graph-search")]
{
let compress = parts.contains(&"--compress");
let tier = extract_tier(parts);
let resolved_tier = match tier {
Some("sql") => crate::extras::entity_router::QueryTier::DirectSql,
Some("walk") => crate::extras::entity_router::QueryTier::GraphWalk,
Some("llm") => crate::extras::entity_router::QueryTier::Llm,
_ => crate::extras::entity_router::QueryTier::GraphWalk,
};
if matches!(resolved_tier, crate::extras::entity_router::QueryTier::Llm) {
ctx.renderer.write_line(
"LLM tier not yet implemented — use --tier sql or --tier walk",
c_error(),
)?;
return Ok(());
}
if matches!(
resolved_tier,
crate::extras::entity_router::QueryTier::DirectSql
) {
// Direct entity lookup by id
let row: Result<(String, String, Option<String>, String), _> =
db.conn.query_row(
"SELECT kind, name, extra, created_at FROM entities WHERE id = ?1",
[seed_id],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
);
match row {
Ok((ek, ename, extra, ts)) => {
let extra_str = extra
.as_deref()
.map(|e| format!(" {}", e))
.unwrap_or_default();
ctx.renderer.write_line(
&format!(
"#{seed_id} {short} {ek}/{ename}{extra_str}",
short = short_time(&ts),
),
c_result(),
)?;
}
Err(_) => {
ctx.renderer
.write_line(&format!("entity #{seed_id} not found"), c_agent())?;
}
}
} else {
let _ = depth;
match crate::extras::entity_search::traverse_from(
&db.conn,
&[seed_id],
depth,
None,
) {
Ok(rows) if rows.is_empty() => {
ctx.renderer.write_line(
&format!("entity #{seed_id} not found or no edges"),
c_agent(),
)?;
}
Ok(rows) => {
if compress {
match crate::extras::entity_compress::compress_bundle(
&db.conn, &rows, "",
) {
Ok(summary) => {
for line in summary.lines() {
ctx.renderer.write_line(line, c_result())?;
}
}
Err(e) => {
ctx.renderer.write_line(
&format!("compress error: {e}"),
c_error(),
)?;
}
}
} else {
for (_id, path, d) in &rows {
ctx.renderer
.write_line(&format!(" d={d} {path}"), c_result())?;
}
ctx.renderer
.write_line(&format!("{} nodes", rows.len()), c_agent())?;
}
}
Err(e) => {
ctx.renderer
.write_line(&format!("traverse error: {e}"), c_error())?;
}
}
}
}
#[cfg(not(feature = "experimental-graph-search"))]
{
let _ = (db, seed_id, depth);
ctx.renderer
.write_line("experimental-graph-search feature not enabled", c_error())?;
}
}
"" => {
ctx.renderer.write_line(
"/graph search <query> [--kind <kind>] [--compress] [--tier auto|sql|walk|llm]",
c_agent(),
)?;
ctx.renderer.write_line(
"/graph traverse <id> [--depth <n>] [--compress] [--tier auto|sql|walk|llm]",
c_agent(),
)?;
ctx.renderer.write_line("", c_agent())?;
ctx.renderer
.write_line(" --tier auto keyword-based routing (default)", c_agent())?;
ctx.renderer
.write_line(" --tier sql force FTS5 entity search", c_agent())?;
ctx.renderer
.write_line(" --tier walk force graph traversal", c_agent())?;
ctx.renderer.write_line(
" --tier llm LLM decomposition (not yet implemented)",
c_agent(),
)?;
ctx.renderer.write_line("", c_agent())?;
ctx.renderer
.write_line("requires experimental-graph-search feature", c_agent())?;
}
other => {
ctx.renderer
.write_line(&format!("unknown /graph sub-command: {other}"), c_error())?;
}
}
Ok(())
}