frame 0.2.0

A markdown task tracker with a terminal UI for humans and a CLI for agents
Documentation
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Completing an interrupted multi-file operation.
//!
//! # Roll forward, not back
//!
//! Rolling *back* would need undo records — effectively a copy of the prior state
//! of every file touched — which is what git already stores for this data.
//! Rolling *forward* needs none of that: the remaining steps are the same steps
//! the operation would have taken, and they complete an intent the user already
//! expressed.
//!
//! Handing this to a human is the worse option, not the safer one. "Delete
//! whichever copy is wrong" invites deleting the right one — after a cross-track
//! move the two copies carry *different* IDs and may have diverged — and every
//! manual edit is a fresh chance to do damage. Where the remaining work is
//! determinate, doing it beats describing it.
//!
//! # Intent in, state inspected
//!
//! [`crate::io::inflight`] records what the operation meant to do. What is *left*
//! is derived here by looking at the project as it stands, so nothing has to be
//! written mid-operation to track progress — that would mean more writes inside
//! the very window being protected.
//!
//! | Interrupted | Inspected | Remaining |
//! |---|---|---|
//! | `mv --track` | does the target hold the new ID? | yes → drop the old ID from the source; no → nothing landed |
//! | `track archive` | is the file still in `tracks/`? | yes → move it to `archive/_tracks/` |
//! | `track activate` (un-archive) | is the file still in `archive/_tracks/`? | yes → move it back to `tracks/` |
//! | `track rename --id` | does the config still name the old id? | yes → finish the renames and the config entry |
//! | `actor merge` | is a source token still active? | yes → retire it |
//! | `triage` | is the item still in the inbox *and* present as a task? | yes → drop the inbox item |
//!
//! Un-archive is the one where leaving it half-applied is worst: the config
//! says active while the file is elsewhere, and `load_project` skips a
//! configured track whose file is missing — so the project runs one whole track
//! short until this completes.
//!
//! # Preconditions gate every destructive step
//!
//! The source copy of a moved task is removed only after confirming the target
//! copy is really there. If a precondition fails — a hand edit, a `git checkout`
//! between the crash and the recovery — this does **not** guess. It leaves
//! everything alone and reports [`Outcome::Indeterminate`], which is the narrow
//! case where a human is genuinely the right answer rather than the default.
//!
//! Every outcome is announced by the caller and written to the recovery log, so
//! an automatic choice that turns out to be wrong stays visible and reversible.

use crate::io::inflight::{self, Marker, MovedTask, Operation};
use crate::io::project_io;
use crate::model::project::Project;
use crate::model::track::TrackNode;

/// What recovery did.
#[derive(Debug)]
pub enum Outcome {
    /// The operation was already complete; only the marker remained.
    AlreadyComplete { operation: String },
    /// Remaining steps were applied.
    Completed {
        operation: String,
        /// Human-readable, one line per step taken.
        steps: Vec<String>,
    },
    /// A precondition did not hold, so nothing was changed.
    Indeterminate { operation: String, reason: String },
}

impl Outcome {
    pub fn operation(&self) -> &str {
        match self {
            Outcome::AlreadyComplete { operation }
            | Outcome::Completed { operation, .. }
            | Outcome::Indeterminate { operation, .. } => operation,
        }
    }
}

/// Recover a pending operation, if there is one.
///
/// Returns `None` when no marker is present, which is the overwhelmingly common
/// case — one `stat` on the write path.
///
/// The caller must hold the project lock. On anything but
/// [`Outcome::Indeterminate`] the marker is cleared; an indeterminate one is
/// deliberately left in place so `fr check` keeps reporting it until a human
/// looks.
pub fn recover_pending(project: &mut Project) -> Option<Outcome> {
    let marker = inflight::read(&project.frame_dir)?;
    let outcome = apply(project, &marker);

    if !matches!(outcome, Outcome::Indeterminate { .. }) {
        let _ = inflight::clear(&project.frame_dir);
    }

    log(project, &marker, &outcome);
    Some(outcome)
}

