carryctx 0.7.0

Local-first memory for coding agents — resume tasks, checkpoints, and context across windows, sessions, and worktrees.
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
use crate::{check_dry_run_envelope, open_runtime_or_report, render_and_print};
use carryctx::application::runtime::{InvocationContext, ProjectRuntime};
use carryctx::domain::graph::{GraphEdge, GraphNode};
use carryctx::error::ExitCode;
use carryctx::output::{OutputSink, render_json};
use chrono::Utc;
use clap::{Args, Parser, Subcommand};
use serde_json::json;

#[derive(Parser, Debug)]
pub struct GraphArgs {
    #[command(subcommand)]
    pub command: GraphSubcommands,
}

#[derive(Subcommand, Debug)]
pub enum GraphSubcommands {
    /// List all edges connected to a specific node
    Edges(GraphEdgesArgs),
    /// Add a new node to the context graph
    AddNode(AddNodeArgs),
    /// Link two nodes with an edge
    Link(LinkArgs),
    /// Automatically extract depends_on edges from a file
    ExtractDeps(ExtractDepsArgs),
    /// Scan all git-tracked files and extract dependency edges into the graph
    Scan(ScanArgs),
    /// Export context graph to Mermaid, DOT, ASCII, or JSON format
    Export(ExportArgs),
}

#[derive(Args, Debug)]
pub struct GraphEdgesArgs {
    #[arg(help = "The ULID of the node")]
    pub id: String,
}

#[derive(Args, Debug)]
pub struct AddNodeArgs {
    #[arg(long, help = "Type of node (e.g., file, module, decision)")]
    pub node_type: String,
    #[arg(long, help = "Name of the node")]
    pub name: String,
    #[arg(long, help = "Description of the node")]
    pub description: Option<String>,
}

#[derive(Args, Debug)]
pub struct LinkArgs {
    #[arg(help = "Source node ULID")]
    pub source: String,
    #[arg(help = "Target node ULID")]
    pub target: String,
    pub relation: String,
}

#[derive(Args, Debug)]
pub struct ExtractDepsArgs {
    #[arg(help = "The file path to extract dependencies from")]
    pub file: String,
}

#[derive(Args, Debug)]
pub struct ScanArgs {
    /// Directory to scan (defaults to the repository root)
    #[arg(long, default_value = ".")]
    pub dir: String,

    /// Comma-separated list of file extensions to include
    #[arg(long, default_value = "rs,ts,js,tsx,jsx")]
    pub ext: String,

    /// Print what would be scanned without writing to the database
    #[arg(long)]
    pub dry_run: bool,
}

#[derive(Args, Debug)]
pub struct ExportArgs {
    /// Format to export graph (mermaid, dot, ascii, json)
    #[arg(
        short = 't',
        long = "type",
        alias = "format",
        default_value = "mermaid"
    )]
    pub export_format: String,

    /// Output file path (.mmd, .dot, .png, .svg, .json, .txt)
    #[arg(short, long)]
    pub output: Option<String>,

    /// Filter graph nodes by type (e.g. file, task)
    #[arg(long)]
    pub node_type: Option<String>,

    /// Focus on a specific node (by name or ULID) and export its subgraph
    #[arg(long)]
    pub focus: Option<String>,

    /// Traversal depth when using --focus (default: 1)
    #[arg(long, default_value_t = 1)]
    pub depth: usize,

    /// Aggregate graph nodes into module-level clusters (e.g. src/commands, src/domain)
    #[arg(long)]
    pub compact: bool,

    /// Directly render output in ASCII diagram format
    #[arg(long)]
    pub ascii: bool,
}

/// Stable command label for a graph subcommand, matching the labels used by
/// the per-arm `render_json` calls.
fn graph_command_label(command: &GraphSubcommands) -> &'static str {
    match command {
        GraphSubcommands::Edges(_) => "graph.edges",
        GraphSubcommands::AddNode(_) => "graph.add-node",
        GraphSubcommands::Link(_) => "graph.link",
        GraphSubcommands::ExtractDeps(_) => "graph.extract-deps",
        GraphSubcommands::Scan(_) => "graph.scan",
        GraphSubcommands::Export(_) => "graph.export",
    }
}

