Skip to main content

vela_protocol/proposals/
mod.rs

1//! Proposal-first frontier writes and proof freshness tracking.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::Path;
5
6use chrono::Utc;
7use serde::{Deserialize, Serialize};
8use serde_json::{Value, json};
9use sha2::{Digest, Sha256};
10
11use crate::bundle::{Annotation, Artifact, ConfidenceMethod, FindingBundle};
12use crate::canonical;
13use crate::events::{self, NULL_HASH, StateActor, StateEvent, StateTarget};
14use crate::project::{self, Project};
15use crate::propagate::{self, PropagationAction};
16use crate::repo;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ProposalWithdrawalAuthorization {
20    pub proposal_root: String,
21    pub receipt_root: String,
22    pub receipt_path: String,
23    pub identity_binding: crate::identity::IdentityBinding,
24}
25
26/// Resolve and verify the producer authority already bound by a landed
27/// proposal's exact Receipt v1. This grants only the ability to withdraw that
28/// still-pending proposal; it is never reviewer or accepted-state authority.
29pub fn proposal_withdrawal_authorization(
30    frontier: &Path,
31    proposal: &StateProposal,
32) -> Result<ProposalWithdrawalAuthorization, String> {
33    if proposal.status != "pending_review" {
34        return Err(format!(
35            "proposal {} is {}, not pending_review",
36            proposal.id, proposal.status
37        ));
38    }
39    let submission = proposal
40        .payload
41        .get("vela_submission")
42        .and_then(Value::as_object)
43        .ok_or_else(|| {
44            format!(
45                "proposal {} has no Receipt-bound vela_submission and cannot be producer-withdrawn",
46                proposal.id
47            )
48        })?;
49    let receipt_root = submission
50        .get("receipt_root")
51        .and_then(Value::as_str)
52        .ok_or("vela_submission.receipt_root must be a string")?
53        .to_string();
54    let receipt_path = submission
55        .get("receipt_path")
56        .and_then(Value::as_str)
57        .ok_or("vela_submission.receipt_path must be a string")?
58        .to_string();
59    let relative = Path::new(&receipt_path);
60    if relative.is_absolute()
61        || relative.components().any(|component| {
62            matches!(
63                component,
64                std::path::Component::ParentDir
65                    | std::path::Component::RootDir
66                    | std::path::Component::Prefix(_)
67            )
68        })
69    {
70        return Err("proposal receipt path must remain frontier-relative".to_string());
71    }
72    let bytes = std::fs::read(frontier.join(relative))
73        .map_err(|error| format!("read bound Receipt {receipt_path}: {error}"))?;
74    let receipt = crate::receipt_v1::ReceiptV1::parse(&bytes)
75        .map_err(|error| format!("verify bound Receipt {receipt_path}: {error}"))?;
76    let observed_root = receipt
77        .canonical_root()
78        .map_err(|error| format!("canonicalize bound Receipt: {error}"))?;
79    if observed_root != receipt_root {
80        return Err(format!(
81            "bound Receipt root mismatch: proposal declares {receipt_root}, observed {observed_root}"
82        ));
83    }
84    let binding_value = receipt
85        .as_value()
86        .pointer("/environment/vela:producer_context/identity_binding")
87        .cloned()
88        .ok_or("bound Receipt has no embedded producer identity binding")?;
89    let identity_binding: crate::identity::IdentityBinding = serde_json::from_value(binding_value)
90        .map_err(|error| format!("decode embedded producer identity binding: {error}"))?;
91    identity_binding
92        .verify()
93        .map_err(|error| format!("verify embedded producer identity binding: {error}"))?;
94    if identity_binding.actor_id != proposal.actor.id
95        || identity_binding.actor_class != crate::identity::ActorClass::Agent
96    {
97        return Err("proposal actor does not match its Receipt producer identity".to_string());
98    }
99    let proposal_root = format!(
100        "sha256:{}",
101        canonical::sha256_canonical(proposal)
102            .map_err(|error| format!("canonicalize proposal: {error}"))?
103    );
104    Ok(ProposalWithdrawalAuthorization {
105        proposal_root,
106        receipt_root,
107        receipt_path,
108        identity_binding,
109    })
110}
111
112/// Verify, sign, append, and materialize one producer withdrawal in memory.
113/// Filesystem installation remains the CLI transaction layer's responsibility.
114pub fn apply_proposal_withdrawal(
115    frontier: &Path,
116    project: &mut Project,
117    proposal_id: &str,
118    actor_id: &str,
119    reason: &str,
120    timestamp: &str,
121    key: &ed25519_dalek::SigningKey,
122) -> Result<StateEvent, String> {
123    let index = project
124        .proposals
125        .iter()
126        .position(|proposal| proposal.id == proposal_id)
127        .ok_or_else(|| format!("proposal {proposal_id} does not exist"))?;
128    let authorization = proposal_withdrawal_authorization(frontier, &project.proposals[index])?;
129    if actor_id != project.proposals[index].actor.id
130        || actor_id != authorization.identity_binding.actor_id
131    {
132        return Err("withdrawal actor is not the Receipt-bound proposal producer".to_string());
133    }
134    let actual_key = crate::sign::pubkey_hex(key);
135    if !actual_key.eq_ignore_ascii_case(&authorization.identity_binding.public_key_hex) {
136        return Err("withdrawal key does not match the Receipt-bound producer key".to_string());
137    }
138    let payload = events::ProposalWithdrawalPayload {
139        schema: events::PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA.to_string(),
140        proposal_id: proposal_id.to_string(),
141        proposal_root: authorization.proposal_root,
142        receipt_root: authorization.receipt_root,
143        identity_binding_id: authorization.identity_binding.binding_id,
144    };
145    let mut event =
146        events::new_proposal_withdrawal_event(payload, actor_id, reason, Some(timestamp))?;
147    event.signature = Some(crate::sign::sign_event(&event, key)?);
148    project.events.push(event.clone());
149    let proposal = &mut project.proposals[index];
150    proposal.status = "withdrawn".to_string();
151    proposal.decision_reason = Some(reason.to_string());
152    proposal.reviewed_by = None;
153    proposal.reviewed_at = None;
154    proposal.applied_event_id = None;
155    // Stats are part of the materialized snapshot. Keep the in-memory
156    // candidate identical to a subsequent split-repository reload, which
157    // always recomputes them after reading the canonical event files.
158    project::recompute_stats(project);
159    Ok(event)
160}
161
162/// Verify every stored withdrawal against its exact proposal/Receipt binding.
163pub fn verify_proposal_withdrawals(frontier: &Path, project: &Project) -> Vec<String> {
164    project
165        .events
166        .iter()
167        .filter(|event| event.kind == events::EVENT_KIND_PROPOSAL_WITHDRAWN)
168        .filter_map(|event| verify_proposal_withdrawal_event(frontier, project, event).err())
169        .collect()
170}
171
172pub fn verify_proposal_withdrawal_event(
173    frontier: &Path,
174    project: &Project,
175    event: &StateEvent,
176) -> Result<(), String> {
177    if event.kind != events::EVENT_KIND_PROPOSAL_WITHDRAWN {
178        return Err(format!("event {} is not a proposal withdrawal", event.id));
179    }
180    let proposal = project
181        .proposals
182        .iter()
183        .find(|proposal| proposal.id == event.target.id)
184        .ok_or_else(|| {
185            format!(
186                "withdrawal event {} targets missing proposal {}",
187                event.id, event.target.id
188            )
189        })?;
190    let authorization = proposal_withdrawal_authorization_for_terminal(frontier, proposal)
191        .map_err(|error| format!("withdrawal event {}: {error}", event.id))?;
192    let matching_withdrawals = project
193        .events
194        .iter()
195        .filter(|candidate| {
196            candidate.kind == events::EVENT_KIND_PROPOSAL_WITHDRAWN
197                && candidate.target.r#type == "proposal"
198                && candidate.target.id == proposal.id
199        })
200        .count();
201    if matching_withdrawals != 1 {
202        return Err(format!(
203            "withdrawal event {}: proposal {} must have exactly one withdrawal event, found {matching_withdrawals}",
204            event.id, proposal.id
205        ));
206    }
207    if project.events.iter().any(|candidate| {
208        candidate.target.r#type == "proposal"
209            && candidate.target.id == proposal.id
210            && matches!(
211                candidate.kind.as_str(),
212                events::EVENT_KIND_REVIEW_ACCEPTED
213                    | events::EVENT_KIND_REVIEW_REJECTED
214                    | events::EVENT_KIND_REVIEW_REVISION_REQUESTED
215            )
216    }) {
217        return Err(format!(
218            "withdrawal event {} conflicts with a human decision for proposal {}",
219            event.id, proposal.id
220        ));
221    }
222    let payload: events::ProposalWithdrawalPayload = serde_json::from_value(event.payload.clone())
223        .map_err(|error| format!("withdrawal event {} has invalid payload: {error}", event.id))?;
224    if payload.schema != events::PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA
225        || payload.proposal_id != proposal.id
226        || event.target.r#type != "proposal"
227        || event.target.id != proposal.id
228        || payload.proposal_root != authorization.proposal_root
229        || payload.receipt_root != authorization.receipt_root
230        || payload.identity_binding_id != authorization.identity_binding.binding_id
231        || event.actor.id != authorization.identity_binding.actor_id
232        || event.actor.r#type != "agent"
233        || event.before_hash != NULL_HASH
234        || event.after_hash != NULL_HASH
235        || event.id != events::compute_event_id(event)
236        || !crate::sign::verify_event_signature(
237            event,
238            &authorization.identity_binding.public_key_hex,
239        )
240        .unwrap_or(false)
241    {
242        return Err(format!(
243            "withdrawal event {} does not match its exact proposal/Receipt producer binding",
244            event.id
245        ));
246    }
247    Ok(())
248}
249
250/// Return the already verified withdrawal for an idempotent retry. A terminal
251/// proposal without exactly one valid matching event fails closed.
252pub fn existing_proposal_withdrawal(
253    frontier: &Path,
254    project: &Project,
255    proposal_id: &str,
256) -> Result<Option<StateEvent>, String> {
257    let Some(proposal) = project
258        .proposals
259        .iter()
260        .find(|proposal| proposal.id == proposal_id)
261    else {
262        return Err(format!("proposal {proposal_id} does not exist"));
263    };
264    if proposal.status != "withdrawn" {
265        return Ok(None);
266    }
267    let matching = project
268        .events
269        .iter()
270        .filter(|event| {
271            event.kind == events::EVENT_KIND_PROPOSAL_WITHDRAWN
272                && event.target.r#type == "proposal"
273                && event.target.id == proposal_id
274        })
275        .cloned()
276        .collect::<Vec<_>>();
277    if matching.len() != 1 {
278        return Err(format!(
279            "withdrawn proposal {proposal_id} must have exactly one withdrawal event, found {}",
280            matching.len()
281        ));
282    }
283    if let Some(error) = verify_proposal_withdrawals(frontier, project)
284        .into_iter()
285        .next()
286    {
287        return Err(error);
288    }
289    Ok(matching.into_iter().next())
290}
291
292fn proposal_withdrawal_authorization_for_terminal(
293    frontier: &Path,
294    proposal: &StateProposal,
295) -> Result<ProposalWithdrawalAuthorization, String> {
296    let mut pending = proposal.clone();
297    pending.status = "pending_review".to_string();
298    pending.decision_reason = None;
299    pending.reviewed_by = None;
300    pending.reviewed_at = None;
301    pending.applied_event_id = None;
302    proposal_withdrawal_authorization(frontier, &pending)
303}
304
305mod decision_inspection;
306pub mod policy_accept;
307mod types;
308pub use decision_inspection::{DecisionInspection, inspect_named_decision};
309pub use types::*;
310
311pub fn new_proposal(
312    kind: impl Into<String>,
313    target: StateTarget,
314    actor_id: impl Into<String>,
315    actor_type: impl Into<String>,
316    reason: impl Into<String>,
317    payload: Value,
318    source_refs: Vec<String>,
319    caveats: Vec<String>,
320) -> StateProposal {
321    new_proposal_at(
322        kind,
323        target,
324        actor_id,
325        actor_type,
326        reason,
327        payload,
328        source_refs,
329        caveats,
330        Utc::now().to_rfc3339(),
331    )
332}
333
334/// Build a content-addressed proposal with an injected timestamp.
335///
336/// Transactional writers use one fixed instant for every staged object so a
337/// retry or post-marker recovery never consults the wall clock again. The
338/// timestamp remains non-canonical proposal metadata; the logical proposal ID
339/// is derived by [`proposal_id`] exactly as before.
340pub fn new_proposal_at(
341    kind: impl Into<String>,
342    target: StateTarget,
343    actor_id: impl Into<String>,
344    actor_type: impl Into<String>,
345    reason: impl Into<String>,
346    payload: Value,
347    source_refs: Vec<String>,
348    caveats: Vec<String>,
349    created_at: impl Into<String>,
350) -> StateProposal {
351    let mut proposal = StateProposal {
352        schema: PROPOSAL_SCHEMA.to_string(),
353        id: String::new(),
354        kind: kind.into(),
355        target,
356        actor: StateActor {
357            id: actor_id.into(),
358            r#type: actor_type.into(),
359        },
360        created_at: created_at.into(),
361        drafted_at: None,
362        reason: reason.into(),
363        payload,
364        source_refs,
365        status: "pending_review".to_string(),
366        reviewed_by: None,
367        reviewed_at: None,
368        decision_reason: None,
369        applied_event_id: None,
370        caveats,
371        agent_run: None,
372    };
373    proposal.id = proposal_id(&proposal);
374    proposal
375}
376
377/// Phase P (v0.5): `vpr_…` is content-addressed over the *logical* proposal
378/// content only — `created_at` is excluded from the preimage. Identical
379/// logical proposals (same actor, target, kind, reason, payload) deterministically
380/// produce the same proposal_id regardless of when they were constructed.
381///
382/// This is the substrate property that makes agent retries idempotent.
383/// `created_at` stays on the proposal as non-canonical metadata; replay-attack
384/// detection layers on the signed envelope, not the content hash.
385pub fn proposal_id(proposal: &StateProposal) -> String {
386    let preimage = json!({
387        "schema": proposal.schema,
388        "kind": proposal.kind,
389        "target": proposal.target,
390        "actor": proposal.actor,
391        "reason": proposal.reason,
392        "payload": proposal.payload,
393        "source_refs": proposal.source_refs,
394        "caveats": proposal.caveats,
395    });
396    let bytes = canonical::to_canonical_bytes(&preimage).unwrap_or_default();
397    format!("vpr_{}", &hex::encode(Sha256::digest(bytes))[..16])
398}
399
400pub fn is_placeholder_reviewer(value: &str) -> bool {
401    let normalized = value.trim().to_ascii_lowercase();
402    normalized.is_empty()
403        || normalized == "local-reviewer"
404        || normalized == "local-user"
405        || normalized == "reviewer"
406        || normalized == "user"
407        || normalized == "unknown"
408        || normalized.starts_with("local-")
409}
410
411pub fn validate_reviewer_identity(value: &str) -> Result<(), String> {
412    if is_placeholder_reviewer(value) {
413        return Err(format!(
414            "Reviewer identity '{}' is missing or placeholder. Use a stable named reviewer id.",
415            value
416        ));
417    }
418    Ok(())
419}
420
421/// v0.128: true iff an actor carries *reviewer* authority for the public
422/// accept boundary. Doctrine: accept authority is the `reviewer:`
423/// namespace and only that namespace — a non-placeholder
424/// `reviewer:<name>` id. Historical actor tiers grant no authority. This is deliberately stricter
425/// than `validate_reviewer_identity` (which only rejects placeholders):
426/// here an `agent:` or bare id is refused outright.
427#[must_use]
428pub fn actor_has_reviewer_authority(actor: &crate::sign::ActorRecord) -> bool {
429    let id = actor.id.trim();
430    id.to_ascii_lowercase().starts_with("reviewer:") && !is_placeholder_reviewer(id)
431}
432
433pub fn summary(frontier: &Project) -> ProposalSummary {
434    let mut out = ProposalSummary::default();
435    let mut seen = BTreeSet::new();
436    let finding_ids = frontier
437        .findings
438        .iter()
439        .map(|finding| finding.id.as_str())
440        .collect::<BTreeSet<_>>();
441    let artifact_ids = frontier
442        .artifacts
443        .iter()
444        .map(|artifact| artifact.id.as_str())
445        .collect::<BTreeSet<_>>();
446    for proposal in &frontier.proposals {
447        out.total += 1;
448        *out.by_kind.entry(proposal.kind.clone()).or_default() += 1;
449        match proposal.status.as_str() {
450            "pending_review" => out.pending_review += 1,
451            "accepted" => out.accepted += 1,
452            "rejected" => out.rejected += 1,
453            "applied" => out.applied += 1,
454            "withdrawn" => out.withdrawn += 1,
455            _ => {}
456        }
457        if !seen.insert(proposal.id.clone()) {
458            out.duplicate_ids.push(proposal.id.clone());
459        }
460        let target_known = match proposal.target.r#type.as_str() {
461            "finding" => {
462                proposal.kind == "finding.add" || finding_ids.contains(proposal.target.id.as_str())
463            }
464            "artifact" => {
465                proposal.kind == "artifact.assert"
466                    || artifact_ids.contains(proposal.target.id.as_str())
467            }
468            _ => true,
469        };
470        if !target_known {
471            out.invalid_targets.push(proposal.target.id.clone());
472        }
473    }
474    out.duplicate_ids.sort();
475    out.duplicate_ids.dedup();
476    out.invalid_targets.sort();
477    out.invalid_targets.dedup();
478    out
479}
480
481pub fn proposals_for_finding<'a>(
482    frontier: &'a Project,
483    finding_id: &str,
484) -> Vec<&'a StateProposal> {
485    frontier
486        .proposals
487        .iter()
488        .filter(|proposal| proposal.target.r#type == "finding" && proposal.target.id == finding_id)
489        .collect()
490}
491
492/// Phase P (v0.5): upsert by content address. If a proposal with the same
493/// `vpr_…` already exists in the frontier, return the existing record instead
494/// of inserting a duplicate. Combined with the `created_at`-free preimage,
495/// this makes agent retries idempotent at the substrate level.
496///
497/// Decision creation is intentionally absent from this insertion primitive.
498pub fn insert_pending_in_frontier(
499    frontier: &mut Project,
500    proposal: StateProposal,
501) -> Result<CreateProposalResult, String> {
502    let finding_id = proposal.target.id.clone();
503    let proposal_id = proposal.id.clone();
504    if let Some(existing) = frontier
505        .proposals
506        .iter()
507        .find(|existing| existing.id == proposal_id)
508    {
509        return Ok(CreateProposalResult {
510            proposal_id,
511            finding_id,
512            status: existing.status.clone(),
513            applied_event_id: existing.applied_event_id.clone(),
514        });
515    }
516
517    validate_new_proposal(frontier, &proposal)?;
518    frontier.proposals.push(proposal);
519    // Split repositories load proposal files in filename/id order. Keep every
520    // in-memory insertion in that same canonical order so a transaction's
521    // rendered postimage remains byte-identical after a subsequent official
522    // materialization.
523    frontier
524        .proposals
525        .sort_by(|left, right| left.id.cmp(&right.id));
526    project::recompute_stats(frontier);
527    Ok(CreateProposalResult {
528        proposal_id,
529        finding_id,
530        status: "pending_review".to_string(),
531        applied_event_id: None,
532    })
533}
534
535pub fn insert_pending_at_path(
536    path: &Path,
537    proposal: StateProposal,
538) -> Result<CreateProposalResult, String> {
539    let mut frontier = repo::load_from_path(path)?;
540    let result = insert_pending_in_frontier(&mut frontier, proposal)?;
541    repo::save_to_path(path, &frontier)?;
542    Ok(result)
543}
544
545pub fn list(frontier: &Project, status: Option<&str>) -> Vec<StateProposal> {
546    let mut proposals = frontier
547        .proposals
548        .iter()
549        .filter(|proposal| status.is_none_or(|wanted| proposal.status == wanted))
550        .cloned()
551        .collect::<Vec<_>>();
552    proposals.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
553    proposals
554}
555
556pub fn show<'a>(frontier: &'a Project, proposal_id: &str) -> Result<&'a StateProposal, String> {
557    frontier
558        .proposals
559        .iter()
560        .find(|proposal| proposal.id == proposal_id)
561        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))
562}
563
564pub fn preview_at_path(
565    path: &Path,
566    proposal_id: &str,
567    reviewer: &str,
568) -> Result<ProposalPreview, String> {
569    validate_reviewer_identity(reviewer)?;
570    let frontier = repo::load_from_path(path)?;
571    preview_in_frontier(&frontier, proposal_id, reviewer)
572}
573
574pub fn preview_in_frontier(
575    frontier: &Project,
576    proposal_id: &str,
577    reviewer: &str,
578) -> Result<ProposalPreview, String> {
579    validate_reviewer_identity(reviewer)?;
580    let proposal = frontier
581        .proposals
582        .iter()
583        .find(|proposal| proposal.id == proposal_id)
584        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?
585        .clone();
586    if proposal.status == "applied" {
587        let applied_event_id = proposal
588            .applied_event_id
589            .clone()
590            .ok_or_else(|| format!("Proposal {} is applied but has no event id", proposal.id))?;
591        return Ok(ProposalPreview {
592            proposal_id: proposal.id,
593            kind: proposal.kind,
594            changed_findings: changed_targets_for_type(frontier, &proposal.target, "finding"),
595            changed_finding_details: Vec::new(),
596            changed_artifacts: changed_targets_for_type(frontier, &proposal.target, "artifact"),
597            new_event_ids: vec![applied_event_id.clone()],
598            event_kinds: frontier
599                .events
600                .iter()
601                .find(|event| event.id == applied_event_id)
602                .map(|event| vec![event.kind.to_string()])
603                .unwrap_or_default(),
604            target: proposal.target,
605            reviewer: reviewer.to_string(),
606            findings_before: frontier.findings.len(),
607            findings_after: frontier.findings.len(),
608            findings_delta: 0,
609            artifacts_before: frontier.artifacts.len(),
610            artifacts_after: frontier.artifacts.len(),
611            artifacts_delta: 0,
612            events_before: frontier.events.len(),
613            events_after: frontier.events.len(),
614            events_delta: 0,
615            proof_would_be_stale: false,
616            applied_event_id,
617        });
618    }
619    if !matches!(proposal.status.as_str(), "pending_review" | "accepted") {
620        return Err(format!(
621            "Proposal {} cannot be previewed from status {}",
622            proposal.id, proposal.status
623        ));
624    }
625    let mut preview_state: Project = serde_json::from_value(
626        serde_json::to_value(frontier).map_err(|e| format!("serialize frontier preview: {e}"))?,
627    )
628    .map_err(|e| format!("clone frontier preview: {e}"))?;
629    let finding_ids_before = preview_state
630        .findings
631        .iter()
632        .map(|finding| finding.id.clone())
633        .collect::<BTreeSet<_>>();
634    let artifact_ids_before = preview_state
635        .artifacts
636        .iter()
637        .map(|artifact| artifact.id.clone())
638        .collect::<BTreeSet<_>>();
639    let findings_before = preview_state.findings.len();
640    let artifacts_before = preview_state.artifacts.len();
641    let events_before = preview_state.events.len();
642    let event_id = apply_proposal(
643        &mut preview_state,
644        &proposal,
645        reviewer,
646        "Preview proposal application",
647        None,
648    )?;
649    let findings_after = preview_state.findings.len();
650    let artifacts_after = preview_state.artifacts.len();
651    let events_after = preview_state.events.len();
652    let new_events = preview_state
653        .events
654        .iter()
655        .skip(events_before)
656        .cloned()
657        .collect::<Vec<_>>();
658    let changed_findings = changed_finding_ids(&preview_state, &finding_ids_before, &new_events);
659    let changed_finding_details =
660        build_changed_finding_details(frontier, &preview_state, &changed_findings);
661    Ok(ProposalPreview {
662        proposal_id: proposal.id,
663        kind: proposal.kind,
664        target: proposal.target,
665        reviewer: reviewer.to_string(),
666        changed_findings,
667        changed_finding_details,
668        changed_artifacts: changed_artifact_ids(&preview_state, &artifact_ids_before, &new_events),
669        new_event_ids: new_events.iter().map(|event| event.id.clone()).collect(),
670        event_kinds: new_events
671            .iter()
672            .map(|event| event.kind.to_string())
673            .collect(),
674        findings_before,
675        findings_after,
676        findings_delta: findings_after as isize - findings_before as isize,
677        artifacts_before,
678        artifacts_after,
679        artifacts_delta: artifacts_after as isize - artifacts_before as isize,
680        events_before,
681        events_after,
682        events_delta: events_after as isize - events_before as isize,
683        proof_would_be_stale: true,
684        applied_event_id: event_id,
685    })
686}
687
688fn changed_targets_for_type(
689    frontier: &Project,
690    target: &StateTarget,
691    target_type: &str,
692) -> Vec<String> {
693    let known = match target_type {
694        "finding" => frontier
695            .findings
696            .iter()
697            .any(|finding| finding.id == target.id),
698        "artifact" => frontier
699            .artifacts
700            .iter()
701            .any(|artifact| artifact.id == target.id),
702        _ => false,
703    };
704    if target.r#type == target_type && known {
705        vec![target.id.clone()]
706    } else {
707        Vec::new()
708    }
709}
710
711fn changed_finding_ids(
712    preview_state: &Project,
713    finding_ids_before: &BTreeSet<String>,
714    new_events: &[StateEvent],
715) -> Vec<String> {
716    let mut ids = preview_state
717        .findings
718        .iter()
719        .filter(|finding| !finding_ids_before.contains(&finding.id))
720        .map(|finding| finding.id.clone())
721        .collect::<BTreeSet<_>>();
722    for event in new_events {
723        if event.target.r#type == "finding" {
724            ids.insert(event.target.id.clone());
725        }
726    }
727    ids.into_iter().collect()
728}
729
730fn changed_artifact_ids(
731    preview_state: &Project,
732    artifact_ids_before: &BTreeSet<String>,
733    new_events: &[StateEvent],
734) -> Vec<String> {
735    let mut ids = preview_state
736        .artifacts
737        .iter()
738        .filter(|artifact| !artifact_ids_before.contains(&artifact.id))
739        .map(|artifact| artifact.id.clone())
740        .collect::<BTreeSet<_>>();
741    for event in new_events {
742        if event.target.r#type == "artifact" {
743            ids.insert(event.target.id.clone());
744        }
745    }
746    ids.into_iter().collect()
747}
748
749pub fn validate_source(source: &Path) -> Result<ProposalValidationReport, String> {
750    let proposals = load_proposals(source)?;
751    let mut report = ProposalValidationReport {
752        checked: proposals.len(),
753        ..ProposalValidationReport::default()
754    };
755    let scratch = project::assemble("proposal-validation", Vec::new(), 0, 0, "validate");
756    let mut seen = BTreeSet::new();
757    for proposal in proposals {
758        if !seen.insert(proposal.id.clone()) {
759            report.invalid += 1;
760            report
761                .errors
762                .push(format!("Duplicate proposal id {}", proposal.id));
763            continue;
764        }
765        report.proposal_ids.push(proposal.id.clone());
766        match validate_standalone_proposal(&scratch, &proposal) {
767            Ok(()) => report.valid += 1,
768            Err(err) => {
769                report.invalid += 1;
770                report.errors.push(format!("{}: {}", proposal.id, err));
771            }
772        }
773    }
774    report.ok = report.invalid == 0;
775    Ok(report)
776}
777
778pub fn export_to_path(
779    frontier_path: &Path,
780    output: &Path,
781    status: Option<&str>,
782) -> Result<usize, String> {
783    let frontier = repo::load_from_path(frontier_path)?;
784    let proposals = list(&frontier, status);
785    let json = serde_json::to_string_pretty(&proposals)
786        .map_err(|e| format!("Failed to serialize proposals for export: {e}"))?;
787    std::fs::write(output, json).map_err(|e| {
788        format!(
789            "Failed to write proposal export '{}': {e}",
790            output.display()
791        )
792    })?;
793    Ok(proposals.len())
794}
795
796/// The Engine's read on an acceptance: what Evidence CI says about the
797/// state the change would produce. Recomputable at any time from
798/// `evidence_ci::run_project`; this captures the *delta* a single
799/// acceptance introduces, which is what a reviewer (or the gate) acts on.
800#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
801pub struct EngineVerdict {
802    /// `pass` (clean), `warn` (new review warnings), `blocked` (would be
803    /// gated; only seen on the preview/error path), or `forced` (gated but
804    /// overridden with --force and persisted).
805    pub status: String,
806    /// Release-blocking checks newly failing because of this change.
807    pub new_blocking: Vec<String>,
808    /// Review-readiness warnings this change introduces.
809    pub new_warnings: Vec<String>,
810    /// Whether a gate was overridden with --force.
811    pub forced: bool,
812    /// Whether warnings were treated as blocking (--strict).
813    pub strict: bool,
814    /// Post-accept Evidence CI counts, for context in the readout.
815    pub release_blocking_failed: usize,
816    pub warnings: usize,
817}
818
819/// A proposal kind is truth-bearing when accepting it changes what the
820/// frontier asserts about the world. Process/provenance records, governance
821/// cleanup, and mechanical repairs are not. This classification controls the
822/// Engine gate only; it does not grant decision authority.
823pub fn is_truth_bearing_kind(kind: &str) -> bool {
824    !(NON_TRUTH_BEARING_KINDS.contains(&kind) || MECHANICAL_REPAIR_KINDS.contains(&kind))
825}
826
827/// Evaluate one already-prepared candidate transaction under the strict Engine
828/// gate without applying proposals again.
829///
830/// Evidence CI is computed exactly once before and once after. New release
831/// failures or review warnings block only when at least one accepted proposal
832/// kind is truth-bearing; rejects and mechanical/process accepts remain visible
833/// in the counts but cannot turn Evidence CI into a truth oracle. The function
834/// mutates nothing and performs no path access beyond Evidence CI's bounded
835/// verifier observations.
836pub fn strict_engine_verdict_for_candidate(
837    original: &Project,
838    candidate: &Project,
839    frontier_path: &Path,
840    accepted_kinds: &[String],
841) -> EngineVerdict {
842    let before = crate::evidence_ci::run_project(original, frontier_path);
843    let after = crate::evidence_ci::run_project(candidate, frontier_path);
844    let before_blocking = crate::evidence_ci::release_blocking_failures(&before);
845    let before_warnings = crate::evidence_ci::review_warnings(&before);
846    let new_blocking = crate::evidence_ci::release_blocking_failures(&after)
847        .difference(&before_blocking)
848        .cloned()
849        .collect::<Vec<_>>();
850    let new_warnings = crate::evidence_ci::review_warnings(&after)
851        .difference(&before_warnings)
852        .cloned()
853        .collect::<Vec<_>>();
854    let gates = accepted_kinds
855        .iter()
856        .any(|kind| is_truth_bearing_kind(kind));
857    let status = if gates && (!new_blocking.is_empty() || !new_warnings.is_empty()) {
858        "blocked"
859    } else if !new_warnings.is_empty() {
860        "warn"
861    } else {
862        "pass"
863    }
864    .to_string();
865    EngineVerdict {
866        status,
867        new_blocking,
868        new_warnings,
869        forced: false,
870        strict: true,
871        release_blocking_failed: after.summary.release_blocking_failed,
872        warnings: after.summary.warnings,
873    }
874}
875
876/// Compute the Engine verdict a candidate acceptance *would* produce,
877/// without persisting anything. Drives the review-time preview ("what
878/// would CI say if I accept this?") on the CLI and the Workbench.
879pub fn preview_engine_verdict(path: &Path, proposal_id: &str) -> Result<EngineVerdict, String> {
880    let frontier = repo::load_from_path(path)?;
881    preview_engine_verdict_in_frontier(&frontier, path, proposal_id, false)
882}
883
884/// Pure Engine preview over an already staged frontier projection.
885///
886/// Submission uses this before policy routing so the exact gate result can be
887/// committed to its private transaction plan even when the proposal has not
888/// yet been installed on disk. The clone is serialized rather than relying on
889/// a partial hand-maintained projection of [`Project`].
890pub fn preview_engine_verdict_in_frontier(
891    frontier: &Project,
892    path: &Path,
893    proposal_id: &str,
894    strict: bool,
895) -> Result<EngineVerdict, String> {
896    let kind = frontier
897        .proposals
898        .iter()
899        .find(|p| p.id == proposal_id)
900        .map(|p| p.kind.clone())
901        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?;
902
903    let before = crate::evidence_ci::run_project(frontier, path);
904    let before_blocking = crate::evidence_ci::release_blocking_failures(&before);
905    let before_warn = crate::evidence_ci::review_warnings(&before);
906
907    // Apply on this in-memory copy under a synthetic reviewer; never saved.
908    let encoded = serde_json::to_value(frontier).map_err(|error| error.to_string())?;
909    let mut candidate: Project =
910        serde_json::from_value(encoded).map_err(|error| error.to_string())?;
911    accept_proposal_in_frontier_with_authority_at(
912        &mut candidate,
913        proposal_id,
914        "reviewer:engine-preview",
915        "engine ci preview",
916        DecisionAuthority::Preview,
917        None,
918        None,
919        false,
920    )?;
921
922    let after = crate::evidence_ci::run_project(&candidate, path);
923    let new_blocking: Vec<String> = crate::evidence_ci::release_blocking_failures(&after)
924        .difference(&before_blocking)
925        .cloned()
926        .collect();
927    let new_warnings: Vec<String> = crate::evidence_ci::review_warnings(&after)
928        .difference(&before_warn)
929        .cloned()
930        .collect();
931
932    let status = if is_truth_bearing_kind(&kind)
933        && (!new_blocking.is_empty() || (strict && !new_warnings.is_empty()))
934    {
935        "blocked"
936    } else if !new_warnings.is_empty() {
937        "warn"
938    } else {
939        "pass"
940    }
941    .to_string();
942
943    Ok(EngineVerdict {
944        status,
945        new_blocking,
946        new_warnings,
947        forced: false,
948        strict,
949        release_blocking_failed: after.summary.release_blocking_failed,
950        warnings: after.summary.warnings,
951    })
952}
953
954pub fn record_proof_export(frontier: &mut Project, record: ProofPacketRecord) {
955    let nonlease_event_log_hash = (record.event_log_hash
956        == events::event_log_hash(&frontier.events))
957    .then(|| events::nonlease_event_log_hash(&frontier.events));
958    frontier.proof_state.latest_packet = ProofPacketState {
959        generated_at: Some(record.generated_at),
960        snapshot_hash: Some(record.snapshot_hash),
961        event_log_hash: Some(record.event_log_hash),
962        // The derived exemption is granted only when the exporter supplied
963        // the exact current full event root. A malformed or mismatched record
964        // retains the historical shape and fails freshness normally.
965        nonlease_event_log_hash,
966        packet_manifest_hash: Some(record.packet_manifest_hash),
967        status: "current".to_string(),
968    };
969    frontier.proof_state.last_event_at_export =
970        frontier.events.last().map(|event| event.timestamp.clone());
971    frontier.proof_state.stale_reason = None;
972}
973
974/// Upgrade a historical proof-state record to the explicit non-lease
975/// commitment only when its old full-root commitment already proves that no
976/// non-lease event has changed.
977///
978/// Returning `false` is deliberately non-mutating. A stale, incomplete, or
979/// ambiguous record must be re-exported rather than repaired by inference.
980pub fn backfill_nonlease_proof_root(frontier: &mut Project) -> bool {
981    let state = &frontier.proof_state.latest_packet;
982    if state.status == "never_exported"
983        || state.status == "stale"
984        || state.nonlease_event_log_hash.is_some()
985    {
986        return false;
987    }
988    let Some(recorded_event_root) = state.event_log_hash.as_deref() else {
989        return false;
990    };
991    let full_root = events::event_log_hash(&frontier.events);
992    let nonlease_root = events::nonlease_event_log_hash(&frontier.events);
993    if recorded_event_root != full_root && recorded_event_root != nonlease_root {
994        return false;
995    }
996    frontier.proof_state.latest_packet.nonlease_event_log_hash = Some(nonlease_root);
997    true
998}
999
1000pub fn mark_proof_stale(frontier: &mut Project, reason: String) {
1001    if frontier.proof_state.latest_packet.status != "never_exported" {
1002        frontier.proof_state.latest_packet.status = "stale".to_string();
1003        frontier.proof_state.stale_reason = Some(reason);
1004    }
1005}
1006
1007pub fn proof_state_json(proof_state: &ProofState) -> Value {
1008    serde_json::to_value(proof_state).unwrap_or_else(|_| json!({"status": "never_exported"}))
1009}
1010
1011pub fn proposal_state_hash(proposals: &[StateProposal]) -> String {
1012    let bytes = canonical::to_canonical_bytes(proposals).unwrap_or_default();
1013    hex::encode(Sha256::digest(bytes))
1014}
1015
1016fn load_proposals(source: &Path) -> Result<Vec<StateProposal>, String> {
1017    if source.is_file() {
1018        let data = std::fs::read_to_string(source)
1019            .map_err(|e| format!("Failed to read proposal file '{}': {e}", source.display()))?;
1020        if let Ok(proposals) = serde_json::from_str::<Vec<StateProposal>>(&data) {
1021            return Ok(proposals);
1022        }
1023        let proposal = serde_json::from_str::<StateProposal>(&data)
1024            .map_err(|e| format!("Failed to parse proposal JSON '{}': {e}", source.display()))?;
1025        return Ok(vec![proposal]);
1026    }
1027    if source.is_dir() {
1028        let mut entries = std::fs::read_dir(source)
1029            .map_err(|e| format!("Failed to read proposal dir '{}': {e}", source.display()))?
1030            .filter_map(|entry| entry.ok().map(|entry| entry.path()))
1031            .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
1032            .collect::<Vec<_>>();
1033        entries.sort();
1034        let mut proposals = Vec::new();
1035        for path in entries {
1036            proposals.extend(load_proposals(&path)?);
1037        }
1038        return Ok(proposals);
1039    }
1040    Err(format!(
1041        "Proposal source does not exist: {}",
1042        source.display()
1043    ))
1044}
1045
1046fn validate_new_proposal(frontier: &Project, proposal: &StateProposal) -> Result<(), String> {
1047    if proposal.schema != PROPOSAL_SCHEMA {
1048        return Err(format!("Unsupported proposal schema '{}'", proposal.schema));
1049    }
1050    if frontier
1051        .proposals
1052        .iter()
1053        .any(|existing| existing.id == proposal.id)
1054    {
1055        return Err(format!("Duplicate proposal id {}", proposal.id));
1056    }
1057    validate_proposal_shape(frontier, proposal)?;
1058    validate_decision_state(proposal)
1059}
1060
1061fn validate_proposal_shape(frontier: &Project, proposal: &StateProposal) -> Result<(), String> {
1062    // v0.52: relax the finding-only constraint so the agent inbox
1063    // can deposit nulls and trajectories through the same review-
1064    // gated flow as findings. The proposal-kind dispatch below
1065    // enforces that target.type matches the kind family.
1066    if !matches!(
1067        proposal.target.r#type.as_str(),
1068        "finding" | "artifact" | "evidence_atom" | "frontier_observation" | "governance"
1069    ) {
1070        return Err(format!(
1071            "Unsupported proposal target type '{}'; valid: finding, artifact, evidence_atom, frontier_observation, governance",
1072            proposal.target.r#type
1073        ));
1074    }
1075    if proposal.reason.trim().is_empty() {
1076        return Err("Proposal reason must be non-empty".to_string());
1077    }
1078    if !matches!(
1079        proposal.status.as_str(),
1080        "pending_review" | "accepted" | "rejected" | "applied" | "withdrawn"
1081    ) {
1082        return Err(format!("Unsupported proposal status '{}'", proposal.status));
1083    }
1084    match proposal.kind.as_str() {
1085        policy_accept::POLICY_HEAD_PROPOSAL_KIND => {
1086            policy_accept::validate_policy_head_proposal(frontier, proposal)?;
1087        }
1088        policy_accept::LEGACY_POLICY_RETIREMENT_PROPOSAL_KIND => {
1089            policy_accept::validate_legacy_policy_retirement_proposal(frontier, proposal)?;
1090        }
1091        "finding.add" => {
1092            let finding_value = proposal
1093                .payload
1094                .get("finding")
1095                .ok_or("finding.add proposal missing payload.finding")?
1096                .clone();
1097            let finding: FindingBundle = serde_json::from_value(finding_value)
1098                .map_err(|e| format!("Invalid finding.add payload: {e}"))?;
1099            if finding.id != proposal.target.id {
1100                return Err(format!(
1101                    "finding.add target {} does not match payload finding {}",
1102                    proposal.target.id, finding.id
1103                ));
1104            }
1105            if frontier
1106                .findings
1107                .iter()
1108                .any(|existing| existing.id == proposal.target.id)
1109            {
1110                return Err(format!(
1111                    "Refusing to add duplicate finding with existing finding ID {}",
1112                    proposal.target.id
1113                ));
1114            }
1115            if let Some(submission) = proposal.payload.get("vela_submission") {
1116                validate_submission_links(submission)?;
1117            }
1118        }
1119        "finding.review" => {
1120            require_existing_finding(frontier, &proposal.target.id)?;
1121            let status = proposal
1122                .payload
1123                .get("status")
1124                .and_then(Value::as_str)
1125                .ok_or("finding.review proposal missing payload.status")?;
1126            if !matches!(
1127                status,
1128                "accepted" | "approved" | "contested" | "needs_revision" | "rejected"
1129            ) {
1130                return Err(format!("Unsupported review proposal status '{status}'"));
1131            }
1132        }
1133        "finding.caveat" => {
1134            require_existing_finding(frontier, &proposal.target.id)?;
1135            let text = proposal
1136                .payload
1137                .get("text")
1138                .and_then(Value::as_str)
1139                .ok_or("finding.caveat proposal missing payload.text")?;
1140            if text.trim().is_empty() {
1141                return Err("finding.caveat payload.text must be non-empty".to_string());
1142            }
1143        }
1144        "finding.note" => {
1145            require_existing_finding(frontier, &proposal.target.id)?;
1146            let text = proposal
1147                .payload
1148                .get("text")
1149                .and_then(Value::as_str)
1150                .ok_or("finding.note proposal missing payload.text")?;
1151            if text.trim().is_empty() {
1152                return Err("finding.note payload.text must be non-empty".to_string());
1153            }
1154        }
1155        "finding.confidence_revise" => {
1156            require_existing_finding(frontier, &proposal.target.id)?;
1157            let score = proposal
1158                .payload
1159                .get("confidence")
1160                .and_then(Value::as_f64)
1161                .ok_or("finding.confidence_revise proposal missing payload.confidence")?;
1162            if !(0.0..=1.0).contains(&score) {
1163                return Err(
1164                    "finding.confidence_revise confidence must be between 0.0 and 1.0".to_string(),
1165                );
1166            }
1167        }
1168        "finding.reject" => {
1169            require_existing_finding(frontier, &proposal.target.id)?;
1170        }
1171        "finding.contribution.recorded" => {
1172            require_existing_finding(frontier, &proposal.target.id)?;
1173            let contribution: crate::bundle::Contribution =
1174                serde_json::from_value(proposal.payload.get("contribution").cloned().ok_or(
1175                    "finding.contribution.recorded proposal missing payload.contribution",
1176                )?)
1177                .map_err(|e| format!("malformed contribution: {e}"))?;
1178            contribution.validate()?;
1179        }
1180        "finding.retract" => {
1181            let idx = require_existing_finding(frontier, &proposal.target.id)?;
1182            if frontier.findings[idx].flags.retracted {
1183                return Err(format!(
1184                    "Finding {} is already retracted",
1185                    proposal.target.id
1186                ));
1187            }
1188        }
1189        "finding.supersede" => {
1190            let idx = require_existing_finding(frontier, &proposal.target.id)?;
1191            if frontier.findings[idx].flags.superseded {
1192                return Err(format!(
1193                    "Finding {} is already superseded",
1194                    proposal.target.id
1195                ));
1196            }
1197            let new_finding_value = proposal
1198                .payload
1199                .get("new_finding")
1200                .ok_or("finding.supersede proposal missing payload.new_finding")?
1201                .clone();
1202            let new_finding: FindingBundle = serde_json::from_value(new_finding_value)
1203                .map_err(|e| format!("Invalid finding.supersede payload.new_finding: {e}"))?;
1204            if new_finding.id == proposal.target.id {
1205                return Err(
1206                    "finding.supersede new_finding has same content address as the superseded target — change assertion text, type, or provenance to derive a distinct vf_…".to_string(),
1207                );
1208            }
1209            if frontier
1210                .findings
1211                .iter()
1212                .any(|existing| existing.id == new_finding.id)
1213            {
1214                return Err(format!(
1215                    "Refusing to add superseding finding with existing finding ID {}",
1216                    new_finding.id
1217                ));
1218            }
1219        }
1220        "artifact.assert" => {
1221            if proposal.target.r#type != "artifact" {
1222                return Err(format!(
1223                    "artifact.assert proposal target.type must be 'artifact', got '{}'",
1224                    proposal.target.r#type
1225                ));
1226            }
1227            let artifact_value = proposal
1228                .payload
1229                .get("artifact")
1230                .ok_or("artifact.assert proposal missing payload.artifact")?
1231                .clone();
1232            let artifact: Artifact = serde_json::from_value(artifact_value)
1233                .map_err(|e| format!("Invalid artifact.assert payload: {e}"))?;
1234            if artifact.id != proposal.target.id {
1235                return Err(format!(
1236                    "artifact.assert target {} does not match payload id {}",
1237                    proposal.target.id, artifact.id
1238                ));
1239            }
1240            if frontier.artifacts.iter().any(|a| a.id == artifact.id) {
1241                return Err(format!(
1242                    "Refusing to add duplicate artifact with existing id {}",
1243                    artifact.id
1244                ));
1245            }
1246        }
1247        "artifact.retract" => {
1248            if proposal.target.r#type != "artifact" {
1249                return Err(format!(
1250                    "artifact.retract proposal target.type must be 'artifact', got '{}'",
1251                    proposal.target.r#type
1252                ));
1253            }
1254            if proposal.reason.trim().is_empty() {
1255                return Err("artifact.retract proposal reason must be non-empty".to_string());
1256            }
1257            let artifact = frontier
1258                .artifacts
1259                .iter()
1260                .find(|artifact| artifact.id == proposal.target.id)
1261                .ok_or_else(|| format!("Artifact not found: {}", proposal.target.id))?;
1262            if artifact.retracted {
1263                return Err(format!("Artifact {} is already retracted", artifact.id));
1264            }
1265        }
1266        "verifier.attach" => {
1267            if proposal.target.r#type != "finding" {
1268                return Err(format!(
1269                    "verifier.attach proposal target.type must be 'finding', got '{}'",
1270                    proposal.target.r#type
1271                ));
1272            }
1273            let value = proposal
1274                .payload
1275                .get("attachment")
1276                .ok_or("verifier.attach proposal missing payload.attachment")?
1277                .clone();
1278            let att: crate::verifier_attachment::VerifierAttachment = serde_json::from_value(value)
1279                .map_err(|e| format!("Invalid verifier.attach payload: {e}"))?;
1280            att.verify()
1281                .map_err(|e| format!("verifier.attach attachment malformed: {e}"))?;
1282            if att.target != proposal.target.id {
1283                return Err(format!(
1284                    "verifier.attach attachment.target {} does not match proposal target {}",
1285                    att.target, proposal.target.id
1286                ));
1287            }
1288        }
1289        // v0.57: Mechanical finding-level span repair. Appends a
1290        // `{section, text}` span to the finding's evidence_spans.
1291        "finding.span_repair" => {
1292            if proposal.target.r#type != "finding" {
1293                return Err(format!(
1294                    "finding.span_repair target.type must be 'finding', got '{}'",
1295                    proposal.target.r#type
1296                ));
1297            }
1298            require_existing_finding(frontier, &proposal.target.id)?;
1299            let section = proposal
1300                .payload
1301                .get("section")
1302                .and_then(Value::as_str)
1303                .ok_or("finding.span_repair proposal missing payload.section")?;
1304            if section.trim().is_empty() {
1305                return Err("finding.span_repair payload.section must be non-empty".to_string());
1306            }
1307            let text = proposal
1308                .payload
1309                .get("text")
1310                .and_then(Value::as_str)
1311                .ok_or("finding.span_repair proposal missing payload.text")?;
1312            if text.trim().is_empty() {
1313                return Err("finding.span_repair payload.text must be non-empty".to_string());
1314            }
1315        }
1316        // v0.56: Mechanical evidence-atom locator repair. Targets one
1317        // evidence atom by id; payload carries the resolved locator
1318        // string and the parent source id it was derived from. The
1319        // proposal is mechanical: the locator is already present on
1320        // `frontier.sources[atom.source_id].locator`. A Decision Plan accepts
1321        // it and the canonical event lands the locator
1322        // on the atom while preserving the derivation in the payload.
1323        "evidence_atom.locator_repair" => {
1324            if proposal.target.r#type != "evidence_atom" {
1325                return Err(format!(
1326                    "evidence_atom.locator_repair target.type must be 'evidence_atom', got '{}'",
1327                    proposal.target.r#type
1328                ));
1329            }
1330            let atom_id = proposal.target.id.as_str();
1331            let atom = frontier
1332                .evidence_atoms
1333                .iter()
1334                .find(|atom| atom.id == atom_id)
1335                .ok_or_else(|| {
1336                    format!("evidence_atom.locator_repair targets unknown atom {atom_id}")
1337                })?;
1338            let locator = proposal
1339                .payload
1340                .get("locator")
1341                .and_then(Value::as_str)
1342                .ok_or("evidence_atom.locator_repair proposal missing payload.locator")?;
1343            if locator.trim().is_empty() {
1344                return Err(
1345                    "evidence_atom.locator_repair payload.locator must be non-empty".to_string(),
1346                );
1347            }
1348            let source_id = proposal
1349                .payload
1350                .get("source_id")
1351                .and_then(Value::as_str)
1352                .ok_or("evidence_atom.locator_repair proposal missing payload.source_id")?;
1353            if source_id.trim().is_empty() {
1354                return Err(
1355                    "evidence_atom.locator_repair payload.source_id must be non-empty".to_string(),
1356                );
1357            }
1358            if atom.source_id != source_id {
1359                return Err(format!(
1360                    "evidence_atom.locator_repair payload.source_id '{source_id}' does not match atom.source_id '{}'",
1361                    atom.source_id
1362                ));
1363            }
1364            // Refuse a no-op repair so the curation pipeline doesn't
1365            // emit empty events. An atom that already carries the same
1366            // locator should be filtered upstream.
1367            if let Some(existing) = &atom.locator
1368                && existing == locator
1369            {
1370                return Err(format!(
1371                    "evidence_atom {atom_id} already carries locator '{existing}'"
1372                ));
1373            }
1374            // Refuse a divergent overwrite. A different existing
1375            // locator is a chain-integrity issue, not a repair.
1376            if let Some(existing) = &atom.locator
1377                && existing != locator
1378            {
1379                return Err(format!(
1380                    "evidence_atom {atom_id} already carries locator '{existing}'; refusing to overwrite with '{locator}'"
1381                ));
1382            }
1383        }
1384        "research_trace.review" => {
1385            validate_research_trace_review_payload(proposal)?;
1386        }
1387        "correction_return.review" => {
1388            validate_correction_return_review_payload(proposal)?;
1389        }
1390        other => {
1391            return Err(format!("Unsupported proposal kind '{other}'"));
1392        }
1393    }
1394    Ok(())
1395}
1396
1397fn validate_submission_links(value: &Value) -> Result<(), String> {
1398    let object = value
1399        .as_object()
1400        .ok_or("finding.add payload.vela_submission must be an object")?;
1401    if object.get("schema").and_then(Value::as_str) != Some("vela.submission-links.internal.v1") {
1402        return Err("finding.add payload.vela_submission has an unsupported schema".to_string());
1403    }
1404    let valid_prefixed_digest = |field: &str, prefix: &str| -> Result<(), String> {
1405        let value = object
1406            .get(field)
1407            .and_then(Value::as_str)
1408            .ok_or_else(|| format!("vela_submission.{field} must be a string"))?;
1409        let digest = value
1410            .strip_prefix(prefix)
1411            .ok_or_else(|| format!("vela_submission.{field} must start with {prefix}"))?;
1412        if digest.len() != 64
1413            || !digest
1414                .bytes()
1415                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1416        {
1417            return Err(format!(
1418                "vela_submission.{field} must contain 64 lowercase hex characters"
1419            ));
1420        }
1421        Ok(())
1422    };
1423    valid_prefixed_digest("receipt_root", "sha256:")?;
1424    valid_prefixed_digest("operation_id", "vop_")?;
1425    let record_id = object
1426        .get("record_id")
1427        .and_then(Value::as_str)
1428        .unwrap_or_default();
1429    if !record_id.strip_prefix("vrc_").is_some_and(|id| {
1430        id.len() == 16
1431            && id
1432                .bytes()
1433                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1434    }) {
1435        return Err("vela_submission.record_id must be vrc_<16 lowercase hex>".to_string());
1436    }
1437    let receipt_path = object
1438        .get("receipt_path")
1439        .and_then(Value::as_str)
1440        .unwrap_or_default();
1441    let path = std::path::Path::new(receipt_path);
1442    if receipt_path.is_empty()
1443        || path.is_absolute()
1444        || path.components().any(|component| {
1445            matches!(
1446                component,
1447                std::path::Component::ParentDir
1448                    | std::path::Component::RootDir
1449                    | std::path::Component::Prefix(_)
1450            )
1451        })
1452    {
1453        return Err("vela_submission.receipt_path must be frontier-relative".to_string());
1454    }
1455    if let Some(review_path) = object.get("review_material_path").and_then(Value::as_str) {
1456        let receipt_digest = object
1457            .get("receipt_root")
1458            .and_then(Value::as_str)
1459            .and_then(|root| root.strip_prefix("sha256:"))
1460            .unwrap_or_default();
1461        let expected = format!("records/review/sha256/{receipt_digest}.json");
1462        if review_path != expected {
1463            return Err(format!(
1464                "vela_submission.review_material_path must be {expected}"
1465            ));
1466        }
1467    }
1468    Ok(())
1469}
1470
1471fn validate_decision_state(proposal: &StateProposal) -> Result<(), String> {
1472    match proposal.status.as_str() {
1473        "pending_review" => Ok(()),
1474        "accepted" | "applied" | "rejected" => {
1475            let reviewer = proposal
1476                .reviewed_by
1477                .as_deref()
1478                .ok_or_else(|| format!("Proposal {} missing reviewed_by", proposal.id))?;
1479            validate_reviewer_identity(reviewer)?;
1480            if proposal
1481                .decision_reason
1482                .as_deref()
1483                .is_none_or(|reason| reason.trim().is_empty())
1484            {
1485                return Err(format!("Proposal {} missing decision_reason", proposal.id));
1486            }
1487            if proposal.status == "applied" && proposal.applied_event_id.is_none() {
1488                return Err(format!(
1489                    "Applied proposal {} missing applied_event_id",
1490                    proposal.id
1491                ));
1492            }
1493            Ok(())
1494        }
1495        "withdrawn" => {
1496            if proposal.reviewed_by.is_some()
1497                || proposal.reviewed_at.is_some()
1498                || proposal.applied_event_id.is_some()
1499            {
1500                return Err(format!(
1501                    "Withdrawn proposal {} must not carry human review fields",
1502                    proposal.id
1503                ));
1504            }
1505            if proposal
1506                .decision_reason
1507                .as_deref()
1508                .is_none_or(|reason| reason.trim().is_empty())
1509            {
1510                return Err(format!("Withdrawn proposal {} missing reason", proposal.id));
1511            }
1512            Ok(())
1513        }
1514        other => Err(format!("Unsupported proposal status '{}'", other)),
1515    }
1516}
1517
1518fn validate_standalone_proposal(
1519    _frontier: &Project,
1520    proposal: &StateProposal,
1521) -> Result<(), String> {
1522    if proposal.schema != PROPOSAL_SCHEMA {
1523        return Err(format!("Unsupported proposal schema '{}'", proposal.schema));
1524    }
1525    if !matches!(
1526        proposal.target.r#type.as_str(),
1527        "finding" | "artifact" | "evidence_atom" | "frontier_observation" | "governance"
1528    ) {
1529        return Err(
1530            "Only finding, artifact, evidence_atom, frontier_observation, and governance proposals are supported in v0"
1531                .to_string(),
1532        );
1533    }
1534    if proposal.reason.trim().is_empty() {
1535        return Err("Proposal reason must be non-empty".to_string());
1536    }
1537    match proposal.kind.as_str() {
1538        policy_accept::POLICY_HEAD_PROPOSAL_KIND => {
1539            if proposal.target.r#type != "governance" {
1540                return Err("policy-head proposal target.type must be governance".to_string());
1541            }
1542            policy_accept::parse_policy_head_payload(proposal)?;
1543        }
1544        policy_accept::LEGACY_POLICY_RETIREMENT_PROPOSAL_KIND => {
1545            if proposal.target.r#type != "governance" {
1546                return Err(
1547                    "legacy-policy-retirement proposal target.type must be governance".to_string(),
1548                );
1549            }
1550            policy_accept::parse_legacy_policy_retirement_payload(proposal)?;
1551        }
1552        "finding.add" => {
1553            let finding_value = proposal
1554                .payload
1555                .get("finding")
1556                .ok_or("finding.add proposal missing payload.finding")?
1557                .clone();
1558            let finding: FindingBundle = serde_json::from_value(finding_value)
1559                .map_err(|e| format!("Invalid finding.add payload: {e}"))?;
1560            if finding.id != proposal.target.id {
1561                return Err(format!(
1562                    "finding.add target {} does not match payload finding {}",
1563                    proposal.target.id, finding.id
1564                ));
1565            }
1566        }
1567        "finding.review" => {
1568            let status = proposal
1569                .payload
1570                .get("status")
1571                .and_then(Value::as_str)
1572                .ok_or("finding.review proposal missing payload.status")?;
1573            if !matches!(
1574                status,
1575                "accepted" | "approved" | "contested" | "needs_revision" | "rejected"
1576            ) {
1577                return Err(format!("Unsupported review proposal status '{status}'"));
1578            }
1579        }
1580        "finding.caveat" => {
1581            let text = proposal
1582                .payload
1583                .get("text")
1584                .and_then(Value::as_str)
1585                .ok_or("finding.caveat proposal missing payload.text")?;
1586            if text.trim().is_empty() {
1587                return Err("finding.caveat payload.text must be non-empty".to_string());
1588            }
1589        }
1590        "finding.note" => {
1591            let text = proposal
1592                .payload
1593                .get("text")
1594                .and_then(Value::as_str)
1595                .ok_or("finding.note proposal missing payload.text")?;
1596            if text.trim().is_empty() {
1597                return Err("finding.note payload.text must be non-empty".to_string());
1598            }
1599        }
1600        "finding.confidence_revise" => {
1601            let score = proposal
1602                .payload
1603                .get("confidence")
1604                .and_then(Value::as_f64)
1605                .ok_or("finding.confidence_revise proposal missing payload.confidence")?;
1606            if !(0.0..=1.0).contains(&score) {
1607                return Err(
1608                    "finding.confidence_revise confidence must be between 0.0 and 1.0".to_string(),
1609                );
1610            }
1611        }
1612        "finding.reject" | "finding.retract" => {}
1613        "artifact.retract" => {
1614            if proposal.target.r#type != "artifact" {
1615                return Err(format!(
1616                    "artifact.retract target.type must be 'artifact', got '{}'",
1617                    proposal.target.r#type
1618                ));
1619            }
1620        }
1621        "finding.supersede" => {
1622            let new_finding_value = proposal
1623                .payload
1624                .get("new_finding")
1625                .ok_or("finding.supersede proposal missing payload.new_finding")?
1626                .clone();
1627            let new_finding: FindingBundle = serde_json::from_value(new_finding_value)
1628                .map_err(|e| format!("Invalid finding.supersede payload.new_finding: {e}"))?;
1629            if new_finding.id == proposal.target.id {
1630                return Err(
1631                    "finding.supersede new_finding has same content address as the superseded target"
1632                        .to_string(),
1633                );
1634            }
1635        }
1636        // v0.57: standalone validation of finding span-repair.
1637        "finding.span_repair" => {
1638            if proposal.target.r#type != "finding" {
1639                return Err(format!(
1640                    "finding.span_repair target.type must be 'finding', got '{}'",
1641                    proposal.target.r#type
1642                ));
1643            }
1644            let section = proposal
1645                .payload
1646                .get("section")
1647                .and_then(Value::as_str)
1648                .ok_or("finding.span_repair proposal missing payload.section")?;
1649            if section.trim().is_empty() {
1650                return Err("finding.span_repair payload.section must be non-empty".to_string());
1651            }
1652            let text = proposal
1653                .payload
1654                .get("text")
1655                .and_then(Value::as_str)
1656                .ok_or("finding.span_repair proposal missing payload.text")?;
1657            if text.trim().is_empty() {
1658                return Err("finding.span_repair payload.text must be non-empty".to_string());
1659            }
1660        }
1661        // v0.56: standalone validation of an evidence-atom locator
1662        // repair. Mirrors the contextual validator in
1663        // `validate_proposal_shape`, except without frontier-side
1664        // existence checks (the standalone validator runs over an
1665        // exported proposal before it is loaded into a frontier).
1666        "evidence_atom.locator_repair" => {
1667            if proposal.target.r#type != "evidence_atom" {
1668                return Err(format!(
1669                    "evidence_atom.locator_repair target.type must be 'evidence_atom', got '{}'",
1670                    proposal.target.r#type
1671                ));
1672            }
1673            let locator = proposal
1674                .payload
1675                .get("locator")
1676                .and_then(Value::as_str)
1677                .ok_or("evidence_atom.locator_repair proposal missing payload.locator")?;
1678            if locator.trim().is_empty() {
1679                return Err(
1680                    "evidence_atom.locator_repair payload.locator must be non-empty".to_string(),
1681                );
1682            }
1683            let source_id = proposal
1684                .payload
1685                .get("source_id")
1686                .and_then(Value::as_str)
1687                .ok_or("evidence_atom.locator_repair proposal missing payload.source_id")?;
1688            if source_id.trim().is_empty() {
1689                return Err(
1690                    "evidence_atom.locator_repair payload.source_id must be non-empty".to_string(),
1691                );
1692            }
1693        }
1694        "finding.contribution.recorded" => {
1695            let contribution: crate::bundle::Contribution =
1696                serde_json::from_value(proposal.payload.get("contribution").cloned().ok_or(
1697                    "finding.contribution.recorded proposal missing payload.contribution",
1698                )?)
1699                .map_err(|e| format!("malformed contribution: {e}"))?;
1700            contribution.validate()?;
1701        }
1702        "research_trace.review" => {
1703            validate_research_trace_review_payload(proposal)?;
1704        }
1705        "correction_return.review" => {
1706            validate_correction_return_review_payload(proposal)?;
1707        }
1708        other => return Err(format!("Unsupported proposal kind '{other}'")),
1709    }
1710    validate_decision_state(proposal)
1711}
1712
1713fn validate_research_trace_review_payload(proposal: &StateProposal) -> Result<(), String> {
1714    if proposal.target.r#type != "frontier_observation" {
1715        return Err(format!(
1716            "research_trace.review target.type must be 'frontier_observation', got '{}'",
1717            proposal.target.r#type
1718        ));
1719    }
1720    let trace_id = proposal
1721        .payload
1722        .get("trace_id")
1723        .and_then(Value::as_str)
1724        .ok_or("research_trace.review proposal missing payload.trace_id")?;
1725    if !trace_id.starts_with("vrt_") {
1726        return Err("research_trace.review payload.trace_id must start with `vrt_`".to_string());
1727    }
1728    let output_kind = proposal
1729        .payload
1730        .get("output_kind")
1731        .and_then(Value::as_str)
1732        .ok_or("research_trace.review proposal missing payload.output_kind")?;
1733    if !matches!(output_kind, "candidate_finding" | "open_need") {
1734        return Err(format!(
1735            "research_trace.review payload.output_kind must be candidate_finding or open_need, got '{output_kind}'"
1736        ));
1737    }
1738    if output_kind == "candidate_finding" && proposal.payload.get("candidate").is_none() {
1739        return Err(
1740            "research_trace.review candidate_finding missing payload.candidate".to_string(),
1741        );
1742    }
1743    if output_kind == "open_need" && proposal.payload.get("open_need").is_none() {
1744        return Err("research_trace.review open_need missing payload.open_need".to_string());
1745    }
1746    if proposal.payload.get("authority_boundary").is_none() {
1747        return Err("research_trace.review missing payload.authority_boundary".to_string());
1748    }
1749    if proposal.payload.get("formalization_fidelity").is_none() {
1750        return Err("research_trace.review missing payload.formalization_fidelity".to_string());
1751    }
1752    if !proposal
1753        .source_refs
1754        .iter()
1755        .any(|source_ref| source_ref == trace_id)
1756    {
1757        return Err(format!(
1758            "research_trace.review source_refs must include trace_id {trace_id}"
1759        ));
1760    }
1761    Ok(())
1762}
1763
1764fn validate_correction_return_review_payload(proposal: &StateProposal) -> Result<(), String> {
1765    if proposal.target.r#type != "frontier_observation" {
1766        return Err(format!(
1767            "correction_return.review target.type must be 'frontier_observation', got '{}'",
1768            proposal.target.r#type
1769        ));
1770    }
1771    let correction = proposal
1772        .payload
1773        .get("correction")
1774        .ok_or("correction_return.review proposal missing payload.correction")?;
1775    for field in [
1776        "target_id",
1777        "issue",
1778        "proposed_change",
1779        "source_locator",
1780        "evidence_span",
1781    ] {
1782        let value = correction
1783            .get(field)
1784            .and_then(Value::as_str)
1785            .ok_or_else(|| {
1786                format!("correction_return.review payload.correction.{field} is required")
1787            })?;
1788        if value.trim().is_empty() {
1789            return Err(format!(
1790                "correction_return.review payload.correction.{field} must be non-empty"
1791            ));
1792        }
1793    }
1794    let verification_runs = correction
1795        .get("verification_run")
1796        .and_then(Value::as_array)
1797        .ok_or("correction_return.review payload.correction.verification_run must be an array")?;
1798    if verification_runs.is_empty() {
1799        return Err(
1800            "correction_return.review payload.correction.verification_run must be non-empty"
1801                .to_string(),
1802        );
1803    }
1804    let boundary = proposal
1805        .payload
1806        .get("claim_boundary")
1807        .and_then(Value::as_object)
1808        .ok_or("correction_return.review missing payload.claim_boundary")?;
1809    for field in [
1810        "claims_clinical_validity",
1811        "claims_external_adoption",
1812        "claims_external_validation",
1813        "claims_lab_validation",
1814        "claims_scientific_discovery",
1815        "claims_target_validation",
1816        "claims_treatment_advice",
1817    ] {
1818        match boundary.get(field).and_then(Value::as_bool) {
1819            Some(false) => {}
1820            Some(true) => {
1821                return Err(format!(
1822                    "correction_return.review payload.claim_boundary.{field} must be false"
1823                ));
1824            }
1825            None => {
1826                return Err(format!(
1827                    "correction_return.review payload.claim_boundary.{field} is required"
1828                ));
1829            }
1830        }
1831    }
1832    if !proposal.source_refs.iter().any(|source_ref| {
1833        source_ref == "correction-return.template.json"
1834            || (source_ref.starts_with("correction-return.") && source_ref.ends_with(".json"))
1835    }) {
1836        return Err(
1837            "correction_return.review source_refs must include correction-return.template.json or a correction-return.*.json file"
1838                .to_string(),
1839        );
1840    }
1841    Ok(())
1842}
1843
1844fn require_existing_finding(frontier: &Project, finding_id: &str) -> Result<usize, String> {
1845    frontier
1846        .findings
1847        .iter()
1848        .position(|finding| finding.id == finding_id)
1849        .ok_or_else(|| format!("Finding not found: {finding_id}"))
1850}
1851
1852// Proposal-kind classification is deliberately separate from authority.
1853// These lists tell policy and presentation code which records are mechanical
1854// or process-only; they do not mint a decision capability. A caller still
1855// needs a Decision Plan.
1856
1857/// Mechanical, truth-preserving repair kinds. This is classification only;
1858/// it does not let an agent apply the proposal without decision authority.
1859const MECHANICAL_REPAIR_KINDS: &[&str] = &["finding.span_repair", "evidence_atom.locator_repair"];
1860
1861/// Non-truth-bearing process and provenance kinds. Content-addressed artifact
1862/// registration and claim-granularity attribution assert no scientific claim
1863/// about the world. Legacy policy retirement is governance cleanup and remains
1864/// human-only through its dedicated acceptance branch; listing it here merely
1865/// prevents the scientific Evidence CI gate from treating byte retirement as a
1866/// scientific assertion. Classification never confers authority.
1867const NON_TRUTH_BEARING_KINDS: &[&str] = &[
1868    "artifact.assert",
1869    "artifact.add",
1870    "finding.contribution.recorded",
1871    policy_accept::LEGACY_POLICY_RETIREMENT_PROPOSAL_KIND,
1872];
1873
1874/// Proposal-level guards for exact-lane auto-admission (Phase 1A, the
1875/// de-human-gate). Returns `(admit, reasons)`; `reasons` is non-empty exactly
1876/// when refused. Pure and deterministic, so two implementations agree.
1877///
1878/// IMPORTANT — this is NOT the whole gate. The un-forgeable floor (a fresh
1879/// `vela reproduce` over the witness AND `vela_verify::claim_witness_faithful`
1880/// binding the parsed assertion to the witness structure) is applied by the
1881/// CLI command BEFORE this is called, because it needs the `vela-verify`
1882/// binary and the witness file, which the protocol crate does not see. This
1883/// function adds the protocol-level guards a human reviewer applies and then
1884/// delegates to the attachment corroboration predicate
1885/// [`crate::verifier_attachment::exact_lane_attachment_admit`]. See
1886/// `docs/VERIFICATION.md` for why the corroboration predicate alone is
1887/// insufficient (a `VerifierAttachment` is unsigned self-asserted data the
1888/// producing agent can author).
1889///
1890/// Fail-closed guard order:
1891///   1. kind allowlist: `finding.add` only.
1892///   2. target binding: target is this finding.
1893///   3. content-address drift-pin: the loaded finding body must content-address
1894///      to its own id (closes assertion-text edits after the id was minted).
1895///   4. lifecycle: the finding is neither retracted nor superseded.
1896///   5. synthetic: no `synthetic_source_requires_review` signal (caller-derived).
1897///   6. contradiction: no live open contradiction names this finding
1898///      (caller-derived, including freshly derived candidates).
1899///   7. producer != verifier: the proposing actor differs from every matched
1900///      attachment's `verifier_actor` (the producer cannot be its own
1901///      corroborator at the actor level).
1902///   8. delegate to the attachment predicate over the matched attachments.
1903pub fn exact_lane_eligible(
1904    proposal: &StateProposal,
1905    finding: &crate::bundle::FindingBundle,
1906    attachments: &[crate::verifier_attachment::VerifierAttachment],
1907    open_contradiction_finding_ids: &BTreeSet<String>,
1908    synthetic_unreviewed_finding_ids: &BTreeSet<String>,
1909    floor_sufficient: bool,
1910) -> (bool, Vec<String>) {
1911    let mut reasons = Vec::new();
1912
1913    // 1. kind allowlist.
1914    if proposal.kind != "finding.add" {
1915        reasons.push(format!(
1916            "exact-lane: proposal kind '{}' is not 'finding.add'",
1917            proposal.kind
1918        ));
1919        return (false, reasons);
1920    }
1921
1922    // 2. target binding.
1923    if proposal.target.r#type != "finding" || proposal.target.id != finding.id {
1924        reasons.push("exact-lane: proposal target does not bind to this finding".to_string());
1925        return (false, reasons);
1926    }
1927
1928    // 3. content-address drift-pin: the body must hash to its own id.
1929    let recomputed =
1930        crate::bundle::FindingBundle::content_address(&finding.assertion, &finding.provenance);
1931    if recomputed != finding.id {
1932        reasons.push(format!(
1933            "exact-lane: finding body does not content-address to its id (drift): {} != {}",
1934            recomputed, finding.id
1935        ));
1936        return (false, reasons);
1937    }
1938
1939    // 4. lifecycle.
1940    if finding.flags.retracted || finding.flags.superseded {
1941        reasons.push("exact-lane: finding is retracted or superseded".to_string());
1942        return (false, reasons);
1943    }
1944
1945    // 5. synthetic-source signal.
1946    if synthetic_unreviewed_finding_ids.contains(&finding.id) {
1947        reasons.push(
1948            "exact-lane: finding carries a synthetic_source_requires_review signal".to_string(),
1949        );
1950        return (false, reasons);
1951    }
1952
1953    // 6. live open contradiction.
1954    if open_contradiction_finding_ids.contains(&finding.id) {
1955        reasons.push("exact-lane: a live open contradiction names this finding".to_string());
1956        return (false, reasons);
1957    }
1958
1959    // The matched attachments (those bound to this finding).
1960    let matched: Vec<crate::verifier_attachment::VerifierAttachment> = attachments
1961        .iter()
1962        .filter(|a| a.target == finding.id)
1963        .cloned()
1964        .collect();
1965
1966    // 7. producer != verifier: the proposing actor cannot also be a corroborator.
1967    let producer = proposal.actor.id.trim();
1968    if !producer.is_empty()
1969        && let Some(bad) = matched.iter().find(|a| a.verifier_actor.trim() == producer)
1970    {
1971        reasons.push(format!(
1972            "exact-lane: the proposing actor '{}' is also a verifier_actor on attachment '{}' \
1973             (producer cannot corroborate itself)",
1974            producer, bad.id
1975        ));
1976        return (false, reasons);
1977    }
1978
1979    // 8. corroboration. When `floor_sufficient` (the caller established the
1980    // un-forgeable floor: a fresh frozen `vela reproduce` over the witness AND
1981    // `claim_witness_faithful` binding the parsed assertion to it), the FLOOR is
1982    // itself the proof of an exact lower-bound / size claim, so the
1983    // >=2-independent-attachment requirement (the GENERAL gate's bar, for claims
1984    // with no single frozen verifier) is waived — attachments become optional
1985    // corroboration. Otherwise the attachment predicate must derive Verified.
1986    if !floor_sufficient {
1987        let digest = crate::verifier_attachment::claim_digest(&finding.assertion.text);
1988        let (admit, att_reasons) =
1989            crate::verifier_attachment::exact_lane_attachment_admit(&digest, &matched);
1990        if !admit {
1991            reasons.extend(att_reasons);
1992            return (false, reasons);
1993        }
1994    }
1995
1996    (true, reasons)
1997}
1998
1999/// The verification trust tier of a finding (Phase 1A). An ordered ladder;
2000/// the machine advances the lower rungs, a human key-custody accept is the
2001/// only path to `Accepted`.
2002#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2003#[serde(rename_all = "snake_case")]
2004pub enum TrustTier {
2005    Candidate,
2006    SchemaChecked,
2007    MachineVerified,
2008    Accepted,
2009}
2010
2011impl TrustTier {
2012    pub fn as_str(&self) -> &'static str {
2013        match self {
2014            TrustTier::Candidate => "candidate",
2015            TrustTier::SchemaChecked => "schema_checked",
2016            TrustTier::MachineVerified => "machine_verified",
2017            TrustTier::Accepted => "accepted",
2018        }
2019    }
2020}
2021
2022/// Project a finding's verification trust tier from canonical state + the
2023/// immutable log + live attachments (Phase 1A). A read-only projection, never
2024/// a stored field: recomputed fresh so a forged `policy.auto_admitted` event
2025/// cannot by itself raise the tier, and a later-weakened attachment set
2026/// silently lowers it.
2027///
2028/// - `Accepted`: the finding is landed in canonical state (`frontier.findings`)
2029///   and not retracted/superseded. Landing runs only through the key-custody
2030///   accept ceremony, so canonical membership IS the human-accept signal (no
2031///   reliance on which event kind the ceremony emitted). Strictly highest; the
2032///   machine never reaches it.
2033/// - `MachineVerified`: the finding is a PENDING `finding.add` proposal carrying
2034///   a `policy.auto_admitted` marker whose gate, recomputed LIVE from the
2035///   proposal's finding text + the current matched attachments, is `Verified`.
2036///   Machine-verified state is a separate queryable layer over pending
2037///   proposals; it is NEVER landed in `frontier.findings` (that is the human
2038///   tier), which preserves the charter boundary.
2039/// - `SchemaChecked`: at least one passing matched attachment, not yet Verified.
2040/// - `Candidate`: everything else, including retracted/superseded.
2041pub fn derive_trust_tier(frontier: &Project, finding_id: &str) -> TrustTier {
2042    use crate::verifier_attachment::{AttachmentOutcome, GateStatus, derive_gate_status};
2043
2044    // Landed in canonical accepted state?
2045    if let Some(f) = frontier.findings.iter().find(|f| f.id == finding_id) {
2046        if f.flags.retracted || f.flags.superseded {
2047            return TrustTier::Candidate;
2048        }
2049        return TrustTier::Accepted;
2050    }
2051
2052    let matched: Vec<crate::verifier_attachment::VerifierAttachment> = frontier
2053        .verifier_attachments
2054        .iter()
2055        .filter(|a| a.target == finding_id)
2056        .cloned()
2057        .collect();
2058
2059    // A pending finding.add proposal for this finding, carrying an auto-admit.
2060    let pending = frontier.proposals.iter().find(|p| {
2061        p.kind == "finding.add"
2062            && p.applied_event_id.is_none()
2063            && (p.target.id == finding_id
2064                || p.payload
2065                    .get("finding")
2066                    .and_then(|f| f.get("id"))
2067                    .and_then(|i| i.as_str())
2068                    == Some(finding_id))
2069    });
2070    if let Some(p) = pending {
2071        let admitted = frontier.events.iter().any(|e| {
2072            e.kind.as_str() == "policy.auto_admitted"
2073                && e.payload.get("proposal_id").and_then(|v| v.as_str()) == Some(p.id.as_str())
2074        });
2075        if admitted
2076            && let Some(finding_val) = p.payload.get("finding")
2077            && let Ok(fb) =
2078                serde_json::from_value::<crate::bundle::FindingBundle>(finding_val.clone())
2079        {
2080            let digest = crate::verifier_attachment::claim_digest(&fb.assertion.text);
2081            if derive_gate_status(&digest, &matched).status == GateStatus::Verified {
2082                return TrustTier::MachineVerified;
2083            }
2084        }
2085    }
2086
2087    if matched
2088        .iter()
2089        .any(|a| a.outcome == AttachmentOutcome::Passed)
2090    {
2091        return TrustTier::SchemaChecked;
2092    }
2093    TrustTier::Candidate
2094}
2095
2096/// Result of a fixed-time, in-memory decision preparation.
2097///
2098/// This is transaction plumbing, not a serialized protocol object. The
2099/// prepared events are unsigned. A human-key caller may pass this exact set to
2100/// [`sign_prepared_decision_events`] only after rederiving and confirming its
2101/// Decision Plan under the frontier lock.
2102#[derive(Debug, Clone, PartialEq, Eq)]
2103pub struct PreparedDecisionMutation {
2104    /// The domain event produced by an accept, or the review event for a
2105    /// reject/policy-head accept.
2106    primary_event_id: String,
2107    /// Every event appended by this one decision, in canonical order.
2108    appended_event_ids: Vec<String>,
2109    /// The `review.accepted` / `review.rejected` event that binds the decision
2110    /// provenance, including the decision-root input reference when supplied.
2111    decision_event_id: String,
2112    proposal_id: String,
2113    reviewer: String,
2114    first_event: usize,
2115    event_count_after: usize,
2116    binding: PreparedDecisionBinding,
2117}
2118
2119#[derive(Debug, Clone, PartialEq, Eq)]
2120enum PreparedDecisionBinding {
2121    Unbound,
2122    Bound { decision_root: String },
2123}
2124
2125impl PreparedDecisionMutation {
2126    #[must_use]
2127    pub fn primary_event_id(&self) -> &str {
2128        &self.primary_event_id
2129    }
2130
2131    #[must_use]
2132    pub fn appended_event_ids(&self) -> &[String] {
2133        &self.appended_event_ids
2134    }
2135
2136    #[must_use]
2137    pub fn decision_event_id(&self) -> &str {
2138        &self.decision_event_id
2139    }
2140
2141    #[must_use]
2142    pub fn proposal_id(&self) -> &str {
2143        &self.proposal_id
2144    }
2145
2146    #[must_use]
2147    pub fn reviewer(&self) -> &str {
2148        &self.reviewer
2149    }
2150
2151    #[must_use]
2152    pub fn decision_root(&self) -> Option<&str> {
2153        match &self.binding {
2154            PreparedDecisionBinding::Unbound => None,
2155            PreparedDecisionBinding::Bound { decision_root } => Some(decision_root),
2156        }
2157    }
2158
2159    #[must_use]
2160    pub fn is_bound(&self) -> bool {
2161        self.decision_root().is_some()
2162    }
2163}
2164
2165/// Check decision-time reviewer facts without reading or receiving a private
2166/// key. New Decision Plan reviews require a registered, active Ed25519 actor;
2167/// agent and CI identities can never enter this human seam. Legacy decision
2168/// creation APIs fail closed; there is no keyless bootstrap decision path.
2169pub fn validate_human_reviewer_authority_at(
2170    frontier: &Project,
2171    reviewer: &str,
2172    decided_at: &str,
2173) -> Result<crate::sign::ActorRecord, String> {
2174    validate_reviewer_identity(reviewer)?;
2175    let decision_at = chrono::DateTime::parse_from_rfc3339(decided_at)
2176        .map_err(|error| format!("decision time is invalid: {error}"))?;
2177    if reviewer.starts_with("agent:") || reviewer.starts_with("ci:") {
2178        return Err(format!(
2179            "reviewer '{reviewer}' may not enter a human Decision Plan"
2180        ));
2181    }
2182    let mut actors = frontier.actors.iter().filter(|actor| actor.id == reviewer);
2183    let actor = actors
2184        .next()
2185        .cloned()
2186        .ok_or_else(|| format!("reviewer '{reviewer}' is not registered on this frontier"))?;
2187    if actors.next().is_some() {
2188        return Err(format!(
2189            "reviewer '{reviewer}' is registered ambiguously (duplicate actor ids)"
2190        ));
2191    }
2192    if actor.algorithm != "ed25519"
2193        || hex::decode(&actor.public_key).map_or(true, |bytes| bytes.len() != 32)
2194    {
2195        return Err(format!(
2196            "reviewer '{}' must have a registered Ed25519 decision key",
2197            actor.id
2198        ));
2199    }
2200    if !actor_has_reviewer_authority(&actor)
2201        && !(actor.id.starts_with("steward:") && !is_placeholder_reviewer(&actor.id))
2202    {
2203        return Err(format!(
2204            "actor '{}' does not carry reviewer or steward decision authority",
2205            actor.id
2206        ));
2207    }
2208    let created_at = chrono::DateTime::parse_from_rfc3339(&actor.created_at)
2209        .map_err(|error| format!("reviewer '{}' creation time is invalid: {error}", actor.id))?;
2210    if created_at > decision_at {
2211        return Err(format!(
2212            "reviewer '{}' is not yet registered at {decided_at}",
2213            actor.id
2214        ));
2215    }
2216    if let Some(revoked_at) = actor.revoked_at.as_deref() {
2217        let revoked_at = chrono::DateTime::parse_from_rfc3339(revoked_at).map_err(|error| {
2218            format!(
2219                "reviewer '{}' revocation time is invalid: {error}",
2220                actor.id
2221            )
2222        })?;
2223        if decision_at >= revoked_at {
2224            return Err(format!(
2225                "reviewer key for actor '{}' is revoked as of {decided_at}",
2226                actor.id
2227            ));
2228        }
2229    }
2230    Ok(actor)
2231}
2232
2233enum DecisionAuthority<'a> {
2234    LocalKey(&'a ed25519_dalek::SigningKey),
2235    PlanPreparation,
2236    Preview,
2237}
2238
2239impl<'a> DecisionAuthority<'a> {
2240    fn signing_key(&self) -> Option<&'a ed25519_dalek::SigningKey> {
2241        match self {
2242            Self::LocalKey(key) => Some(*key),
2243            _ => None,
2244        }
2245    }
2246
2247    fn is_preview(&self) -> bool {
2248        matches!(self, Self::Preview)
2249    }
2250}
2251
2252fn enforce_decision_authority(
2253    frontier: &Project,
2254    _proposal: &StateProposal,
2255    reviewer: &str,
2256    decided_at: &str,
2257    authority: &DecisionAuthority<'_>,
2258) -> Result<(), String> {
2259    match authority {
2260        DecisionAuthority::LocalKey(key) => {
2261            let actor = validate_human_reviewer_authority_at(frontier, reviewer, decided_at)?;
2262            let derived = hex::encode(key.verifying_key().to_bytes());
2263            if !derived.eq_ignore_ascii_case(&actor.public_key) {
2264                return Err(format!(
2265                    "the supplied key derives pubkey {}…, which does not match {reviewer}'s registered decision key {}…",
2266                    &derived[..12],
2267                    &actor.public_key[..actor.public_key.len().min(12)]
2268                ));
2269            }
2270            Ok(())
2271        }
2272        DecisionAuthority::PlanPreparation => {
2273            validate_human_reviewer_authority_at(frontier, reviewer, decided_at).map(|_| ())
2274        }
2275        DecisionAuthority::Preview => validate_reviewer_identity(reviewer),
2276    }
2277}
2278
2279/// Accept exactly one policy-head proposal at a caller-bound instant.
2280///
2281/// This is the transaction planner seam used by the human policy ceremony:
2282/// the CLI reads the key once, fixes one timestamp, signs both the policy and
2283/// the existing `review.accepted` authority event, then journals their public
2284/// postimages together. It cannot be used for ordinary proposal kinds.
2285pub fn accept_policy_head_proposal_in_frontier_at(
2286    frontier: &mut Project,
2287    proposal_id: &str,
2288    reviewer: &str,
2289    reason: &str,
2290    signing_key: &ed25519_dalek::SigningKey,
2291    decided_at: &str,
2292) -> Result<String, String> {
2293    chrono::DateTime::parse_from_rfc3339(decided_at)
2294        .map_err(|error| format!("policy-head decision time is invalid: {error}"))?;
2295    let proposal = frontier
2296        .proposals
2297        .iter()
2298        .find(|proposal| proposal.id == proposal_id)
2299        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?;
2300    if proposal.kind != policy_accept::POLICY_HEAD_PROPOSAL_KIND {
2301        return Err("fixed-time policy-head acceptance cannot accept another proposal kind".into());
2302    }
2303    accept_proposal_in_frontier_with_authority_at(
2304        frontier,
2305        proposal_id,
2306        reviewer,
2307        reason,
2308        DecisionAuthority::LocalKey(signing_key),
2309        None,
2310        Some(decided_at),
2311        false,
2312    )
2313}
2314
2315#[allow(clippy::too_many_arguments)]
2316fn accept_proposal_in_frontier_with_authority_at(
2317    frontier: &mut Project,
2318    proposal_id: &str,
2319    reviewer: &str,
2320    reason: &str,
2321    authority: DecisionAuthority<'_>,
2322    provenance: Option<&crate::provenance::Provenance>,
2323    fixed_decided_at: Option<&str>,
2324    record_review_event: bool,
2325) -> Result<String, String> {
2326    validate_reviewer_identity(reviewer)?;
2327    if reason.trim().is_empty() {
2328        return Err("Decision reason must be non-empty".to_string());
2329    }
2330    let index = frontier
2331        .proposals
2332        .iter()
2333        .position(|proposal| proposal.id == proposal_id)
2334        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?;
2335    let is_legacy_retirement =
2336        frontier.proposals[index].kind == policy_accept::LEGACY_POLICY_RETIREMENT_PROPOSAL_KIND;
2337    if is_legacy_retirement && !authority.is_preview() {
2338        return Err(
2339            "legacy-policy retirement must use the recoverable human Decision Plan".to_string(),
2340        );
2341    }
2342    let status = frontier.proposals[index].status.clone();
2343    if status == "rejected" {
2344        return Err(format!("Cannot accept rejected proposal {}", proposal_id));
2345    }
2346    if status == "applied" {
2347        let proposal = frontier.proposals[index].clone();
2348        let decided_at = fixed_decided_at
2349            .map(ToString::to_string)
2350            .unwrap_or_else(|| Utc::now().to_rfc3339());
2351        enforce_decision_authority(frontier, &proposal, reviewer, &decided_at, &authority)?;
2352        return frontier.proposals[index]
2353            .applied_event_id
2354            .clone()
2355            .ok_or_else(|| format!("Proposal {} is applied but has no event id", proposal_id));
2356    }
2357    let proposal = frontier.proposals[index].clone();
2358    validate_proposal_shape(frontier, &proposal)?;
2359    let decided_at = fixed_decided_at
2360        .map(ToString::to_string)
2361        .unwrap_or_else(|| Utc::now().to_rfc3339());
2362    enforce_decision_authority(frontier, &proposal, reviewer, &decided_at, &authority)?;
2363    let signing_key = authority.signing_key();
2364    if proposal.kind == policy_accept::POLICY_HEAD_PROPOSAL_KIND {
2365        if signing_key.is_none() && !record_review_event {
2366            return Err(
2367                "policy-head acceptance requires a real human event signature; custody-only or keyless review cannot activate authority"
2368                    .to_string(),
2369            );
2370        }
2371        if !(reviewer.starts_with("reviewer:") || reviewer.starts_with("steward:")) {
2372            return Err("policy-head acceptance requires a reviewer:/steward: actor".to_string());
2373        }
2374        let decided_at = decided_at.clone();
2375        let actor = validate_human_reviewer_authority_at(frontier, reviewer, &decided_at)?;
2376        if signing_key.is_some_and(|key| {
2377            !actor
2378                .public_key
2379                .eq_ignore_ascii_case(&hex::encode(key.verifying_key().to_bytes()))
2380        }) {
2381            return Err(
2382                "policy-head signer key does not match the resolved frontier actor".to_string(),
2383            );
2384        }
2385        let review_time = chrono::DateTime::parse_from_rfc3339(&decided_at)
2386            .map_err(|error| format!("policy-head decision time is invalid: {error}"))?;
2387        for parent in &frontier.events {
2388            let parent_time =
2389                chrono::DateTime::parse_from_rfc3339(&parent.timestamp).map_err(|error| {
2390                    format!("policy-head parent {} time is invalid: {error}", parent.id)
2391                })?;
2392            if parent_time >= review_time {
2393                return Err(format!(
2394                    "policy-head review must occur after causal parent {}",
2395                    parent.id
2396                ));
2397            }
2398        }
2399        let mut event = events::new_review_decision_event(
2400            &proposal.id,
2401            &proposal.kind,
2402            "accepted",
2403            None,
2404            reviewer,
2405            reason,
2406            Some(&decided_at),
2407        )?;
2408        if let Some(provenance) = provenance
2409            && !provenance.is_empty()
2410        {
2411            crate::provenance::attach_to_payload(&mut event.payload, provenance)?;
2412            event.id = events::compute_event_id(&event);
2413        }
2414        if let Some(key) = signing_key {
2415            event.signature = Some(crate::sign::sign_event(&event, key)?);
2416        }
2417        let event_id = event.id.clone();
2418        frontier.events.push(event);
2419        frontier.proposals[index].status = "applied".to_string();
2420        frontier.proposals[index].reviewed_by = Some(reviewer.to_string());
2421        frontier.proposals[index].reviewed_at = Some(decided_at);
2422        frontier.proposals[index].decision_reason = Some(reason.to_string());
2423        frontier.proposals[index].applied_event_id = Some(event_id.clone());
2424        mark_proof_stale(
2425            frontier,
2426            format!("Accepted policy-head proposal {}", proposal.id),
2427        );
2428        return Ok(event_id);
2429    }
2430    if is_legacy_retirement {
2431        // Retirement changes fixed governance files outside Project. The pure
2432        // Engine preview may simulate its review event, but every real
2433        // protocol acceptance path must fail closed: only vela-cli's private,
2434        // recoverable Decision Plan can bind this event to the atomic
2435        // Authority-file deletions.
2436        let mut event = events::new_review_decision_event(
2437            &proposal.id,
2438            &proposal.kind,
2439            "accepted",
2440            None,
2441            reviewer,
2442            reason,
2443            Some(&decided_at),
2444        )?;
2445        if let Some(provenance) = provenance
2446            && !provenance.is_empty()
2447        {
2448            crate::provenance::attach_to_payload(&mut event.payload, provenance)?;
2449            event.id = events::compute_event_id(&event);
2450        }
2451        let event_id = event.id.clone();
2452        frontier.events.push(event);
2453        frontier.proposals[index].status = "applied".to_string();
2454        frontier.proposals[index].reviewed_by = Some(reviewer.to_string());
2455        frontier.proposals[index].reviewed_at = Some(decided_at);
2456        frontier.proposals[index].decision_reason = Some(reason.to_string());
2457        frontier.proposals[index].applied_event_id = Some(event_id.clone());
2458        mark_proof_stale(
2459            frontier,
2460            format!("Accepted legacy-policy retirement proposal {}", proposal.id),
2461        );
2462        return Ok(event_id);
2463    }
2464    frontier.proposals[index].status = "accepted".to_string();
2465    frontier.proposals[index].reviewed_by = Some(reviewer.to_string());
2466    frontier.proposals[index].reviewed_at = Some(decided_at.clone());
2467    frontier.proposals[index].decision_reason = Some(reason.to_string());
2468    let domain_provenance = if record_review_event {
2469        None
2470    } else {
2471        provenance
2472    };
2473    let event_id = apply_proposal_at(
2474        frontier,
2475        &proposal,
2476        reviewer,
2477        reason,
2478        domain_provenance,
2479        fixed_decided_at,
2480    )?;
2481    frontier.proposals[index].status = "applied".to_string();
2482    frontier.proposals[index].applied_event_id = Some(event_id.clone());
2483    // Sign the accept event under the reviewer's key: the signature is
2484    // over the canonical event bytes (signature field excluded), so the
2485    // content-addressed id is unchanged and the accept is attributable
2486    // by cryptography, not by string.
2487    if let Some(key) = signing_key
2488        && let Some(ev) = frontier.events.iter_mut().find(|e| e.id == event_id)
2489    {
2490        ev.signature = Some(crate::sign::sign_event(ev, key)?);
2491    }
2492    if record_review_event {
2493        let decided_at = fixed_decided_at.ok_or_else(|| {
2494            "prepared acceptance requires a caller-bound decision time".to_string()
2495        })?;
2496        push_signed_review_event(
2497            frontier,
2498            &proposal.id,
2499            &proposal.kind,
2500            "accepted",
2501            Some(event_id.clone()),
2502            reviewer,
2503            reason,
2504            decided_at,
2505            signing_key,
2506            provenance,
2507        )?;
2508    }
2509    Ok(event_id)
2510}
2511
2512/// Build, sign, and append a `review.*` decision event to the log. The
2513/// event is the tamper-evident, replayable record of the decision — the
2514/// thing a reject previously lacked entirely. Signed under the reviewer
2515/// key when present (custody is enforced by the caller before this runs),
2516/// so the decision is non-repudiable; the content-addressed id is over the
2517/// unsigned shape, so signing never changes it. `decided_at` is reused for
2518/// both the event timestamp and the proposal's `reviewed_at`, so the two
2519/// never diverge by a second clock read.
2520#[allow(clippy::too_many_arguments)]
2521fn push_signed_review_event(
2522    frontier: &mut Project,
2523    proposal_id: &str,
2524    proposal_kind: &str,
2525    verdict: &str,
2526    applied_event_id: Option<String>,
2527    reviewer: &str,
2528    reason: &str,
2529    decided_at: &str,
2530    signing_key: Option<&ed25519_dalek::SigningKey>,
2531    provenance: Option<&crate::provenance::Provenance>,
2532) -> Result<String, String> {
2533    let mut event = events::new_review_decision_event(
2534        proposal_id,
2535        proposal_kind,
2536        verdict,
2537        applied_event_id,
2538        reviewer,
2539        reason,
2540        Some(decided_at),
2541    )?;
2542    if let Some(provenance) = provenance
2543        && !provenance.is_empty()
2544    {
2545        crate::provenance::attach_to_payload(&mut event.payload, provenance)?;
2546        event.id = events::compute_event_id(&event);
2547    }
2548    if let Some(key) = signing_key {
2549        event.signature = Some(crate::sign::sign_event(&event, key)?);
2550    }
2551    let event_id = event.id.clone();
2552    frontier.events.push(event);
2553    mark_proof_stale(
2554        frontier,
2555        format!("Recorded review decision on proposal {proposal_id} after latest proof export"),
2556    );
2557    Ok(event_id)
2558}
2559
2560#[allow(clippy::too_many_arguments)]
2561fn reject_proposal_in_frontier_signed_at(
2562    frontier: &mut Project,
2563    proposal_id: &str,
2564    reviewer: &str,
2565    reason: &str,
2566    authority: DecisionAuthority<'_>,
2567    provenance: Option<&crate::provenance::Provenance>,
2568    decided_at: &str,
2569) -> Result<(), String> {
2570    validate_reviewer_identity(reviewer)?;
2571    // A reject is a truth-bearing review verdict with no process exception:
2572    // burying a proposal is as much a decision as applying one. It is
2573    // reserved for a registered human reviewer executing a Decision Plan.
2574    if reviewer.starts_with("agent:") || reviewer.starts_with("ci:") {
2575        return Err(format!(
2576            "reviewer '{reviewer}' may not reject proposals: review decisions are \
2577             reserved for named human reviewers (key custody). Agents may propose, \
2578             attach mechanical evidence, or draft — never decide."
2579        ));
2580    }
2581    if reason.trim().is_empty() {
2582        return Err("Decision reason must be non-empty".to_string());
2583    }
2584    chrono::DateTime::parse_from_rfc3339(decided_at)
2585        .map_err(|error| format!("decision time is invalid: {error}"))?;
2586    let index = frontier
2587        .proposals
2588        .iter()
2589        .position(|proposal| proposal.id == proposal_id)
2590        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?;
2591    match frontier.proposals[index].status.as_str() {
2592        "pending_review" | "accepted" | "needs_revision" => {}
2593        "rejected" => {
2594            return Err(format!("Proposal {} is already rejected", proposal_id));
2595        }
2596        "applied" => {
2597            return Err(format!("Proposal {} is already applied", proposal_id));
2598        }
2599        other => {
2600            return Err(format!("Unsupported proposal status '{}'", other));
2601        }
2602    }
2603    let proposal_kind = frontier.proposals[index].kind.clone();
2604    let proposal = frontier.proposals[index].clone();
2605    enforce_decision_authority(frontier, &proposal, reviewer, decided_at, &authority)?;
2606    let signing_key = authority.signing_key();
2607    frontier.proposals[index].status = "rejected".to_string();
2608    frontier.proposals[index].reviewed_by = Some(reviewer.to_string());
2609    frontier.proposals[index].reviewed_at = Some(decided_at.to_string());
2610    frontier.proposals[index].decision_reason = Some(reason.to_string());
2611    push_signed_review_event(
2612        frontier,
2613        proposal_id,
2614        &proposal_kind,
2615        "rejected",
2616        None,
2617        reviewer,
2618        reason,
2619        decided_at,
2620        signing_key,
2621        provenance,
2622    )?;
2623    Ok(())
2624}
2625
2626fn prepared_decision_mutation(
2627    frontier: &Project,
2628    first_event: usize,
2629    primary_event_id: String,
2630    proposal_id: &str,
2631    reviewer: &str,
2632) -> Result<PreparedDecisionMutation, String> {
2633    let appended = frontier
2634        .events
2635        .get(first_event..)
2636        .ok_or_else(|| "prepared decision event range is invalid".to_string())?;
2637    let appended_event_ids = appended
2638        .iter()
2639        .map(|event| event.id.clone())
2640        .collect::<Vec<_>>();
2641    let decision_event_id = appended
2642        .iter()
2643        .rev()
2644        .find(|event| {
2645            event.target.r#type == "proposal"
2646                && event.target.id == proposal_id
2647                && matches!(
2648                    event.kind.as_str(),
2649                    events::EVENT_KIND_REVIEW_ACCEPTED | events::EVENT_KIND_REVIEW_REJECTED
2650                )
2651        })
2652        .map(|event| event.id.clone())
2653        .ok_or_else(|| "prepared decision did not append a review decision event".to_string())?;
2654    let prepared = PreparedDecisionMutation {
2655        primary_event_id,
2656        appended_event_ids,
2657        decision_event_id,
2658        proposal_id: proposal_id.to_string(),
2659        reviewer: reviewer.to_string(),
2660        first_event,
2661        event_count_after: frontier.events.len(),
2662        binding: PreparedDecisionBinding::Unbound,
2663    };
2664    validate_prepared_decision_invariants(frontier, &prepared, true)?;
2665    Ok(prepared)
2666}
2667
2668fn clone_project(project: &Project) -> Result<Project, String> {
2669    serde_json::from_value(serde_json::to_value(project).map_err(|error| error.to_string())?)
2670        .map_err(|error| error.to_string())
2671}
2672
2673fn decision_root_refs(event: &StateEvent) -> Result<Vec<String>, String> {
2674    let Some(provenance) = event.payload.get("provenance") else {
2675        return Ok(Vec::new());
2676    };
2677    let object = provenance
2678        .as_object()
2679        .ok_or_else(|| format!("event {} provenance must be an object", event.id))?;
2680    let Some(input_refs) = object.get("input_refs") else {
2681        return Ok(Vec::new());
2682    };
2683    let input_refs = input_refs
2684        .as_array()
2685        .ok_or_else(|| format!("event {} provenance.input_refs must be an array", event.id))?;
2686    let mut refs = Vec::new();
2687    for value in input_refs {
2688        let value = value.as_str().ok_or_else(|| {
2689            format!(
2690                "event {} provenance.input_refs must contain only strings",
2691                event.id
2692            )
2693        })?;
2694        if value.starts_with(crate::provenance::DECISION_ROOT_INPUT_REF_PREFIX) {
2695            refs.push(value.to_string());
2696        }
2697    }
2698    Ok(refs)
2699}
2700
2701fn validate_prepared_decision_invariants(
2702    frontier: &Project,
2703    prepared: &PreparedDecisionMutation,
2704    require_unsigned: bool,
2705) -> Result<(), String> {
2706    if prepared.appended_event_ids.is_empty() {
2707        return Err("prepared decision has no appended events".to_string());
2708    }
2709    if prepared.first_event + prepared.appended_event_ids.len() != prepared.event_count_after
2710        || prepared.event_count_after > frontier.events.len()
2711    {
2712        return Err("prepared decision event range is not contiguous".to_string());
2713    }
2714    let events = &frontier.events[prepared.first_event..prepared.event_count_after];
2715    let exact_ids = events
2716        .iter()
2717        .map(|event| event.id.as_str())
2718        .collect::<Vec<_>>();
2719    if exact_ids
2720        != prepared
2721            .appended_event_ids
2722            .iter()
2723            .map(String::as_str)
2724            .collect::<Vec<_>>()
2725    {
2726        return Err("prepared decision ids do not match their contiguous event range".to_string());
2727    }
2728    let unique_ids = prepared.appended_event_ids.iter().collect::<BTreeSet<_>>();
2729    if unique_ids.len() != prepared.appended_event_ids.len() {
2730        return Err("prepared decision contains duplicate event ids".to_string());
2731    }
2732    if !unique_ids.contains(&prepared.primary_event_id)
2733        || !unique_ids.contains(&prepared.decision_event_id)
2734    {
2735        return Err(
2736            "prepared primary and decision events must belong to the exact event set".to_string(),
2737        );
2738    }
2739    for event_id in &prepared.appended_event_ids {
2740        if frontier
2741            .events
2742            .iter()
2743            .filter(|event| event.id == *event_id)
2744            .count()
2745            != 1
2746        {
2747            return Err(format!(
2748                "prepared decision event id is not globally unique: {event_id}"
2749            ));
2750        }
2751    }
2752
2753    let proposals = frontier
2754        .proposals
2755        .iter()
2756        .filter(|proposal| proposal.id == prepared.proposal_id)
2757        .collect::<Vec<_>>();
2758    if proposals.len() != 1 {
2759        return Err(format!(
2760            "prepared proposal {} is missing or duplicated",
2761            prepared.proposal_id
2762        ));
2763    }
2764    let proposal = proposals[0];
2765    let mut decision_events = 0_usize;
2766    for event in events {
2767        if event.id != events::compute_event_id(event) {
2768            return Err(format!("prepared event {} id does not rederive", event.id));
2769        }
2770        if event.actor.id != prepared.reviewer
2771            || event.actor.r#type != events::actor_kind(&prepared.reviewer)
2772        {
2773            return Err(format!(
2774                "prepared event {} actor does not match reviewer {}",
2775                event.id, prepared.reviewer
2776            ));
2777        }
2778        if event.payload.get("proposal_id").and_then(Value::as_str)
2779            != Some(prepared.proposal_id.as_str())
2780        {
2781            return Err(format!(
2782                "prepared event {} does not bind proposal {}",
2783                event.id, prepared.proposal_id
2784            ));
2785        }
2786        if require_unsigned && event.signature.is_some() {
2787            return Err(format!("prepared event {} is already signed", event.id));
2788        }
2789        let refs = decision_root_refs(event)?;
2790        let is_review_decision = event.target.r#type == "proposal"
2791            && event.target.id == prepared.proposal_id
2792            && matches!(
2793                event.kind.as_str(),
2794                events::EVENT_KIND_REVIEW_ACCEPTED | events::EVENT_KIND_REVIEW_REJECTED
2795            );
2796        if is_review_decision {
2797            decision_events += 1;
2798            if event.id != prepared.decision_event_id {
2799                return Err("prepared set contains an untracked review decision event".to_string());
2800            }
2801        }
2802        if event.id == prepared.decision_event_id {
2803            if !is_review_decision {
2804                return Err("prepared decision event has inconsistent target or kind".to_string());
2805            }
2806            match &prepared.binding {
2807                PreparedDecisionBinding::Unbound if !refs.is_empty() => {
2808                    return Err(
2809                        "unbound prepared decision already carries a decision-root reference"
2810                            .to_string(),
2811                    );
2812                }
2813                PreparedDecisionBinding::Unbound => {}
2814                PreparedDecisionBinding::Bound { decision_root } => {
2815                    let expected = crate::provenance::decision_root_input_ref(decision_root)?;
2816                    if refs != [expected] {
2817                        return Err(
2818                            "bound prepared decision must carry exactly one canonical decision-root reference"
2819                                .to_string(),
2820                        );
2821                    }
2822                }
2823            }
2824        } else if !refs.is_empty() {
2825            return Err(format!(
2826                "non-decision event {} carries a decision-root reference",
2827                event.id
2828            ));
2829        }
2830    }
2831    if decision_events != 1 {
2832        return Err("prepared decision must contain exactly one review decision event".to_string());
2833    }
2834    let decision_event = events
2835        .iter()
2836        .find(|event| event.id == prepared.decision_event_id)
2837        .expect("membership checked above");
2838    if decision_event
2839        .payload
2840        .get("proposal_kind")
2841        .and_then(Value::as_str)
2842        != Some(proposal.kind.as_str())
2843    {
2844        return Err("prepared decision event proposal kind is inconsistent".to_string());
2845    }
2846    if proposal.reviewed_by.as_deref() != Some(prepared.reviewer.as_str())
2847        || proposal.reviewed_at.as_deref() != Some(decision_event.timestamp.as_str())
2848    {
2849        return Err(
2850            "prepared proposal review metadata does not match its decision event".to_string(),
2851        );
2852    }
2853    match proposal.status.as_str() {
2854        "applied"
2855            if proposal.applied_event_id.as_deref() == Some(prepared.primary_event_id.as_str())
2856                && decision_event.kind == events::EVENT_KIND_REVIEW_ACCEPTED => {}
2857        "rejected"
2858            if proposal.applied_event_id.is_none()
2859                && decision_event.kind == events::EVENT_KIND_REVIEW_REJECTED => {}
2860        _ => {
2861            return Err(
2862                "prepared proposal status/applied_event_id is inconsistent with its primary event"
2863                    .to_string(),
2864            );
2865        }
2866    }
2867    Ok(())
2868}
2869
2870/// Apply one exact accept to an in-memory project without receiving or reading
2871/// a private key. The caller supplies the sole timestamp used by the proposal
2872/// status, every semantic state timestamp, and every appended event.
2873///
2874/// This mutates only the provided `Project`. It always appends an unsigned
2875/// `review.accepted` event in addition to any domain events. After the final
2876/// plan root is known, bind it with [`bind_decision_root_to_prepared`]; then,
2877/// after a locked rederivation, sign exactly the returned event set with
2878/// [`sign_prepared_decision_events`]. Legacy policy retirement is deliberately
2879/// excluded because its accepted event is valid only when atomically journaled
2880/// with fixed Authority-file deletions by vela-cli's private Decision Plan.
2881pub fn prepare_proposal_accept_in_memory_at(
2882    frontier: &mut Project,
2883    proposal_id: &str,
2884    reviewer: &str,
2885    reason: &str,
2886    provenance: Option<&crate::provenance::Provenance>,
2887    decided_at: &str,
2888) -> Result<PreparedDecisionMutation, String> {
2889    let mut candidate = clone_project(frontier)?;
2890    let prepared = prepare_proposal_accept_on_candidate(
2891        &mut candidate,
2892        proposal_id,
2893        reviewer,
2894        reason,
2895        provenance,
2896        decided_at,
2897    )?;
2898    *frontier = candidate;
2899    Ok(prepared)
2900}
2901
2902fn prepare_proposal_accept_on_candidate(
2903    frontier: &mut Project,
2904    proposal_id: &str,
2905    reviewer: &str,
2906    reason: &str,
2907    provenance: Option<&crate::provenance::Provenance>,
2908    decided_at: &str,
2909) -> Result<PreparedDecisionMutation, String> {
2910    if frontier.proposals.iter().any(|proposal| {
2911        proposal.id == proposal_id
2912            && proposal.kind == policy_accept::LEGACY_POLICY_RETIREMENT_PROPOSAL_KIND
2913    }) {
2914        return Err(
2915            "legacy-policy retirement cannot use a public protocol preparation API; use the recoverable human Decision Plan"
2916                .to_string(),
2917        );
2918    }
2919    validate_human_reviewer_authority_at(frontier, reviewer, decided_at)?;
2920    let first_event = frontier.events.len();
2921    let primary_event_id = accept_proposal_in_frontier_with_authority_at(
2922        frontier,
2923        proposal_id,
2924        reviewer,
2925        reason,
2926        DecisionAuthority::PlanPreparation,
2927        provenance,
2928        Some(decided_at),
2929        true,
2930    )?;
2931    crate::sources::materialize_project(frontier);
2932    prepared_decision_mutation(
2933        frontier,
2934        first_event,
2935        primary_event_id,
2936        proposal_id,
2937        reviewer,
2938    )
2939}
2940
2941/// Clone-only convenience wrapper for the first item in a Decision Plan.
2942/// Callers can chain later items by applying the mutating in-memory seam to the
2943/// returned candidate; the input project is never changed. The same legacy
2944/// policy retirement exclusion as [`prepare_proposal_accept_in_memory_at`]
2945/// applies.
2946pub fn prepare_proposal_accept_candidate_at(
2947    frontier: &Project,
2948    proposal_id: &str,
2949    reviewer: &str,
2950    reason: &str,
2951    provenance: Option<&crate::provenance::Provenance>,
2952    decided_at: &str,
2953) -> Result<(Project, PreparedDecisionMutation), String> {
2954    let mut candidate = clone_project(frontier)?;
2955    let prepared = prepare_proposal_accept_on_candidate(
2956        &mut candidate,
2957        proposal_id,
2958        reviewer,
2959        reason,
2960        provenance,
2961        decided_at,
2962    )?;
2963    Ok((candidate, prepared))
2964}
2965
2966/// Apply one exact reject to an in-memory project without receiving or reading
2967/// a private key. The result is an unsigned, fixed-time `review.rejected`
2968/// event, optionally carrying a decision-root provenance input reference.
2969pub fn prepare_proposal_reject_in_memory_at(
2970    frontier: &mut Project,
2971    proposal_id: &str,
2972    reviewer: &str,
2973    reason: &str,
2974    provenance: Option<&crate::provenance::Provenance>,
2975    decided_at: &str,
2976) -> Result<PreparedDecisionMutation, String> {
2977    let mut candidate = clone_project(frontier)?;
2978    let prepared = prepare_proposal_reject_on_candidate(
2979        &mut candidate,
2980        proposal_id,
2981        reviewer,
2982        reason,
2983        provenance,
2984        decided_at,
2985    )?;
2986    *frontier = candidate;
2987    Ok(prepared)
2988}
2989
2990fn prepare_proposal_reject_on_candidate(
2991    frontier: &mut Project,
2992    proposal_id: &str,
2993    reviewer: &str,
2994    reason: &str,
2995    provenance: Option<&crate::provenance::Provenance>,
2996    decided_at: &str,
2997) -> Result<PreparedDecisionMutation, String> {
2998    validate_human_reviewer_authority_at(frontier, reviewer, decided_at)?;
2999    let first_event = frontier.events.len();
3000    reject_proposal_in_frontier_signed_at(
3001        frontier,
3002        proposal_id,
3003        reviewer,
3004        reason,
3005        DecisionAuthority::PlanPreparation,
3006        provenance,
3007        decided_at,
3008    )?;
3009    let primary_event_id = frontier
3010        .events
3011        .get(first_event)
3012        .map(|event| event.id.clone())
3013        .ok_or_else(|| "prepared reject appended no event".to_string())?;
3014    prepared_decision_mutation(
3015        frontier,
3016        first_event,
3017        primary_event_id,
3018        proposal_id,
3019        reviewer,
3020    )
3021}
3022
3023/// Clone-only reject counterpart to
3024/// [`prepare_proposal_accept_candidate_at`].
3025pub fn prepare_proposal_reject_candidate_at(
3026    frontier: &Project,
3027    proposal_id: &str,
3028    reviewer: &str,
3029    reason: &str,
3030    provenance: Option<&crate::provenance::Provenance>,
3031    decided_at: &str,
3032) -> Result<(Project, PreparedDecisionMutation), String> {
3033    let mut candidate = clone_project(frontier)?;
3034    let prepared = prepare_proposal_reject_on_candidate(
3035        &mut candidate,
3036        proposal_id,
3037        reviewer,
3038        reason,
3039        provenance,
3040        decided_at,
3041    )?;
3042    Ok((candidate, prepared))
3043}
3044
3045/// Insert the final decision root into the prepared review event and rederive
3046/// its content address before any signature is made.
3047///
3048/// Only the dedicated `review.*` event carries this input reference. Domain and
3049/// fanout event IDs therefore remain stable, including the
3050/// `review.accepted.payload.applied_event_id` pointer, and the Decision Plan has
3051/// no hash cycle. Policy-head acceptance uses its review event as the primary
3052/// event, so this helper also updates the proposal's cached applied-event id.
3053pub fn bind_decision_root_to_prepared(
3054    frontier: &mut Project,
3055    prepared: &mut PreparedDecisionMutation,
3056    decision_root: &str,
3057) -> Result<(), String> {
3058    crate::provenance::decision_root_input_ref(decision_root)?;
3059    match prepared.decision_root() {
3060        Some(existing) if existing == decision_root => {
3061            return validate_prepared_decision_invariants(frontier, prepared, true);
3062        }
3063        Some(_) => {
3064            return Err(
3065                "prepared decision is already bound; rebuild it before changing the root"
3066                    .to_string(),
3067            );
3068        }
3069        None => {}
3070    }
3071    let mut candidate = clone_project(frontier)?;
3072    let mut candidate_prepared = prepared.clone();
3073    bind_decision_root_to_prepared_inner(&mut candidate, &mut candidate_prepared, decision_root)?;
3074    validate_prepared_decision_invariants(&candidate, &candidate_prepared, true)?;
3075    *frontier = candidate;
3076    *prepared = candidate_prepared;
3077    Ok(())
3078}
3079
3080fn bind_decision_root_to_prepared_inner(
3081    frontier: &mut Project,
3082    prepared: &mut PreparedDecisionMutation,
3083    decision_root: &str,
3084) -> Result<(), String> {
3085    validate_prepared_decision_invariants(frontier, prepared, true)?;
3086    let old_event_id = prepared.decision_event_id.clone();
3087    let index = frontier
3088        .events
3089        .iter()
3090        .position(|event| event.id == old_event_id)
3091        .ok_or_else(|| format!("prepared decision event not found: {old_event_id}"))?;
3092    let event = &frontier.events[index];
3093    if event.signature.is_some() {
3094        return Err("cannot bind a decision root after the decision event is signed".to_string());
3095    }
3096    if !matches!(
3097        event.kind.as_str(),
3098        events::EVENT_KIND_REVIEW_ACCEPTED | events::EVENT_KIND_REVIEW_REJECTED
3099    ) {
3100        return Err(format!(
3101            "prepared decision event {} has non-review kind '{}'",
3102            event.id, event.kind
3103        ));
3104    }
3105    let mut candidate_event: StateEvent =
3106        serde_json::from_value(serde_json::to_value(event).map_err(|error| error.to_string())?)
3107            .map_err(|error| error.to_string())?;
3108    let mut provenance = candidate_event
3109        .payload
3110        .get("provenance")
3111        .cloned()
3112        .map(serde_json::from_value::<crate::provenance::Provenance>)
3113        .transpose()
3114        .map_err(|error| format!("prepared decision provenance is invalid: {error}"))?
3115        .unwrap_or_default();
3116    provenance.bind_decision_root(decision_root)?;
3117    crate::provenance::attach_to_payload(&mut candidate_event.payload, &provenance)?;
3118    candidate_event.id = events::compute_event_id(&candidate_event);
3119    let new_event_id = candidate_event.id.clone();
3120
3121    if frontier
3122        .events
3123        .iter()
3124        .enumerate()
3125        .any(|(other_index, other)| other_index != index && other.id == new_event_id)
3126    {
3127        return Err(format!(
3128            "decision-root binding collides with existing event {new_event_id}"
3129        ));
3130    }
3131    frontier.events[index] = candidate_event;
3132    for proposal in &mut frontier.proposals {
3133        if proposal.applied_event_id.as_deref() == Some(old_event_id.as_str()) {
3134            proposal.applied_event_id = Some(new_event_id.clone());
3135        }
3136    }
3137    for event_id in &mut prepared.appended_event_ids {
3138        if *event_id == old_event_id {
3139            *event_id = new_event_id.clone();
3140        }
3141    }
3142    if prepared.primary_event_id == old_event_id {
3143        prepared.primary_event_id = new_event_id.clone();
3144    }
3145    prepared.decision_event_id = new_event_id;
3146    prepared.binding = PreparedDecisionBinding::Bound {
3147        decision_root: decision_root.to_string(),
3148    };
3149    Ok(())
3150}
3151
3152/// Sign the exact unsigned events returned by a prepared decision mutation.
3153///
3154/// Every event is validated before any signature is written, so a malformed or
3155/// stale set produces zero signature delta. This function performs no I/O and
3156/// no clock read; key resolution and human confirmation remain CLI concerns.
3157pub fn sign_prepared_decision_events(
3158    frontier: &mut Project,
3159    prepared: &PreparedDecisionMutation,
3160    reviewer: &str,
3161    signing_key: &ed25519_dalek::SigningKey,
3162) -> Result<(), String> {
3163    if reviewer != prepared.reviewer {
3164        return Err(format!(
3165            "prepared reviewer '{}' does not match signing reviewer '{reviewer}'",
3166            prepared.reviewer
3167        ));
3168    }
3169    if !prepared.is_bound() {
3170        return Err("prepared decision must be decision-root bound before signing".to_string());
3171    }
3172    validate_prepared_decision_invariants(frontier, prepared, true)?;
3173    let decision_event = &frontier.events[prepared.first_event
3174        + prepared
3175            .appended_event_ids
3176            .iter()
3177            .position(|event_id| event_id == &prepared.decision_event_id)
3178            .expect("prepared invariant checks decision-event membership")];
3179    let actor =
3180        validate_human_reviewer_authority_at(frontier, reviewer, &decision_event.timestamp)?;
3181    let derived = hex::encode(signing_key.verifying_key().to_bytes());
3182    if !derived.eq_ignore_ascii_case(&actor.public_key) {
3183        return Err(format!(
3184            "the supplied key does not match {reviewer}'s registered decision key"
3185        ));
3186    }
3187    let indexes = (prepared.first_event..prepared.event_count_after).collect::<Vec<_>>();
3188    let signatures = indexes
3189        .iter()
3190        .map(|index| crate::sign::sign_event(&frontier.events[*index], signing_key))
3191        .collect::<Result<Vec<_>, _>>()?;
3192    for (index, signature) in indexes.into_iter().zip(signatures) {
3193        frontier.events[index].signature = Some(signature);
3194    }
3195    Ok(())
3196}
3197
3198/// Validate the exact event set before or after an external signer operates.
3199///
3200/// This is the seed-free counterpart to [`sign_prepared_decision_events`]. It
3201/// exposes no authority surface: the caller still has to obtain Ed25519
3202/// signatures and every returned signature is verified by the decision
3203/// executor before a frontier write. The helper exists so a separate custody
3204/// process can sign without returning private key material to `vela`.
3205pub fn validate_prepared_decision_for_external_signing(
3206    frontier: &Project,
3207    prepared: &PreparedDecisionMutation,
3208    reviewer: &str,
3209    require_unsigned: bool,
3210) -> Result<Vec<StateEvent>, String> {
3211    if reviewer != prepared.reviewer {
3212        return Err(format!(
3213            "prepared reviewer '{}' does not match signing reviewer '{reviewer}'",
3214            prepared.reviewer
3215        ));
3216    }
3217    if !prepared.is_bound() {
3218        return Err("prepared decision must be decision-root bound before signing".to_string());
3219    }
3220    validate_prepared_decision_invariants(frontier, prepared, require_unsigned)?;
3221    let decision_event = &frontier.events[prepared.first_event
3222        + prepared
3223            .appended_event_ids
3224            .iter()
3225            .position(|event_id| event_id == &prepared.decision_event_id)
3226            .expect("prepared invariant checks decision-event membership")];
3227    validate_human_reviewer_authority_at(frontier, reviewer, &decision_event.timestamp)?;
3228    Ok((prepared.first_event..prepared.event_count_after)
3229        .map(|index| frontier.events[index].clone())
3230        .collect())
3231}
3232
3233pub(crate) fn apply_proposal(
3234    frontier: &mut Project,
3235    proposal: &StateProposal,
3236    reviewer: &str,
3237    decision_reason: &str,
3238    provenance: Option<&crate::provenance::Provenance>,
3239) -> Result<String, String> {
3240    apply_proposal_at(
3241        frontier,
3242        proposal,
3243        reviewer,
3244        decision_reason,
3245        provenance,
3246        None,
3247    )
3248}
3249
3250fn apply_proposal_at(
3251    frontier: &mut Project,
3252    proposal: &StateProposal,
3253    reviewer: &str,
3254    decision_reason: &str,
3255    provenance: Option<&crate::provenance::Provenance>,
3256    fixed_decided_at: Option<&str>,
3257) -> Result<String, String> {
3258    // Phase L: retraction emits a fan of events — one for the source
3259    // and one `finding.dependency_invalidated` per dependent in BFS
3260    // order. apply_retract is responsible for pushing all of them in
3261    // sequence; this branch only assigns the primary event ID.
3262    if proposal.kind.as_str() == "finding.retract" {
3263        let events = apply_retract(
3264            frontier,
3265            proposal,
3266            reviewer,
3267            decision_reason,
3268            fixed_decided_at,
3269        )?;
3270        let primary_id = events
3271            .first()
3272            .map(|event| event.id.clone())
3273            .ok_or_else(|| "apply_retract returned no events".to_string())?;
3274        for event in events {
3275            frontier.events.push(event);
3276        }
3277        mark_proof_stale(
3278            frontier,
3279            format!("Applied proposal {} after latest proof export", proposal.id),
3280        );
3281        return Ok(primary_id);
3282    }
3283    // v0.55: confidence_revise can also fan out a cascade when the new
3284    // score crosses below the 0.5 propagation threshold. Same fan-out
3285    // pattern as retract.
3286    if proposal.kind.as_str() == "finding.confidence_revise" {
3287        let events = apply_confidence_revise(
3288            frontier,
3289            proposal,
3290            reviewer,
3291            decision_reason,
3292            fixed_decided_at,
3293        )?;
3294        let primary_id = events
3295            .first()
3296            .map(|event| event.id.clone())
3297            .ok_or_else(|| "apply_confidence_revise returned no events".to_string())?;
3298        for event in events {
3299            frontier.events.push(event);
3300        }
3301        mark_proof_stale(
3302            frontier,
3303            format!("Applied proposal {} after latest proof export", proposal.id),
3304        );
3305        return Ok(primary_id);
3306    }
3307    let mut event = match proposal.kind.as_str() {
3308        "finding.add" => apply_add(frontier, proposal, reviewer, decision_reason)?,
3309        "finding.review" => apply_review(frontier, proposal, reviewer, decision_reason)?,
3310        "research_trace.review" | "correction_return.review" => {
3311            apply_frontier_observation_review(proposal, reviewer, decision_reason)?
3312        }
3313        "finding.caveat" => apply_caveat(
3314            frontier,
3315            proposal,
3316            reviewer,
3317            decision_reason,
3318            fixed_decided_at,
3319        )?,
3320        "finding.note" => apply_note(
3321            frontier,
3322            proposal,
3323            reviewer,
3324            decision_reason,
3325            fixed_decided_at,
3326        )?,
3327        "finding.reject" => apply_reject(frontier, proposal, reviewer, decision_reason)?,
3328        "finding.contribution.recorded" => {
3329            apply_contribution(frontier, proposal, reviewer, decision_reason)?
3330        }
3331        "finding.supersede" => apply_supersede(
3332            frontier,
3333            proposal,
3334            reviewer,
3335            decision_reason,
3336            fixed_decided_at,
3337        )?,
3338        "artifact.assert" => apply_artifact_assert(frontier, proposal, reviewer, decision_reason)?,
3339        "artifact.retract" => {
3340            apply_artifact_retract(frontier, proposal, reviewer, decision_reason)?
3341        }
3342        "verifier.attach" => apply_verifier_attach(frontier, proposal, reviewer, decision_reason)?,
3343        // v0.56: mechanical evidence-atom locator repair.
3344        "evidence_atom.locator_repair" => {
3345            apply_evidence_atom_locator_repair(frontier, proposal, reviewer, decision_reason)?
3346        }
3347        // v0.57: mechanical finding-level span repair.
3348        "finding.span_repair" => {
3349            apply_finding_span_repair(frontier, proposal, reviewer, decision_reason)?
3350        }
3351        other => return Err(format!("Unsupported proposal kind '{other}'")),
3352    };
3353    if let Some(decided_at) = fixed_decided_at {
3354        event.timestamp = decided_at.to_string();
3355        event.id = events::compute_event_id(&event);
3356    }
3357    // Co-authorship: when a non-human (an AI that drafted, CI that attested)
3358    // contributed, record it as signed-over attribution on this single decision
3359    // event. The reviewer stays the accountable signer; the provenance carries
3360    // zero authority (validated non-human in `attach_to_payload`). Because the
3361    // block enters the signed payload, the content-addressed id is re-derived.
3362    // None leaves the event byte-identical, so existing frontiers are untouched.
3363    if let Some(prov) = provenance
3364        && !prov.is_empty()
3365    {
3366        crate::provenance::attach_to_payload(&mut event.payload, prov)?;
3367        event.id = events::event_id(&event);
3368    }
3369    let event_id = event.id.clone();
3370    frontier.events.push(event);
3371    mark_proof_stale(
3372        frontier,
3373        format!("Applied proposal {} after latest proof export", proposal.id),
3374    );
3375    Ok(event_id)
3376}
3377
3378fn apply_frontier_observation_review(
3379    proposal: &StateProposal,
3380    reviewer: &str,
3381    decision_reason: &str,
3382) -> Result<StateEvent, String> {
3383    match proposal.kind.as_str() {
3384        "research_trace.review" => validate_research_trace_review_payload(proposal)?,
3385        "correction_return.review" => validate_correction_return_review_payload(proposal)?,
3386        other => {
3387            return Err(format!(
3388                "Unsupported frontier observation proposal kind '{other}'"
3389            ));
3390        }
3391    }
3392    let mut event = StateEvent {
3393        schema: events::EVENT_SCHEMA.to_string(),
3394        id: String::new(),
3395        kind: events::EVENT_KIND_FRONTIER_OBSERVATION_REVIEWED.into(),
3396        target: proposal.target.clone(),
3397        actor: StateActor {
3398            id: reviewer.to_string(),
3399            r#type: "human".to_string(),
3400        },
3401        timestamp: Utc::now().to_rfc3339(),
3402        reason: proposal.reason.clone(),
3403        before_hash: NULL_HASH.to_string(),
3404        after_hash: NULL_HASH.to_string(),
3405        payload: json!({
3406            "proposal_id": proposal.id,
3407            "proposal_kind": proposal.kind,
3408            "status": "accepted",
3409            "decision_reason": decision_reason,
3410            "reviewed_payload": proposal.payload,
3411            "source_refs": proposal.source_refs,
3412        }),
3413        caveats: proposal.caveats.clone(),
3414        signature: None,
3415    };
3416    events::validate_event_payload(event.kind.as_str(), &event.payload)?;
3417    event.id = events::compute_event_id(&event);
3418    Ok(event)
3419}
3420
3421/// v0.14: `finding.supersede` — first-class flow for *changing a claim's text*.
3422///
3423/// Until v0.14 the only way to update a finding was to stack caveats/notes
3424/// on top, because the assertion text is part of the content address. The
3425/// substrate-correct path for a real correction is a *new* content-addressed
3426/// finding that explicitly supersedes the old one. This proposal kind:
3427///
3428/// 1. Validates the old finding exists and is not already superseded.
3429/// 2. Adds the new finding bundle (a fresh `vf_…` content address) to
3430///    `frontier.findings`.
3431/// 3. Auto-injects a `supersedes` link from the new finding's `links` to the
3432///    old finding's id (if not already present in the payload).
3433/// 4. Sets `flags.superseded = true` on the old finding.
3434/// 5. Emits a `finding.superseded` canonical event targeting the *old*
3435///    finding (since that's the state change). The new finding's existence
3436///    is recorded in the event payload as `new_finding_id`.
3437///
3438/// Both findings remain queryable; readers walk the supersedes chain via
3439/// the link or via the `flags.superseded` marker.
3440fn apply_supersede(
3441    frontier: &mut Project,
3442    proposal: &StateProposal,
3443    reviewer: &str,
3444    _decision_reason: &str,
3445    fixed_decided_at: Option<&str>,
3446) -> Result<StateEvent, String> {
3447    use crate::bundle::Link;
3448
3449    let old_id = proposal.target.id.clone();
3450    let new_finding_value = proposal
3451        .payload
3452        .get("new_finding")
3453        .ok_or("finding.supersede proposal missing payload.new_finding")?
3454        .clone();
3455    let mut new_finding: FindingBundle = serde_json::from_value(new_finding_value)
3456        .map_err(|e| format!("Invalid finding.supersede payload.new_finding: {e}"))?;
3457
3458    // Locate the old finding before mutating; capture before_hash for the event.
3459    let old_idx = find_finding_index(frontier, &old_id)?;
3460    if frontier.findings[old_idx].flags.superseded {
3461        return Err(format!(
3462            "Refusing to supersede already-superseded finding {old_id}"
3463        ));
3464    }
3465    if new_finding.id == old_id {
3466        return Err(
3467            "Refusing to supersede with a finding that has the same content address as the old finding (assertion / type / provenance_id are unchanged)".to_string(),
3468        );
3469    }
3470    if frontier
3471        .findings
3472        .iter()
3473        .any(|existing| existing.id == new_finding.id)
3474    {
3475        return Err(format!(
3476            "Refusing to add superseding finding with existing finding ID {}",
3477            new_finding.id
3478        ));
3479    }
3480    let before_hash = events::finding_hash(&frontier.findings[old_idx]);
3481
3482    // Auto-inject the supersedes link if the caller didn't already include it.
3483    let already_links_old = new_finding
3484        .links
3485        .iter()
3486        .any(|l| l.target == old_id && l.link_type == "supersedes");
3487    if !already_links_old {
3488        new_finding.links.push(Link {
3489            target: old_id.clone(),
3490            link_type: "supersedes".to_string(),
3491            note: format!(
3492                "Supersedes {old_id} via finding.supersede proposal {}.",
3493                proposal.id
3494            ),
3495            inferred_by: "reviewer".to_string(),
3496            created_at: fixed_decided_at
3497                .map(ToString::to_string)
3498                .unwrap_or_else(|| Utc::now().to_rfc3339()),
3499            mechanism: None,
3500        });
3501    }
3502
3503    let new_finding_id = new_finding.id.clone();
3504    frontier.findings.push(new_finding);
3505    frontier.findings[old_idx].flags.superseded = true;
3506    let after_hash = events::finding_hash(&frontier.findings[old_idx]);
3507
3508    Ok(events::new_finding_event(events::FindingEventInput {
3509        kind: "finding.superseded",
3510        finding_id: &old_id,
3511        actor_id: reviewer,
3512        actor_type: events::actor_kind(reviewer),
3513        reason: &proposal.reason,
3514        before_hash: &before_hash,
3515        after_hash: &after_hash,
3516        payload: json!({
3517            "proposal_id": proposal.id,
3518            "new_finding_id": new_finding_id,
3519        }),
3520        caveats: proposal.caveats.clone(),
3521        timestamp: fixed_decided_at,
3522    }))
3523}
3524
3525fn apply_add(
3526    frontier: &mut Project,
3527    proposal: &StateProposal,
3528    reviewer: &str,
3529    _decision_reason: &str,
3530) -> Result<StateEvent, String> {
3531    let finding_value = proposal
3532        .payload
3533        .get("finding")
3534        .ok_or("finding.add proposal missing payload.finding")?
3535        .clone();
3536    let finding: FindingBundle = serde_json::from_value(finding_value)
3537        .map_err(|e| format!("Invalid finding.add payload: {e}"))?;
3538    let finding_id = finding.id.clone();
3539    // Activity is not state: an accepted finding may not depend on an
3540    // activity-plane id (`vac_`/`vrr_`). A search/trace/retrieval is recorded in
3541    // the activity plane and referenced by content address, never admitted as
3542    // accepted lineage (the `activity::assert_not_in_lineage` law, at the write).
3543    if let Some(l) = finding
3544        .links
3545        .iter()
3546        .find(|l| crate::activity::is_activity_id(&l.target))
3547    {
3548        return Err(format!(
3549            "finding.add refused: link target `{}` is an activity-plane id; activity is non-authoritative and cannot enter lineage",
3550            l.target
3551        ));
3552    }
3553    if frontier
3554        .findings
3555        .iter()
3556        .any(|existing| existing.id == finding_id)
3557    {
3558        return Err(format!(
3559            "Refusing to add duplicate finding with existing finding ID {finding_id}"
3560        ));
3561    }
3562    // Prior-art collision: an EXACT duplicate of an accepted finding's
3563    // statement is refused unless the proposal names what it supersedes
3564    // (the Sakana rediscovery failure mode, made mechanical).
3565    {
3566        let new_hash = crate::canonical::normalized_statement_hash(&finding.assertion.text);
3567        let declares_supersession = proposal.payload.get("supersedes").is_some()
3568            || proposal.payload.get("improves_on").is_some();
3569        if !declares_supersession
3570            && let Some(dup) = frontier.findings.iter().find(|f| {
3571                crate::canonical::normalized_statement_hash(&f.assertion.text) == new_hash
3572            })
3573        {
3574            return Err(format!(
3575                "prior-art collision: statement duplicates accepted finding {} — name it via payload.supersedes/improves_on or change the claim",
3576                dup.id
3577            ));
3578        }
3579    }
3580    frontier.findings.push(finding);
3581    let after_hash = events::finding_hash_by_id(frontier, &finding_id);
3582    Ok(events::new_finding_event(events::FindingEventInput {
3583        kind: "finding.asserted",
3584        finding_id: &finding_id,
3585        actor_id: reviewer,
3586        actor_type: events::actor_kind(reviewer),
3587        reason: &proposal.reason,
3588        before_hash: NULL_HASH,
3589        after_hash: &after_hash,
3590        payload: json!({
3591            "proposal_id": proposal.id,
3592        }),
3593        caveats: proposal.caveats.clone(),
3594        timestamp: None,
3595    }))
3596}
3597
3598fn apply_artifact_assert(
3599    frontier: &mut Project,
3600    proposal: &StateProposal,
3601    reviewer: &str,
3602    _decision_reason: &str,
3603) -> Result<StateEvent, String> {
3604    let artifact_value = proposal
3605        .payload
3606        .get("artifact")
3607        .ok_or("artifact.assert proposal missing payload.artifact")?
3608        .clone();
3609    let artifact: Artifact = serde_json::from_value(artifact_value)
3610        .map_err(|e| format!("Invalid artifact.assert payload: {e}"))?;
3611    let artifact_id = artifact.id.clone();
3612    if frontier
3613        .artifacts
3614        .iter()
3615        .any(|existing| existing.id == artifact_id)
3616    {
3617        return Err(format!(
3618            "Refusing to add duplicate artifact with existing id {artifact_id}"
3619        ));
3620    }
3621    frontier.artifacts.push(artifact.clone());
3622    let mut event = StateEvent {
3623        schema: events::EVENT_SCHEMA.to_string(),
3624        id: String::new(),
3625        kind: events::EVENT_KIND_ARTIFACT_ASSERTED.into(),
3626        target: StateTarget {
3627            r#type: "artifact".to_string(),
3628            id: artifact_id,
3629        },
3630        actor: StateActor {
3631            id: reviewer.to_string(),
3632            r#type: if reviewer.starts_with("agent:") {
3633                "agent"
3634            } else {
3635                "human"
3636            }
3637            .to_string(),
3638        },
3639        timestamp: Utc::now().to_rfc3339(),
3640        reason: proposal.reason.clone(),
3641        before_hash: NULL_HASH.to_string(),
3642        after_hash: NULL_HASH.to_string(),
3643        payload: json!({
3644            "proposal_id": proposal.id,
3645            "artifact": artifact,
3646        }),
3647        caveats: proposal.caveats.clone(),
3648        signature: None,
3649    };
3650    events::validate_event_payload(event.kind.as_str(), &event.payload)?;
3651    event.id = events::compute_event_id(&event);
3652    Ok(event)
3653}
3654
3655fn apply_artifact_retract(
3656    frontier: &mut Project,
3657    proposal: &StateProposal,
3658    reviewer: &str,
3659    _decision_reason: &str,
3660) -> Result<StateEvent, String> {
3661    let artifact_id = proposal.target.id.as_str();
3662    let artifact = frontier
3663        .artifacts
3664        .iter_mut()
3665        .find(|artifact| artifact.id == artifact_id)
3666        .ok_or_else(|| format!("Artifact not found: {artifact_id}"))?;
3667    if artifact.retracted {
3668        return Err(format!("Artifact {artifact_id} is already retracted"));
3669    }
3670    artifact.retracted = true;
3671    let mut event = StateEvent {
3672        schema: events::EVENT_SCHEMA.to_string(),
3673        id: String::new(),
3674        kind: events::EVENT_KIND_ARTIFACT_RETRACTED.into(),
3675        target: StateTarget {
3676            r#type: "artifact".to_string(),
3677            id: artifact_id.to_string(),
3678        },
3679        actor: StateActor {
3680            id: reviewer.to_string(),
3681            r#type: events::actor_kind(reviewer).to_string(),
3682        },
3683        timestamp: Utc::now().to_rfc3339(),
3684        reason: proposal.reason.clone(),
3685        before_hash: NULL_HASH.to_string(),
3686        after_hash: NULL_HASH.to_string(),
3687        payload: json!({
3688            "proposal_id": proposal.id,
3689        }),
3690        caveats: proposal.caveats.clone(),
3691        signature: None,
3692    };
3693    events::validate_event_payload(event.kind.as_str(), &event.payload)?;
3694    event.id = events::compute_event_id(&event);
3695    Ok(event)
3696}
3697
3698/// Bind a verifier attachment to a finding (`target.type == "finding"`). Appends
3699/// to the sidecar `verifier_attachments` collection and emits
3700/// `verifier_attachment.added`. Per-finding trust-gate status is derived on read.
3701fn apply_verifier_attach(
3702    frontier: &mut Project,
3703    proposal: &StateProposal,
3704    reviewer: &str,
3705    _decision_reason: &str,
3706) -> Result<StateEvent, String> {
3707    if proposal.target.r#type != "finding" {
3708        return Err(format!(
3709            "verifier.attach target.type must be 'finding', got '{}'",
3710            proposal.target.r#type
3711        ));
3712    }
3713    let value = proposal
3714        .payload
3715        .get("attachment")
3716        .ok_or("verifier.attach proposal missing payload.attachment")?
3717        .clone();
3718    let att: crate::verifier_attachment::VerifierAttachment = serde_json::from_value(value)
3719        .map_err(|e| format!("Invalid verifier.attach payload: {e}"))?;
3720    att.verify()
3721        .map_err(|e| format!("verifier.attach attachment malformed: {e}"))?;
3722    if att.target != proposal.target.id {
3723        return Err(format!(
3724            "verifier.attach attachment.target {} does not match proposal target {}",
3725            att.target, proposal.target.id
3726        ));
3727    }
3728    // Activity is not state: a verifier gate may not attach to, or claim
3729    // independence from, an activity-plane id (`vac_`/`vrr_`).
3730    if crate::activity::is_activity_id(&att.target) {
3731        return Err(format!(
3732            "verifier.attach refused: target `{}` is an activity-plane id (activity is not lineage)",
3733            att.target
3734        ));
3735    }
3736    if let Some(indep) = att
3737        .independent_of
3738        .iter()
3739        .find(|i| crate::activity::is_activity_id(i))
3740    {
3741        return Err(format!(
3742            "verifier.attach refused: independent_of `{indep}` is an activity-plane id"
3743        ));
3744    }
3745    if !frontier.verifier_attachments.iter().any(|a| a.id == att.id) {
3746        frontier.verifier_attachments.push(att.clone());
3747    }
3748    Ok(events::new_finding_event(events::FindingEventInput {
3749        kind: events::EVENT_KIND_VERIFIER_ATTACHMENT_ADDED,
3750        finding_id: &proposal.target.id,
3751        actor_id: reviewer,
3752        actor_type: events::actor_kind(reviewer),
3753        reason: &proposal.reason,
3754        before_hash: NULL_HASH,
3755        after_hash: NULL_HASH,
3756        payload: json!({ "proposal_id": proposal.id, "attachment": att }),
3757        caveats: proposal.caveats.clone(),
3758        timestamp: None,
3759    }))
3760}
3761
3762fn apply_review(
3763    frontier: &mut Project,
3764    proposal: &StateProposal,
3765    reviewer: &str,
3766    _decision_reason: &str,
3767) -> Result<StateEvent, String> {
3768    let finding_id = proposal.target.id.as_str();
3769    let idx = find_finding_index(frontier, finding_id)?;
3770    let before_hash = events::finding_hash(&frontier.findings[idx]);
3771    let status = proposal
3772        .payload
3773        .get("status")
3774        .and_then(Value::as_str)
3775        .ok_or("finding.review proposal missing payload.status")?;
3776    use crate::bundle::ReviewState;
3777    let new_state = match status {
3778        "accepted" | "approved" => ReviewState::Accepted,
3779        "contested" => ReviewState::Contested,
3780        "needs_revision" => ReviewState::NeedsRevision,
3781        "rejected" => ReviewState::Rejected,
3782        other => return Err(format!("Unknown review proposal status '{other}'")),
3783    };
3784    frontier.findings[idx].flags.contested = new_state.implies_contested();
3785    frontier.findings[idx].flags.review_state = Some(new_state);
3786    let after_hash = events::finding_hash(&frontier.findings[idx]);
3787    Ok(events::new_finding_event(events::FindingEventInput {
3788        kind: "finding.reviewed",
3789        finding_id,
3790        actor_id: reviewer,
3791        actor_type: events::actor_kind(reviewer),
3792        reason: &proposal.reason,
3793        before_hash: &before_hash,
3794        after_hash: &after_hash,
3795        payload: json!({
3796            "status": status,
3797            "proposal_id": proposal.id,
3798        }),
3799        caveats: proposal.caveats.clone(),
3800        timestamp: None,
3801    }))
3802}
3803
3804/// Append a claim-granularity attribution to a finding's provenance. Descriptive
3805/// only: no flag, no confidence, no review state. Idempotent — a contribution
3806/// already present (same unit + agent + role) is not re-added.
3807fn apply_contribution(
3808    frontier: &mut Project,
3809    proposal: &StateProposal,
3810    reviewer: &str,
3811    _decision_reason: &str,
3812) -> Result<StateEvent, String> {
3813    let finding_id = proposal.target.id.as_str();
3814    let idx = find_finding_index(frontier, finding_id)?;
3815    let contribution: crate::bundle::Contribution = serde_json::from_value(
3816        proposal
3817            .payload
3818            .get("contribution")
3819            .cloned()
3820            .ok_or("finding.contribution.recorded proposal missing payload.contribution")?,
3821    )
3822    .map_err(|e| format!("malformed contribution: {e}"))?;
3823    contribution.validate()?;
3824    let before_hash = events::finding_hash(&frontier.findings[idx]);
3825    let existing = &mut frontier.findings[idx].provenance.contributions;
3826    if !existing.iter().any(|c| {
3827        c.unit == contribution.unit
3828            && c.agent_id == contribution.agent_id
3829            && c.role == contribution.role
3830    }) {
3831        existing.push(contribution.clone());
3832    }
3833    let after_hash = events::finding_hash(&frontier.findings[idx]);
3834    let payload = json!({
3835        "contribution": serde_json::to_value(&contribution)
3836            .map_err(|e| format!("serialize contribution: {e}"))?,
3837        "proposal_id": proposal.id,
3838    });
3839    Ok(events::new_finding_event(events::FindingEventInput {
3840        kind: "finding.contribution.recorded",
3841        finding_id,
3842        actor_id: reviewer,
3843        actor_type: events::actor_kind(reviewer),
3844        reason: &proposal.reason,
3845        before_hash: &before_hash,
3846        after_hash: &after_hash,
3847        payload,
3848        caveats: proposal.caveats.clone(),
3849        timestamp: None,
3850    }))
3851}
3852
3853fn apply_caveat(
3854    frontier: &mut Project,
3855    proposal: &StateProposal,
3856    reviewer: &str,
3857    _decision_reason: &str,
3858    fixed_decided_at: Option<&str>,
3859) -> Result<StateEvent, String> {
3860    let finding_id = proposal.target.id.as_str();
3861    let idx = find_finding_index(frontier, finding_id)?;
3862    let before_hash = events::finding_hash(&frontier.findings[idx]);
3863    let now = fixed_decided_at
3864        .map(ToString::to_string)
3865        .unwrap_or_else(|| Utc::now().to_rfc3339());
3866    let text = proposal
3867        .payload
3868        .get("text")
3869        .and_then(Value::as_str)
3870        .ok_or("finding.caveat proposal missing payload.text")?;
3871    let provenance = extract_annotation_provenance(&proposal.payload);
3872    let annotation_id = annotation_id(finding_id, text, reviewer, &now);
3873    frontier.findings[idx].annotations.push(Annotation {
3874        id: annotation_id.clone(),
3875        text: text.to_string(),
3876        author: reviewer.to_string(),
3877        timestamp: now.clone(),
3878        provenance: provenance.clone(),
3879    });
3880    let after_hash = events::finding_hash(&frontier.findings[idx]);
3881    let mut payload = json!({
3882        "annotation_id": annotation_id,
3883        "text": text,
3884        "proposal_id": proposal.id,
3885    });
3886    if let Some(prov) = &provenance {
3887        payload["provenance"] = serde_json::to_value(prov).unwrap_or(Value::Null);
3888    }
3889    Ok(events::new_finding_event(events::FindingEventInput {
3890        kind: "finding.caveated",
3891        finding_id,
3892        actor_id: reviewer,
3893        actor_type: events::actor_kind(reviewer),
3894        reason: text,
3895        before_hash: &before_hash,
3896        after_hash: &after_hash,
3897        payload,
3898        caveats: proposal.caveats.clone(),
3899        timestamp: Some(&now),
3900    }))
3901}
3902
3903fn apply_note(
3904    frontier: &mut Project,
3905    proposal: &StateProposal,
3906    reviewer: &str,
3907    _decision_reason: &str,
3908    fixed_decided_at: Option<&str>,
3909) -> Result<StateEvent, String> {
3910    let finding_id = proposal.target.id.as_str();
3911    let idx = find_finding_index(frontier, finding_id)?;
3912    let before_hash = events::finding_hash(&frontier.findings[idx]);
3913    let now = fixed_decided_at
3914        .map(ToString::to_string)
3915        .unwrap_or_else(|| Utc::now().to_rfc3339());
3916    let text = proposal
3917        .payload
3918        .get("text")
3919        .and_then(Value::as_str)
3920        .ok_or("finding.note proposal missing payload.text")?;
3921    let provenance = extract_annotation_provenance(&proposal.payload);
3922    let annotation_id = annotation_id(finding_id, text, reviewer, &now);
3923    frontier.findings[idx].annotations.push(Annotation {
3924        id: annotation_id.clone(),
3925        text: text.to_string(),
3926        author: reviewer.to_string(),
3927        timestamp: now.clone(),
3928        provenance: provenance.clone(),
3929    });
3930    let after_hash = events::finding_hash(&frontier.findings[idx]);
3931    let mut payload = json!({
3932        "annotation_id": annotation_id,
3933        "text": text,
3934        "proposal_id": proposal.id,
3935    });
3936    if let Some(prov) = &provenance {
3937        payload["provenance"] = serde_json::to_value(prov).unwrap_or(Value::Null);
3938    }
3939    Ok(events::new_finding_event(events::FindingEventInput {
3940        kind: "finding.noted",
3941        finding_id,
3942        actor_id: reviewer,
3943        actor_type: events::actor_kind(reviewer),
3944        reason: text,
3945        before_hash: &before_hash,
3946        after_hash: &after_hash,
3947        payload,
3948        caveats: proposal.caveats.clone(),
3949        timestamp: Some(&now),
3950    }))
3951}
3952
3953/// v0.57: Apply a `finding.span_repair` proposal. Appends a
3954/// `{section, text}` span to `state.findings[i].evidence.evidence_spans`
3955/// and emits one signed `finding.span_repaired` event.
3956fn apply_finding_span_repair(
3957    frontier: &mut Project,
3958    proposal: &StateProposal,
3959    reviewer: &str,
3960    _decision_reason: &str,
3961) -> Result<StateEvent, String> {
3962    let finding_id = proposal.target.id.as_str();
3963    let section = proposal
3964        .payload
3965        .get("section")
3966        .and_then(Value::as_str)
3967        .ok_or("finding.span_repair proposal missing payload.section")?
3968        .to_string();
3969    let text = proposal
3970        .payload
3971        .get("text")
3972        .and_then(Value::as_str)
3973        .ok_or("finding.span_repair proposal missing payload.text")?
3974        .to_string();
3975    let idx = find_finding_index(frontier, finding_id)?;
3976    let already_present = frontier.findings[idx]
3977        .evidence
3978        .evidence_spans
3979        .iter()
3980        .any(|existing| {
3981            existing.get("section").and_then(Value::as_str) == Some(section.as_str())
3982                && existing.get("text").and_then(Value::as_str) == Some(text.as_str())
3983        });
3984    if already_present {
3985        return Err(format!(
3986            "finding {finding_id} already carries an identical (section, text) span"
3987        ));
3988    }
3989    let before_hash = events::finding_hash(&frontier.findings[idx]);
3990    let span_value = json!({"section": section, "text": text});
3991    frontier.findings[idx]
3992        .evidence
3993        .evidence_spans
3994        .push(span_value);
3995    let after_hash = events::finding_hash(&frontier.findings[idx]);
3996    let payload = json!({
3997        "proposal_id": proposal.id,
3998        "section": section,
3999        "text": text,
4000    });
4001    Ok(events::new_finding_event(events::FindingEventInput {
4002        kind: "finding.span_repaired",
4003        finding_id,
4004        actor_id: reviewer,
4005        actor_type: events::actor_kind(reviewer),
4006        reason: &proposal.reason,
4007        before_hash: &before_hash,
4008        after_hash: &after_hash,
4009        payload,
4010        caveats: proposal.caveats.clone(),
4011        timestamp: None,
4012    }))
4013}
4014
4015/// v0.56: Apply an `evidence_atom.locator_repair` proposal. Sets
4016/// `locator` on the named evidence atom, removes the
4017/// "missing evidence locator" caveat, and emits one signed
4018/// `evidence_atom.locator_repaired` canonical event. The before/after
4019/// hashes are over the canonical bytes of the named atom only, so a
4020/// chain validator can confirm the exact atom changed and exactly the
4021/// named repair was applied.
4022fn apply_evidence_atom_locator_repair(
4023    frontier: &mut Project,
4024    proposal: &StateProposal,
4025    reviewer: &str,
4026    _decision_reason: &str,
4027) -> Result<StateEvent, String> {
4028    let atom_id = proposal.target.id.as_str();
4029    let locator = proposal
4030        .payload
4031        .get("locator")
4032        .and_then(Value::as_str)
4033        .ok_or("evidence_atom.locator_repair proposal missing payload.locator")?
4034        .to_string();
4035    let source_id = proposal
4036        .payload
4037        .get("source_id")
4038        .and_then(Value::as_str)
4039        .ok_or("evidence_atom.locator_repair proposal missing payload.source_id")?
4040        .to_string();
4041
4042    let idx = frontier
4043        .evidence_atoms
4044        .iter()
4045        .position(|atom| atom.id == atom_id)
4046        .ok_or_else(|| format!("evidence_atom.locator_repair targets unknown atom {atom_id}"))?;
4047    if frontier.evidence_atoms[idx].source_id != source_id {
4048        return Err(format!(
4049            "evidence_atom.locator_repair payload.source_id '{source_id}' does not match atom.source_id '{}'",
4050            frontier.evidence_atoms[idx].source_id
4051        ));
4052    }
4053    if let Some(existing) = &frontier.evidence_atoms[idx].locator {
4054        if existing == &locator {
4055            return Err(format!(
4056                "evidence_atom {atom_id} already carries locator '{existing}'"
4057            ));
4058        }
4059        return Err(format!(
4060            "evidence_atom {atom_id} already carries locator '{existing}'; refusing to overwrite with '{locator}'"
4061        ));
4062    }
4063
4064    let before_hash = events::evidence_atom_hash(&frontier.evidence_atoms[idx]);
4065    frontier.evidence_atoms[idx].locator = Some(locator.clone());
4066    frontier.evidence_atoms[idx]
4067        .caveats
4068        .retain(|c| c != "missing evidence locator");
4069    let after_hash = events::evidence_atom_hash(&frontier.evidence_atoms[idx]);
4070
4071    let payload = json!({
4072        "proposal_id": proposal.id,
4073        "locator": locator,
4074        "source_id": source_id,
4075    });
4076
4077    Ok(events::new_evidence_atom_locator_repair_event(
4078        atom_id,
4079        reviewer,
4080        "human",
4081        &proposal.reason,
4082        &before_hash,
4083        &after_hash,
4084        payload,
4085        proposal.caveats.clone(),
4086    ))
4087}
4088
4089/// Phase β (v0.6): pull optional structured provenance off a note/caveat
4090/// proposal payload. The propose-* tools accept it; the validator gates
4091/// it; this helper threads it through to the materialized annotation
4092/// and the canonical event payload.
4093fn extract_annotation_provenance(payload: &Value) -> Option<crate::bundle::ProvenanceRef> {
4094    let prov = payload.get("provenance")?;
4095    let parsed: crate::bundle::ProvenanceRef = serde_json::from_value(prov.clone()).ok()?;
4096    if parsed.has_identifier() {
4097        Some(parsed)
4098    } else {
4099        None
4100    }
4101}
4102
4103fn apply_confidence_revise(
4104    frontier: &mut Project,
4105    proposal: &StateProposal,
4106    reviewer: &str,
4107    _decision_reason: &str,
4108    fixed_decided_at: Option<&str>,
4109) -> Result<Vec<StateEvent>, String> {
4110    let finding_id = proposal.target.id.as_str();
4111    let idx = find_finding_index(frontier, finding_id)?;
4112    let now = fixed_decided_at
4113        .map(ToString::to_string)
4114        .unwrap_or_else(|| Utc::now().to_rfc3339());
4115    let previous = frontier.findings[idx].confidence.score;
4116    let new_score = proposal
4117        .payload
4118        .get("confidence")
4119        .and_then(Value::as_f64)
4120        .ok_or("finding.confidence_revise proposal missing payload.confidence")?;
4121
4122    // v0.55: when the revised confidence crosses the propagation threshold
4123    // (previous >= 0.5, new < 0.5), invoke the same cascade pattern that
4124    // `apply_retract` uses — emit `finding.dependency_invalidated` events for
4125    // each downstream supports/depends finding at depth ≤ MAX_DEPTH. Pre-v0.55
4126    // this path silently mutated confidence without firing the cascade, which
4127    // forced callers to chase a separate `vela propagate --reduce-confidence`
4128    // command for the substrate's signature feature.
4129    let cascade_threshold_crossed = previous >= 0.5 && new_score < 0.5;
4130
4131    let pre_cascade_hashes: std::collections::HashMap<String, String> = if cascade_threshold_crossed
4132    {
4133        frontier
4134            .findings
4135            .iter()
4136            .map(|finding| (finding.id.clone(), events::finding_hash(finding)))
4137            .collect()
4138    } else {
4139        std::collections::HashMap::new()
4140    };
4141
4142    let before_hash = events::finding_hash(&frontier.findings[idx]);
4143
4144    // Apply the local mutation first so propagate_correction sees the new
4145    // confidence on the source finding.
4146    frontier.findings[idx].confidence.score = new_score;
4147    frontier.findings[idx].confidence.basis = format!(
4148        "expert revision from {:.3} to {:.3}: {}",
4149        previous, new_score, proposal.reason
4150    );
4151    frontier.findings[idx].confidence.method = ConfidenceMethod::ExpertJudgment;
4152    frontier.findings[idx].updated = Some(now.clone());
4153
4154    let cascade = if cascade_threshold_crossed {
4155        Some(propagate::propagate_correction(
4156            frontier,
4157            finding_id,
4158            PropagationAction::ConfidenceReduced { new_score },
4159        ))
4160    } else {
4161        None
4162    };
4163
4164    let after_hash = events::finding_hash(&frontier.findings[idx]);
4165
4166    let source_event = events::new_finding_event(events::FindingEventInput {
4167        kind: "finding.confidence_revised",
4168        finding_id,
4169        actor_id: reviewer,
4170        actor_type: events::actor_kind(reviewer),
4171        reason: &proposal.reason,
4172        before_hash: &before_hash,
4173        after_hash: &after_hash,
4174        payload: json!({
4175            "previous_score": previous,
4176            "new_score": new_score,
4177            "updated_at": now,
4178            "proposal_id": proposal.id,
4179            "cascade_fired": cascade_threshold_crossed,
4180            "affected": cascade.as_ref().map(|c| c.affected).unwrap_or(0),
4181        }),
4182        caveats: proposal.caveats.clone(),
4183        timestamp: Some(&now),
4184    });
4185
4186    let source_event_id = source_event.id.clone();
4187    let mut emitted = vec![source_event];
4188
4189    if let Some(cascade) = cascade {
4190        // Mirror apply_retract's per-dependent dependency_invalidated emission:
4191        // each affected dep at each depth gets a canonical event with the
4192        // before/after hash boundary so chain validation works downstream.
4193        for (depth_idx, level) in cascade.cascade.iter().enumerate() {
4194            let depth = (depth_idx as u32) + 1;
4195            for dep_id in level {
4196                let before = pre_cascade_hashes
4197                    .get(dep_id)
4198                    .cloned()
4199                    .unwrap_or_else(|| events::NULL_HASH.to_string());
4200                let after = events::finding_hash_by_id(frontier, dep_id);
4201                emitted.push(events::new_finding_event(events::FindingEventInput {
4202                    kind: "finding.dependency_invalidated",
4203                    finding_id: dep_id,
4204                    actor_id: reviewer,
4205                    actor_type: events::actor_kind(reviewer),
4206                    reason: &format!(
4207                        "Upstream finding {finding_id} confidence reduced to {new_score:.2}; cascade depth {depth}"
4208                    ),
4209                    before_hash: &before,
4210                    after_hash: &after,
4211                    payload: json!({
4212                        "upstream_finding_id": finding_id,
4213                        "upstream_event_id": source_event_id,
4214                        "depth": depth,
4215                        "new_score": new_score,
4216                        "previous_score": previous,
4217                        "proposal_id": proposal.id,
4218                    }),
4219                    caveats: vec![],
4220                    timestamp: fixed_decided_at,
4221                }));
4222            }
4223        }
4224    }
4225
4226    Ok(emitted)
4227}
4228
4229fn apply_reject(
4230    frontier: &mut Project,
4231    proposal: &StateProposal,
4232    reviewer: &str,
4233    _decision_reason: &str,
4234) -> Result<StateEvent, String> {
4235    let finding_id = proposal.target.id.as_str();
4236    let idx = find_finding_index(frontier, finding_id)?;
4237    let before_hash = events::finding_hash(&frontier.findings[idx]);
4238    frontier.findings[idx].flags.contested = true;
4239    let after_hash = events::finding_hash(&frontier.findings[idx]);
4240    Ok(events::new_finding_event(events::FindingEventInput {
4241        kind: "finding.rejected",
4242        finding_id,
4243        actor_id: reviewer,
4244        actor_type: events::actor_kind(reviewer),
4245        reason: &proposal.reason,
4246        before_hash: &before_hash,
4247        after_hash: &after_hash,
4248        payload: json!({
4249            "proposal_id": proposal.id,
4250            "status": "rejected",
4251        }),
4252        caveats: proposal.caveats.clone(),
4253        timestamp: None,
4254    }))
4255}
4256
4257fn apply_retract(
4258    frontier: &mut Project,
4259    proposal: &StateProposal,
4260    reviewer: &str,
4261    _decision_reason: &str,
4262    fixed_decided_at: Option<&str>,
4263) -> Result<Vec<StateEvent>, String> {
4264    let finding_id = proposal.target.id.as_str();
4265    let idx = find_finding_index(frontier, finding_id)?;
4266    if frontier.findings[idx].flags.retracted {
4267        return Err(format!("Finding {finding_id} is already retracted"));
4268    }
4269    // Phase L: capture every finding's pre-cascade hash so each emitted
4270    // `finding.dependency_invalidated` event can name a real before_hash
4271    // that matches whatever event last touched that dep.
4272    let pre_cascade_hashes: std::collections::HashMap<String, String> = frontier
4273        .findings
4274        .iter()
4275        .map(|finding| (finding.id.clone(), events::finding_hash(finding)))
4276        .collect();
4277
4278    let before_hash = events::finding_hash(&frontier.findings[idx]);
4279    let cascade =
4280        propagate::propagate_correction(frontier, finding_id, PropagationAction::Retracted);
4281    let after_hash = events::finding_hash_by_id(frontier, finding_id);
4282
4283    let source_event = events::new_finding_event(events::FindingEventInput {
4284        kind: "finding.retracted",
4285        finding_id,
4286        actor_id: reviewer,
4287        actor_type: events::actor_kind(reviewer),
4288        reason: &proposal.reason,
4289        before_hash: &before_hash,
4290        after_hash: &after_hash,
4291        payload: json!({
4292            "proposal_id": proposal.id,
4293            "affected": cascade.affected,
4294            "cascade": cascade.cascade,
4295        }),
4296        caveats: vec!["Retraction impact is simulated over declared dependency links.".to_string()],
4297        timestamp: fixed_decided_at,
4298    });
4299    let source_event_id = source_event.id.clone();
4300
4301    let mut emitted = vec![source_event];
4302
4303    // Phase L: emit one canonical `finding.dependency_invalidated`
4304    // event per affected dependent, in BFS depth order. Each event
4305    // carries the before/after hash boundary for that specific dep so
4306    // chain validation works downstream.
4307    for (depth_idx, level) in cascade.cascade.iter().enumerate() {
4308        let depth = (depth_idx as u32) + 1;
4309        for dep_id in level {
4310            let before = pre_cascade_hashes
4311                .get(dep_id)
4312                .cloned()
4313                .unwrap_or_else(|| events::NULL_HASH.to_string());
4314            let after = events::finding_hash_by_id(frontier, dep_id);
4315            emitted.push(events::new_finding_event(events::FindingEventInput {
4316                kind: "finding.dependency_invalidated",
4317                finding_id: dep_id,
4318                actor_id: reviewer,
4319                actor_type: events::actor_kind(reviewer),
4320                reason: &format!("Upstream finding {finding_id} retracted; cascade depth {depth}"),
4321                before_hash: &before,
4322                after_hash: &after,
4323                payload: json!({
4324                    "upstream_finding_id": finding_id,
4325                    "upstream_event_id": source_event_id,
4326                    "depth": depth,
4327                    "proposal_id": proposal.id,
4328                }),
4329                caveats: vec![],
4330                timestamp: fixed_decided_at,
4331            }));
4332        }
4333    }
4334
4335    Ok(emitted)
4336}
4337
4338fn find_finding_index(frontier: &Project, finding_id: &str) -> Result<usize, String> {
4339    frontier
4340        .findings
4341        .iter()
4342        .position(|finding| finding.id == finding_id)
4343        .ok_or_else(|| format!("Finding not found: {finding_id}"))
4344}
4345
4346fn annotation_id(finding_id: &str, text: &str, author: &str, timestamp: &str) -> String {
4347    let hash = Sha256::digest(format!("{finding_id}|{text}|{author}|{timestamp}").as_bytes());
4348    format!("ann_{}", &hex::encode(hash)[..16])
4349}
4350
4351// ── Review-decision projection + parity (status derived from the log) ──
4352//
4353// A proposal's decision state is no longer a free-floating mutable field:
4354// it is a PROJECTION of the signed `review.*` events (and, for accepts,
4355// the domain event the accept produced). The stored `status` is a cache
4356// of that projection. `verify_proposal_decision_parity` is the gate that
4357// pins the cache to the log — if someone hand-edits a `status` field, or a
4358// decision exists with no signed event behind it, parity fails. That is
4359// the tamper-evidence the mutable field never had.
4360
4361/// A decision reconstructed from the event log for one proposal.
4362#[derive(Debug, Clone, PartialEq, Eq)]
4363pub struct DerivedDecision {
4364    /// `applied` | `rejected` | `needs_revision`.
4365    pub status: String,
4366    /// The reviewer that made the latest decision.
4367    pub reviewer: String,
4368    /// The latest decision event's timestamp.
4369    pub decided_at: String,
4370    /// The `review.*` event id that carried the decision, when one exists.
4371    /// `None` for an accept whose only trace is its domain event (the
4372    /// pre-`review.accepted` accept path; see module note).
4373    pub review_event_id: Option<String>,
4374}
4375
4376/// Reduce the event log to the current decision for a single proposal.
4377///
4378/// Folds, in timestamp order:
4379///   - `review.rejected` → rejected
4380///   - `review.revision_requested` → needs_revision
4381///   - `review.accepted` → applied
4382///   - `proposal.withdrawn` → withdrawn
4383///   - any domain event produced by an accept of this proposal
4384///     (matched via the proposal's `applied_event_id`) → applied
4385///
4386/// The latest decision wins. Returns `None` when no decision event exists
4387/// (the proposal is pending).
4388pub fn proposal_status_from_log(
4389    frontier: &Project,
4390    proposal_id: &str,
4391    applied_event_id: Option<&str>,
4392) -> Option<DerivedDecision> {
4393    let mut decisions: Vec<DerivedDecision> = Vec::new();
4394    for event in &frontier.events {
4395        let is_review_for_this = event.target.r#type == "proposal"
4396            && event.target.id == proposal_id
4397            && matches!(
4398                event.kind.as_str(),
4399                events::EVENT_KIND_REVIEW_ACCEPTED
4400                    | events::EVENT_KIND_REVIEW_REJECTED
4401                    | events::EVENT_KIND_REVIEW_REVISION_REQUESTED
4402                    | events::EVENT_KIND_PROPOSAL_WITHDRAWN
4403            );
4404        if is_review_for_this {
4405            let status = match event.kind.as_str() {
4406                events::EVENT_KIND_REVIEW_ACCEPTED => "applied",
4407                events::EVENT_KIND_REVIEW_REJECTED => "rejected",
4408                events::EVENT_KIND_PROPOSAL_WITHDRAWN => "withdrawn",
4409                _ => "needs_revision",
4410            };
4411            decisions.push(DerivedDecision {
4412                status: status.to_string(),
4413                reviewer: event.actor.id.clone(),
4414                decided_at: event.timestamp.clone(),
4415                review_event_id: Some(event.id.clone()),
4416            });
4417            continue;
4418        }
4419        // An accept's domain event is its decision trace when no explicit
4420        // review.accepted exists (the historical accept path).
4421        if let Some(applied) = applied_event_id
4422            && event.id == applied
4423        {
4424            decisions.push(DerivedDecision {
4425                status: "applied".to_string(),
4426                reviewer: event.actor.id.clone(),
4427                decided_at: event.timestamp.clone(),
4428                review_event_id: None,
4429            });
4430        }
4431    }
4432    decisions.sort_by(|a, b| a.decided_at.cmp(&b.decided_at));
4433    decisions.pop()
4434}
4435
4436/// Verify that every proposal's stored decision state is backed by the
4437/// event log, and vice versa. Returns a list of human-readable conflicts
4438/// (empty == parity holds). This is the invariant the conformance gate
4439/// runs: it makes the mutable `status` field a verifiable projection
4440/// rather than an unconstrained side-table.
4441///
4442/// Checks, per proposal:
4443///   - a decided status (`applied` / `rejected` / `needs_revision`) MUST
4444///     have a backing event in the log (a `review.*` event, or for
4445///     `applied` the referenced domain event);
4446///   - the stored status MUST equal the status derived from the log;
4447///   - `pending_review` MUST NOT have a decision event.
4448/// And globally:
4449///   - every `review.*` event MUST reference a proposal that exists.
4450pub fn verify_proposal_decision_parity(frontier: &Project) -> Vec<String> {
4451    let mut conflicts = Vec::new();
4452    let proposal_ids: BTreeSet<&str> = frontier.proposals.iter().map(|p| p.id.as_str()).collect();
4453
4454    for proposal in &frontier.proposals {
4455        let derived =
4456            proposal_status_from_log(frontier, &proposal.id, proposal.applied_event_id.as_deref());
4457        match proposal.status.as_str() {
4458            "pending_review" => {
4459                if let Some(d) = derived {
4460                    conflicts.push(format!(
4461                        "proposal {} is stored pending_review but the log carries a {} decision ({})",
4462                        proposal.id,
4463                        d.status,
4464                        d.review_event_id.as_deref().unwrap_or("domain event")
4465                    ));
4466                }
4467            }
4468            "accepted" => {
4469                // Transient in-memory state only; never persisted.
4470                conflicts.push(format!(
4471                    "proposal {} is stored in transient 'accepted' state (should be 'applied')",
4472                    proposal.id
4473                ));
4474            }
4475            stored @ ("applied" | "rejected" | "needs_revision" | "withdrawn") => match derived {
4476                None => conflicts.push(format!(
4477                    "proposal {} is stored '{}' but NO decision event backs it in the log \
4478                     — a decision with no signed, replayable record (the silent-drop vector)",
4479                    proposal.id, stored
4480                )),
4481                Some(d) if d.status != stored => conflicts.push(format!(
4482                    "proposal {} is stored '{}' but the log's latest decision is '{}'",
4483                    proposal.id, stored, d.status
4484                )),
4485                Some(_) => {}
4486            },
4487            other => conflicts.push(format!(
4488                "proposal {} has unknown status '{}'",
4489                proposal.id, other
4490            )),
4491        }
4492    }
4493
4494    for event in &frontier.events {
4495        if matches!(
4496            event.kind.as_str(),
4497            events::EVENT_KIND_REVIEW_ACCEPTED
4498                | events::EVENT_KIND_REVIEW_REJECTED
4499                | events::EVENT_KIND_REVIEW_REVISION_REQUESTED
4500                | events::EVENT_KIND_PROPOSAL_WITHDRAWN
4501        ) && !proposal_ids.contains(event.target.id.as_str())
4502        {
4503            conflicts.push(format!(
4504                "review event {} targets proposal {} which does not exist in the frontier",
4505                event.id, event.target.id
4506            ));
4507        }
4508    }
4509
4510    conflicts
4511}
4512
4513fn build_changed_finding_details(
4514    before: &Project,
4515    after: &Project,
4516    ids: &[String],
4517) -> Vec<ChangedFindingDetail> {
4518    ids.iter()
4519        .map(|id| {
4520            let fa = before.findings.iter().find(|f| &f.id == id);
4521            let fb = after.findings.iter().find(|f| &f.id == id);
4522            ChangedFindingDetail {
4523                id: id.clone(),
4524                assertion_before: fa.map(|f| f.assertion.text.clone()),
4525                assertion_after: fb.map(|f| f.assertion.text.clone()),
4526                assertion_type_before: fa.map(|f| f.assertion.assertion_type.clone()),
4527                assertion_type_after: fb.map(|f| f.assertion.assertion_type.clone()),
4528                confidence_before: fa.map(|f| format!("{:.2}", f.confidence.score)),
4529                confidence_after: fb.map(|f| format!("{:.2}", f.confidence.score)),
4530            }
4531        })
4532        .collect()
4533}
4534
4535#[cfg(test)]
4536pub(crate) mod tests;