phora 0.3.0

A git-based artifact package manager and multiplexer for content-addressed file distribution
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
//! Mutating commands: `sync`, `update`, `rebuild-registry`, and lock I/O.

use std::io::IsTerminal;
use std::num::NonZeroUsize;
use std::path::Path;

use crate::config::Config;
use crate::error::{Error, Result};
use crate::lock::{Lock, merge_locks};
use crate::paths::{cache_root_for, state_root_for};
use crate::sync::state::ProjectId;
use crate::sync::state::{FileStateStore, StateError, StateStore};
use crate::sync::{
    Concurrency, ConflictPolicy, ConflictResolver, HookPolicy, LockSet, MovedPinPolicy,
    PrunePolicy, SkippedChange, SourcePolicy, SyncOptions, SyncReport, SyncRequest, SyncWarning,
    sync_opened,
};

use super::json::JsonSink;
use super::progress::{ProgressMode, TtySink};
use super::{
    CliOutcome, DropSources, TtyResolver, build_router, drop_sources, load_config,
    load_local_config, open_project_registry,
};

fn open_sync_registry(cwd: &Path, config: &Config) -> Result<FileStateStore> {
    let projects_base = state_root_for(config.paths.state.as_deref(), cwd)?.join("projects");
    let project = ProjectId::for_path(cwd)?;
    Ok(FileStateStore::open(projects_base.join(project.as_str()))?)
}

#[expect(
    clippy::fn_params_excessive_bools,
    clippy::too_many_arguments,
    reason = "independent CLI run flags, not a state machine"
)]
pub(super) fn run_sync(
    prune: bool,
    force: bool,
    no_hooks: bool,
    no_transitive_hooks: bool,
    frozen: bool,
    fast_forward: bool,
    no_progress: bool,
    json: bool,
    drop: Option<DropSources>,
    jobs: Option<usize>,
) -> Result<CliOutcome> {
    let cwd = std::env::current_dir()?;
    let base = load_config()?;
    let local = load_local_config(&cwd)?;
    let (mut base_lock, mut local_lock) = load_locks(&cwd)?;

    let original_locks = LockSet {
        base: base_lock.clone(),
        local: local_lock.clone(),
    };
    if let Some(drop) = drop {
        drop_sources(base_lock.as_mut(), &drop);
        drop_sources(local_lock.as_mut(), &drop);
    }

    let effective = crate::config::merge_configs(base.clone(), local.clone());
    let cache_git = cache_root_for(effective.paths.cache.as_deref(), &cwd)?.join("git");
    let backend = build_router(&effective, cache_git)?;
    let registry = open_sync_registry(&cwd, &effective)?;
    // Only a read-only root under --frozen falls back lockless; contention (exit 75) still propagates.
    let guard = match registry.acquire_lock() {
        Ok(guard) => Some(guard),
        Err(StateError::ReadOnly(_)) if frozen => None,
        Err(e) => return Err(e.into()),
    };
    let lockless = guard.is_none();
    let _guard = guard;
    if !lockless && let Some(advisory) = registry.lock_advisory() {
        eprintln!("{advisory}");
    }
    let interactive = std::io::stdin().is_terminal();
    let resolver = TtyResolver;
    let trust_prompt = super::TtyTrustPrompt;
    let reporter = Reporter::select(json, no_progress);

    let source_policy = if frozen {
        SourcePolicy::Frozen
    } else if force {
        SourcePolicy::Refresh
    } else {
        SourcePolicy::Locked
    };
    let conflict_policy = if force {
        ConflictPolicy::Overwrite
    } else if interactive {
        ConflictPolicy::ResolveInteractively
    } else {
        ConflictPolicy::Refuse
    };
    let hook_policy = if no_hooks {
        HookPolicy::None
    } else if no_transitive_hooks {
        HookPolicy::NoTransitive
    } else {
        HookPolicy::All
    };
    let jobs = jobs
        .map(|jobs| {
            NonZeroUsize::new(jobs)
                .ok_or_else(|| Error::Config("--jobs must be greater than zero".to_owned()))
        })
        .transpose()?;
    let request = SyncRequest {
        base_config: &base,
        local_config: local.as_ref(),
        locks: LockSet {
            base: base_lock,
            local: local_lock,
        },
        options: SyncOptions {
            source_policy,
            conflict_policy,
            prune_policy: if prune {
                PrunePolicy::RemoveOrphans
            } else {
                PrunePolicy::KeepOrphans
            },
            hook_policy,
            moved_pin_policy: if fast_forward {
                MovedPinPolicy::FastForward
            } else {
                MovedPinPolicy::Seal
            },
            concurrency: Concurrency { jobs },
        },
        resolver: interactive.then_some(&resolver as &dyn ConflictResolver),
        sink: reporter.sink(),
        trust_prompt: interactive.then_some(&trust_prompt as &dyn crate::sync::TrustPrompt),
    };
    let mut out = sync_opened(&request, &backend, &registry, lockless).inspect_err(|error| {
        request.sink.aborted(&error.to_string());
    })?;

    if out.status == crate::sync::SyncStatus::Failed
        && (effective
            .targets
            .values()
            .any(|t| t.phase() == crate::config::TargetPhase::Prepare)
            || effective
                .hooks
                .as_ref()
                .is_some_and(|h| h.post_prepare.is_some()))
    {
        out.locks = crate::sync::merge_lock_sets(&original_locks, &out.locks);
    }
    finish_sync(&cwd, &out, interactive, &reporter)
}