fn apply(project: &mut Project, marker: &Marker) -> Outcome {
    let operation = marker.operation.name().to_string();
    match &marker.operation {
        Operation::CrossTrackMove {
            moves,
            source_track,
            target_track,
        } => recover_cross_track_move(project, operation, moves, source_track, target_track),
        Operation::TrackArchive { track_id, file } => {
            recover_track_archive(project, operation, track_id, file)
        }
        Operation::TrackUnarchive { track_id, file } => {
            recover_track_unarchive(project, operation, track_id, file)
        }
        Operation::TrackRename {
            old_id,
            new_id,
            old_file,
            new_file,
        } => recover_track_rename(project, operation, old_id, new_id, old_file, new_file),
        Operation::ActorMerge { sources, target } => {
            recover_actor_merge(project, operation, sources, target)
        }
        Operation::Triage {
            index,
            title,
            track_id,
        } => recover_triage(project, operation, *index, title, track_id),
    }
}

// ---------------------------------------------------------------------------
// Cross-track move
// ---------------------------------------------------------------------------

/// The target is written before the source, so for each moved task the possible
/// states are: neither write landed (nothing to do), or the target landed and
/// the source still holds the old copy (drop it).
///
/// A bulk move carries many tasks in one marker, and they are recovered
/// independently — an interruption lands somewhere in the middle of the batch,
/// so some will need the source copy dropped and others will not.
fn recover_cross_track_move(
    project: &mut Project,
    operation: String,
    moves: &[MovedTask],
    source_track: &str,
    target_track: &str,
) -> Outcome {
    let mut to_drop = Vec::new();

    for moved in moves {
        let target_has_it = project
            .tracks
            .iter()
            .find(|(id, _)| id == target_track)
            .map(|(_, t)| crate::ops::task_ops::find_task_in_track(t, &moved.new_id).is_some())
            .unwrap_or(false);
        let source_has_it = project
            .tracks
            .iter()
            .find(|(id, _)| id == source_track)
            .map(|(_, t)| crate::ops::task_ops::find_task_in_track(t, &moved.old_id).is_some())
            .unwrap_or(false);

        // The precondition for the destructive step: the target copy is really
        // there, so dropping the source copy completes the move. Anything else
        // means either the move finished or nothing landed — no work either way.
        if target_has_it && source_has_it {
            to_drop.push(moved);
        }
    }

    if to_drop.is_empty() {
        return Outcome::AlreadyComplete { operation };
    }

    let Some((_, track)) = project.tracks.iter_mut().find(|(id, _)| id == source_track) else {
        return Outcome::Indeterminate {
            operation,
            reason: format!("source track '{source_track}' is gone"),
        };
    };
    let mut steps = Vec::new();
    for moved in &to_drop {
        if !remove_task(track, &moved.old_id) {
            return Outcome::Indeterminate {
                operation,
                reason: format!(
                    "{} could not be removed from '{source_track}'",
                    moved.old_id
                ),
            };
        }
        steps.push(format!(
            "removed {} from '{source_track}' — it is already in '{target_track}' as {}",
            moved.old_id, moved.new_id
        ));
    }

    if let Err(e) = save_track(project, source_track) {
        return Outcome::Indeterminate {
            operation,
            reason: format!("could not write '{source_track}': {e}"),
        };
    }

    Outcome::Completed { operation, steps }
}

/// Remove a top-level task by ID from whichever section holds it.
fn remove_task(track: &mut crate::model::track::Track, task_id: &str) -> bool {
    for node in &mut track.nodes {
        if let TrackNode::Section { tasks, .. } = node {
            let before = tasks.len();
            tasks.retain(|t| t.id.as_deref() != Some(task_id));
            if tasks.len() != before {
                return true;
            }
        }
    }
    false
}

// ---------------------------------------------------------------------------
// Track archive
// ---------------------------------------------------------------------------

/// Config is written before the file is moved, so the remaining step is the
/// move. Verified by the file still being in `tracks/`.
fn recover_track_archive(
    project: &mut Project,
    operation: String,
    track_id: &str,
    file: &str,
) -> Outcome {
    let live = project.frame_dir.join(file);
    if !live.exists() {
        return Outcome::AlreadyComplete { operation };
    }
    match crate::ops::track_ops::archive_track_file(&project.frame_dir, track_id, file) {
        Ok(()) => Outcome::Completed {
            operation,
            steps: vec![format!(
                "moved {file} to archive/_tracks/{track_id}.md — config already had it archived"
            )],
        },
        Err(e) => Outcome::Indeterminate {
            operation,
            reason: format!("could not move {file}: {e}"),
        },
    }
}

