rhei-cli 0.3.0

Command-line driver for the Rhei agent runtime.
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806

struct TransitionTaskInfo {
    task: rhei_core::ast::Task,
    level: u8,
    /// The task's ancestors, nearest first. Supervision reads them to find the
    /// nearest supervising one. §FS-rhei-supervision.2.2
    ancestors: Vec<rhei_core::ast::Task>,
}

fn task_profile_allows_state(
    machine: &rhei_validator::StateMachine,
    kind: &str,
    level: u8,
    state: &str,
) -> bool {
    machine
        .profile_for_node(kind, level)
        .is_none_or(|profile| profile.allowed.iter().any(|allowed| allowed == state))
}

/// The plan path as a user would type it: relative to the working directory
/// when it sits beneath it, absolute otherwise.
///
/// A `help =` names commands the user is meant to run next, and every other one
/// echoes the argument they typed. The transition path only has the resolved,
/// canonicalized plan path, so it renders that back down to the same shape
/// rather than pasting an absolute path into the middle of a suggested command.
// §FS-rhei-errors.2
fn plan_arg_for_help(plan_path: &Path) -> String {
    let shown = std::env::current_dir()
        .ok()
        .and_then(|cwd| cwd.canonicalize().ok())
        .and_then(|cwd| plan_path.strip_prefix(cwd).ok())
        .map(|relative| {
            if relative.as_os_str().is_empty() {
                PathBuf::from(".")
            } else {
                relative.to_path_buf()
            }
        })
        .unwrap_or_else(|| plan_path.to_path_buf());
    shell_quote(&shown.display().to_string())
}

/// Reject a move into a `final: true` state while the task still has a
/// non-terminal descendant.
///
/// Descendants-first is a property of the graph, not of a command: it belongs
/// on the shared transition path beside compare-and-swap, artifact
/// enforcement, and callbacks, so `rhei transition`, `rhei complete`, `rhei
/// run`'s auto-advance, and a callback redirect all enforce it identically.
/// It cannot be delegated to machine authors either — transition `condition:`
/// expressions see only visit and exit-code variables, so no machine can gate
/// a parent's terminal edge on its children.
///
/// This is deliberately not symmetric with `**Prior:**` readiness, which
/// `rhei transition` skips as the human escape hatch: an out-of-order prior is
/// a `rhei validate` warning, a terminal parent with an open descendant is an
/// error. `transition` may produce a warning; it must never produce an error.
// §FS-rhei-transition-cmd.3.1 §FS-rhei-states.2.3
fn ensure_descendants_terminal_for_terminal_entry(
    machine: &rhei_validator::StateMachine,
    task: &rhei_core::ast::Task,
    local_id: &str,
    qualified_id: &str,
    to: &str,
    plan_path: &Path,
) -> MietteResult<()> {
    if task.children.is_empty()
        || !machine.states.get(to).map(|def| def.terminal).unwrap_or(false)
    {
        return Ok(());
    }
    // The task tree parsed here carries rhei-local ids; the caller knows the
    // project-qualified form, so recover the prefix and report descendants the
    // way every other surface prints them. §FS-rhei-panta.6
    let prefix = qualified_id.strip_suffix(local_id).unwrap_or("");
    let open = non_terminal_descendants(task, machine, prefix);
    if open.is_empty() {
        return Ok(());
    }
    // Name the command that shows the open work and the one that claims it:
    // "finish the descendants" is the answer, but the user still has to find
    // them. §FS-rhei-errors.2
    let plan = plan_arg_for_help(plan_path);
    Err(miette!(
        help = format!(
            "a parent is finished after its subtree is, and nothing finishes it on its \
             children's behalf. See the open work with: rhei list {plan} --non-terminal, \
             then claim it with: rhei next {plan}"
        ),
        "Task {} cannot enter terminal state '{}' while descendant tasks remain non-terminal.\n\
         Offending descendants: {}",
        qualified_id,
        to,
        open.join(", ")
    ))
}