struct StrippedHookNotice {
    message: String,
    fail: bool,
}

fn stripped_hook_notice(stripped: usize, interactive: bool) -> Option<StrippedHookNotice> {
    (stripped > 0).then(|| StrippedHookNotice {
        message: format!(
            "phora: {stripped} untrusted transitive hook(s) were stripped and not run — affected \
             artifacts are deployed but NOT post-processed and may be incomplete\n\
             phora: run `phora trust <name>` to inspect and approve {stripped} hook(s)"
        ),
        fail: interactive,
    })
}

/// Machine output owns stdout under `--json`; human text never shares the stream.
enum Reporter {
    Tty { sink: Box<TtySink>, live: bool },
    Json(JsonSink),
}

impl Reporter {
    fn select(json: bool, no_progress: bool) -> Self {
        if json {
            return Self::Json(JsonSink::new());
        }
        let mode = ProgressMode::resolve(no_progress);
        Self::Tty {
            sink: Box::new(TtySink::new(mode)),
            live: mode == ProgressMode::Live,
        }
    }

    fn sink(&self) -> &dyn crate::sync::ProgressSink {
        match self {
            Self::Tty { sink, .. } => sink.as_ref(),
            Self::Json(sink) => sink,
        }
    }

    fn is_json(&self) -> bool {
        matches!(self, Self::Json(_))
    }

    fn summary(&self) -> Option<crate::sync::SyncSummary> {
        match self {
            Self::Tty { sink, live: true } => sink.summary(),
            Self::Tty { live: false, .. } | Self::Json(_) => None,
        }
    }
}

