carryctx 0.6.1

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
use crate::*;
use carryctx::adapter::git::GitCli;
use carryctx::adapter::sqlite_repos::{
    SqliteAgentRepository, SqliteSessionRepository, SqliteTaskRepository, SqliteWorktreeRepository,
};
use carryctx::adapter::xdg::XdgPaths;
use carryctx::application::runtime::InvocationContext;
use carryctx::domain::session::SessionState;
use carryctx::domain::task::TaskStatus;
use carryctx::error::{CarryCtxError, ExitCode};
use carryctx::repository::{
    AgentRepository, SessionRepository, TaskFilter, TaskRepository, WorktreeRepository,
};
use clap::Parser;

// ── Doctor ───────────────────────────────────────────────────────────────

/// Diagnose and automatically fix potential issues with the project's SQLite state database.
///
/// Checks Git repository health, database connectivity, schema version, orphaned
/// tasks (tasks with non-existent owners), stale active sessions, and git hook
/// installation status.
#[derive(Parser, Debug)]
pub struct DoctorArgs {
    /// Automatically attempt to fix detected anomalies in the database and configuration.
    #[arg(long)]
    pub fix: bool,

    /// Remove registered worktrees whose directories are missing. This never deletes files.
    #[arg(long)]
    pub prune_stale_worktrees: bool,

    /// Output the diagnostic results in JSON format.
    #[arg(long)]
    pub json: bool,
}

// ═══════════════════════════════════════════════════════════════════════════
//  Handler: doctor
// ═══════════════════════════════════════════════════════════════════════════

