Skip to main content

dort_core/tools/
declaration.rs

1//! Manifest tool declarations.
2use crate::{
3    Error, Manifest, Result,
4    adoption::{self, Boundary, Event, anchors, checked_bytes, parent_identity, same},
5    context::HostContext,
6    error::io_error,
7    journal::{self, Phase, Progress},
8    local::LocalConfig,
9    model::Tool,
10    observation::{self, Entry, Kind},
11    state::WriterLock,
12    tool_journal::{Header, Journal, Operation},
13};
14use rustix::fs::{self, Mode, OFlags, RenameFlags};
15use serde::{Deserialize, Serialize};
16use std::{
17    fs::File,
18    path::{Path, PathBuf},
19};
20const MAX_TOOLS: usize = 4096;
21/// Schema-6 manifest operations. Absence retains schema-5 add-only semantics.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum Change {
25    Edit,
26    Remove,
27}
28/// Reports contain typed declarations and identities only, never raw manifest bytes.
29#[derive(Serialize)]
30pub struct Preview {
31    pub schema: u32,
32    pub preview_only: bool,
33    pub repository: PathBuf,
34    pub repository_id: String,
35    pub tool: Tool,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub change: Option<Change>,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub before: Option<Tool>,
40    pub profiles: Vec<String>,
41    #[serde(skip)]
42    active: std::collections::BTreeSet<String>,
43    pub no_op: bool,
44    pub effects: Vec<PathBuf>,
45    #[serde(skip)]
46    host: HostContext,
47    #[serde(skip)]
48    manifest: Entry,
49    #[serde(skip)]
50    local_config: Entry,
51    #[serde(skip)]
52    binding: String,
53}
54pub struct Approval(Preview);
55impl Approval {
56    pub fn from_preview(preview: Preview) -> Result<Self> {
57        if bind(&preview)? != preview.binding {
58            return Err(Error::Invalid(
59                "tool declaration preview was modified".into(),
60            ));
61        }
62        Ok(Self(preview))
63    }
64}
65fn bind(p: &Preview) -> Result<String> {
66    Ok(journal::digest(
67        adoption::canonical(&(p, &p.host, &p.manifest, &p.local_config, &p.active))?.as_bytes(),
68    ))
69}
70fn parse(bytes: &[u8]) -> Result<Manifest> {
71    let text =
72        std::str::from_utf8(bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?;
73    Manifest::parse(text).map_err(|_| Error::Invalid("invalid manifest (content withheld)".into()))
74}
75fn entry(path: &Path) -> Result<Entry> {
76    let mut e = observation::inspect(path, false)?;
77    let fp = e.fingerprint.as_ref().filter(|f| e.kind == Kind::Regular && f.links == 1 && f.uid == rustix::process::geteuid().as_raw() && f.mode & 0o7000 == 0).ok_or_else(|| Error::Invalid("manifest must be an owned single-link regular file without special permission bits".into()))?;
78    let handle = observation::parent_handle(path)?;
79    let bytes = observation::read_checked(&handle, path, fp)?;
80    e.sha256 = Some(journal::digest(&bytes));
81    Ok(e)
82}
83fn clear_positions(table: &mut toml_edit::Table) {
84    table.set_position(None);
85    for (_, item) in table.iter_mut() {
86        match item {
87            toml_edit::Item::Table(t) => clear_positions(t),
88            toml_edit::Item::ArrayOfTables(a) => {
89                for t in a.iter_mut() {
90                    clear_positions(t);
91                }
92            }
93            _ => (),
94        }
95    }
96}
97/// Pure focused edit. Semantic equality includes every unrelated declaration;
98/// unrelated comments/formatting stay in the original document. Identical edits are no-op.
99fn edit(
100    bytes: &[u8],
101    tool: &Tool,
102    host: &HostContext,
103    active: &std::collections::BTreeSet<String>,
104    repository: &Path,
105    change: Option<Change>,
106) -> Result<Option<Vec<u8>>> {
107    if journal::encode(tool)?.len() > 32 * 1024 {
108        return Err(Error::Invalid("tool declaration exceeds 32 KiB".into()));
109    }
110    let mut expected = parse(bytes)?;
111    let index = expected.tools.iter().position(|t| t.id == tool.id);
112    match (change, index) {
113        (Some(Change::Remove), Some(i)) => {
114            expected.tools.remove(i);
115        }
116        (Some(Change::Edit), Some(i)) => {
117            if journal::encode(&expected.tools[i])? == journal::encode(tool)? {
118                return Ok(None);
119            }
120            expected.tools[i] = tool.clone();
121        }
122        (Some(_), None) => return Err(Error::Invalid("tool declaration not found".into())),
123        (None, Some(i)) => {
124            if journal::encode(&expected.tools[i])? == journal::encode(tool)? {
125                return Ok(None);
126            }
127            return Err(Error::Invalid(
128                "tool ID already has a different declaration; use edit".into(),
129            ));
130        }
131        (None, None) => {
132            if expected.tools.len() >= MAX_TOOLS {
133                return Err(Error::Invalid("tool declaration limit".into()));
134            }
135            expected.tools.push(tool.clone());
136        }
137    }
138    // The original manifest has already passed structural parsing. These are
139    // typed declaration diagnostics, never TOML parser excerpts or file bodies.
140    expected.validate_selection(host, active, Some(repository))?;
141    #[derive(Serialize)]
142    struct Addition<'a> {
143        tools: [&'a Tool; 1],
144    }
145    let addition = toml::to_string(&Addition { tools: [tool] })
146        .map_err(|_| Error::Invalid("cannot encode tool declaration".into()))?;
147    let added = addition
148        .parse::<toml_edit::DocumentMut>()
149        .map_err(|_| Error::Invalid("cannot encode tool tables".into()))?;
150    let mut tables = added["tools"]
151        .as_array_of_tables()
152        .ok_or_else(|| Error::Invalid("missing tool table".into()))?
153        .clone();
154    for t in tables.iter_mut() {
155        clear_positions(t);
156    }
157    let text =
158        std::str::from_utf8(bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?;
159    let mut doc = text
160        .parse::<toml_edit::DocumentMut>()
161        .map_err(|_| Error::Invalid("cannot edit manifest (content withheld)".into()))?;
162    if let Some(i) = index.filter(|_| change.is_some()) {
163        if let Some(a) = doc["tools"].as_array_of_tables_mut() {
164            if change == Some(Change::Remove) {
165                a.remove(i);
166            } else {
167                let mut replacement = tables
168                    .get(0)
169                    .ok_or_else(|| Error::Invalid("missing tool declaration table".into()))?
170                    .clone();
171                replacement.set_position(
172                    a.get(i)
173                        .ok_or_else(|| Error::Invalid("missing tool table at index".into()))?
174                        .position(),
175                );
176                let slot = a
177                    .get_mut(i)
178                    .ok_or_else(|| Error::Invalid("missing tool table at index".into()))?;
179                *slot = replacement;
180            }
181        } else if let Some(a) = doc["tools"].as_array_mut() {
182            if change == Some(Change::Remove) {
183                a.remove(i);
184            } else {
185                a.replace(
186                    i,
187                    tables
188                        .get(0)
189                        .ok_or_else(|| Error::Invalid("missing tool declaration table".into()))?
190                        .clone()
191                        .into_inline_table(),
192                );
193            }
194        } else {
195            return Err(Error::Invalid(
196                "unsupported manifest tools representation".into(),
197            ));
198        }
199    } else if doc.get("tools").is_none() {
200        doc["tools"] = toml_edit::Item::ArrayOfTables(tables);
201    } else if let Some(a) = doc["tools"].as_array_of_tables_mut() {
202        for t in &tables {
203            a.push(t.clone());
204        }
205    } else if let Some(a) = doc["tools"].as_array_mut() {
206        for t in &tables {
207            a.push(t.clone().into_inline_table());
208        }
209    } else {
210        return Err(Error::Invalid(
211            "unsupported manifest tools representation".into(),
212        ));
213    }
214    let result = doc.to_string().into_bytes();
215    if result.len() as u64 > journal::LIMIT
216        || journal::encode(&parse(&result)?)? != journal::encode(&expected)?
217    {
218        return Err(Error::Invalid(
219            "tool edit changed unrelated declarations or exceeded manifest limit".into(),
220        ));
221    }
222    Ok(Some(result))
223}
224/// Read-only, requires existing registration. Does not create state or lock files.
225pub fn preview(
226    host: &HostContext,
227    repository: &Path,
228    profiles: &[String],
229    tool: Tool,
230) -> Result<Preview> {
231    prepare(host, repository, profiles, tool, None)
232}
233/// Edit an existing declaration without changing its ID.
234pub fn preview_edit(
235    host: &HostContext,
236    repository: &Path,
237    profiles: &[String],
238    tool: Tool,
239) -> Result<Preview> {
240    prepare(host, repository, profiles, tool, Some(Change::Edit))
241}
242/// Remove desired metadata only. References must remain valid.
243pub fn preview_remove(
244    host: &HostContext,
245    repository: &Path,
246    profiles: &[String],
247    id: &str,
248) -> Result<Preview> {
249    crate::context::validate_absolute(repository)?;
250    observation::validate_output_path(repository)?;
251    if !LocalConfig::load(host)?
252        .repositories
253        .values()
254        .any(|r| r.root == repository)
255    {
256        return Err(Error::Invalid(
257            "tool declarations require an already registered repository".into(),
258        ));
259    }
260    let manifest = entry(&repository.join("dort.toml"))?;
261    let tool = parse(&checked_bytes(&manifest)?)?
262        .tools
263        .into_iter()
264        .find(|t| t.id == id)
265        .ok_or_else(|| Error::Invalid("tool declaration not found".into()))?;
266    prepare(host, repository, profiles, tool, Some(Change::Remove))
267}
268fn prepare(
269    host: &HostContext,
270    repository: &Path,
271    profiles: &[String],
272    tool: Tool,
273    change: Option<Change>,
274) -> Result<Preview> {
275    crate::context::validate_absolute(repository)?;
276    observation::validate_output_path(repository)?;
277    let (local, local_config) = LocalConfig::load_bound(host)?;
278    let repository_id = local
279        .repositories
280        .iter()
281        .find(|(_, r)| r.root == repository)
282        .map(|(id, _)| id.clone())
283        .ok_or_else(|| {
284            Error::Invalid("tool declarations require an already registered repository".into())
285        })?;
286    let manifest = entry(&repository.join("dort.toml"))?;
287    let bytes = checked_bytes(&manifest)?;
288    let before = change.and_then(|_| {
289        parse(&bytes)
290            .ok()?
291            .tools
292            .into_iter()
293            .find(|t| t.id == tool.id)
294    });
295    if change == Some(Change::Remove)
296        && before.as_ref().map(journal::encode).transpose()? != Some(journal::encode(&tool)?)
297    {
298        return Err(Error::Invalid(
299            "declaration changed during preparation; review again".into(),
300        ));
301    }
302    let active = crate::profiles::active(&local.profile_rows(
303        &parse(&bytes)?.profiles,
304        host.platform,
305        Some(repository),
306        profiles,
307    )?);
308    let no_op = edit(&bytes, &tool, host, &active, repository, change)?.is_none();
309    let mut p = Preview {
310        schema: if change.is_some() { 2 } else { 1 },
311        preview_only: true,
312        repository: repository.to_owned(),
313        repository_id,
314        tool,
315        change,
316        before,
317        profiles: profiles.to_vec(),
318        active,
319        no_op,
320        effects: if no_op {
321            vec![]
322        } else {
323            vec![manifest.path.clone()]
324        },
325        host: host.clone(),
326        manifest,
327        local_config,
328        binding: String::new(),
329    };
330    p.binding = bind(&p)?;
331    Ok(p)
332}
333fn notify(
334    j: &Journal,
335    boundary: Boundary,
336    observer: &mut impl FnMut(&Event) -> Result<()>,
337) -> Result<()> {
338    observer(&Event {
339        transaction_id: j.record.header.transaction_id.clone(),
340        boundary,
341        sequence: j.record.sequence,
342    })
343}
344fn checkpoint(j: &mut Journal, observer: &mut impl FnMut(&Event) -> Result<()>) -> Result<()> {
345    j.save()?;
346    notify(j, Boundary::Checkpoint, observer)
347}
348fn stage_path(j: &Journal) -> PathBuf {
349    j.directory.path.join("op-0000")
350}
351fn check_parents(j: &Journal, e: &Entry) -> Result<()> {
352    if e.parents.iter().any(|p| {
353        j.record
354            .header
355            .anchors
356            .iter()
357            .find(|a| a.path == p.path)
358            .is_none_or(|a| !parent_identity(&a.fingerprint, &p.fingerprint))
359    }) {
360        return Err(Error::Invalid(
361            "declaration parent identity/permissions changed".into(),
362        ));
363    }
364    Ok(())
365}
366fn applied(j: &Journal) -> Result<bool> {
367    let h = &j.record.header;
368    let op = j
369        .record
370        .operation
371        .as_ref()
372        .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?;
373    let live = entry(&h.manifest.path)?;
374    check_parents(j, &live)?;
375    let stage = entry(&stage_path(j))?;
376    let strict = op.progress == Progress::Pending;
377    let before = same(&h.manifest, &live, strict) && same(&op.staged, &stage, strict);
378    let after = same(&op.staged, &live, false) && same(&h.manifest, &stage, false);
379    match op.progress {
380        Progress::Pending if before => Ok(false),
381        Progress::Intent | Progress::UndoIntent if before => Ok(false),
382        Progress::Intent | Progress::UndoIntent if after => Ok(true),
383        Progress::Done if after && op.after.as_ref().is_some_and(|e| same(e, &live, true)) => {
384            Ok(true)
385        }
386        Progress::Undone if before => Ok(false),
387        _ => Err(Error::Invalid(
388            "manifest/stage changed; declaration recovery refused".into(),
389        )),
390    }
391}
392fn validate_scope(host: &HostContext, j: &Journal) -> Result<()> {
393    let h = &j.record.header;
394    journal::registered_root(host, &h.repository_id, &h.repository)?;
395    if h.local_config.path != host.local_config_path()
396        || h.manifest.path != h.repository.join("dort.toml")
397    {
398        return Err(Error::Invalid("declaration scope mismatch".into()));
399    }
400    if j.record.operation.is_none() {
401        return Ok(());
402    }
403    j.verify_backup()?;
404    let bytes = journal::read_bytes(&j.directory, "manifest.backup")?;
405    let active = match &h.active {
406        Some(active) => active.clone(),
407        None => parse(&bytes)?.active_profiles(host, &h.profiles)?,
408    };
409    if edit(&bytes, &h.tool, host, &active, &h.repository, h.change)?
410        .as_ref()
411        .map(|b| journal::digest(b))
412        .as_ref()
413        != Some(&h.new_manifest_sha256)
414    {
415        return Err(Error::Invalid("declaration edit binding mismatch".into()));
416    }
417    Ok(())
418}
419fn validate_layout(host: &HostContext, j: &Journal) -> Result<()> {
420    journal::registered_root(
421        host,
422        &j.record.header.repository_id,
423        &j.record.header.repository,
424    )?;
425    j.verify_backup()?;
426    let mut config = observation::inspect(&host.local_config_path(), false)?;
427    if j.record.header.local_config.sha256.is_some() {
428        config = LocalConfig::load_bound(host)?.1;
429    }
430    if !same(&j.record.header.local_config, &config, true) {
431        return Err(Error::Invalid(
432            "local configuration changed since declaration approval".into(),
433        ));
434    }
435    check_parents(j, &config)?;
436    applied(j)?;
437    Ok(())
438}
439fn mutate(j: &Journal, undo: bool) -> Result<()> {
440    let path = &j.record.header.manifest.path;
441    let handle = observation::parent_handle(path)?;
442    let current = entry(path)?;
443    check_parents(j, &current)?;
444    if handle.missing
445        || handle.parents.len() != current.parents.len()
446        || handle
447            .parents
448            .iter()
449            .zip(&current.parents)
450            .any(|(a, b)| a.path != b.path || !parent_identity(&a.fingerprint, &b.fingerprint))
451        || applied(j)? != undo
452    {
453        return Err(Error::Invalid(
454            "declaration mutation precondition changed".into(),
455        ));
456    }
457    fs::renameat_with(
458        &j.directory.file,
459        "op-0000",
460        &handle.directory,
461        &handle.name,
462        RenameFlags::EXCHANGE,
463    )
464    .map_err(|e| {
465        io_error(
466            "exchange declaration manifest (no unsafe fallback)",
467            path,
468            e,
469        )
470    })?;
471    handle
472        .directory
473        .sync_all()
474        .map_err(|e| io_error("sync declaration parent", path, e))?;
475    j.directory.sync()
476}
477pub fn execute(
478    host: &HostContext,
479    lock: &WriterLock,
480    approval: Approval,
481    mut observer: impl FnMut(&Event) -> Result<()>,
482) -> Result<Option<String>> {
483    lock.check_context(host)?;
484    journal::ensure_writable(host)?;
485    let old = approval.0;
486    if journal::encode(host)? != journal::encode(&old.host)? {
487        return Err(Error::Invalid(
488            "declaration approval belongs to another host".into(),
489        ));
490    }
491    let fresh = prepare(
492        host,
493        &old.repository,
494        &old.profiles,
495        old.tool.clone(),
496        old.change,
497    )?;
498    if old.binding != fresh.binding {
499        return Err(Error::Invalid(
500            "stale declaration preview; inspect and approve again".into(),
501        ));
502    }
503    if fresh.no_op {
504        return Ok(None);
505    }
506    let bytes = checked_bytes(&fresh.manifest)?;
507    let edited = edit(
508        &bytes,
509        &fresh.tool,
510        host,
511        &fresh.active,
512        &fresh.repository,
513        fresh.change,
514    )?
515    .ok_or_else(|| Error::Invalid("declaration unexpectedly became no-op".into()))?;
516    let h = Header {
517        repository_id: fresh.repository_id,
518        repository: fresh.repository,
519        transaction_id: adoption::transaction_id(),
520        approved_plan_sha256: old.binding,
521        tool: fresh.tool,
522        change: fresh.change,
523        profiles: fresh.profiles,
524        active: Some(fresh.active),
525        anchors: anchors(&[&fresh.manifest, &fresh.local_config]),
526        manifest: fresh.manifest,
527        local_config: fresh.local_config,
528        new_manifest_sha256: journal::digest(&edited),
529    };
530    let mut j = Journal::begin(host, h)?;
531    notify(&j, Boundary::Checkpoint, &mut observer)?;
532    j.directory.create("manifest.backup", &bytes)?;
533    j.verify_backup()?;
534    let fp = j
535        .record
536        .header
537        .manifest
538        .fingerprint
539        .as_ref()
540        .ok_or_else(|| Error::Invalid("missing manifest fingerprint".into()))?;
541    let device = fs::fstat(&j.directory.file)
542        .map_err(|e| io_error("inspect declaration filesystem", &j.directory.path, e))?
543        .st_dev;
544    if fp.device != device as u64
545        || j.record.header.manifest.parents.last().is_none_or(|p| {
546            p.fingerprint.device != fp.device
547                || p.fingerprint.uid != rustix::process::geteuid().as_raw()
548        })
549    {
550        return Err(Error::Invalid(
551            "declaration requires owned parent and same filesystem; no cross-device fallback"
552                .into(),
553        ));
554    }
555    j.directory.create("op-0000", &edited)?;
556    let file = File::from(
557        fs::openat(
558            &j.directory.file,
559            "op-0000",
560            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
561            Mode::empty(),
562        )
563        .map_err(|e| io_error("open prepared declaration", &j.directory.path, e))?,
564    );
565    fs::fchown(&file, None, Some(rustix::process::Gid::from_raw(fp.gid)))
566        .map_err(|e| io_error("preserve manifest group", &j.directory.path, e))?;
567    fs::fchmod(&file, Mode::from_bits_truncate((fp.mode & 0o777) as _))
568        .map_err(|e| io_error("preserve manifest permissions", &j.directory.path, e))?;
569    file.sync_all()
570        .map_err(|e| io_error("sync prepared declaration", &j.directory.path, e))?;
571    j.directory.sync()?;
572    j.record.operation = Some(Operation {
573        staged: entry(&stage_path(&j))?,
574        after: None,
575        progress: Progress::Pending,
576    });
577    j.record.phase = Phase::Running;
578    checkpoint(&mut j, &mut observer)?;
579    validate_scope(host, &j)?;
580    validate_layout(host, &j)?;
581    j.record
582        .operation
583        .as_mut()
584        .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
585        .progress = Progress::Intent;
586    checkpoint(&mut j, &mut observer)?;
587    validate_layout(host, &j)?;
588    mutate(&j, false)?;
589    notify(&j, Boundary::Mutation, &mut observer)?;
590    let after = entry(&j.record.header.manifest.path)?;
591    let staged = &j
592        .record
593        .operation
594        .as_ref()
595        .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
596        .staged;
597    if !same(staged, &after, false) {
598        return Err(Error::Invalid("declaration postcondition mismatch".into()));
599    }
600    let op = j
601        .record
602        .operation
603        .as_mut()
604        .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?;
605    op.after = Some(after);
606    op.progress = Progress::Done;
607    checkpoint(&mut j, &mut observer)?;
608    j.record.phase = Phase::Verifying;
609    checkpoint(&mut j, &mut observer)?;
610    validate_layout(host, &j)?;
611    j.record.phase = Phase::Completed;
612    checkpoint(&mut j, &mut observer)?;
613    Ok(Some(j.record.header.transaction_id))
614}
615pub(crate) fn rollback_preview(
616    host: &HostContext,
617    repository: &str,
618    tx: &str,
619) -> Result<(String, Vec<PathBuf>)> {
620    let j = Journal::open(host, repository, tx)?;
621    validate_scope(host, &j)?;
622    let effects = if matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
623        vec![]
624    } else {
625        validate_layout(host, &j)?;
626        vec![j.record.header.manifest.path.clone()]
627    };
628    Ok((
629        journal::digest(journal::encode(&j.record)?.as_bytes()),
630        effects,
631    ))
632}
633pub(crate) fn rollback(
634    host: &HostContext,
635    lock: &WriterLock,
636    repository: &str,
637    tx: &str,
638    mut observer: impl FnMut(&Event) -> Result<()>,
639) -> Result<()> {
640    lock.check_context(host)?;
641    let mut j = Journal::open(host, repository, tx)?;
642    validate_scope(host, &j)?;
643    if j.record.phase == Phase::RolledBack {
644        return Ok(());
645    }
646    if j.record.phase == Phase::Preparing {
647        j.record.phase = Phase::RolledBack;
648        return checkpoint(&mut j, &mut observer);
649    }
650    validate_layout(host, &j)?;
651    if j.record.phase != Phase::RollingBack {
652        j.record.phase = Phase::RollingBack;
653        checkpoint(&mut j, &mut observer)?;
654    }
655    if j.record
656        .operation
657        .as_ref()
658        .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
659        .progress
660        != Progress::Undone
661    {
662        let was_applied = applied(&j)?;
663        j.record
664            .operation
665            .as_mut()
666            .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
667            .progress = Progress::UndoIntent;
668        checkpoint(&mut j, &mut observer)?;
669        validate_layout(host, &j)?;
670        if was_applied {
671            mutate(&j, true)?;
672            notify(&j, Boundary::Mutation, &mut observer)?;
673        }
674        j.record
675            .operation
676            .as_mut()
677            .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
678            .progress = Progress::Undone;
679        checkpoint(&mut j, &mut observer)?;
680    }
681    validate_layout(host, &j)?;
682    j.record.phase = Phase::RolledBack;
683    checkpoint(&mut j, &mut observer)
684}