fn finish_sync(
    cwd: &Path,
    out: &SyncReport,
    interactive: bool,
    reporter: &Reporter,
) -> Result<CliOutcome> {
    // `update` drops pins in memory. A failed pre-sync gate must not persist that drop.
    let pre_sync_failed = out.hook_outcomes.iter().any(|hook| {
        hook.scope == crate::sync::HookScope::PreSync
            && hook.status == crate::sync::HookStatus::Failure
    });
    if !pre_sync_failed {
        let base_lock = out
            .locks
            .base
            .as_ref()
            .ok_or_else(|| Error::Lock("sync completed without a base lock".to_owned()))?;
        write_locks(cwd, base_lock, out.locks.local.as_ref())?;
    }
    render_sync_warnings(out);
    for applied in &out.applied {
        match applied {
            crate::sync::AppliedChange::Removed {
                source, artifact, ..
            } => eprintln!("phora: pruning orphaned {source}:{artifact}"),
            crate::sync::AppliedChange::OverlayRewritten {
                source, artifact, ..
            } => eprintln!("phora: rewrote history overlay {source}:{artifact}"),
            _ => {}
        }
    }
    for skipped in &out.skipped {
        match skipped {
            SkippedChange::Failed {
                source,
                artifact,
                message,
                ..
            } => eprintln!("phora: failed to deploy {source}:{artifact}: {message}"),
            SkippedChange::ReadonlyOverlayRewrite {
                source, artifact, ..
            } => eprintln!(
                "phora: skipped history overlay rewrite {source}:{artifact}: read-only state"
            ),
            SkippedChange::Conflict { .. } => {}
        }
    }
    let report = super::render::render_hook_report(&out.hook_outcomes);
    let stripped = out
        .warnings
        .iter()
        .find_map(|warning| match warning {
            SyncWarning::UntrustedTransitiveHooks { count } => Some(*count),
            _ => None,
        })
        .unwrap_or(0);
    if let Some(notice) = stripped_hook_notice(stripped, interactive) {
        if !report.is_empty() {
            eprint!("{report}");
        }
        eprintln!("{}", notice.message);
        if notice.fail {
            return Ok(CliOutcome::Failure);
        }
    }
    if out.status == crate::sync::SyncStatus::Failed {
        if !report.is_empty() {
            eprint!("{report}");
        }
        let hooks_failed = out
            .hook_outcomes
            .iter()
            .any(|o| o.status == crate::sync::HookStatus::Failure);
        let deploy_failures = out
            .skipped
            .iter()
            .any(|skipped| matches!(skipped, SkippedChange::Failed { .. }));
        let message = match (deploy_failures, hooks_failed) {
            (true, true) => "phora: some artifacts failed to deploy and one or more hooks failed",
            (true, false) => "phora: some artifacts failed to deploy",
            (false, _) => "phora: one or more hooks failed",
        };
        eprintln!("{message}");
        return Ok(CliOutcome::Failure);
    }
    if reporter.is_json() {
        if !report.is_empty() {
            eprint!("{report}");
        }
        return Ok(CliOutcome::Success);
    }
    if !report.is_empty() {
        print!("{report}");
    }
    // `sync complete` is the pinned non-tty stdout contract (src/lib.rs); the
    // richer summary is terminal decoration only.
    match reporter.summary() {
        Some(summary) => print!("{}", super::render::format_sync_summary(&summary)),
        None => println!("sync complete"),
    }
    Ok(CliOutcome::Success)
}

fn render_sync_warnings(out: &SyncReport) {
    for warning in &out.warnings {
        if let Some(rendered) = super::render::format_sync_warning(warning) {
            eprintln!("{rendered}");
        }
    }
}

pub(super) fn run_rebuild_registry() -> Result<()> {
    let cwd = std::env::current_dir()?;
    let base = load_config()?;
    let local = load_local_config(&cwd)?;
    let mut config = crate::config::merge_configs(base, local);
    config.validate()?;

    let registry = open_project_registry(&config)?;
    let _guard = registry.acquire_lock()?;

    let (base_lock, local_lock) = load_locks(&cwd)?;
    let lock = match base_lock {
        Some(base) => merge_locks(&base, local_lock.as_ref()),
        None => local_lock
            .ok_or_else(|| Error::Lock("no lock file found; run sync first".to_owned()))?,
    };

    let cache_git = cache_root_for(config.paths.cache.as_deref(), &cwd)?.join("git");
    let backend = build_router(&config, cache_git)?;
    let mut parsed = config.parsed_sources()?;
    let mut remotes = crate::sync::resolved_remotes(&config, &parsed)?;
    crate::sync::inject_composed_graph(
        &mut config,
        &mut parsed,
        &mut remotes,
        &backend,
        Some(&lock),
    );
    let report =
        crate::sync::rebuild_registry_with(&config, &parsed, &remotes, &lock, &backend, &registry)?;

    println!("reconstructed {}", report.reconstructed.len());
    if !report.modified.is_empty() {
        let modified: Vec<String> = report
            .modified
            .iter()
            .map(|k| format!("{}/{}", k.source, k.artifact))
            .collect();
        println!("modified [{}]", modified.join(", "));
    }
    if !report.foreign.is_empty() {
        let foreign: Vec<String> = report
            .foreign
            .iter()
            .map(|p| p.display().to_string())
            .collect();
        println!("foreign [{}]", foreign.join(", "));
    }
    Ok(())
}