/// The inverse, verified the same way from the other side: the file is still in
/// `archive/_tracks/` and the config already says active, so the remaining step
/// is the move back.
///
/// Worth completing promptly rather than merely reporting, because until it
/// happens the track is not merely misfiled — it is absent. `load_project`
/// skips it, so every command runs against a project one whole track short.
fn recover_track_unarchive(
    project: &mut Project,
    operation: String,
    track_id: &str,
    file: &str,
) -> Outcome {
    let archived = project
        .frame_dir
        .join("archive")
        .join("_tracks")
        .join(format!("{track_id}.md"));
    if !archived.exists() {
        return Outcome::AlreadyComplete { operation };
    }
    match crate::ops::track_ops::restore_track_file(&project.frame_dir, track_id, file) {
        Ok(()) => Outcome::Completed {
            operation,
            steps: vec![format!(
                "moved archive/_tracks/{track_id}.md back to {file} — config already had it active"
            )],
        },
        Err(e) => Outcome::Indeterminate {
            operation,
            reason: format!("could not restore {file}: {e}"),
        },
    }
}

// ---------------------------------------------------------------------------
// Track rename
// ---------------------------------------------------------------------------

/// The files move first and the config follows, so an interruption leaves the
/// config naming a file that no longer exists — and a configured track whose
/// file is missing is skipped by `load_project`, so the track and its tasks
/// disappear from every view until this runs.
///
/// Each step is checked before it is taken and each is idempotent, so this is
/// safe whether the interruption fell before the track rename, between the two
/// renames, or between them and the config write.
fn recover_track_rename(
    project: &mut Project,
    operation: String,
    old_id: &str,
    new_id: &str,
    old_file: &str,
    new_file: &str,
) -> Outcome {
    let mut steps = Vec::new();

    // The track file, then the archive: the same order the operation uses.
    let moves = [
        (
            project.frame_dir.join(old_file),
            project.frame_dir.join(new_file),
            format!("moved {old_file} to {new_file}"),
        ),
        (
            project
                .frame_dir
                .join("archive")
                .join(format!("{old_id}.md")),
            project
                .frame_dir
                .join("archive")
                .join(format!("{new_id}.md")),
            format!("moved archive/{old_id}.md to archive/{new_id}.md"),
        ),
    ];
    for (from, to, describe) in moves {
        // Both present is not ours to resolve: the destination was not written
        // by this operation, and picking a winner could discard either.
        if from.exists() && to.exists() {
            return Outcome::Indeterminate {
                operation,
                reason: format!(
                    "{} and {} both exist — move or remove one, then re-run",
                    from.display(),
                    to.display()
                ),
            };
        }
        // Absent from the source means either already moved or never there.
        if !from.exists() {
            continue;
        }
        if let Err(e) = std::fs::rename(&from, &to) {
            return Outcome::Indeterminate {
                operation,
                reason: format!("could not move {}: {e}", from.display()),
            };
        }
        steps.push(describe);
    }

    // The config write is what makes the track findable again.
    if project.config.tracks.iter().any(|t| t.id == old_id) {
        let Ok((_, mut doc)) = crate::io::config_io::read_config(&project.frame_dir) else {
            return Outcome::Indeterminate {
                operation,
                reason: "project.toml could not be read".to_string(),
            };
        };
        crate::io::config_io::update_track_id(&mut doc, old_id, new_id);
        crate::io::config_io::rename_prefix_key(&mut doc, old_id, new_id);
        if let Err(e) = crate::io::config_io::write_config(&project.frame_dir, &doc) {
            return Outcome::Indeterminate {
                operation,
                reason: format!("could not write project.toml: {e}"),
            };
        }
        steps.push(format!(
            "renamed track {old_id} to {new_id} in project.toml"
        ));
    }

    if steps.is_empty() {
        Outcome::AlreadyComplete { operation }
    } else {
        Outcome::Completed { operation, steps }
    }
}

// ---------------------------------------------------------------------------
// Actor merge
// ---------------------------------------------------------------------------

/// Tracks and archives are renumbered before the registry is written, so the
/// remaining step is retiring the source tokens. Safe to repeat: retiring an
/// already-retired token is a no-op here.
fn recover_actor_merge(
    project: &mut Project,
    operation: String,
    sources: &[String],
    target: &str,
) -> Outcome {
    let Ok(mut registry) = crate::io::actors::read_actors(&project.frame_dir) else {
        return Outcome::Indeterminate {
            operation,
            reason: "actors.toml could not be read".to_string(),
        };
    };

    let today = crate::io::actors::today();
    let mut retired = Vec::new();
    for token in sources {
        if registry.retire(token, &today).is_ok() {
            retired.push(token.clone());
        }
    }

    if retired.is_empty() {
        return Outcome::AlreadyComplete { operation };
    }

    if let Err(e) = crate::io::actors::write_actors(&project.frame_dir, &registry) {
        return Outcome::Indeterminate {
            operation,
            reason: format!("could not write actors.toml: {e}"),
        };
    }

    Outcome::Completed {
        operation,
        steps: vec![format!(
            "retired {} into '{target}' — ids were already renumbered",
            retired.join(", ")
        )],
    }
}