pub fn handle_doctor(
    args: &DoctorArgs,
    ctx: &InvocationContext,
    is_json: bool,
) -> Result<ExitCode, ExitCode> {
    let mut checks: Vec<serde_json::Value> = Vec::new();
    let mut all_ok = true;

    // ── 1. Global config ─────────────────────────────────────────────────
    let xdg = XdgPaths::new();
    let global_config = xdg.global_config();
    if global_config.exists() {
        match std::fs::read_to_string(&global_config) {
            Ok(content) => {
                match toml::from_str::<carryctx::domain::config::CarryCtxConfig>(&content) {
                    Ok(_) => checks.push(serde_json::json!({
                        "check": "config.global",
                        "status": "ok",
                        "message": "Global config is valid"
                    })),
                    Err(e) => {
                        all_ok = false;
                        checks.push(serde_json::json!({
                            "check": "config.global",
                            "status": "error",
                            "message": format!("Invalid global config: {e}"),
                            "repairable": false
                        }));
                    }
                }
            }
            Err(e) => {
                checks.push(serde_json::json!({
                    "check": "config.global",
                    "status": "warning",
                    "message": format!("Cannot read global config: {e}"),
                    "repairable": false
                }));
            }
        }
    } else {
        checks.push(serde_json::json!({
            "check": "config.global",
            "status": "info",
            "message": "No global config found (using defaults)"
        }));
    }

    // ── 2. Git repository ─────────────────────────────────────────────────
    let work_dir = resolve_work_dir(ctx);
    let git = GitCli::new();
    let git_project = match git.discover(work_dir) {
        Ok(gp) => {
            checks.push(serde_json::json!({
                "check": "git.repository",
                "status": "ok",
                "message": format!("Git repository at {}", gp.repository_root.display())
            }));
            Some(gp)
        }
        Err(e) => {
            all_ok = false;
            checks.push(serde_json::json!({
                "check": "git.repository",
                "status": "error",
                "message": format!("{e}"),
                "repairable": false
            }));
            None
        }
    };

    // ── 3. Git hooks ──────────────────────────────────────────────────────
    if let Some(ref gp) = git_project {
        let hooks_dir = gp.git_common_dir.join("hooks");
        let managed_hooks: Vec<&str> = ["post-commit", "prepare-commit-msg"]
            .iter()
            .filter(|&&name| {
                let p = hooks_dir.join(name);
                if !p.exists() {
                    return false;
                }
                std::fs::read_to_string(p)
                    .unwrap_or_default()
                    .contains("CarryCtx")
            })
            .copied()
            .collect();

        if managed_hooks.is_empty() {
            checks.push(serde_json::json!({
                "check": "git.hooks",
                "status": "info",
                "message": "No CarryCtx git hooks installed. Run `carryctx hooks install` to enable auto-checkpoint on commit.",
                "fix_command": "carryctx hooks install"
            }));
        } else {
            checks.push(serde_json::json!({
                "check": "git.hooks",
                "status": "ok",
                "message": format!("CarryCtx hooks installed: {}", managed_hooks.join(", "))
            }));
        }
    }

    // ── 3b. Jujutsu (jj) colocation ─────────────────────────────────────────
    if let Some(gp) = &git_project {
        if carryctx::adapter::git::detect_jj_colocation(&gp.git_common_dir) {
            checks.push(serde_json::json!({
                "check": "vcs.jj_colocation",
                "status": "info",
                "message": "jj colocation detected (.jj/ alongside .git/). CarryCtx reads Git state directly; some data (e.g. checkpoint staged/unstaged split) may be less precise under jj. See carryctx-docs/plans/2026-07-25-jujutsu-compatibility.md."
            }));
        }
    }

    // ── 4. Database connection + schema ───────────────────────────────────
    let runtime = match try_open_runtime(ctx) {
        Ok(rt) => {
            checks.push(serde_json::json!({
                "check": "database.connection",
                "status": "ok",
                "message": format!("Database at {}", rt.db_path.display())
            }));
            let pending = rt.database.pending_migrations().unwrap_or_default();
            if pending.is_empty() {
                checks.push(serde_json::json!({
                    "check": "database.schema",
                    "status": "ok",
                    "message": "Schema version up to date"
                }));
            } else {
                all_ok = false;
                checks.push(serde_json::json!({
                    "check": "database.schema",
                    "status": "error",
                    "message": format!(
                        "{} pending migration(s) not applied: {}",
                        pending.len(),
                        pending.iter().map(|m| m.name.as_str()).collect::<Vec<_>>().join(", ")
                    ),
                    "repairable": true,
                    "fix_command": "carryctx project migrate"
                }));
            }
            Some(rt)
        }
        Err(exit_code) => {
            all_ok = false;
            let msg = match exit_code {
                ExitCode::Database => {
                    "Database connection failed — try `carryctx init` to reinitialise"
                }
                ExitCode::Git => "Not in a Git repository",
                _ => "Cannot open project (not initialised? Run `carryctx init`)",
            };
            checks.push(serde_json::json!({
                "check": "database.connection",
                "status": "error",
                "message": msg,
                "repairable": true,
                "fix_command": "carryctx init"
            }));
            None
        }
    };

    // ── 5. Orphaned tasks + in-progress state ──────────────────────────────
    if let Some(ref rt) = runtime {
        let conn = rt.database.connection();
        let project_id = &rt.config.project.id;
        let repository_root = &rt.git_project.repository_root;
        let task_repo = SqliteTaskRepository::new(conn);
        let agent_repo = SqliteAgentRepository::new(conn);
        let worktree_repo = SqliteWorktreeRepository::new(conn);

        let filter = TaskFilter {
            project_id: project_id.to_string(),
            status: None,
            owner_agent_id: None,
            ready: false,
            blocked: false,
            mine: None,
        };

        match task_repo.list(&filter) {
            Ok(tasks) => {
                let mut orphaned: Vec<String> = Vec::new();
                for task in &tasks {
                    if let Some(owner_id) = &task.owner_agent_id {
                        if agent_repo
                            .find_by_id(project_id, owner_id)
                            .ok()
                            .flatten()
                            .is_none()
                        {
                            orphaned.push(format!("{} ({})", task.display_id, task.title));
                        }
                    }
                }
                if orphaned.is_empty() {
                    checks.push(serde_json::json!({
                        "check": "tasks.orphaned",
                        "status": "ok",
                        "message": "No orphaned tasks (all owners exist)"
                    }));
                } else {
                    all_ok = false;
                    checks.push(serde_json::json!({
                        "check": "tasks.orphaned",
                        "status": "warning",
                        "message": format!("{} task(s) have deleted owners: {}", orphaned.len(), orphaned.join(", ")),
                        "note": "Use `carryctx task unclaim <id>` to release ownership"
                    }));
                }

                let in_progress: Vec<_> = tasks
                    .iter()
                    .filter(|t| t.status == TaskStatus::InProgress)
                    .collect();
                if !in_progress.is_empty() {
                    checks.push(serde_json::json!({
                        "check": "tasks.in_progress",
                        "status": "info",
                        "message": format!("{} task(s) currently in progress", in_progress.len()),
                        "tasks": in_progress.iter().map(|t| t.display_id.as_str()).collect::<Vec<_>>()
                    }));
                }
            }
            Err(e) => {
                checks.push(serde_json::json!({
                    "check": "tasks.orphaned",
                    "status": "warning",
                    "message": format!("Could not check tasks: {e}")
                }));
            }
        }

        // ── 6. Active sessions ──────────────────────────────────────────────
        let session_repo = SqliteSessionRepository::new(conn);
        let audit_session_id = ctx.session.clone().or_else(|| {
            session_repo
                .list(project_id)
                .ok()?
                .into_iter()
                .find(|session| matches!(session.state, SessionState::Active))
                .map(|session| session.id)
        });
        match session_repo.list(project_id) {
            Ok(sessions) => {
                let active: Vec<_> = sessions
                    .iter()
                    .filter(|s| matches!(s.state, SessionState::Active))
                    .collect();
                if !active.is_empty() {
                    checks.push(serde_json::json!({
                        "check": "sessions.active",
                        "status": "ok",
                        "message": format!("{} active session(s)", active.len())
                    }));
                } else {
                    checks.push(serde_json::json!({
                        "check": "sessions.active",
                        "status": "info",
                        "message": "No active session. Run `carryctx session start` to begin."
                    }));
                }
            }
            Err(e) => {
                checks.push(serde_json::json!({
                    "check": "sessions.active",
                    "status": "warning",
                    "message": format!("Could not check sessions: {e}")
                }));
            }
        }

        if args.prune_stale_worktrees && ctx.dry_run {
            // Detection remains read-only; dry-run reports the same plan without writing.
        } else if args.prune_stale_worktrees && !ctx.yes {
            return render_and_print::<serde_json::Value>(
                "doctor",
                Err(CarryCtxError::permission_scope(
                    "Pruning stale worktrees requires explicit confirmation with --yes.",
                )),
                is_json || args.json,
                ctx.quiet,
            );
        }
        let stale_result = if args.prune_stale_worktrees && !ctx.dry_run {
            let actor = ctx
                .agent
                .as_deref()
                .map(|agent| resolve_agent_id(project_id, agent, conn))
                .transpose()
                .map_err(|e| e.exit_code)?;
            worktree_repo.prune_stale(
                project_id,
                repository_root,
                actor.as_deref(),
                audit_session_id.as_deref(),
                &chrono::Utc::now().to_rfc3339(),
            )
        } else {
            carryctx::application::worktree::stale_worktrees(
                &worktree_repo,
                project_id,
                repository_root,
            )
        };
        match stale_result {
            Ok(stale) if stale.is_empty() => checks.push(serde_json::json!({
                "check": "worktrees.stale",
                "status": "ok",
                "message": "No registered worktrees have missing directories"
            })),
            Ok(stale) => {
                if !args.prune_stale_worktrees {
                    all_ok = false;
                }
                checks.push(serde_json::json!({
                    "check": "worktrees.stale",
                    "status": if args.prune_stale_worktrees && !ctx.dry_run { "ok" } else { "warning" },
                    "message": if args.prune_stale_worktrees && !ctx.dry_run {
                        format!("Pruned {} stale worktree registration(s)", stale.len())
                    } else if args.prune_stale_worktrees {
                        format!("Would prune {} stale worktree registration(s)", stale.len())
                    } else {
                        format!("{} registered worktree(s) point to missing directories", stale.len())
                    },
                    "count": stale.len(),
                    "worktrees": stale.iter().map(|w| &w.path).collect::<Vec<_>>(),
                    "fix_command": "carryctx doctor --prune-stale-worktrees"
                }));
            }
            Err(e) => {
                return render_and_print::<serde_json::Value>(
                    "doctor",
                    Err(e),
                    is_json || args.json,
                    ctx.quiet,
                );
            }
        }
    }

    // ── Output ────────────────────────────────────────────────────────────
    let summary = if all_ok { "healthy" } else { "issues_found" };
    let result = serde_json::json!({
        "summary": summary,
        "checks": checks,
        "fix_requested": args.fix,
        "allOk": all_ok,
    });

    let exit_code = if all_ok {
        ExitCode::Success
    } else {
        ExitCode::General
    };

    if !is_json && !args.json && !ctx.quiet {
        println!("CarryCtx Doctor\n");
        for check in result["checks"].as_array().unwrap() {
            let status = check["status"].as_str().unwrap_or("?");
            let message = check["message"].as_str().unwrap_or("");
            let icon = match status {
                "ok" => "",
                "error" => "",
                "warning" => "",
                _ => "·",
            };
            println!("  {icon} {message}");
            if let Some(fix_cmd) = check["fix_command"].as_str() {
                println!("      → Fix: {fix_cmd}");
            }
        }
        println!();
        if all_ok {
            println!("Everything looks good!");
        } else {
            println!("Issues detected. Some may be fixed with `carryctx doctor --fix`.");
        }
        return Ok(exit_code);
    }

    let err_result: Result<serde_json::Value, CarryCtxError> = Ok(result);
    let _ = render_and_print("doctor", err_result, is_json || args.json, ctx.quiet);
    Ok(exit_code)
}