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
use crate::*;
use carryctx::application;
use carryctx::application::runtime::{InvocationContext, ProjectRuntime};
use carryctx::error::{CarryCtxError, ExitCode};
use clap::Parser;
// ── Checkpoint ───────────────────────────────────────────────────────────
#[derive(Parser, Debug)]
pub enum CheckpointCommand {
/// List all checkpoints created for the current session or task
List,
/// Display details, including changes and state metadata, for a specific checkpoint ULID
Show { checkpoint_id: String },
/// Rollback the project and agent state to a previous checkpoint, discarding subsequent changes
Correct { checkpoint_id: String },
}
#[derive(Parser, Debug)]
pub struct CheckpointArgs {
/// Checkpoint subcommand to execute
#[command(subcommand)]
pub command: Option<CheckpointCommand>,
/// Attach a "done" progress event (e.g. what was completed) to this checkpoint.
#[arg(long)]
pub done: Vec<String>,
/// Record "remaining" work items (what still needs to be done) at this checkpoint.
#[arg(long)]
pub remaining: Vec<String>,
/// Record any blockers or issues that are preventing further progress.
#[arg(long)]
pub blocker: Vec<String>,
/// Document identified risks or architectural concerns.
#[arg(long)]
pub risk: Vec<String>,
/// Note the very next step or command the agent intends to run.
#[arg(long)]
pub next: Vec<String>,
/// Attach an arbitrary text note or observation to this checkpoint.
#[arg(long)]
pub note: Vec<String>,
/// Explicitly bind this checkpoint to a specific task ULID.
#[arg(long)]
pub task: Option<String>,
/// Explicitly bind this checkpoint to a specific session ULID.
#[arg(long)]
pub session: Option<String>,
/// Do not automatically invoke `git add` or `git commit` to capture file changes.
#[arg(long)]
pub no_git: bool,
/// Embed the active, uncommitted Git diff directly into the checkpoint database record.
#[arg(long)]
pub include_diff: bool,
}
// ═══════════════════════════════════════════════════════════════════════════
// Handler: checkpoint
// ═══════════════════════════════════════════════════════════════════════════
pub fn handle_checkpoint(
args: &CheckpointArgs,
pre_opened: Option<ProjectRuntime>,
ctx: &InvocationContext,
is_json: bool,
) -> Result<ExitCode, ExitCode> {
let command_label = match &args.command {
Some(CheckpointCommand::Show { .. }) => "checkpoint.show",
Some(CheckpointCommand::Correct { .. }) => "checkpoint.correct",
Some(CheckpointCommand::List) => "checkpoint.list",
None => "checkpoint.create",
};
if let Some(result) = check_dry_run_envelope(
ctx,
command_label,
&format!("checkpoint {:?}", 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, command_label)?,
};
let verbose = ctx.verbose || runtime.config.output.verbose;
let fields = ctx.fields.as_deref();
let config_fields = Some(&runtime.config.output.fields);
// A failed transaction start used to bail with a bare exit code
// (issue #96 remainder); render it through the standard error envelope.
let uow =
match carryctx::adapter::unit_of_work::UnitOfWork::begin(runtime.database.connection_mut())
{
Ok(uow) => uow,
Err(e) => {
return render_and_print_entity::<serde_json::Value>(
command_label,
Err(e),
is_json,
ctx.quiet,
verbose,
fields,
config_fields,
);
}
};
let project_id = &runtime.config.project.id;
let checkpoint_repo = SqliteCheckpointRepository::new(uow.connection());
let event_repo = SqliteEventRepository::new(uow.connection());
let git_cli = GitCli::new();
match &args.command {
Some(CheckpointCommand::List) => {
let task_ref = args.task.as_deref().or(ctx.task.as_deref());
let resolved_task_id = match task_ref {
Some(t_ref) => match crate::resolve_task_id(project_id, t_ref, uow.connection()) {
Ok(id) => Some(id),
Err(e) => {
return render_and_print::<serde_json::Value>(
"checkpoint.list",
Err(e),
is_json,
ctx.quiet,
);
}
},
None => None,
};
let checkpoints = match checkpoint_repo.list(project_id, resolved_task_id.as_deref()) {
Ok(checkpoints) => checkpoints,
// A failed listing used to exit bare (issue #96 remainder).
Err(e) => {
return render_and_print_entity::<serde_json::Value>(
"checkpoint.list",
Err(e),
is_json,
ctx.quiet,
verbose,
fields,
config_fields,
);
}
};
// Markdown format support
if ctx.format == carryctx::application::runtime::OutputFormat::Markdown {
let mut out = String::from("# Checkpoints\n\n");
out.push_str("| ID | Task | Done Items | Created |\n");
out.push_str("|---|---|---|---|\n");
for cp in &checkpoints {
let id_short = truncate_chars(&cp.id, 8);
let task_trunc = truncate_chars(cp.task_id.as_str(), 8);
out.push_str(&format!(
"| {} | {} | {} | {} |\n",
id_short,
task_trunc,
cp.done.len(),
truncate_chars(&cp.created_at, 19)
));
}
if !ctx.quiet {
print!("{out}");
}
return Ok(ExitCode::Success);
}
render_and_print_entity(
"checkpoint.list",
Ok(checkpoints),
is_json,
ctx.quiet,
verbose,
ctx.fields.as_deref(),
Some(&runtime.config.output.fields),
)
}
Some(CheckpointCommand::Show { checkpoint_id }) => {
let cp = match checkpoint_repo.find_by_id(project_id, checkpoint_id) {
Ok(Some(cp)) => cp,
Ok(None) => {
return render_and_print_entity::<serde_json::Value>(
"checkpoint.show",
Err(CarryCtxError::resource_not_found(format!(
"Checkpoint '{checkpoint_id}' not found."
))),
is_json,
ctx.quiet,
verbose,
ctx.fields.as_deref(),
Some(&runtime.config.output.fields),
);
}
Err(e) => {
return render_and_print_entity::<serde_json::Value>(
"checkpoint.show",
Err(e),
is_json,
ctx.quiet,
verbose,
ctx.fields.as_deref(),
Some(&runtime.config.output.fields),
);
}
};
render_and_print_entity(
"checkpoint.show",
Ok(cp),
is_json,
ctx.quiet,
verbose,
ctx.fields.as_deref(),
Some(&runtime.config.output.fields),
)
}
Some(CheckpointCommand::Correct { checkpoint_id }) => {
let now = chrono::Utc::now().to_rfc3339();
let input = application::checkpoint::CorrectCheckpointInput {
project_id: project_id.to_string(),
checkpoint_id: checkpoint_id.clone(),
done: if args.done.is_empty() {
None
} else {
Some(args.done.clone())
},
remaining: if args.remaining.is_empty() {
None
} else {
Some(args.remaining.clone())
},
blockers: if args.blocker.is_empty() {
None
} else {
Some(args.blocker.clone())
},
risks: if args.risk.is_empty() {
None
} else {
Some(args.risk.clone())
},
next_actions: if args.next.is_empty() {
None
} else {
Some(args.next.clone())
},
notes: if args.note.is_empty() {
None
} else {
Some(args.note.clone())
},
};
let result = application::checkpoint::correct_checkpoint(
&checkpoint_repo,
&event_repo,
&input,
&now,
);
render_and_print_entity(
"checkpoint.correct",
result,
is_json,
ctx.quiet,
verbose,
ctx.fields.as_deref(),
Some(&runtime.config.output.fields),
)
}
None => {
let resolver =
carryctx::application::runtime::CurrentEntityResolver::new(project_id, &uow);
let agent = resolver
.resolve_agent(
ctx.agent.as_deref(),
None,
None,
runtime.config.agent.default_name.as_deref(),
runtime.config.agent.default_name.as_deref(),
)
.ok();
let resolved_agent_id = agent.as_ref().map(|a| a.id.clone());
let t_ref = args.task.as_deref().or(ctx.task.as_deref());
let t_ref = if t_ref == Some("current") {
None
} else {
t_ref
};
let resolved_task_id = match resolver.resolve_task(
t_ref,
Some(&ctx.cwd.to_string_lossy()),
resolved_agent_id.as_deref(),
) {
Ok(Some(t)) => t.id,
Ok(None) => {
return render_and_print::<serde_json::Value>(
"checkpoint.create",
Err(CarryCtxError::validation_error(
"No task specified. Provide --task <TASK_REF> or bind a task to the active session.",
)),
is_json,
ctx.quiet,
);
}
Err(e) => {
return render_and_print::<serde_json::Value>(
"checkpoint.create",
Err(e),
is_json,
ctx.quiet,
);
}
};
let repo_path = if args.no_git {
None
} else {
Some(
runtime
.git_project
.repository_root
.to_string_lossy()
.to_string(),
)
};
let input = application::checkpoint::CreateCheckpointInput {
project_id: project_id.to_string(),
task_id: resolved_task_id,
session_id: args.session.clone().or_else(|| ctx.session.clone()),
agent_id: resolved_agent_id,
worktree_id: None,
branch: runtime.git_project.branch.clone(),
head: runtime.git_project.head.clone(),
done: args.done.clone(),
remaining: args.remaining.clone(),
blockers: args.blocker.clone(),
risks: args.risk.clone(),
next_actions: args.next.clone(),
notes: args.note.clone(),
repo_path,
};
let now = chrono::Utc::now().to_rfc3339();
let graph_repo = carryctx::repository::graph::GraphRepository::new(uow.connection());
let result = application::checkpoint::create_checkpoint(
&checkpoint_repo,
&event_repo,
Some(&graph_repo),
&git_cli,
&input,
&now,
);
if result.is_ok() {
// A failed commit used to exit bare (issue #96 remainder);
// surface it as a checkpoint.create error envelope instead.
if let Err(e) = uow.commit() {
return render_and_print_entity::<serde_json::Value>(
"checkpoint.create",
Err(e),
is_json,
ctx.quiet,
verbose,
fields,
config_fields,
);
}
}
render_and_print_entity(
"checkpoint.create",
result,
is_json,
ctx.quiet,
verbose,
ctx.fields.as_deref(),
Some(&runtime.config.output.fields),
)
}
}
}