pub fn handle_graph(
    args: &GraphArgs,
    pre_opened: Option<ProjectRuntime>,
    ctx: &InvocationContext,
    is_json: bool,
) -> Result<ExitCode, ExitCode> {
    // The global --dry-run promise is "no database changes": mutating graph
    // subcommands must be gated before the runtime opens, while read-only
    // subcommands (edges/export) render normally.
    let mutating = matches!(
        &args.command,
        GraphSubcommands::AddNode(_)
            | GraphSubcommands::Link(_)
            | GraphSubcommands::ExtractDeps(_)
            | GraphSubcommands::Scan(_)
    );
    if mutating {
        if let Some(result) = check_dry_run_envelope(
            ctx,
            graph_command_label(&args.command),
            &format!("graph {:?}", args.command),
        ) {
            return result;
        }
    }

    // Reuse the dispatcher's pre-opened runtime when available; a second
    // open only happens (and reports) when that failed.
    let mut runtime = match pre_opened {
        Some(runtime) => runtime,
        None => open_runtime_or_report(ctx, "graph")?,
    };

    if mutating {
        let project_id = runtime.config.project.id.clone();
        let conn = runtime.database.connection_mut();
        return run_mutating_graph(&args.command, conn, &project_id, ctx, is_json);
    }

    let repo = carryctx::repository::graph::GraphRepository::new(runtime.database.connection());

    match &args.command {
        GraphSubcommands::Edges(cmd) => {
            let result = match repo.get_node(&cmd.id) {
                Ok(Some(_)) => repo.get_edges_for_node(&cmd.id),
                Ok(None) => Err(carryctx::error::CarryCtxError::resource_not_found(format!(
                    "'{}' is not a Context Graph node ID. Note: task/agent/session ULIDs are a separate ID space from graph nodes; use `carryctx task show <TASK_REF>` to see a task's dependencies instead.",
                    cmd.id
                ))),
                Err(e) => Err(e),
            };
            let (out, sink, code) = render_json("graph.edges", result.as_ref(), is_json);
            match sink {
                OutputSink::Stdout => println!("{out}"),
                OutputSink::Stderr => eprintln!("{out}"),
            }
            if code == ExitCode::Success {
                Ok(code)
            } else {
                Err(code)
            }
        }
        GraphSubcommands::Export(cmd) => {
            use carryctx::application::export_graph::{
                GraphExportFormat, export_graph, render_image_to_file,
            };
            use std::str::FromStr;

            let fmt_str = if cmd.ascii {
                "ascii"
            } else {
                cmd.export_format.as_str()
            };

            let result: Result<serde_json::Value, carryctx::error::CarryCtxError> = (|| {
                let parsed_format = GraphExportFormat::from_str(fmt_str)?;
                let content = export_graph(
                    &repo,
                    parsed_format,
                    cmd.node_type.as_deref(),
                    cmd.focus.as_deref(),
                    cmd.depth,
                    cmd.compact,
                )?;

                if let Some(out_path) = &cmd.output {
                    render_image_to_file(&content, parsed_format, out_path)?;
                    Ok(json!({
                        "status": "success",
                        "format": fmt_str,
                        "outputPath": out_path,
                    }))
                } else {
                    Ok(json!({
                        "status": "success",
                        "format": fmt_str,
                        "content": content,
                    }))
                }
            })(
            );

            match result {
                Ok(data) => {
                    if is_json {
                        let (out, _, code) = render_json("graph.export", Ok(data), true);
                        println!("{out}");
                        Ok(code)
                    } else if let Some(content) = data["content"].as_str() {
                        print!("{content}");
                        Ok(ExitCode::Success)
                    } else if let Some(path) = data["outputPath"].as_str() {
                        println!("Successfully exported graph to {path}");
                        Ok(ExitCode::Success)
                    } else {
                        Ok(ExitCode::Success)
                    }
                }
                Err(err) => render_and_print("graph.export", Err::<(), _>(err), is_json, ctx.quiet),
            }
        }
        GraphSubcommands::AddNode(_)
        | GraphSubcommands::Link(_)
        | GraphSubcommands::ExtractDeps(_)
        | GraphSubcommands::Scan(_) => {
            unreachable!("mutating graph subcommands are handled by run_mutating_graph")
        }
    }
}

