use std::collections::{BTreeMap, BTreeSet};
use std::process::Command;
use crate::config::{Config, DEFAULT_SHELL_PREFIX, HookCommand, HookWhen, LayoutConfig};
use crate::error::{Error, Result};
use crate::sync::request::{TrustPrompt, TrustRequest};
use crate::sync::state::{ArtifactRecord, StateStore};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookScope {
PreSync,
PreDeploy,
OnChange,
PostSync,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookStatus {
Success,
Failure,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HookOutcome {
pub hook_id: String,
pub command: String,
pub scope: HookScope,
pub status: HookStatus,
}
pub(super) fn dispatch_hooks(
config: &Config,
registry: &dyn StateStore,
lockless: bool,
) -> Result<Vec<HookOutcome>> {
let mut outcomes = Vec::new();
for (target_name, target) in &config.targets {
let Some(hooks) = &target.hooks else { continue };
let Some(on_change) = &hooks.on_change else {
continue;
};
let records = registry.target_artifacts(target_name)?;
let current: BTreeSet<String> = records.iter().map(|r| r.digest.clone()).collect();
let layout = target.layout();
let target_path = target.expanded_path();
for hook in dedupe(on_change) {
let (body, suffix) = hook_key(hook);
let id = format!("{target_name}#{body}#{suffix}");
let recorded = recorded_set(registry, target_name, &id)?;
let changed = changed_records(&records, &recorded);
if changed.is_empty() {
continue;
}
if lockless {
let journal_root = registry.journal_root();
let state_root = journal_root.parent().unwrap_or(&journal_root);
return Err(crate::sync::state::readonly_root_error(state_root).into());
}
let names = changed_names(&changed);
let paths = changed_paths(&changed, &target_path, &layout);
let status = run_hook(
hook,
&[
("PHORA_TARGET", target_name.as_str()),
("PHORA_CHANGED", &paths),
("PHORA_CHANGED_NAMES", &names),
],
)?;
if status == HookStatus::Success {
registry.record_hook_success(target_name, &id, ¤t)?;
}
outcomes.push(HookOutcome {
hook_id: id,
command: hook.display(),
scope: HookScope::OnChange,
status,
});
}
}
if let Some(global) = &config.hooks
&& let Some(post_sync) = &global.post_sync
&& matches!(global.when, HookWhen::Always)
{
for hook in dedupe(post_sync) {
let status = run_hook(hook, &[])?;
let (body, suffix) = hook_key(hook);
outcomes.push(HookOutcome {
hook_id: format!("post_sync#{body}#{suffix}"),
command: hook.display(),
scope: HookScope::PostSync,
status,
});
}
}
Ok(outcomes)
}
pub(super) fn dispatch_pre_sync(config: &Config, target_names: &str) -> Result<Vec<HookOutcome>> {
let Some(pre_sync) = config.hooks.as_ref().and_then(|g| g.pre_sync.as_ref()) else {
return Ok(Vec::new());
};
let mut outcomes = Vec::new();
for hook in dedupe(pre_sync) {
let status = run_hook(hook, &[("PHORA_TARGETS", target_names)])?;
let (body, suffix) = hook_key(hook);
outcomes.push(HookOutcome {
hook_id: format!("pre_sync#{body}#{suffix}"),
command: hook.display(),
scope: HookScope::PreSync,
status,
});
}
Ok(outcomes)
}
pub(super) fn dispatch_pre_deploy(
hooks: &crate::config::TargetHooks,
target_name: &str,
target_path: &std::path::Path,
) -> Result<Vec<HookOutcome>> {
let Some(pre_deploy) = hooks.pre_deploy.as_ref() else {
return Ok(Vec::new());
};
let path = target_path.to_string_lossy();
let mut outcomes = Vec::new();
for hook in dedupe(pre_deploy) {
let status = run_hook(
hook,
&[("PHORA_TARGET", target_name), ("PHORA_TARGET_PATH", &path)],
)?;
let (body, suffix) = hook_key(hook);
outcomes.push(HookOutcome {
hook_id: format!("{target_name}#pre_deploy#{body}#{suffix}"),
command: hook.display(),
scope: HookScope::PreDeploy,
status,
});
}
Ok(outcomes)
}
pub(super) struct TransitiveHookRun<'a> {
pub(super) dep_instance: &'a str,
pub(super) hook_id: &'a str,
pub(super) command: &'a HookCommand,
pub(super) preimage: &'a str,
pub(super) target_path: &'a std::path::Path,
pub(super) source: &'a str,
pub(super) commit: &'a str,
}
pub(super) struct TransitiveApproval {
pub(super) dep_instance: String,
pub(super) hook_id: String,
pub(super) preimage: String,
pub(super) source: String,
pub(super) commit: String,
}
pub(super) fn dispatch_transitive_hooks(
candidates: &[TransitiveHookRun<'_>],
trusted: &BTreeSet<String>,
prompt: &dyn TrustPrompt,
) -> Result<(Vec<HookOutcome>, Vec<TransitiveApproval>)> {
let mut outcomes = Vec::new();
let mut approvals = Vec::new();
let mut decided: BTreeMap<&str, bool> = BTreeMap::new();
for candidate in candidates {
let approved = if trusted.contains(candidate.preimage) {
true
} else if let Some(&prior) = decided.get(candidate.preimage) {
prior
} else {
let answer = prompt.confirm(&TrustRequest {
dep_instance: candidate.dep_instance,
hook_id: candidate.hook_id,
command: candidate.command.display(),
});
decided.insert(candidate.preimage, answer);
answer
};
if !approved {
continue;
}
if !trusted.contains(candidate.preimage) {
approvals.push(TransitiveApproval {
dep_instance: candidate.dep_instance.to_owned(),
hook_id: candidate.hook_id.to_owned(),
preimage: candidate.preimage.to_owned(),
source: candidate.source.to_owned(),
commit: candidate.commit.to_owned(),
});
}
let status = run_hook(
candidate.command,
&[("PHORA_TARGET", &candidate.target_path.to_string_lossy())],
)?;
outcomes.push(HookOutcome {
hook_id: candidate.hook_id.to_owned(),
command: candidate.command.display(),
scope: HookScope::OnChange,
status,
});
}
Ok((outcomes, approvals))
}
fn hook_key(hook: &HookCommand) -> (String, String) {
match hook {
HookCommand::Shell { run, shell } => (
run.clone(),
shell.as_deref().unwrap_or(DEFAULT_SHELL_PREFIX).to_owned(),
),
HookCommand::Exec { cmd } => (cmd.join(" "), "exec".to_owned()),
}
}
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum DedupeKey<'a> {
Shell(&'a str, &'a str),
Exec(&'a [String]),
}
fn dedupe(commands: &[HookCommand]) -> Vec<&HookCommand> {
let mut seen = BTreeSet::new();
commands
.iter()
.filter(|cmd| {
let key = match cmd {
HookCommand::Shell { run, shell } => {
DedupeKey::Shell(run, shell.as_deref().unwrap_or(DEFAULT_SHELL_PREFIX))
}
HookCommand::Exec { cmd } => DedupeKey::Exec(cmd),
};
seen.insert(key)
})
.collect()
}
fn recorded_set(registry: &dyn StateStore, target: &str, id: &str) -> Result<BTreeSet<String>> {
Ok(registry
.hook_state(target)?
.into_iter()
.find(|h| h.hook_id == id)
.map(|h| h.last_success)
.unwrap_or_default())
}
fn changed_records<'a>(
records: &'a [ArtifactRecord],
recorded: &BTreeSet<String>,
) -> Vec<&'a ArtifactRecord> {
records
.iter()
.filter(|record| !recorded.contains(&record.digest))
.collect()
}
fn changed_names(changed: &[&ArtifactRecord]) -> String {
let names: BTreeSet<&str> = changed.iter().map(|r| r.key.artifact.as_str()).collect();
names.into_iter().collect::<Vec<_>>().join("\n")
}
fn changed_paths(
changed: &[&ArtifactRecord],
target_path: &std::path::Path,
layout: &LayoutConfig,
) -> String {
let paths: BTreeSet<String> = changed
.iter()
.map(|r| {
target_path
.join(super::target::record_relative_destination(layout, r))
.to_string_lossy()
.into_owned()
})
.collect();
paths.into_iter().collect::<Vec<_>>().join("\n")
}
fn run_hook(hook: &HookCommand, env: &[(&str, &str)]) -> Result<HookStatus> {
let mut command = command(hook)?;
for (key, value) in env {
command.env(key, value);
}
let status = command
.status()
.map_err(|e| Error::Sync(format!("failed to run hook `{}`: {e}", hook.display())))?;
Ok(if status.success() {
HookStatus::Success
} else {
HookStatus::Failure
})
}
pub(super) fn command(hook: &HookCommand) -> Result<Command> {
Ok(match hook {
HookCommand::Shell { run, shell } => {
let shell = shell.as_deref().unwrap_or(DEFAULT_SHELL_PREFIX);
let mut parts = shell.split_whitespace();
let program = parts
.next()
.ok_or_else(|| Error::Sync(format!("hook shell `{shell}` is empty")))?;
let mut command = Command::new(program);
command.args(parts).arg(run);
command
}
HookCommand::Exec { cmd } => {
let (program, args) = cmd
.split_first()
.ok_or_else(|| Error::Sync("hook command `cmd` must not be empty".to_owned()))?;
let mut command = Command::new(program);
command.args(args);
command
}
})
}
#[cfg(test)]
mod transitive_trust_tests {
use super::*;
use crate::config::HookCommand;
use std::path::Path;
struct CannedPrompt(bool);
impl TrustPrompt for CannedPrompt {
fn confirm(&self, _request: &TrustRequest<'_>) -> bool {
self.0
}
}
struct NeverPrompt;
impl TrustPrompt for NeverPrompt {
fn confirm(&self, _request: &TrustRequest<'_>) -> bool {
panic!("a hook already pinned in trusted_hooks must run without prompting");
}
}
struct CountingPrompt(std::sync::atomic::AtomicUsize, bool);
impl TrustPrompt for CountingPrompt {
fn confirm(&self, _request: &TrustRequest<'_>) -> bool {
self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
self.1
}
}
fn noop_hook() -> HookCommand {
HookCommand::Shell {
run: "true".to_owned(),
shell: Some("sh -c".to_owned()),
}
}
fn run<'a>(command: &'a HookCommand, target: &'a Path) -> TransitiveHookRun<'a> {
TransitiveHookRun {
dep_instance: "owninginstance01",
hook_id: "composed#on_change#deadbeef",
command,
preimage: "blake3:candidatepreimage",
target_path: target,
source: "nvim-kit",
commit: "c0ffeecommit",
}
}
#[test]
fn answering_yes_yields_an_approval_matching_the_candidate_preimage_and_id() {
let cmd = noop_hook();
let target = Path::new("/tmp/phora-test-target");
let candidate = run(&cmd, target);
let trusted = BTreeSet::new();
let (_outcomes, approvals) =
dispatch_transitive_hooks(&[candidate], &trusted, &CannedPrompt(true))
.expect("dispatch with a yes-answering prompt must succeed");
assert_eq!(
approvals.len(),
1,
"an untrusted hook approved with `y` must produce exactly one persistable approval"
);
let approval = &approvals[0];
assert_eq!(
approval.preimage, "blake3:candidatepreimage",
"the persisted approval must carry the candidate's commit-bound preimage verbatim, so \
trust is pinned to the resolved commit"
);
assert_eq!(
approval.dep_instance, "owninginstance01",
"the approval must address the candidate's owning dep instance"
);
assert_eq!(
approval.hook_id, "composed#on_change#deadbeef",
"the approval must address the candidate's hook id"
);
assert_eq!(
(approval.source.as_str(), approval.commit.as_str()),
("nvim-kit", "c0ffeecommit"),
"the approval must carry the candidate's source and commit so the persisted \
trusted_hooks entry can be diffed by `phora trust`, never silently emptied"
);
}
#[test]
fn answering_no_yields_no_approval_and_does_not_run_the_hook() {
let cmd = noop_hook();
let target = Path::new("/tmp/phora-test-target");
let candidate = run(&cmd, target);
let trusted = BTreeSet::new();
let (outcomes, approvals) =
dispatch_transitive_hooks(&[candidate], &trusted, &CannedPrompt(false))
.expect("dispatch with a no-answering prompt must succeed");
assert!(
approvals.is_empty(),
"anti-TOFU: declining the prompt must write NO trusted_hooks approval"
);
assert!(
outcomes.is_empty(),
"a declined untrusted hook must NOT run, so it produces no outcome"
);
}
fn run_keyed<'a>(
command: &'a HookCommand,
target: &'a Path,
dep_instance: &'a str,
hook_id: &'a str,
preimage: &'a str,
) -> TransitiveHookRun<'a> {
TransitiveHookRun {
dep_instance,
hook_id,
command,
preimage,
target_path: target,
source: "nvim-kit",
commit: "c0ffeecommit",
}
}
#[test]
fn duplicate_preimages_prompt_once_but_each_records_its_own_approval() {
let cmd = noop_hook();
let target = Path::new("/tmp/phora-test-target");
let a = run_keyed(
&cmd,
target,
"instanceaaaa0001",
"a#on_change#dead",
"blake3:shared",
);
let b = run_keyed(
&cmd,
target,
"instancebbbb0002",
"b#on_change#dead",
"blake3:shared",
);
let trusted = BTreeSet::new();
let prompt = CountingPrompt(std::sync::atomic::AtomicUsize::new(0), true);
let (outcomes, approvals) = dispatch_transitive_hooks(&[a, b], &trusted, &prompt)
.expect("dispatch with two same-preimage candidates must succeed");
assert_eq!(
prompt.0.load(std::sync::atomic::Ordering::SeqCst),
1,
"two candidates sharing a preimage must prompt exactly once"
);
assert_eq!(
approvals.len(),
2,
"each distinct (dep_instance, hook_id) must still get its own approval record"
);
assert_eq!(
outcomes.len(),
2,
"both shared-preimage hooks must run after the single yes"
);
}
#[test]
fn declining_a_shared_preimage_skips_all_duplicates_without_re_prompting() {
let cmd = noop_hook();
let target = Path::new("/tmp/phora-test-target");
let a = run_keyed(
&cmd,
target,
"instanceaaaa0001",
"a#on_change#dead",
"blake3:shared",
);
let b = run_keyed(
&cmd,
target,
"instancebbbb0002",
"b#on_change#dead",
"blake3:shared",
);
let trusted = BTreeSet::new();
let prompt = CountingPrompt(std::sync::atomic::AtomicUsize::new(0), false);
let (outcomes, approvals) = dispatch_transitive_hooks(&[a, b], &trusted, &prompt)
.expect("dispatch declining a shared preimage must succeed");
assert_eq!(
prompt.0.load(std::sync::atomic::Ordering::SeqCst),
1,
"a declined preimage must not re-prompt for duplicates"
);
assert!(
approvals.is_empty(),
"a declined preimage records no approval"
);
assert!(outcomes.is_empty(), "a declined preimage runs nothing");
}
#[test]
fn an_already_trusted_hook_runs_without_prompting_or_re_approving() {
let cmd = noop_hook();
let target = Path::new("/tmp/phora-test-target");
let candidate = run(&cmd, target);
let mut trusted = BTreeSet::new();
trusted.insert("blake3:candidatepreimage".to_owned());
let (outcomes, approvals) = dispatch_transitive_hooks(&[candidate], &trusted, &NeverPrompt)
.expect("a pinned hook dispatches without error");
assert_eq!(
outcomes.len(),
1,
"a preimage-pinned hook must RUN without consulting the prompt"
);
assert!(
approvals.is_empty(),
"a hook already trusted needs no fresh approval to persist"
);
}
}