// ---------------------------------------------------------------------------
// Triage
// ---------------------------------------------------------------------------

/// The track is written before the inbox, so the remaining step is dropping the
/// inbox item. Gated on the item still being there *and* still matching the
/// recorded title, so a shifted or edited inbox is not silently mangled.
fn recover_triage(
    project: &mut Project,
    operation: String,
    index: usize,
    title: &str,
    track_id: &str,
) -> Outcome {
    let Some(inbox) = &project.inbox else {
        return Outcome::AlreadyComplete { operation };
    };
    let Some(item) = inbox.items.get(index.saturating_sub(1)) else {
        return Outcome::AlreadyComplete { operation };
    };
    if item.title != title {
        // The inbox moved on. Removing by index now would delete the wrong item.
        return Outcome::AlreadyComplete { operation };
    }

    // Precondition for the destructive step: the task really did land.
    let landed = project
        .tracks
        .iter()
        .find(|(id, _)| id == track_id)
        .map(|(_, track)| task_titled(track, title))
        .unwrap_or(false);
    if !landed {
        return Outcome::Indeterminate {
            operation,
            reason: format!(
                "inbox item {index} \"{title}\" is still in the inbox but no matching task \
                 exists in '{track_id}' — triage it again rather than losing it"
            ),
        };
    }

    let Some(inbox) = project.inbox.as_mut() else {
        return Outcome::AlreadyComplete { operation };
    };
    inbox.items.remove(index.saturating_sub(1));
    if let Err(e) = project_io::save_inbox(&project.frame_dir, inbox) {
        return Outcome::Indeterminate {
            operation,
            reason: format!("could not write inbox.md: {e}"),
        };
    }

    Outcome::Completed {
        operation,
        steps: vec![format!(
            "removed inbox item {index} \"{title}\" — it is already a task in '{track_id}'"
        )],
    }
}

fn task_titled(track: &crate::model::track::Track, title: &str) -> bool {
    fn walk(tasks: &[crate::model::task::Task], title: &str) -> bool {
        tasks
            .iter()
            .any(|t| t.title == title || walk(&t.subtasks, title))
    }
    track.nodes.iter().any(|node| match node {
        TrackNode::Section { tasks, .. } => walk(tasks, title),
        TrackNode::Literal(_) => false,
    })
}

// ---------------------------------------------------------------------------
// Shared
// ---------------------------------------------------------------------------

fn save_track(project: &Project, track_id: &str) -> Result<(), project_io::ProjectError> {
    let file = project
        .config
        .tracks
        .iter()
        .find(|tc| tc.id == track_id)
        .map(|tc| tc.file.clone())
        .ok_or(project_io::ProjectError::NotAProject)?;
    let track = project
        .tracks
        .iter()
        .find(|(id, _)| id == track_id)
        .map(|(_, t)| t)
        .ok_or(project_io::ProjectError::NotAProject)?;
    project_io::save_track(&project.frame_dir, &file, track)
}

/// Every recovery is written to the recovery log, including the ones that did
/// nothing. An automatic decision is only defensible if it leaves a trail.
fn log(project: &Project, marker: &Marker, outcome: &Outcome) {
    let (description, body) = match outcome {
        Outcome::AlreadyComplete { operation } => (
            format!("interrupted `{operation}` needed no recovery"),
            String::new(),
        ),
        Outcome::Completed { operation, steps } => (
            format!("interrupted `{operation}` completed automatically"),
            steps.join("\n"),
        ),
        Outcome::Indeterminate { operation, reason } => (
            format!("interrupted `{operation}` could not be completed automatically"),
            reason.clone(),
        ),
    };

    crate::io::recovery::log_recovery(
        &project.frame_dir,
        crate::io::recovery::RecoveryEntry {
            timestamp: chrono::Utc::now(),
            category: crate::io::recovery::RecoveryCategory::Write,
            description,
            fields: vec![
                ("Command".to_string(), marker.command.clone()),
                ("Started".to_string(), marker.started.clone()),
            ],
            body,
        },
    );
}