toha 0.3.0

Generate projects and files from templates through one interview for people, scripts, agents, and Rust callers.
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
// ---
// relationships:
//   implements: architecture
// ---
//! The template-update route: `apply --from ID` and `apply --baseline`.
//!
//! An update re-renders a template and merges the difference into the target,
//! three-way against a base. `--from` reads the base from a stored snapshot and
//! replays its recorded answers through the unchanged interview engine; the
//! `--answers` envelope supplies overrides and `--reanswer` re-asks every answer.
//! `--baseline` merges the whole render against an empty base, so unrelated local
//! edits survive. An update refuses a dirty target, a snapshot taken for another
//! target, and a template whose source is not the snapshot's (identity 17). At a
//! terminal a one-shot update prompts the questions the recorded answers do not
//! settle; the agent stages it with `stage --from` (see `update_stage`).

use std::path::Path;

use indexmap::IndexMap;
use serde_json::{Value, json};
use std::io::IsTerminal;
use toha::context::InvocationContext;
use toha::hook::ProcessRunner;
use toha::interview::Seed;

use toha::protocol::Context;
use toha::snapshot::{
    Action, Base, Change, Cleanliness, ConflictKind, FrozenNow, MergeOptions, Merged, Project,
    RepoPath, Snapshot, SnapshotInputs, UpdateDrive, drive_update, drive_update_resume,
    merge_apply_reported,
};
use toha::template::{Id, Template};
use toha::{RawAnswer, RawAnswers};

use crate::cli::resolve::ResolvedTemplate;
use crate::{
    Dirs, EnvironmentDecision, Outcome, apply_environment_grant, build_context, load_template,
    read_answers_text, requirement_error, resolution, setup,
};

/// The base an update merges from.
#[derive(Clone)]
pub enum UpdateBase {
    /// A stored snapshot, named by id or id prefix.
    From(String),
    /// An empty base: the whole render is merged, three-way against nothing.
    Baseline,
}

/// `apply --from ID PATH [--answers FILE] [--reanswer]` and `apply --baseline
/// TEMPLATE PATH --answers FILE`.
#[allow(clippy::too_many_arguments)]
pub fn run_update(
    base: UpdateBase,
    template_arg: Option<String>,
    path: &Path,
    answers: Option<String>,
    reanswer: bool,
    dry_run: bool,
    trust: bool,
    dirs: &Dirs,
) -> Outcome {
    let (target, _store) = match setup(path, dirs) {
        Ok(value) => value,
        Err(error) => return Outcome::Error(error),
    };
    let prep = match prepare(
        &base,
        template_arg,
        &target,
        dirs,
        trust,
        PrepareMode::Apply,
        false,
        answers.is_some(),
    ) {
        Ok(value) => value,
        Err(outcome) => return outcome,
    };

    // The override answers from `--answers`, identity-checked against the
    // resolved template.
    let overrides = match &answers {
        Some(file) => {
            let text = match read_answers_text(file) {
                Ok(value) => value,
                Err(error) => return Outcome::Error(error),
            };
            match toha::protocol::verify_answers(&prep.resolved.formal_name, &text) {
                Ok(value) => value,
                Err(error) => return Outcome::Error(error.to_string()),
            }
        }
        None => IndexMap::new(),
    };

    // The person route (no `--answers`, a terminal) prompts the questions the
    // recorded answers do not settle, then merges; the script and agent route
    // reports them.
    if answers.is_none() && std::io::stdin().is_terminal() {
        return person_update(prep, &target, reanswer, dry_run);
    }

    let seed = Seed {
        now: prep.now.clone(),
        defaults: prep.configured_defaults.clone(),
        context: prep.context.clone(),
    };
    let driven = match drive_update(&prep.template, seed, &prep.recorded, overrides, reanswer) {
        Ok(value) => value,
        Err(error) => return Outcome::Error(error.to_string()),
    };
    let (completed, submissions) = match driven {
        UpdateDrive::Completed {
            completed,
            submissions,
        } => (completed, submissions),
        UpdateDrive::Ask {
            pending,
            rejections,
            ..
        } => {
            // The script route cannot prompt. A batch the replay could not
            // complete is reported as `questions` (exit 4), the same document the
            // scripted apply returns. Without `--answers` this is the person
            // route; its `stage`/`continue` continuation is the update staging
            // flow, so a one-shot person update with unsettled questions refuses.
            if answers.is_none() {
                return Outcome::Error(
                    "the update has questions the recorded answers do not settle; \
                     stage it with `stage --from` to answer them"
                        .to_owned(),
                );
            }
            let saved = crate::StagedRecord::new_with_context(
                prep.context.clone(),
                prep.resolved.commit.clone(),
                prep.resolved.named,
                prep.now.to_string(),
                vec![],
            );
            let ctx = crate::context(&target, &saved);
            return Outcome::Document(
                toha::protocol::batch_document(pending.batch(), &ctx, Some(&rejections)),
                4,
            );
        }
        UpdateDrive::Ended(ended) => {
            eprintln!("{}", crate::guidance::flow_ended(&ended));
            return Outcome::Error(format!(
                "the template ended the interview: {:?}",
                ended.kind()
            ));
        }
    };

    // A flow `dry-run` composes with the CLI `--dry-run` by union.
    let dry_run = effective_dry_run(dry_run, &completed);
    finish_merge(
        prep,
        &target,
        completed,
        submissions,
        dry_run,
        answers.is_some(),
    )
}

