toha 0.4.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
// ---
// relationships:
//   implements: architecture
// ---
use crate::context::{
    EnvironmentAdmissionError, InvocationContext, InvocationContextWire, RenderOrigin,
};
use crate::interview::{ApplicationSeed, Resolution};
use crate::{AnswerError, Interview, RawAnswer, RawAnswers, Seed, Template};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::{
    fs,
    io::Write,
    path::{Component, Path, PathBuf},
    sync::atomic::{AtomicU64, Ordering},
};

static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StagedRecord {
    target: PathBuf,
    pub template: String,
    pub commit: String,
    #[serde(default)]
    pub named: bool,
    pub now: String,
    pub submissions: Vec<IndexMap<String, Value>>,
    /// Original update inputs, including values awaiting correction. Accepted batches
    /// consume these values during replay; they are not accepted submissions.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub(crate) update_overrides: IndexMap<String, Value>,
    /// The serialized application selected for this update, or the baseline
    /// marker. Resume checks that the selected application still matches.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base: Option<String>,
    /// Whether the staged update re-asks every recorded answer.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub reanswer: bool,
    #[serde(default, skip_serializing_if = "crate::parts::Selection::is_default")]
    pub part_selection: crate::parts::Selection,
    /// The seed target selected by `--like`. `seed_entry` copies its application
    /// so later changes to the live record do not change staged defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed_entry: Option<Value>,
    /// The versioned invocation context. A record written by [`StagedRecord::new`]
    /// carries the legacy projection; [`StagedRecord::new_with_context`] carries
    /// the current context. A pre-context record on disk has no field and
    /// deserializes as legacy.
    #[serde(default, skip_serializing_if = "InvocationContextWire::is_legacy")]
    context: InvocationContextWire,
}

#[derive(Debug, thiserror::Error)]
pub enum StagingError {
    #[error("{0}")]
    Io(#[from] std::io::Error),
    #[error("{0}")]
    Json(#[from] serde_json::Error),
    #[error("{0}")]
    Replay(String),
    /// A stage need was analyzed but stage trust was not granted. The stage
    /// adapter maps only this admission fault; it carries the authored location
    /// and no captured value.
    #[error("environment access at {reference} requires stage trust")]
    EnvironmentTrustRequired { reference: RenderOrigin },
    /// Any other environment-admission fault, retaining its typed source.
    #[error("{source}")]
    EnvironmentAdmission {
        #[source]
        source: EnvironmentAdmissionError,
    },
}

/// Maps an environment-admission fault to the stage command's typed error. Only
/// a trust refusal becomes [`StagingError::EnvironmentTrustRequired`]; every
/// other fault keeps its typed source under [`StagingError::EnvironmentAdmission`].
pub fn stage_admission_error(error: EnvironmentAdmissionError) -> StagingError {
    match error {
        EnvironmentAdmissionError::TrustRequired { reference } => {
            StagingError::EnvironmentTrustRequired { reference }
        }
    }
}

/// A target identity produced only by [`canonical_target`].
///
/// Raw paths cannot enter identity-sensitive consumers:
///
/// ```compile_fail
/// use std::path::PathBuf;
/// use toha::staging::{StagedRecord, Store};
/// let raw = PathBuf::from("output");
/// let store: Store = unimplemented!();
/// let record: StagedRecord = unimplemented!();
/// store.save(&raw, &record);
/// ```
///
/// The abort action's removal key is a `CanonicalTarget`, never a raw path:
///
/// ```compile_fail
/// use std::path::PathBuf;
/// use toha::staging::Store;
/// let raw = PathBuf::from("output");
/// let store: Store = unimplemented!();
/// store.remove(&raw);
/// ```
///
/// ```compile_fail
/// use std::path::PathBuf;
/// use toha::staging::StagedRecord;
/// let raw = PathBuf::from("output");
/// StagedRecord::new(
///     &raw,
///     "sample".into(),
///     String::new(),
///     false,
///     "2026-01-02T03:04:05+00:00[UTC]".into(),
///     vec![],
/// );
/// ```
///
/// ```compile_fail
/// use std::path::PathBuf;
/// use toha::staging::StagedRecord;
/// let raw = PathBuf::from("output");
/// let _ = StagedRecord {
///     target: raw,
///     template: "sample".into(),
///     commit: String::new(),
///     named: false,
///     now: "2026-01-02T03:04:05+00:00[UTC]".into(),
///     submissions: vec![],
/// };
/// ```
///
/// ```compile_fail
/// use std::path::PathBuf;
/// use toha::{Completed, Plan, Template};
/// let raw = PathBuf::from("output");
/// let template: Template = unimplemented!();
/// let completed: Completed = unimplemented!();
/// Plan::build(&template, &completed, &raw);
/// ```
///
/// ```compile_fail
/// use std::path::PathBuf;
/// use toha::protocol::Context;
/// use toha::staging::StagedRecord;
/// let raw = PathBuf::from("output");
/// let record: StagedRecord = unimplemented!();
/// Context::new(&raw, &record);
/// ```
///
/// ```compile_fail
/// use std::path::PathBuf;
/// use toha::{ApplyOptions, Plan};
/// use toha::hook::RecordingRunner;
/// let raw = PathBuf::from("output");
/// let plan: Plan = unimplemented!();
/// plan.apply(&raw, ApplyOptions::default(), &RecordingRunner::default());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CanonicalTarget(PathBuf);

impl CanonicalTarget {
    pub fn as_path(&self) -> &Path {
        &self.0
    }
}

impl std::fmt::Display for CanonicalTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.display().fmt(f)
    }
}