/// Execute a mutating graph subcommand inside a UnitOfWork: the mutation rows
/// and their audit events (`graph.node_added`, `graph.edge_added`,
/// `graph.deps_extracted`, `graph.scanned`) commit in one transaction, or the
/// UnitOfWork Drop rolls both back together (issue #99).
fn run_mutating_graph(
    command: &GraphSubcommands,
    conn: &mut rusqlite::Connection,
    project_id: &str,
    ctx: &InvocationContext,
    is_json: bool,
) -> Result<ExitCode, ExitCode> {
    use carryctx::adapter::sqlite_repos::SqliteEventRepository;

    /// Append an audit event describing a committed graph mutation.
    fn append_graph_event(
        event_repo: &SqliteEventRepository,
        project_id: &str,
        actor_agent_id: &Option<String>,
        session_id: Option<&str>,
        event_type: &str,
        payload: serde_json::Value,
        occurred_at: String,
    ) -> Result<(), carryctx::error::CarryCtxError> {
        use carryctx::repository::event::{EventRepository, NewEvent};
        event_repo
            .append(&NewEvent {
                id: ulid::Ulid::generate().to_string(),
                project_id: project_id.to_string(),
                event_type: event_type.into(),
                actor_agent_id: actor_agent_id.clone(),
                session_id: session_id.map(str::to_string),
                task_id: None,
                payload,
                occurred_at,
            })
            .map(|_| ())
    }

    /// Commit on success; on failure the UnitOfWork Drop rolls the mutation and
    /// any already-appended event rows back together.
    fn commit_graph_uow<T>(
        uow: Option<carryctx::adapter::unit_of_work::UnitOfWork>,
        result: Result<T, carryctx::error::CarryCtxError>,
    ) -> Result<T, carryctx::error::CarryCtxError> {
        match uow {
            Some(uow) => match result {
                Ok(value) => uow.commit().map(|()| value),
                Err(err) => Err(err),
            },
            None => result,
        }
    }

    let actor_agent_id = ctx.agent.clone();
    let mut uow =
        Some(carryctx::adapter::unit_of_work::UnitOfWork::begin(conn).map_err(|e| e.exit_code)?);

    match command {
        GraphSubcommands::AddNode(cmd) => {
            let compute = || -> Result<GraphNode, carryctx::error::CarryCtxError> {
                let repo = carryctx::repository::graph::GraphRepository::new(
                    uow.as_ref().expect("open").connection(),
                );
                let event_repo =
                    SqliteEventRepository::new(uow.as_ref().expect("open").connection());
                let id = ulid::Ulid::generate().to_string();
                let now = Utc::now().to_rfc3339();

                let node = GraphNode::new(
                    &id,
                    &cmd.node_type,
                    &cmd.name,
                    cmd.description.clone(),
                    json!({}),
                    now,
                );

                repo.insert_node(&node)?;
                append_graph_event(
                    &event_repo,
                    project_id,
                    &actor_agent_id,
                    ctx.session.as_deref(),
                    "graph.node_added",
                    json!({
                        "nodeId": node.id,
                        "nodeType": node.node_type,
                        "name": node.name,
                    }),
                    node.created_at.clone(),
                )?;
                Ok(node)
            };
            let computed = compute();
            let result = commit_graph_uow(uow.take(), computed);
            let (out, sink, code) = render_json("graph.add-node", result.as_ref(), is_json);
            match sink {
                OutputSink::Stdout => println!("{out}"),
                OutputSink::Stderr => eprintln!("{out}"),
            }
            if code == ExitCode::Success {
                Ok(code)
            } else {
                Err(code)
            }
        }
        GraphSubcommands::Link(cmd) => {
            let compute = || -> Result<GraphEdge, carryctx::error::CarryCtxError> {
                let repo = carryctx::repository::graph::GraphRepository::new(
                    uow.as_ref().expect("open").connection(),
                );
                let event_repo =
                    SqliteEventRepository::new(uow.as_ref().expect("open").connection());
                let now = Utc::now().to_rfc3339();
                let edge = GraphEdge::new(
                    &cmd.source,
                    &cmd.target,
                    &cmd.relation,
                    now,
                    ctx.agent.clone(),
                    json!({}),
                );

                repo.insert_edge(&edge)?;
                append_graph_event(
                    &event_repo,
                    project_id,
                    &actor_agent_id,
                    ctx.session.as_deref(),
                    "graph.edge_added",
                    json!({
                        "sourceId": edge.source_id,
                        "targetId": edge.target_id,
                        "relation": edge.relation_type,
                    }),
                    edge.created_at.clone(),
                )?;
                Ok(edge)
            };
            let computed = compute();
            let result = commit_graph_uow(uow.take(), computed);
            let (out, sink, code) = render_json("graph.link", result.as_ref(), is_json);
            match sink {
                OutputSink::Stdout => println!("{out}"),
                OutputSink::Stderr => eprintln!("{out}"),
            }
            if code == ExitCode::Success {
                Ok(code)
            } else {
                Err(code)
            }
        }
        GraphSubcommands::ExtractDeps(cmd) => {
            // The use case writes through a repository bound to the UoW
            // connection; a summary audit event covers the import and the
            // whole batch commits atomically.
            let compute = || -> Result<Vec<GraphEdge>, carryctx::error::CarryCtxError> {
                let repo = carryctx::repository::graph::GraphRepository::new(
                    uow.as_ref().expect("open").connection(),
                );
                let event_repo =
                    SqliteEventRepository::new(uow.as_ref().expect("open").connection());
                let created_edges = carryctx::application::extract_deps::extract_deps_for_file(
                    &cmd.file, &repo, ctx,
                )?;
                append_graph_event(
                    &event_repo,
                    project_id,
                    &actor_agent_id,
                    ctx.session.as_deref(),
                    "graph.deps_extracted",
                    json!({
                        "file": cmd.file,
                        "edgesCreated": created_edges.len(),
                    }),
                    Utc::now().to_rfc3339(),
                )?;
                Ok(created_edges)
            };
            let computed = compute();
            let result = commit_graph_uow(uow.take(), computed);
            let (out, sink, code) = render_json("graph.extract-deps", result.as_ref(), is_json);
            match sink {
                OutputSink::Stdout => println!("{out}"),
                OutputSink::Stderr => eprintln!("{out}"),
            }
            if code == ExitCode::Success {
                Ok(code)
            } else {
                Err(code)
            }
        }
        GraphSubcommands::Scan(cmd) => {
            use carryctx::application::scan_graph::{DEFAULT_EXTENSIONS, scan_project};
            use std::path::Path;

            // Parse extensions from comma-separated string
            let ext_owned: Vec<String> = cmd.ext.split(',').map(|s| s.trim().to_string()).collect();
            let extensions: Vec<&str> = ext_owned.iter().map(|s| s.as_str()).collect();

            // Fallback to defaults if empty
            let extensions: &[&str] = if extensions.is_empty() {
                DEFAULT_EXTENSIONS
            } else {
                &extensions
            };

            let dir = Path::new(&cmd.dir);
            let compute = || -> Result<serde_json::Value, carryctx::error::CarryCtxError> {
                let repo = carryctx::repository::graph::GraphRepository::new(
                    uow.as_ref().expect("open").connection(),
                );
                let event_repo =
                    SqliteEventRepository::new(uow.as_ref().expect("open").connection());

                scan_project(dir, extensions, cmd.dry_run, &repo, ctx).and_then(|r| {
                    let errors: Vec<serde_json::Value> = r
                        .errors
                        .iter()
                        .map(|e| json!({ "file": e.file, "error": e.message }))
                        .collect();
                    let summary = json!({
                        "dry_run": cmd.dry_run,
                        "extensions": extensions,
                        "scanned": r.scanned,
                        "skipped": r.skipped,
                        "nodes_created": r.nodes_created,
                        "edges_created": r.edges_created,
                        "error_count": errors.len(),
                        "errors": errors,
                    });
                    if !cmd.dry_run {
                        append_graph_event(
                            &event_repo,
                            project_id,
                            &actor_agent_id,
                            ctx.session.as_deref(),
                            "graph.scanned",
                            json!({
                                "dir": cmd.dir,
                                "nodesCreated": r.nodes_created,
                                "edgesCreated": r.edges_created,
                                "scanned": r.scanned,
                                "errorCount": errors.len(),
                            }),
                            Utc::now().to_rfc3339(),
                        )?;
                    }
                    Ok(summary)
                })
            };
            let computed = compute();
            let result = commit_graph_uow(uow.take(), computed);
            let (out, sink, code) = render_json("graph.scan", result.as_ref(), is_json);
            match sink {
                OutputSink::Stdout => println!("{out}"),
                OutputSink::Stderr => eprintln!("{out}"),
            }
            if code == ExitCode::Success {
                Ok(code)
            } else {
                Err(code)
            }
        }
        GraphSubcommands::Edges(_) | GraphSubcommands::Export(_) => {
            unreachable!("read-only graph subcommands are handled by the caller")
        }
    }
}