pub(super) fn run_update(
    source: Option<&str>,
    fast_forward: bool,
    prune: bool,
) -> Result<CliOutcome> {
    let drop = source.map_or(DropSources::All, |s| DropSources::One(s.to_owned()));
    run_sync(
        prune,
        false,
        false,
        false,
        false,
        fast_forward,
        false,
        false,
        Some(drop),
        None,
    )
}

/// Writes the base lock to `<dir>/phora.lock` and, when `local` is `Some`, the
/// local lock to `<dir>/phora.local.lock`; when `local` is `None`, removes any
/// stale `<dir>/phora.local.lock`.
///
/// # Errors
///
/// Returns an error if serialization or filesystem I/O fails.
pub fn write_locks(dir: &Path, base: &Lock, local: Option<&Lock>) -> Result<()> {
    let base_path = dir.join("phora.lock");
    let base_text =
        toml::to_string(base).map_err(|e| Error::Lock(format!("serialize phora.lock: {e}")))?;
    std::fs::write(&base_path, base_text)
        .map_err(|e| Error::Lock(format!("write {}: {e}", base_path.display())))?;

    let local_path = dir.join("phora.local.lock");
    match local {
        Some(local) => {
            let local_text = toml::to_string(local)
                .map_err(|e| Error::Lock(format!("serialize phora.local.lock: {e}")))?;
            std::fs::write(&local_path, local_text)
                .map_err(|e| Error::Lock(format!("write {}: {e}", local_path.display())))?;
        }
        None => match std::fs::remove_file(&local_path) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => {
                return Err(Error::Lock(format!(
                    "remove stale {}: {e}",
                    local_path.display()
                )));
            }
        },
    }
    Ok(())
}

/// Reads `<dir>/phora.lock` and `<dir>/phora.local.lock`, returning `None` for
/// either file that is absent.
///
/// # Errors
///
/// Returns an error if a present lock file cannot be read or parsed.
pub fn load_locks(dir: &Path) -> Result<(Option<Lock>, Option<Lock>)> {
    Ok((
        read_lock(&dir.join("phora.lock"))?,
        read_lock(&dir.join("phora.local.lock"))?,
    ))
}

fn read_lock(path: &Path) -> Result<Option<Lock>> {
    match std::fs::read_to_string(path) {
        Ok(text) => toml::from_str(&text)
            .map(Some)
            .map_err(|e| Error::Lock(format!("parse {}: {e}", path.display()))),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(Error::Lock(format!("read {}: {e}", path.display()))),
    }
}

#[cfg(test)]
mod tests {
    use super::stripped_hook_notice;

    #[test]
    fn no_stripped_hooks_yields_no_notice() {
        assert!(stripped_hook_notice(0, true).is_none());
        assert!(stripped_hook_notice(0, false).is_none());
    }

    #[test]
    fn stripped_hooks_under_a_tty_fail_the_command() {
        let notice = stripped_hook_notice(2, true).expect("a notice when hooks are stripped");
        assert!(
            notice.fail,
            "a TTY sync must fail so a human acts on the stripped hooks"
        );
        assert!(notice.message.contains("phora trust") && notice.message.contains("approve"));
        assert!(notice.message.contains("incomplete"));
    }

    #[test]
    fn stripped_hooks_under_non_tty_surface_but_do_not_fail() {
        let notice = stripped_hook_notice(1, false).expect("a notice when hooks are stripped");
        assert!(
            !notice.fail,
            "non-TTY/CI must stay green; the gap is surfaced, not fatal"
        );
        assert!(notice.message.contains("phora trust") && notice.message.contains("approve"));
    }
}