pub fn canonical_target(path: &Path) -> Result<CanonicalTarget, StagingError> {
    let absolute = if path.is_absolute() {
        path.to_owned()
    } else {
        std::env::current_dir()?.join(path)
    };
    let mut normalized = PathBuf::new();
    for component in absolute.components() {
        match component {
            Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
                normalized.push(component)
            }
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
        }
    }
    let mut ancestor = normalized.as_path();
    while !ancestor.exists() {
        ancestor = ancestor
            .parent()
            .ok_or_else(|| StagingError::Replay("target has no existing ancestor".into()))?;
    }
    let suffix = normalized
        .strip_prefix(ancestor)
        .expect("ancestor is a prefix");
    let mut canonical = ancestor.canonicalize()?;
    if !suffix.as_os_str().is_empty() {
        canonical.push(suffix);
    }
    Ok(CanonicalTarget(canonical))
}

pub struct Store {
    dir: PathBuf,
}
impl Store {
    pub fn new(dir: PathBuf) -> Self {
        Self { dir }
    }
    pub fn path_for(&self, target: &CanonicalTarget) -> PathBuf {
        let digest = Sha256::digest(target.as_path().to_string_lossy().as_bytes());
        self.dir.join(format!("{digest:x}.json"))
    }
    fn legacy_path_for(&self, target: &CanonicalTarget) -> Option<PathBuf> {
        let path = target.as_path();
        path.parent()?;
        let mut legacy = path.as_os_str().to_os_string();
        legacy.push(std::path::MAIN_SEPARATOR_STR);
        let digest = Sha256::digest(Path::new(&legacy).to_string_lossy().as_bytes());
        Some(self.dir.join(format!("{digest:x}.json")))
    }
    pub fn load(&self, target: &CanonicalTarget) -> Result<Option<StagedRecord>, StagingError> {
        let read = |path: PathBuf| -> Result<Option<StagedRecord>, StagingError> {
            match fs::read(path) {
                Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
                Err(e) => Err(e.into()),
            }
        };
        if let Some(record) = read(self.path_for(target))? {
            if canonical_target(&record.target)? != *target {
                return Err(StagingError::Replay(
                    "staged record target does not match its storage key".into(),
                ));
            }
            return Ok(Some(record));
        }
        let Some(path) = self.legacy_path_for(target) else {
            return Ok(None);
        };
        let Some(record) = read(path)? else {
            return Ok(None);
        };
        if canonical_target(&record.target)? != *target {
            return Err(StagingError::Replay(
                "staged record target does not match its storage key".into(),
            ));
        }
        Ok(Some(record))
    }
    pub fn save(
        &self,
        target: &CanonicalTarget,
        record: &StagedRecord,
    ) -> Result<(), StagingError> {
        if canonical_target(&record.target)? != *target {
            return Err(StagingError::Replay(
                "staged record target does not match the active target".into(),
            ));
        }
        fs::create_dir_all(&self.dir)?;
        let canonical_path = self.path_for(target);
        let mut stored = record.clone();
        stored.target = target.as_path().to_owned();
        let bytes = serde_json::to_vec_pretty(&stored)?;
        let (temp, mut file) = loop {
            let n = NEXT_TEMP.fetch_add(1, Ordering::Relaxed);
            let temp = self
                .dir
                .join(format!(".toha-{}-{n}.tmp", std::process::id()));
            match fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&temp)
            {
                Ok(file) => break (temp, file),
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
                Err(e) => return Err(e.into()),
            }
        };
        let result = (|| {
            file.write_all(&bytes)?;
            file.sync_all()?;
            fs::rename(&temp, &canonical_path)
        })();
        if result.is_err() {
            let _ = fs::remove_file(&temp);
        }
        result.map_err(StagingError::Io)?;
        if let Some(legacy) = self
            .legacy_path_for(target)
            .filter(|p| p != &canonical_path)
        {
            match fs::remove_file(legacy) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => return Err(e.into()),
            }
        }
        Ok(())
    }
    pub fn remove(&self, target: &CanonicalTarget) -> Result<bool, StagingError> {
        let canonical = self.path_for(target);
        let legacy = self
            .legacy_path_for(target)
            .filter(|path| path != &canonical);
        let remove = |path: PathBuf| -> Result<bool, StagingError> {
            match fs::remove_file(path) {
                Ok(()) => Ok(true),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
                Err(e) => Err(e.into()),
            }
        };
        let canonical_removed = remove(canonical)?;
        let legacy_removed = match legacy {
            Some(path) => remove(path)?,
            None => false,
        };
        Ok(canonical_removed || legacy_removed)
    }
}