fn ensure_task_profile_allows_state(
    machine: &rhei_validator::StateMachine,
    task_id_str: &str,
    kind: &str,
    level: u8,
    state: &str,
) -> MietteResult<()> {
    let Some(profile) = machine.profile_for_node(kind, level) else {
        return Ok(());
    };
    if profile.allowed.iter().any(|allowed| allowed == state) {
        return Ok(());
    }

    Err(miette!(
        help = "the task's node profile restricts which states it may enter. Change the task's profile, or widen the profile in the state machine.",
        "Task {} cannot enter state '{}': state is not allowed by its resolved profile. Profile allows: [{}]",
        task_id_str,
        state,
        profile.allowed.join(", ")
    ))
}

#[allow(clippy::too_many_arguments)]
fn execute_transition_with_origin(
    files: TransitionFiles<'_>,
    callback_paths: &CallbackPaths,
    machine: &rhei_validator::StateMachine,
    task_id_str: &str,
    from: &str,
    to: &str,
    no_callbacks: bool,
    origin: TransitionOrigin,
) -> MietteResult<String> {
    let task_file = files.task_file;
    let metadata_file = files.metadata_file;
    let workspace_root = execution_workspace_root(&callback_paths.plan_path);
    let settings = load_merged_settings(&workspace_root)?;

    // Validate that both `from` and `to` are valid states.
    if !machine.is_valid_state(from) {
        let allowed = machine.allowed_states().collect::<Vec<_>>().join(", ");
        return Err(miette!(
            help = unknown_state_help(),
            "'{}' is not a valid state. Allowed: [{}]", from, allowed
        ));
    }
    if !machine.is_valid_state(to) {
        let allowed = machine.allowed_states().collect::<Vec<_>>().join(", ");
        return Err(miette!(
            help = unknown_state_help(),
            "'{}' is not a valid state. Allowed: [{}]", to, allowed
        ));
    }

    // Open the file(s) with an exclusive lock for the duration of the operation.
    let metadata_handle = fs::File::open(metadata_file)
        .map_err(|err| file_io_report(metadata_file, "failed to open plan file", err))?;
    metadata_handle
        .lock_exclusive()
        .map_err(|err| file_io_report(metadata_file, "failed to acquire file lock", err))?;
    let task_handle = if task_file == metadata_file {
        None
    } else {
        let handle = fs::File::open(task_file)
            .map_err(|err| file_io_report(task_file, "failed to open plan file", err))?;
        handle
            .lock_exclusive()
            .map_err(|err| file_io_report(task_file, "failed to acquire file lock", err))?;
        Some(handle)
    };

    // Read the raw markdown while holding the locks.
    let metadata_raw = fs::read_to_string(metadata_file)
        .map_err(|err| file_io_report(metadata_file, "failed to read plan file", err))?;
    let task_raw = if task_file == metadata_file {
        metadata_raw.clone()
    } else {
        fs::read_to_string(task_file)
            .map_err(|err| file_io_report(task_file, "failed to read plan file", err))?
    };

    // Parse to validate structure and find the task.
    // Try full plan parse first; fall back to manifest + task-file parse.
    let target_id = parse_task_id(task_id_str);
    // The metadata key is the ticket's local id everywhere except the basin,
    // whose metadata shares the project manifest under qualified ids.
    let metadata_key = parse_task_id(files.metadata_id);
    let manifest = if task_file == metadata_file {
        None
    } else {
        Some(parse_metadata_manifest(metadata_file, &metadata_raw)?)
    };
    let task_info = find_task_transition_info(
        &task_raw,
        task_file,
        manifest.as_ref().map(|index| &index.structure),
        &target_id,
        task_id_str,
    )?;
    let current_state_raw = task_info.task.state.clone();
    let current_state = normalized_state_name(&current_state_raw, machine);
    let metadata = if task_file == metadata_file {
        rhei_core::parse(&metadata_raw)
            .map_err(|err| {
                miette!(
                    help = plan_authoring_help(),
                    "failed to parse plan for transition metadata: {}", err.message
                )
            })?
            .metadata
    } else {
        manifest.and_then(|index| index.metadata)
    };

    // Compare-and-swap: verify the task's current state matches `from`.
    // This runs before the transition-legality check so a wrong `--from`
    // produces the actionable "task is in state X" error instead of the
    // less informative "transition not allowed" error.
    if current_state != from {
        if let Some(task_handle) = &task_handle {
            let _ = fs2::FileExt::unlock(task_handle);
        }
        let _ = fs2::FileExt::unlock(&metadata_handle);
        return Err(miette!(
            help = task_moved_help(),
            "conflict: Task {} is in state '{}', expected '{}'",
            files.artifact_id,
            current_state_raw,
            from
        ));
    }
    if let Err(err) = ensure_task_profile_allows_state(
        machine,
        files.artifact_id,
        &task_info.task.kind,
        task_info.level,
        to,
    ) {
        if let Some(task_handle) = &task_handle {
            let _ = fs2::FileExt::unlock(task_handle);
        }
        let _ = fs2::FileExt::unlock(&metadata_handle);
        return Err(err);
    }

    // Now that we know the task really is in `from`, check whether the
    // declared transitions permit `from -> to`.
    let matching_rule =
        machine.transitions().iter().find(|rule| rule.from.0 == from && rule.to.0 == to).or_else(
            || machine.transitions().iter().find(|rule| rule.from.0 == "*" && rule.to.0 == to),
        );
    let Some(matching_rule) = matching_rule else {
        if let Some(task_handle) = &task_handle {
            let _ = fs2::FileExt::unlock(task_handle);
        }
        let _ = fs2::FileExt::unlock(&metadata_handle);
        return Err(miette!(
            help = "the machine declares no such edge. List the edges with: rhei states",
            "transition from '{}' to '{}' is not allowed by the state machine",
            from,
            to
        ));
    };

    let normalized_metadata = ensure_current_state_visit_count(
        metadata.as_ref(),
        &metadata_key,
        from,
        &current_state_raw,
        machine,
    );
    let metadata_for_checks = normalized_metadata.as_ref().or(metadata.as_ref());

    if !transition_rule_is_applicable(
        matching_rule,
        machine,
        metadata_for_checks,
        &metadata_key,
        Some(&task_info.task),
        from,
        &current_state_raw,
    )? {
        if let Some(task_handle) = &task_handle {
            let _ = fs2::FileExt::unlock(task_handle);
        }
        let _ = fs2::FileExt::unlock(&metadata_handle);
        let reason = describe_blocked_transition(
            matching_rule,
            machine,
            metadata_for_checks,
            &metadata_key,
            from,
            &current_state_raw,
        );
        let alternatives = applicable_alternatives(
            machine,
            metadata_for_checks,
            &metadata_key,
            Some(&task_info.task),
            from,
            &current_state_raw,
        );
        let suffix = if alternatives.is_empty() {
            "No other transitions from this state are currently applicable.".to_string()
        } else {
            format!(
                "Currently applicable transitions from '{}': {}.",
                from,
                alternatives.join(", ")
            )
        };
        return Err(miette!(
            help = "the edge exists but its condition is unmet. Inspect the machine with: rhei states",
            "transition from '{}' to '{}' is not currently applicable: {}. {}",
            from,
            to,
            reason,
            suffix
        ));
    }

    // Descendants-first runs once the edge is declared and applicable, before
    // any callback: no "close your subtree" for a move that was never
    // available anyway. §FS-rhei-transition-cmd.3
    if let Err(err) = ensure_descendants_terminal_for_terminal_entry(
        machine,
        &task_info.task,
        task_id_str,
        files.artifact_id,
        to,
        &callback_paths.plan_path,
    ) {
        if let Some(task_handle) = &task_handle {
            let _ = fs2::FileExt::unlock(task_handle);
        }
        let _ = fs2::FileExt::unlock(&metadata_handle);
        return Err(err);
    }

    let from_state_def = machine
        .states
        .get(from)
        .ok_or_else(|| miette!(
            help = internal_error_help(),
            "state '{}' missing from loaded machine", from
        ))?;

    let from_invocations = resolve_agent_invocations_for_task(
        machine,
        from,
        &settings,
        &default_run_options(),
        Some(&task_info.task),
    )
    .unwrap_or_default();
    let callback_contexts = callback_contexts_for_state(from_state_def, &from_invocations);

    // Parse the plan once for callback-context serialization. Failure here
    // means we fall back to a minimal payload rather than aborting — the
    // transition should still run even if the plan is only partially
    // structured.
    let plan_for_context = rhei_core::parse(&metadata_raw).ok();

    // Accumulated `transitionData` that flows from on_leave callbacks to
    // on_enter. Starts from the engine-seeded payload (e.g. timeout data)
    // and each callback's `data` merges last-write-wins.
    let mut transition_data: serde_json::Value = origin
        .seed_data
        .clone()
        .unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
    // A callback may request a redirect via `next_state`. The first such
    // request wins; later callbacks are still executed against the original
    // `to` for rejection checks, but their redirects are ignored.
    let mut redirect_next_state: Option<String> = None;

    // Execute on_leave callback before the state change.
    if !no_callbacks {
        if let Some(ref cb) = matching_rule.on_leave {
            let executor = ShellCallbackExecutor;
            for (model, agent) in callback_contexts {
                let context_json = build_transition_context_json(
                    plan_for_context.as_ref(),
                    &callback_paths.plan_path,
                    task_id_str,
                    files.artifact_id,
                    from,
                    to,
                    origin.triggered_by.unwrap_or("user"),
                    &transition_data,
                    &callback_paths.working_dir,
                );
                let ctx = CallbackContext {
                    // §FS-rhei-panta.6: callbacks see the qualified id; the
                    // rhei-local heading id rides along for file edits.
                    task_id: files.artifact_id,
                    task_id_local: task_id_str,
                    from_state: from,
                    to_state: to,
                    plan_path: &callback_paths.plan_path,
                    callback_cwd: &callback_paths.working_dir,
                    model,
                    agent,
                    context_json: Some(&context_json),
                };
                let result = executor.execute(cb, &ctx).map_err(|e| miette!(
                    help = state_machine_help(),
                    "{e}"
                ))?;
                if !result.success {
                    if let Some(task_handle) = &task_handle {
                        let _ = fs2::FileExt::unlock(task_handle);
                    }
                    let _ = fs2::FileExt::unlock(&metadata_handle);
                    let message = result
                        .error
                        .clone()
                        .unwrap_or_else(|| "transition rejected by callback".to_string());
                    return Err(miette!(
                        help = callback_command_help(),
                        "on_leave callback '{}' rejected the transition: {message}",
                        cb.0
                    ));
                }
                if let Some(data) = result.data.as_ref() {
                    merge_transition_data(&mut transition_data, data);
                }
                if let Some(redirect) = result.next_state.clone() {
                    if redirect_next_state.is_none() {
                        redirect_next_state = Some(redirect);
                    }
                }
            }
        }
    }

    // Resolve redirects before committing state: validate the redirect is a
    // declared transition from the current state. A redirect to the same
    // target is a no-op.
    let (effective_to, effective_rule) = if let Some(redirect) = redirect_next_state.as_deref() {
        if redirect == to {
            (to.to_string(), matching_rule)
        } else if !machine.is_valid_state(redirect) {
            if let Some(task_handle) = &task_handle {
                let _ = fs2::FileExt::unlock(task_handle);
            }
            let _ = fs2::FileExt::unlock(&metadata_handle);
            return Err(miette!(
                help = callback_command_help(),
                "on_leave callback redirected to unknown state '{}'", redirect
            ));
        } else if let Err(err) = ensure_task_profile_allows_state(
            machine,
            files.artifact_id,
            &task_info.task.kind,
            task_info.level,
            redirect,
        ) {
            if let Some(task_handle) = &task_handle {
                let _ = fs2::FileExt::unlock(task_handle);
            }
            let _ = fs2::FileExt::unlock(&metadata_handle);
            return Err(err);
        } else if let Some(rule) =
            machine.transitions().iter().find(|r| r.from.0 == from && r.to.0 == redirect).or_else(
                || machine.transitions().iter().find(|r| r.from.0 == "*" && r.to.0 == redirect),
            )
        {
            (redirect.to_string(), rule)
        } else {
            if let Some(task_handle) = &task_handle {
                let _ = fs2::FileExt::unlock(task_handle);
            }
            let _ = fs2::FileExt::unlock(&metadata_handle);
            return Err(miette!(
                help = callback_command_help(),
                "on_leave callback redirected to '{}', but no transition from '{}' to '{}' is declared",
                redirect,
                from,
                redirect
            ));
        }
    } else {
        (to.to_string(), matching_rule)
    };
    let to = effective_to.as_str();
    let matching_rule = effective_rule;

    // §FS-rhei-transition-cmd.3.1: re-check against the effective target so a
    // `nextState` redirect cannot smuggle a terminal entry past the guard.
    if let Err(err) = ensure_descendants_terminal_for_terminal_entry(
        machine,
        &task_info.task,
        task_id_str,
        files.artifact_id,
        to,
        &callback_paths.plan_path,
    ) {
        if let Some(task_handle) = &task_handle {
            let _ = fs2::FileExt::unlock(task_handle);
        }
        let _ = fs2::FileExt::unlock(&metadata_handle);
        return Err(err);
    }

    let to_state_def = machine
        .states
        .get(to)
        .ok_or_else(|| miette!(
            help = internal_error_help(),
            "state '{}' missing from loaded machine", to
        ))?;

    let mut updated_metadata =
        update_metadata_for_transition(metadata_for_checks, &metadata_key, to, machine)
            .or_else(|| normalized_metadata.clone());
    if from_state_def.poll.is_some() && to != from {
        updated_metadata = clear_poll_state_metadata(
            updated_metadata.as_ref().or(metadata_for_checks),
            &metadata_key,
            from,
        );
    }
    let from_visit_count = Some(render_visit_count(
        metadata_for_checks,
        &metadata_key,
        from,
        &current_state_raw,
        machine,
    ));
    let to_visit_count = updated_metadata
        .as_ref()
        .map(|meta| task_visit_count(Some(meta), &metadata_key, to))
        .filter(|count| *count > 0);

    // The barrier is maintained here so `rhei run`'s auto-advance, `rhei
    // transition`, `rhei complete`, and a callback redirect all maintain it
    // identically. §FS-rhei-supervision.2 §FS-rhei-supervision.3.3
    if let Some(next) = supervision_after_transition(
        updated_metadata.as_ref().or(metadata_for_checks),
        machine,
        &task_info,
        files,
        &metadata_key,
        (task_id_str, from, to),
        to_visit_count.unwrap_or(1),
    ) {
        updated_metadata = Some(next);
    }

    // §AR-rhei-panta.2: artifact templates render the project-qualified id
    // against the owning rhei's execution root, matching the paths agents and
    // ready-checks were shown.

    // A cancel abandons the work, so the abandoned step's artifact contract is
    // moot; the target's inputs and the terminal result below still apply.
    // §FS-rhei-transitions.4.5

    // Only the reserved name waives it, in either spelling; anything else gets
    // the ordinary check and a refusal that says so. §FS-rhei-states.1.4
    let cancelling = rhei_validator::is_cancelled_state_name(&normalized_state_name(to, machine));
    if !origin.skip_source_outputs && !cancelling {
        ensure_state_outputs_exist_for_transition(
            files.artifact_root,
            Some(&task_info.task),
            files.artifact_id,
            from,
            from_state_def,
            from_visit_count,
            machine,
            &settings,
            machine.states.get(to).map(|def| def.terminal).unwrap_or(false),
        )?;
    }
    ensure_state_inputs_exist_for_transition(
        files.artifact_root,
        Some(&task_info.task),
        files.artifact_id,
        to,
        to_state_def,
        to_visit_count,
        machine,
        &settings,
        &format!("Task {} cannot enter state {}.", files.artifact_id, to),
    )?;
    // A caller that knows the outcome carries the message; otherwise the
    // engine's own account stands in, but only where it is true.
    // §FS-rhei-states.3.3 §FS-rhei-run.3
    let recorded_message = origin.result_message.clone().or_else(|| {
        let lands_terminal = machine.states.get(to).map(|def| def.terminal).unwrap_or(false);
        if lands_terminal && !task_result_is_present(files.artifact_root, files.artifact_id) {
            origin.terminal_result_fallback.clone()
        } else {
            None
        }
    });

    // The terminal result is the one artifact contract of a `final: true` state
    // that no machine declares, checked here beside the declared ones and
    // against the same effective target. §FS-rhei-states.3.3
    if let Err(err) = ensure_terminal_result_available(
        machine,
        files.artifact_root,
        files.artifact_id,
        from,
        to,
        recorded_message.as_deref(),
        &callback_paths.plan_path,
    ) {
        if let Some(task_handle) = &task_handle {
            let _ = fs2::FileExt::unlock(task_handle);
        }
        let _ = fs2::FileExt::unlock(&metadata_handle);
        return Err(err);
    }

    let rendered_to_state = format_task_state_value(to, to_visit_count, machine);
    // §FS-rhei-supervision.3.4: the release self-loop ends the visit, so it
    // ends the claim the visit was taken under.
    let ends_visit = transition_ends_supervisor_visit(machine, from, to);
    let metadata_raw_updated = if task_file == metadata_file {
        let new_task_raw =
            rewrite_task_for_transition(&task_raw, task_id_str, &rendered_to_state, ends_visit)?;
        if let Some(updated_metadata) = updated_metadata.as_ref() {
            rewrite_frontmatter(&new_task_raw, updated_metadata)?
        } else {
            new_task_raw
        }
    } else if let Some(updated_metadata) = updated_metadata.as_ref() {
        rewrite_frontmatter(&metadata_raw, updated_metadata)?
    } else {
        metadata_raw.clone()
    };

    let task_raw_updated = if task_file == metadata_file {
        None
    } else {
        Some(rewrite_task_for_transition(
            &task_raw,
            task_id_str,
            &rendered_to_state,
            ends_visit,
        )?)
    };

    // Atomic write(s): write to temp file in the same directory, then rename.
    write_file_atomic(metadata_file, &metadata_raw_updated)?;
    if let Some(ref task_raw_updated) = task_raw_updated {
        write_file_atomic(task_file, task_raw_updated)?;
    }

    // Execute on_enter callback after the state change (not model-looped).
    let triggered_by = origin.triggered_by.unwrap_or(if redirect_next_state.is_some() {
        "callback"
    } else {
        "user"
    });
    let on_enter_context_json = build_transition_context_json(
        plan_for_context.as_ref(),
        &callback_paths.plan_path,
        task_id_str,
        files.artifact_id,
        from,
        to,
        triggered_by,
        &transition_data,
        &callback_paths.working_dir,
    );
    let callback_ctx = CallbackContext {
        task_id: files.artifact_id,
        task_id_local: task_id_str,
        from_state: from,
        to_state: to,
        plan_path: &callback_paths.plan_path,
        callback_cwd: &callback_paths.working_dir,
        model: None,
        agent: None,
        context_json: Some(&on_enter_context_json),
    };
    if !no_callbacks {
        if let Some(ref cb) = matching_rule.on_enter {
            let executor = ShellCallbackExecutor;
            let result = executor.execute(cb, &callback_ctx).map_err(|e| miette!(
                help = state_machine_help(),
                "{e}"
            ))?;
            if !result.success {
                // Spec §Example 8: on_enter failure rolls back the state
                // write to the original, then the error_handling policy
                // applies. We implement the rollback; policy execution is
                // a follow-up.
                let rollback_err = write_file_atomic(metadata_file, &metadata_raw).err();
                let task_rollback_err = if task_raw_updated.is_some() {
                    write_file_atomic(task_file, &task_raw).err()
                } else {
                    None
                };
                if let Some(task_handle) = &task_handle {
                    let _ = fs2::FileExt::unlock(task_handle);
                }
                let _ = fs2::FileExt::unlock(&metadata_handle);
                let message =
                    result.error.clone().unwrap_or_else(|| "on_enter callback failed".to_string());
                if rollback_err.is_some() || task_rollback_err.is_some() {
                    return Err(miette!(
                        help = callback_command_help(),
                        "on_enter callback '{}' failed ({message}); rollback also failed — plan file may be inconsistent",
                        cb.0
                    ));
                }
                return Err(miette!(
                    help = callback_command_help(),
                    "on_enter callback '{}' failed: {message}", cb.0
                ));
            }
        }
    }

    // Inside the lock, after `on_enter` had its chance to roll the write back,
    // so no caller can apply a transition and forget the ledger or the result.
    // §FS-rhei-complete.3 §FS-rhei-transition-cmd.3
    let record = record_transition_result(
        files.artifact_root,
        files.task_file,
        task_id_str,
        machine,
        files.artifact_id,
        from,
        to,
        recorded_message.as_deref(),
    );

    if let Some(task_handle) = task_handle {
        let _ = fs2::FileExt::unlock(&task_handle);
    }
    let _ = fs2::FileExt::unlock(&metadata_handle);
    record?;
    Ok(to.to_string())
}

