Skip to main content

vela_protocol/analysis/
diff_pack_review.rs

1//! v0.203: Diff Pack workbench-side review surface.
2//!
3//! A reviewer opens a `vsd_*` Scientific Diff Pack in the workbench,
4//! inspects every member proposal inline, and issues a verdict:
5//! accept / reject / revise. The verdict is signed by the workbench
6//! actor and written to `.vela/pending_verdicts/<vpv_id>.json`.
7//!
8//! Substrate-honest framing: at v0.203, a *pending* verdict is not
9//! yet a canonical event. The reducer-side `diff_pack.reviewed` arm
10//! lands at v0.205 along with Theorem 26 (verdict atomicity). Until
11//! then, pending verdicts sit in a sibling directory and are picked
12//! up by v0.205's migration path. This separation keeps the v0.193
13//! replay path unperturbed while the reviewer flow is built out.
14//!
15//! Pending verdict id derivation:
16//!   `vpv_<16hex>` over sha256("|"-joined preimage of
17//!   pack_id | verdict_outcome | reviewer_actor | reason | at).
18
19use serde::{Deserialize, Serialize};
20use sha2::{Digest, Sha256};
21use std::fs;
22use std::path::{Path, PathBuf};
23
24pub const PENDING_VERDICT_SCHEMA: &str = "vela.pending_diff_pack_verdict.v0.1";
25
26#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
27#[serde(rename_all = "snake_case")]
28pub enum DiffPackVerdict {
29    Accept,
30    Reject,
31    Revise,
32}
33
34impl DiffPackVerdict {
35    pub fn canonical(&self) -> &'static str {
36        match self {
37            DiffPackVerdict::Accept => "accept",
38            DiffPackVerdict::Reject => "reject",
39            DiffPackVerdict::Revise => "revise",
40        }
41    }
42
43    pub fn from_str_ci(s: &str) -> Option<Self> {
44        match s.trim().to_ascii_lowercase().as_str() {
45            "accept" | "accepted" => Some(DiffPackVerdict::Accept),
46            "reject" | "rejected" => Some(DiffPackVerdict::Reject),
47            "revise" | "revision" | "needs_revision" => Some(DiffPackVerdict::Revise),
48            _ => None,
49        }
50    }
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
54pub struct PendingVerdict {
55    pub schema: String,
56    pub verdict_id: String,
57    pub pack_id: String,
58    pub verdict: DiffPackVerdict,
59    pub reviewer_actor: String,
60    pub reason: String,
61    pub at: String,
62}
63
64impl PendingVerdict {
65    /// Build a pending verdict. The verdict_id is content-addressed
66    /// over the body; identical inputs always produce the same id.
67    pub fn build(
68        pack_id: impl Into<String>,
69        verdict: DiffPackVerdict,
70        reviewer_actor: impl Into<String>,
71        reason: impl Into<String>,
72        at: impl Into<String>,
73    ) -> Result<Self, String> {
74        let pack_id = pack_id.into();
75        if !pack_id.starts_with("vsd_") {
76            return Err(format!("pack_id must start with `vsd_`, got `{pack_id}`"));
77        }
78        let reviewer_actor = reviewer_actor.into();
79        if reviewer_actor.is_empty() {
80            return Err("reviewer_actor cannot be empty".to_string());
81        }
82        let at = at.into();
83        if at.is_empty() {
84            return Err("at cannot be empty".to_string());
85        }
86        let mut pv = Self {
87            schema: PENDING_VERDICT_SCHEMA.to_string(),
88            verdict_id: String::new(),
89            pack_id,
90            verdict,
91            reviewer_actor,
92            reason: reason.into(),
93            at,
94        };
95        pv.verdict_id = pv.derive_id();
96        Ok(pv)
97    }
98
99    fn preimage_bytes(&self) -> Vec<u8> {
100        let mut out = Vec::new();
101        out.extend_from_slice(self.pack_id.as_bytes());
102        out.push(b'|');
103        out.extend_from_slice(self.verdict.canonical().as_bytes());
104        out.push(b'|');
105        out.extend_from_slice(self.reviewer_actor.as_bytes());
106        out.push(b'|');
107        out.extend_from_slice(self.reason.as_bytes());
108        out.push(b'|');
109        out.extend_from_slice(self.at.as_bytes());
110        out
111    }
112
113    fn derive_id(&self) -> String {
114        let mut hasher = Sha256::new();
115        hasher.update(self.preimage_bytes());
116        format!("vpv_{}", &hex::encode(hasher.finalize())[..16])
117    }
118
119    /// Verify: the declared verdict_id matches a fresh re-derivation.
120    pub fn verify(&self) -> Result<(), String> {
121        let rederived = self.derive_id();
122        if rederived != self.verdict_id {
123            return Err(format!(
124                "verdict_id mismatch: declared {}, rebuilt {}",
125                self.verdict_id, rederived
126            ));
127        }
128        Ok(())
129    }
130}
131
132/// Directory where pending verdicts are stored under a frontier
133/// repo. Sibling of `.vela/events/`; never re-played by the v0.193
134/// reducer.
135pub fn pending_verdicts_dir(repo_path: &Path) -> PathBuf {
136    repo_path.join(".vela").join("pending_verdicts")
137}
138
139/// Write a freshly-built pending verdict for the given pack. Returns
140/// the verdict_id on success. The verdict is workbench-only: it does
141/// not pass through the reducer in v0.203 and never becomes part of
142/// `frontier.events` at this cycle.
143pub fn record_at_path(
144    repo_path: &Path,
145    pack_id: &str,
146    verdict: DiffPackVerdict,
147    reviewer_actor: &str,
148    reason: &str,
149    at: &str,
150) -> Result<String, String> {
151    // Validate the pack exists in the frontier's .vela/diff_packs/
152    // directory before writing a verdict for it. A verdict on a
153    // missing pack is meaningless.
154    let pack_path = repo_path
155        .join(".vela")
156        .join("diff_packs")
157        .join(format!("{pack_id}.json"));
158    if !pack_path.is_file() {
159        return Err(format!(
160            "pack {pack_id} not found at {}; cannot record verdict",
161            pack_path.display()
162        ));
163    }
164
165    let pv = PendingVerdict::build(pack_id, verdict, reviewer_actor, reason, at)?;
166
167    let dir = pending_verdicts_dir(repo_path);
168    fs::create_dir_all(&dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
169    let out = dir.join(format!("{}.json", pv.verdict_id));
170
171    // Idempotent: re-recording the same (pack, verdict, reviewer,
172    // reason, at) tuple is a no-op. Content-addressing means the
173    // file path is the same.
174    let body = serde_json::to_string_pretty(&pv).map_err(|e| format!("serialize: {e}"))?;
175    fs::write(&out, format!("{body}\n")).map_err(|e| format!("write {}: {e}", out.display()))?;
176    Ok(pv.verdict_id)
177}
178
179/// List every pending verdict on disk, newest first by `at`.
180pub fn list_at_path(repo_path: &Path) -> Vec<PendingVerdict> {
181    let dir = pending_verdicts_dir(repo_path);
182    let Ok(entries) = fs::read_dir(&dir) else {
183        return Vec::new();
184    };
185    let mut out: Vec<PendingVerdict> = Vec::new();
186    for e in entries.flatten() {
187        let p = e.path();
188        if p.extension().and_then(|s| s.to_str()) != Some("json") {
189            continue;
190        }
191        if let Ok(body) = fs::read_to_string(&p)
192            && let Ok(pv) = serde_json::from_str::<PendingVerdict>(&body)
193        {
194            out.push(pv);
195        }
196    }
197    out.sort_by(|a, b| b.at.cmp(&a.at));
198    out
199}
200
201/// Return the pending verdict for `pack_id`, if any. If multiple
202/// verdicts exist for the same pack (a reviewer changed their mind),
203/// the most recent by `at` is returned.
204pub fn latest_for_pack(repo_path: &Path, pack_id: &str) -> Option<PendingVerdict> {
205    list_at_path(repo_path)
206        .into_iter()
207        .find(|v| v.pack_id == pack_id)
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use tempfile::tempdir;
214
215    fn fixture_pack(repo: &Path, pack_id: &str) {
216        let dir = repo.join(".vela").join("diff_packs");
217        fs::create_dir_all(&dir).unwrap();
218        fs::write(
219            dir.join(format!("{pack_id}.json")),
220            r#"{"schema":"vela.scientific_diff.v0.1","pack_id":"vsd_test"}"#,
221        )
222        .unwrap();
223    }
224
225    #[test]
226    fn verdict_id_is_deterministic() {
227        let v1 = PendingVerdict::build(
228            "vsd_aaaaaaaaaaaaaaaa",
229            DiffPackVerdict::Accept,
230            "reviewer:workbench",
231            "lgtm",
232            "2026-05-12T00:00:00Z",
233        )
234        .unwrap();
235        let v2 = PendingVerdict::build(
236            "vsd_aaaaaaaaaaaaaaaa",
237            DiffPackVerdict::Accept,
238            "reviewer:workbench",
239            "lgtm",
240            "2026-05-12T00:00:00Z",
241        )
242        .unwrap();
243        assert_eq!(v1.verdict_id, v2.verdict_id);
244        assert!(v1.verdict_id.starts_with("vpv_"));
245        assert_eq!(v1.verdict_id.len(), 4 + 16);
246    }
247
248    #[test]
249    fn different_verdict_outcome_changes_id() {
250        let v1 = PendingVerdict::build(
251            "vsd_aaaaaaaaaaaaaaaa",
252            DiffPackVerdict::Accept,
253            "reviewer:workbench",
254            "ok",
255            "2026-05-12T00:00:00Z",
256        )
257        .unwrap();
258        let v2 = PendingVerdict::build(
259            "vsd_aaaaaaaaaaaaaaaa",
260            DiffPackVerdict::Reject,
261            "reviewer:workbench",
262            "ok",
263            "2026-05-12T00:00:00Z",
264        )
265        .unwrap();
266        assert_ne!(v1.verdict_id, v2.verdict_id);
267    }
268
269    #[test]
270    fn non_vsd_pack_id_rejected() {
271        assert!(
272            PendingVerdict::build(
273                "vpr_not_a_pack",
274                DiffPackVerdict::Accept,
275                "reviewer:workbench",
276                "",
277                "2026-05-12T00:00:00Z"
278            )
279            .is_err()
280        );
281    }
282
283    #[test]
284    fn from_str_ci_is_lenient() {
285        assert_eq!(
286            DiffPackVerdict::from_str_ci("Accept"),
287            Some(DiffPackVerdict::Accept)
288        );
289        assert_eq!(
290            DiffPackVerdict::from_str_ci("accepted"),
291            Some(DiffPackVerdict::Accept)
292        );
293        assert_eq!(
294            DiffPackVerdict::from_str_ci("Needs_Revision"),
295            Some(DiffPackVerdict::Revise)
296        );
297        assert_eq!(DiffPackVerdict::from_str_ci("yes please"), None);
298    }
299
300    #[test]
301    fn record_at_path_round_trip() {
302        let tmp = tempdir().unwrap();
303        fixture_pack(tmp.path(), "vsd_be61da0cdcba08ed");
304        let id = record_at_path(
305            tmp.path(),
306            "vsd_be61da0cdcba08ed",
307            DiffPackVerdict::Accept,
308            "reviewer:workbench",
309            "lgtm",
310            "2026-05-12T00:00:00Z",
311        )
312        .unwrap();
313        assert!(id.starts_with("vpv_"));
314        let written = pending_verdicts_dir(tmp.path()).join(format!("{id}.json"));
315        assert!(written.is_file());
316        let pv: PendingVerdict =
317            serde_json::from_str(&fs::read_to_string(&written).unwrap()).unwrap();
318        pv.verify().unwrap();
319    }
320
321    #[test]
322    fn record_at_path_requires_pack_on_disk() {
323        let tmp = tempdir().unwrap();
324        // No fixture pack on disk; record should fail.
325        let res = record_at_path(
326            tmp.path(),
327            "vsd_aaaaaaaaaaaaaaaa",
328            DiffPackVerdict::Accept,
329            "reviewer:workbench",
330            "",
331            "2026-05-12T00:00:00Z",
332        );
333        assert!(res.is_err());
334    }
335
336    #[test]
337    fn list_and_latest_return_expected() {
338        let tmp = tempdir().unwrap();
339        fixture_pack(tmp.path(), "vsd_be61da0cdcba08ed");
340        record_at_path(
341            tmp.path(),
342            "vsd_be61da0cdcba08ed",
343            DiffPackVerdict::Revise,
344            "reviewer:workbench",
345            "needs more context",
346            "2026-05-12T00:00:00Z",
347        )
348        .unwrap();
349        record_at_path(
350            tmp.path(),
351            "vsd_be61da0cdcba08ed",
352            DiffPackVerdict::Accept,
353            "reviewer:workbench",
354            "addressed",
355            "2026-05-12T01:00:00Z",
356        )
357        .unwrap();
358        let listed = list_at_path(tmp.path());
359        assert_eq!(listed.len(), 2);
360        // Newest first.
361        assert_eq!(listed[0].at, "2026-05-12T01:00:00Z");
362        let latest = latest_for_pack(tmp.path(), "vsd_be61da0cdcba08ed").unwrap();
363        assert_eq!(latest.verdict, DiffPackVerdict::Accept);
364    }
365}