impl StagedRecord {
    /// Creates a legacy-projection record. Retained for existing crate callers;
    /// current invocations use [`Self::new_with_context`].
    pub fn new(
        target: &CanonicalTarget,
        template: String,
        commit: String,
        named: bool,
        now: String,
        submissions: Vec<IndexMap<String, Value>>,
    ) -> Self {
        Self {
            target: target.as_path().to_owned(),
            template,
            commit,
            named,
            now,
            submissions,
            update_overrides: IndexMap::new(),
            base: None,
            reanswer: false,
            part_selection: Default::default(),
            seed: None,
            seed_entry: None,
            context: InvocationContextWire::Legacy,
        }
    }

    /// Creates a current record from a completed invocation context. The stored
    /// target and formal name are derived from the context; the versioned wire
    /// carries identity, host, execution, and the environment snapshot.
    pub fn new_with_context(
        context: InvocationContext,
        commit: String,
        named: bool,
        now: String,
        submissions: Vec<IndexMap<String, Value>>,
    ) -> Self {
        let (target, formal_name, wire) = context.staged_parts();
        Self {
            target: target.as_path().to_owned(),
            template: formal_name.unwrap_or_default(),
            commit,
            named,
            now,
            submissions,
            update_overrides: IndexMap::new(),
            base: None,
            reanswer: false,
            part_selection: Default::default(),
            seed: None,
            seed_entry: None,
            context: wire,
        }
    }

    /// Restores the invocation context from the versioned wire, validating the
    /// persisted target text against the producer-created carrier. A pre-context
    /// record restores a legacy context.
    pub fn invocation_context(
        &self,
        target: &CanonicalTarget,
    ) -> Result<InvocationContext, StagingError> {
        if canonical_target(&self.target)? != *target {
            return Err(StagingError::Replay(
                "staged record target does not match its storage key".into(),
            ));
        }
        Ok(InvocationContext::from_wire(
            target.clone(),
            &self.template,
            self.context.clone(),
        ))
    }