/// The person route for a one-shot update: prompt the questions the recorded
/// answers do not settle — re-driving through the adapter each round so a batch
/// the recorded answers cover is never prompted — then merge.
fn person_update(
    prep: Prepared,
    target: &toha::staging::CanonicalTarget,
    reanswer: bool,
    dry_run: bool,
) -> Outcome {
    let mut staged: Vec<IndexMap<Id, RawAnswer>> = Vec::new();
    loop {
        let seed = Seed {
            now: prep.now.clone(),
            defaults: prep.configured_defaults.clone(),
            context: prep.context.clone(),
        };
        let driven =
            match drive_update_resume(&prep.template, seed, &prep.recorded, &staged, reanswer) {
                Ok(value) => value,
                Err(error) => return Outcome::Error(error.to_string()),
            };
        match driven {
            UpdateDrive::Completed {
                completed,
                submissions,
            } => {
                // A flow `dry-run` composes with the CLI `--dry-run` by union.
                let dry_run = effective_dry_run(dry_run, &completed);
                return finish_merge(prep, target, completed, submissions, dry_run, false);
            }
            UpdateDrive::Ask { pending, .. } => {
                let submission =
                    match crate::terminal::prompt_batch(&pending, &mut crate::terminal::InquireAsk)
                    {
                        Ok(submission) => submission,
                        Err(error) => return Outcome::Error(error),
                    };
                staged.push(submission);
            }
            UpdateDrive::Ended(ended) => {
                eprintln!("{}", crate::guidance::flow_ended(&ended));
                return Outcome::Error(format!(
                    "the template ended the interview: {:?}",
                    ended.kind()
                ));
            }
        }
    }
}

/// The shared pieces an update route needs after resolving its base and
/// template: the opened project, the merge base, the resolved template and its
/// render context, the base's recorded submissions, and the trust grant.
pub(crate) struct Prepared {
    pub project: Project,
    pub merge_base: Base,
    pub base_snapshot: Option<Snapshot>,
    pub resolved: ResolvedTemplate,
    pub template: Template,
    pub now: jiff::Zoned,
    pub context: InvocationContext,
    pub configured_defaults: RawAnswers,
    pub recorded: Vec<IndexMap<Id, RawAnswer>>,
    pub trusted: bool,
}