/// The task's markdown after this transition: the new `**State:**` value, and
/// — only when the edge ends a supervisor's visit — without the
/// `**Assignee:**` that visit was claimed under.
///
/// Rewritten in memory rather than through the claim command so an `on_enter`
/// failure rolls the claim back with the state it was written beside.
// §FS-rhei-supervision.3.4 §FS-rhei-transition-cmd.3
fn rewrite_task_for_transition(
    raw: &str,
    local_id: &str,
    rendered_to_state: &str,
    ends_supervisor_visit: bool,
) -> MietteResult<String> {
    let rewritten = rewrite_task_state(raw, local_id, rendered_to_state)?;
    if !ends_supervisor_visit {
        return Ok(rewritten);
    }
    Ok(without_task_assignee(&rewritten, local_id).0)
}

/// Extract the current state and node-policy inputs for a task from raw
/// markdown content.
///
/// Tries full-plan parsing first, falls back to workspace task-file parsing.
fn find_task_transition_info(
    raw: &str,
    file_path: &Path,
    workspace_structure: Option<&rhei_core::ast::Structure>,
    target_id: &TaskId,
    task_id_str: &str,
) -> MietteResult<TransitionTaskInfo> {
    // Try full plan parse.
    if let Ok(rhei) = rhei_core::parse(raw) {
        if let Some(task) = find_task_by_id(&rhei.tasks, target_id) {
            return Ok(TransitionTaskInfo {
                task: task.clone(),
                level: task.id.depth() as u8,
                ancestors: ancestor_chain(&rhei.tasks, target_id)
                    .into_iter()
                    .cloned()
                    .collect(),
            });
        }
    }

    // Try workspace task-file parse.
    let workspace_tasks = match workspace_structure {
        Some(structure) => rhei_core::parser::parse_workspace_tasks_with_structure(raw, structure),
        None => rhei_core::parser::parse_workspace_tasks(raw),
    };
    if let Ok(tasks) = workspace_tasks {
        if let Some(task) = find_task_by_id(&tasks, target_id) {
            return Ok(TransitionTaskInfo {
                task: task.clone(),
                level: task.id.depth() as u8,
                ancestors: ancestor_chain(&tasks, target_id).into_iter().cloned().collect(),
            });
        }
    }

    Err(miette!(
        help = task_id_help(),
        "task '{}' not found in {}", task_id_str, file_path.display()
    ))
}

// ─── Agent Configuration ──────────────────────────────────────────────