    pub fn replay<'a>(
        &self,
        template: &'a Template,
        target: &CanonicalTarget,
    ) -> Result<Interview<'a>, StagingError> {
        self.replay_with_defaults(template, IndexMap::new(), target)
    }
    pub fn replay_with_defaults<'a>(
        &self,
        template: &'a Template,
        defaults: IndexMap<crate::Id, RawAnswer>,
        target: &CanonicalTarget,
    ) -> Result<Interview<'a>, StagingError> {
        let now = self
            .now
            .parse()
            .map_err(|e: jiff::Error| StagingError::Replay(e.to_string()))?;
        let context = self.invocation_context(target)?;
        let interview = Interview::start_with_selection(
            template,
            Seed {
                now,
                defaults,
                context,
            },
            self.part_selection.clone(),
        )
        .map_err(|e| StagingError::Replay(e.to_string()))?;
        self.replay_from(interview, template)
    }

    pub fn replay_with_resolution<'a>(
        &self,
        template: &'a Template,
        resolution: Resolution,
        target: &CanonicalTarget,
    ) -> Result<Interview<'a>, StagingError> {
        let now = self
            .now
            .parse()
            .map_err(|e: jiff::Error| StagingError::Replay(e.to_string()))?;
        let context = self.invocation_context(target)?;
        let interview = resolution
            .start_with_selection(template, now, context, None, self.part_selection.clone())
            .map(|(interview, _)| interview)
            .map_err(|e| StagingError::Replay(e.to_string()))?;
        self.replay_from(interview, template)
    }

    /// Replay a staged interview with the copied application seed layered over
    /// configured resolution through [`Resolution::start_with_seed`]. The caller
    /// folds `seed_entry` so resumed defaults match the staged run. With no seed
    /// this is byte-for-byte [`Self::replay_with_resolution`]. Any wrong-kind
    /// warning was already reported at stage time; resume discards it.
    pub fn replay_with_seed<'a>(
        &self,
        template: &'a Template,
        resolution: Resolution,
        seed: Option<ApplicationSeed>,
        target: &CanonicalTarget,
    ) -> Result<Interview<'a>, StagingError> {
        self.replay_with_seed_reporting(template, resolution, seed, target)
            .map(|(interview, _)| interview)
    }

    pub(crate) fn replay_with_seed_reporting<'a>(
        &self,
        template: &'a Template,
        resolution: Resolution,
        seed: Option<ApplicationSeed>,
        target: &CanonicalTarget,
    ) -> Result<(Interview<'a>, Vec<String>), StagingError> {
        let now = self
            .now
            .parse()
            .map_err(|e: jiff::Error| StagingError::Replay(e.to_string()))?;
        let context = self.invocation_context(target)?;
        let (interview, warnings) = resolution
            .start_with_selection(template, now, context, seed, self.part_selection.clone())
            .map_err(|e| StagingError::Replay(e.to_string()))?;
        self.replay_from(interview, template)
            .map(|interview| (interview, warnings))
    }

    fn replay_from<'a>(
        &self,
        mut interview: Interview<'a>,
        template: &Template,
    ) -> Result<Interview<'a>, StagingError> {
        for submission in &self.submissions {
            // Documents admitted for this run have already entered the engine.
            // Replay the other answers without submitting those documents twice.
            let filtered: IndexMap<_, _> = submission.iter().filter(|(id, _)| {
                let Ok(id) = crate::Id::parse(id) else { return true; };
                !matches!(template.question(&id).map(|q| &q.kind), Some(crate::QuestionKind::Document { contract }) if contract.admitted().is_some())
            }).map(|(id, value)| (id.clone(), value.clone())).collect();
            if !submission.is_empty() && filtered.is_empty() {
                continue;
            }
            let submission = &filtered;
            let Interview::Asking(pending) = interview else {
                return Err(StagingError::Replay(
                    "submission after completed interview".into(),
                ));
            };
            let raw: RawAnswers = submission
                .iter()
                .map(|(key, value)| crate::Id::parse(key).map(|id| (id, RawAnswer(value.clone()))))
                .collect::<Result<_, _>>()
                .map_err(StagingError::Replay)?;
            interview = pending.answer(raw).map_err(|e| match e {
                AnswerError::Rejected { rejections, .. } => StagingError::Replay(
                    rejections
                        .iter()
                        .map(ToString::to_string)
                        .collect::<Vec<_>>()
                        .join("\n"),
                ),
                AnswerError::Eval(e) => StagingError::Replay(e.to_string()),
            })?;
        }
        Ok(interview)
    }
}