/// Open the project, resolve the base snapshot and template, enforce the update
/// preconditions and identity (17), and build the render context and trust
/// grant. Shared by the one-shot update route and the staged update flow.
/// How `prepare` grants the environment and computes trust: an `apply` merges
/// now; a `stage` captures the grant for later batches.
pub(crate) enum PrepareMode {
    Apply,
    Stage,
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn prepare(
    base: &UpdateBase,
    template_arg: Option<String>,
    target: &toha::staging::CanonicalTarget,
    dirs: &Dirs,
    trust: bool,
    mode: PrepareMode,
    interactive: bool,
    scripted: bool,
) -> Result<Prepared, Outcome> {
    let project = match Project::open(target) {
        Ok(Some(project)) => project,
        Ok(None) => {
            return Err(Outcome::Error(
                "the target is not inside a git repository; an update needs git".to_owned(),
            ));
        }
        Err(error) => return Err(Outcome::Error(error.to_string())),
    };

    let (merge_base, base_snapshot) = match base {
        UpdateBase::From(prefix) => match project.find(prefix) {
            Ok(snapshot) => (Base::Snapshot(snapshot.clone()), Some(snapshot)),
            Err(error) => return Err(Outcome::Error(error.to_string())),
        },
        UpdateBase::Baseline => (Base::Empty, None),
    };

    // Preconditions: the target must be clean, and a base snapshot must have been
    // taken for this same target (identity 17, target side).
    if let Some(snapshot) = &base_snapshot
        && snapshot.target() != project.target()
    {
        return Err(Outcome::Error(format!(
            "the snapshot was taken for target {:?}, not {:?}",
            snapshot.target().as_str(),
            project.target().as_str()
        )));
    }
    match project.cleanliness() {
        Ok(Cleanliness::Clean) => {}
        Ok(Cleanliness::Dirty { .. }) => {
            return Err(Outcome::Error(
                "the target has uncommitted changes; commit or discard them before an update"
                    .to_owned(),
            ));
        }
        Err(error) => return Err(Outcome::Error(error.to_string())),
    }

    let cwd = std::env::current_dir().map_err(|e| Outcome::Error(e.to_string()))?;
    let (config, registry) = cli_context(dirs, &cwd)?;

    let resolved = match (&base_snapshot, &template_arg) {
        (Some(snapshot), None) => {
            let formal = snapshot.template().to_owned();
            match crate::cli::resolve::resume_snapshot_template(
                &formal,
                snapshot.revision(),
                &config,
                &registry,
                dirs,
                &cwd,
            ) {
                Ok(value) => value,
                Err(error) => return Err(crate::resolve_error(error)),
            }
        }
        (Some(snapshot), Some(arg)) => {
            let resolved =
                match crate::cli::resolve::resolve_template(arg, &config, &registry, dirs, &cwd) {
                    Ok(value) => value,
                    Err(error) => return Err(crate::resolve_error(error)),
                };
            if !source_identity_matches(&resolved.formal_name, snapshot.source()) {
                return Err(Outcome::Error(format!(
                    "the template's source {:?} is not the snapshot's source {:?}",
                    source_of(&resolved.formal_name),
                    snapshot.source()
                )));
            }
            resolved
        }
        (None, Some(arg)) => {
            match crate::cli::resolve::resolve_template(arg, &config, &registry, dirs, &cwd) {
                Ok(value) => value,
                Err(error) => return Err(crate::resolve_error(error)),
            }
        }
        (None, None) => {
            return Err(Outcome::Error(
                "apply --baseline needs a template operand: apply TEMPLATE PATH --baseline"
                    .to_owned(),
            ));
        }
    };
    // The scripted route (`--answers`) reports a missing requirement as its
    // `requirement` error document; the other routes report it as text.
    let template = match Template::load(&resolved.folder) {
        Ok(value) => value,
        Err(error) => return Err(Outcome::Error(error.to_string())),
    };
    if let Err(error) = toha::requirement::check(&template) {
        return Err(if scripted {
            requirement_error(&error)
        } else {
            Outcome::Error(error.to_string())
        });
    }

    let (resolution, runtime_now) = match resolution(&resolved.formal_name, &template, &config) {
        Ok(value) => value,
        Err(error) => return Err(Outcome::Error(error)),
    };
    let (configured_defaults, _) = resolution.into_flat_defaults();
    let now = match &base_snapshot {
        Some(snapshot) => snapshot.generated().get().clone(),
        None => runtime_now,
    };

    // The environment decision and trust grant. An apply grants env values when
    // the template is already trusted (an approval or `--trust`). A stage
    // captures the fixed five when `--trust` is given, discovers the references
    // upfront, and refuses before any batch when one needs trust it lacks, so the
    // grant carries through every later batch and the apply.
    let (decision, trusted) = match mode {
        PrepareMode::Apply => {
            let trusted = apply_environment_grant(trust, &resolved, &template);
            (EnvironmentDecision::grant_if_needed(trusted), trusted)
        }
        PrepareMode::Stage => {
            let decision = if trust {
                EnvironmentDecision::CarryStageGrant
            } else {
                EnvironmentDecision::RequireStageGrant
            };
            (decision, trust)
        }
    };
    let context = match build_context(target, &resolved, &template, decision, interactive) {
        Ok(value) => value,
        Err(error) => return Err(Outcome::Error(error)),
    };

    let recorded = match &base_snapshot {
        Some(snapshot) => recorded_submissions(snapshot).map_err(Outcome::Error)?,
        None => Vec::new(),
    };

    Ok(Prepared {
        project,
        merge_base,
        base_snapshot,
        resolved,
        template,
        now,
        context,
        configured_defaults,
        recorded,
        trusted,
    })
}

/// Restore the pieces a staged-update resume needs from its record: reopen the
/// project, re-resolve the template and base snapshot, restore the identity-
/// bearing context (not rebuilt), and recompute the trust grant for the apply.
/// The target's cleanliness is re-checked so a merge never runs on a dirty tree.
pub(crate) fn resume_prepared(
    saved: &crate::StagedRecord,
    base: &UpdateBase,
    target: &toha::staging::CanonicalTarget,
    dirs: &Dirs,
    trust: bool,
) -> Result<(Prepared, Vec<IndexMap<Id, RawAnswer>>), Outcome> {
    let project = match Project::open(target) {
        Ok(Some(project)) => project,
        Ok(None) => {
            return Err(Outcome::Error(
                "the target is not inside a git repository; an update needs git".to_owned(),
            ));
        }
        Err(error) => return Err(Outcome::Error(error.to_string())),
    };
    match project.cleanliness() {
        Ok(Cleanliness::Clean) => {}
        Ok(Cleanliness::Dirty { .. }) => {
            return Err(Outcome::Error(
                "the target has uncommitted changes; commit or discard them before an update"
                    .to_owned(),
            ));
        }
        Err(error) => return Err(Outcome::Error(error.to_string())),
    }

    let (merge_base, base_snapshot) = match base {
        UpdateBase::From(id) => match project.find(id) {
            Ok(snapshot) => (Base::Snapshot(snapshot.clone()), Some(snapshot)),
            Err(error) => return Err(Outcome::Error(error.to_string())),
        },
        UpdateBase::Baseline => (Base::Empty, None),
    };
    if let Some(snapshot) = &base_snapshot
        && snapshot.target() != project.target()
    {
        return Err(Outcome::Error(format!(
            "the snapshot was taken for target {:?}, not {:?}",
            snapshot.target().as_str(),
            project.target().as_str()
        )));
    }

    let cwd = std::env::current_dir().map_err(|e| Outcome::Error(e.to_string()))?;
    let (config, registry) = cli_context(dirs, &cwd)?;
    let resolved = match crate::cli::resolve::resume_template(
        &saved.template,
        &saved.commit,
        saved.named,
        &config,
        &registry,
        dirs,
        &cwd,
    ) {
        Ok(value) => value,
        Err(error) => return Err(crate::resolve_error(error)),
    };
    let template = match load_template(&resolved) {
        Ok(value) => value,
        Err(error) => return Err(Outcome::Error(error)),
    };

    let (resolution, _) = match resolution(&resolved.formal_name, &template, &config) {
        Ok(value) => value,
        Err(error) => return Err(Outcome::Error(error)),
    };
    let (configured_defaults, _) = resolution.into_flat_defaults();
    let now = match saved.now.parse::<jiff::Zoned>() {
        Ok(value) => value,
        Err(error) => return Err(Outcome::Error(error.to_string())),
    };
    let context = match saved.invocation_context(target) {
        Ok(value) => value,
        Err(error) => return Err(Outcome::Error(error.to_string())),
    };
    let trusted = apply_environment_grant(trust, &resolved, &template);
    let recorded = match &base_snapshot {
        Some(snapshot) => recorded_submissions(snapshot).map_err(Outcome::Error)?,
        None => Vec::new(),
    };
    let staged = to_raw_staged(&saved.submissions).map_err(Outcome::Error)?;

    Ok((
        Prepared {
            project,
            merge_base,
            base_snapshot,
            resolved,
            template,
            now,
            context,
            configured_defaults,
            recorded,
            trusted,
        },
        staged,
    ))
}

/// A staged record's stored submissions as the interview's raw answers.
fn to_raw_staged(
    stored: &[IndexMap<String, Value>],
) -> Result<Vec<IndexMap<Id, RawAnswer>>, String> {
    stored
        .iter()
        .map(|submission| {
            submission
                .iter()
                .map(|(key, value)| {
                    Id::parse(key)
                        .map(|id| (id, RawAnswer(value.clone())))
                        .map_err(|message| format!("staged answer id {key:?}: {message}"))
                })
                .collect::<Result<IndexMap<_, _>, _>>()
        })
        .collect()
}

/// Whether an update route's merge is a dry run: the invocation's `--dry-run`
/// composes with a completed interview's own `flow: dry-run` disposition by
/// union, either suppresses the write, matching the scripted and agent-apply
/// routes (`main.rs`'s `scripted_completed` and fresh-apply resume).
pub(crate) fn effective_dry_run(dry_run: bool, completed: &toha::Completed) -> bool {
    dry_run || matches!(completed.step(), toha::Step::Plan { apply: false })
}

/// Build the snapshot inputs from a completed update interview and merge them
/// into the project, mapping the merge result to an `Outcome`.
pub(crate) fn finish_merge(
    prep: Prepared,
    target: &toha::staging::CanonicalTarget,
    completed: toha::Completed,
    submissions: Vec<IndexMap<Id, RawAnswer>>,
    dry_run: bool,
    scripted: bool,
) -> Outcome {
    // The result documents carry the invocation context; build it from `prep`
    // before the merge consumes the base.
    let saved = crate::StagedRecord::new_with_context(
        prep.context.clone(),
        prep.resolved.commit.clone(),
        prep.resolved.named,
        prep.now.to_string(),
        vec![],
    );
    let ctx = crate::context(target, &saved);
    let base_id = prep
        .base_snapshot
        .as_ref()
        .map(|snapshot| snapshot.id().to_string());

    // Record the revision actually rendered, including a newly selected content
    // revision when the caller names the current template explicitly.
    let revision = match crate::cli::resolve::snapshot_revision(
        &prep.resolved.formal_name,
        &prep.resolved.commit,
    ) {
        Ok(revision) => revision,
        Err(error) => return Outcome::Error(error.to_string()),
    };
    let generated = match &prep.base_snapshot {
        Some(snapshot) => snapshot.generated().clone(),
        None => FrozenNow::new(completed.now.clone()),
    };
    let inputs = SnapshotInputs {
        template: prep.resolved.formal_name.clone(),
        revision,
        generated,
        submissions: submissions.into_iter().map(raw_to_values).collect(),
    };
    let options = MergeOptions {
        trusted: prep.trusted,
        dry_run,
    };
    let runner: &dyn toha::hook::HookRunner = if scripted {
        &crate::ScriptedRunner
    } else {
        &ProcessRunner
    };
    match merge_apply_reported(
        &prep.project,
        prep.merge_base,
        &prep.template,
        &completed,
        inputs,
        options,
        runner,
    ) {
        Ok((merged, report)) => {
            let outcome = merged_outcome(merged, &ctx, base_id.as_deref());
            if scripted {
                outcome
            } else {
                crate::update_output::text_outcome(outcome, &report, dry_run)
            }
        }
        Err(error) => Outcome::Error(error.to_string()),
    }
}

/// Load the command context, mapping a resolve error to an `Outcome`.
fn cli_context(
    dirs: &Dirs,
    cwd: &Path,
) -> Result<(toha::config::Config, toha::registry::Registry), Outcome> {
    crate::cli::resolve::load_context(dirs, cwd).map_err(crate::resolve_error)
}

/// A formal name's source identity: the name without its `@reference`, the same
/// value a snapshot records as its `source`.
fn source_of(formal: &str) -> &str {
    formal.split_once('@').map_or(formal, |(source, _)| source)
}

/// Whether a resolved template's source identity matches the snapshot's recorded
/// source. The match is on the source identity — the formal name without its
/// `@reference` — so the same source updates across template versions while a
/// foreign source is refused. Comparing the full formal name (with its
/// reference) instead would wrongly refuse a legitimate version bump.
fn source_identity_matches(resolved_formal: &str, snapshot_source: &str) -> bool {
    source_of(resolved_formal) == snapshot_source
}

/// The base snapshot's recorded submissions, as the interview's raw answers.
fn recorded_submissions(snapshot: &Snapshot) -> Result<Vec<IndexMap<Id, RawAnswer>>, String> {
    snapshot
        .submissions()
        .iter()
        .map(|submission| {
            submission
                .iter()
                .map(|(key, value)| {
                    Id::parse(key)
                        .map(|id| (id, RawAnswer(value.clone())))
                        .map_err(|message| format!("recorded answer id {key:?}: {message}"))
                })
                .collect::<Result<IndexMap<_, _>, _>>()
        })
        .collect()
}

/// One replayed submission as the id→value map a snapshot records.
fn raw_to_values(submission: IndexMap<Id, RawAnswer>) -> IndexMap<Id, Value> {
    submission
        .into_iter()
        .map(|(id, raw)| (id, raw.0))
        .collect()
}

/// Map a merge result to the caller's result document. An update reports the
/// canonical `applied`/`planned`/`already-current` document with its `merge`
/// member (the changed paths and any conflicts) and, when it saved one, a
/// `snapshot` member.
fn merged_outcome(merged: Merged, ctx: &Context, base_id: Option<&str>) -> Outcome {
    match merged {
        Merged::AlreadyCurrent => {
            let mut document = toha::protocol::shell("already-current", ctx);
            if let Some(id) = base_id {
                document["snapshot"] = json!({ "id": id });
            }
            Outcome::Document(document, 0)
        }
        // An untrusted update previews the plan and writes nothing, like a dry run.
        Merged::NeedsTrust => {
            let mut document = toha::protocol::shell("planned", ctx);
            document["files"] = json!([]);
            document["messages"] = json!([]);
            document["hooks"] = json!([]);
            document["trusted"] = json!(false);
            document["merge"] = json!({ "changes": [], "conflicted": [] });
            Outcome::Document(document, 0)
        }
        Merged::Planned { changes } => {
            let mut document = toha::protocol::shell("planned", ctx);
            document["files"] = json!([]);
            document["messages"] = json!([]);
            document["hooks"] = json!([]);
            document["trusted"] = json!(true);
            document["merge"] = merge_member(&changes, &[]);
            Outcome::Document(document, 0)
        }
        Merged::Written {
            snapshot,
            changes,
            conflicted,
        } => {
            let mut document = toha::protocol::shell("applied", ctx);
            document["files"] = json!([]);
            document["messages"] = json!([]);
            document["hooks"] = json!([]);
            document["snapshot"] = json!({ "id": snapshot.to_string() });
            document["merge"] = merge_member(&changes, &conflicted);
            Outcome::Document(document, 0)
        }
    }
}

/// The `merge` member: the changed paths with their actions, and the conflicted
/// paths the operator must resolve.
fn merge_member(changes: &[Change], conflicted: &[RepoPath]) -> Value {
    json!({
        "changes": changes.iter().map(change_json).collect::<Vec<_>>(),
        "conflicted": conflicted.iter().map(|path| path.to_string()).collect::<Vec<_>>(),
    })
}

/// One merge change as `{ path, action, conflict? }`.
fn change_json(change: &Change) -> Value {
    let (action, conflict) = match change.action {
        Action::Added => ("added", None),
        Action::Updated => ("updated", None),
        Action::Merged => ("merged", None),
        Action::Deleted => ("deleted", None),
        Action::NotPreviewed => ("not-previewed", None),
        Action::Conflicted(kind) => ("conflicted", Some(conflict_name(kind))),
    };
    let mut object = json!({ "path": change.path.to_string(), "action": action });
    if let Some(conflict) = conflict {
        object["conflict"] = json!(conflict);
    }
    object
}

/// The stable name of a conflict kind.
fn conflict_name(kind: ConflictKind) -> &'static str {
    match kind {
        ConflictKind::Content => "content",
        ConflictKind::AddAdd => "add-add",
        ConflictKind::ModifyDelete => "modify-delete",
        ConflictKind::FileDirectory => "file-directory",
        ConflictKind::Binary => "binary",
        ConflictKind::Driver => "driver",
    }
}

#[cfg(test)]
mod tests {
    use super::{source_identity_matches, source_of};

    #[test]
    fn source_identity_matches_on_source_across_versions_and_refuses_a_foreign_source() {
        // Behavior 17 (source side), at the identity boundary: the match is on the
        // source identity, so the SAME source at a DIFFERENT version is accepted —
        // comparing the full formal name (with its reference) would wrongly refuse
        // this legitimate version bump. Generic versioned names, no hosted infra.
        assert!(
            source_identity_matches("forge:catalog/receipt@v2", "forge:catalog/receipt"),
            "a new version of the same source is accepted"
        );
        assert!(
            source_identity_matches("forge:catalog/receipt@a1b2c3d", "forge:catalog/receipt"),
            "a commit-pinned reference of the same source is accepted"
        );
        // A bare (unversioned) name of the same source still matches.
        assert!(source_identity_matches(
            "forge:catalog/receipt",
            "forge:catalog/receipt"
        ));
        // A foreign source is refused even at a plausible version.
        assert!(
            !source_identity_matches("forge:catalog/invoice@v2", "forge:catalog/receipt"),
            "a different source is refused"
        );
        assert_eq!(
            source_of("forge:catalog/receipt@v2"),
            "forge:catalog/receipt"
        );
    }
}