Skip to main content

vela_protocol/policy/
frontier_policy.rs

1//! Frontier-owned policy files.
2//!
3//! Policy guides local review and validation. It is not evidence and it does
4//! not mutate frontier state by itself.
5
6use serde::{Deserialize, Serialize};
7use sha2::{Digest, Sha256};
8use std::collections::{BTreeMap, BTreeSet};
9use std::io::Read;
10use std::path::{Component, Path, PathBuf};
11
12use crate::{canonical, repo};
13
14pub const ENGINE_POLICY_MANIFEST_MAX_BYTES: usize = 256 * 1024;
15pub const ENGINE_POLICY_DOCUMENT_MAX_BYTES: usize = 256 * 1024;
16pub const ENGINE_POLICY_SUMMARY_OBSERVATION_SCHEMA: &str =
17    "vela.engine-policy-summary-observation.v1";
18const ENGINE_POLICY_SUMMARY_ROOT_DOMAIN: &str = "vela.engine-policy-summary-root.v1";
19const ENGINE_POLICY_ERROR_ROOT_DOMAIN: &str = "vela.engine-policy-error-root.v1";
20
21#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
22#[serde(rename_all = "snake_case")]
23pub enum PolicyDocumentKind {
24    Evidence,
25    Review,
26    Confidence,
27    Agent,
28}
29
30impl PolicyDocumentKind {
31    pub fn as_str(self) -> &'static str {
32        match self {
33            Self::Evidence => "evidence",
34            Self::Review => "review",
35            Self::Confidence => "confidence",
36            Self::Agent => "agent",
37        }
38    }
39
40    pub fn filename(self) -> &'static str {
41        match self {
42            Self::Evidence => "evidence_policy.md",
43            Self::Review => "review_policy.md",
44            Self::Confidence => "confidence_policy.md",
45            Self::Agent => "agent_policy.md",
46        }
47    }
48
49    fn all() -> [Self; 4] {
50        [Self::Evidence, Self::Review, Self::Confidence, Self::Agent]
51    }
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
55pub struct PolicyDocumentSummary {
56    pub kind: PolicyDocumentKind,
57    pub path: String,
58    pub title: String,
59    pub body_sha256: String,
60    pub bytes: usize,
61    pub declared_in_manifest: bool,
62    #[serde(default)]
63    pub front_matter: BTreeMap<String, serde_json::Value>,
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
67pub struct FrontierPolicySummary {
68    pub ok: bool,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub frontier_id: Option<String>,
71    pub frontier_path: String,
72    #[serde(default)]
73    pub documents: Vec<PolicyDocumentSummary>,
74    #[serde(default)]
75    pub missing_required: Vec<String>,
76    /// True when the frontier declares at least one policy path or carries at
77    /// least one document at the conventional default path. This separates a
78    /// deliberately unconfigured frontier from a configured-but-broken one.
79    #[serde(default)]
80    pub configured: bool,
81    pub defaults_used: bool,
82    pub canonical_json_sha256: String,
83}
84
85/// Read-only, bounded observation of the policy inputs consumed by Engine
86/// preview. It never contains an absolute path or raw parser/filesystem error.
87#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
88#[serde(rename_all = "snake_case")]
89pub enum EnginePolicySummaryState {
90    Present,
91    Absent,
92    Invalid,
93}
94
95impl EnginePolicySummaryState {
96    fn as_str(self) -> &'static str {
97        match self {
98            Self::Present => "present",
99            Self::Absent => "absent",
100            Self::Invalid => "invalid",
101        }
102    }
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
106pub struct EnginePolicySummaryObservation {
107    pub schema: String,
108    pub state: EnginePolicySummaryState,
109    pub root: String,
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub summary_root: Option<String>,
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub error_code: Option<String>,
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub error_root: Option<String>,
116}
117
118#[derive(Debug)]
119struct PolicyLoadError {
120    code: &'static str,
121    reference: String,
122    input_root: Option<String>,
123    message: String,
124}
125
126impl PolicyLoadError {
127    fn new(
128        code: &'static str,
129        reference: impl Into<String>,
130        input_root: Option<String>,
131        message: impl Into<String>,
132    ) -> Self {
133        Self {
134            code,
135            reference: reference.into(),
136            input_root,
137            message: message.into(),
138        }
139    }
140
141    fn io(code: &'static str, reference: &str, error: &std::io::Error) -> Self {
142        let kind = format!("{:?}", error.kind()).to_ascii_lowercase();
143        Self::new(
144            code,
145            reference,
146            Some(text_root(&kind)),
147            format!("{reference}: filesystem operation failed ({kind})"),
148        )
149    }
150
151    fn stable_root(&self) -> String {
152        domain_hash(
153            ENGINE_POLICY_ERROR_ROOT_DOMAIN,
154            &[
155                Some(self.code),
156                Some(&self.reference),
157                self.input_root.as_deref(),
158            ],
159        )
160    }
161}
162
163impl std::fmt::Display for PolicyLoadError {
164    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        write!(formatter, "[{}] {}", self.code, self.message)
166    }
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
170pub struct OperationReviewRequirement {
171    pub review_class: String,
172    pub required_reviewer_count: usize,
173    #[serde(default)]
174    pub reviewer_roles: Vec<String>,
175    #[serde(default)]
176    pub required_reason_fields: Vec<String>,
177    #[serde(default)]
178    pub allowed_agent_actions: Vec<String>,
179    #[serde(default)]
180    pub policy_sources: Vec<String>,
181}
182
183pub fn load_policy_summary(frontier_path: &Path) -> Result<FrontierPolicySummary, String> {
184    load_policy_summary_inner(frontier_path, true).map_err(|error| error.to_string())
185}
186
187/// Observe the exact bounded policy inputs that Engine preview would read.
188/// Invalid inputs remain cursor-bindable without exposing raw error text.
189#[must_use]
190pub fn engine_policy_summary_observation(frontier_path: &Path) -> EnginePolicySummaryObservation {
191    match load_policy_summary_inner(frontier_path, false) {
192        Ok(summary) => {
193            let state = if summary.configured {
194                EnginePolicySummaryState::Present
195            } else {
196                EnginePolicySummaryState::Absent
197            };
198            let summary_root = Some(summary.canonical_json_sha256);
199            let root = observation_root(state, summary_root.as_deref(), None, None);
200            EnginePolicySummaryObservation {
201                schema: ENGINE_POLICY_SUMMARY_OBSERVATION_SCHEMA.to_string(),
202                state,
203                root,
204                summary_root,
205                error_code: None,
206                error_root: None,
207            }
208        }
209        Err(error) => {
210            let error_root = error.stable_root();
211            let root = observation_root(
212                EnginePolicySummaryState::Invalid,
213                None,
214                Some(error.code),
215                Some(&error_root),
216            );
217            EnginePolicySummaryObservation {
218                schema: ENGINE_POLICY_SUMMARY_OBSERVATION_SCHEMA.to_string(),
219                state: EnginePolicySummaryState::Invalid,
220                root,
221                summary_root: None,
222                error_code: Some(error.code.to_string()),
223                error_root: Some(error_root),
224            }
225        }
226    }
227}
228
229/// Convenience root for callers that only need to bind the observation into a
230/// larger read snapshot. Prefer [`engine_policy_summary_observation`] when the
231/// present/absent/invalid state must also be displayed.
232#[must_use]
233pub fn engine_policy_summary_root(frontier_path: &Path) -> String {
234    engine_policy_summary_observation(frontier_path).root
235}
236
237fn load_policy_summary_inner(
238    frontier_path: &Path,
239    allow_frontier_id_fallback: bool,
240) -> Result<FrontierPolicySummary, PolicyLoadError> {
241    let resolved = resolve_frontier_root(frontier_path)?;
242    let manifest_bytes = read_frontier_regular_file(
243        resolved.canonical.as_deref(),
244        Path::new("frontier.yaml"),
245        ENGINE_POLICY_MANIFEST_MAX_BYTES,
246        "frontier_manifest",
247    )?;
248    let manifest = manifest_bytes.as_deref().map(parse_manifest).transpose()?;
249    let frontier_id = manifest
250        .as_ref()
251        .and_then(|m| yaml_string_at(m, &["frontier_id"]))
252        .or_else(|| {
253            allow_frontier_id_fallback
254                .then_some(resolved.canonical.as_deref())
255                .flatten()
256                .and_then(|root| repo::load_from_path(root).ok())
257                .and_then(|project| project.frontier_id)
258        });
259
260    let manifest_refs = manifest
261        .as_ref()
262        .map(policy_refs_from_manifest)
263        .unwrap_or_default();
264    let has_manifest_refs = !manifest_refs.is_empty();
265    let mut documents = Vec::new();
266    let mut missing_required = Vec::new();
267    let mut used_default_path = false;
268
269    for kind in PolicyDocumentKind::all() {
270        let manifest_ref = manifest_refs.get(&kind);
271        let default_path = PathBuf::from(".vela").join("policy").join(kind.filename());
272        let reference = format!("policy: {}", kind.as_str());
273        let chosen = if let Some(path) = manifest_ref {
274            // An explicit path is authoritative configuration. A missing
275            // declared file must remain missing; silently falling back to a
276            // conventional path would make a broken policy look healthy.
277            read_frontier_regular_file(
278                resolved.canonical.as_deref(),
279                path,
280                ENGINE_POLICY_DOCUMENT_MAX_BYTES,
281                &reference,
282            )?
283            .map(|bytes| (path.clone(), bytes, true))
284        } else {
285            let default = read_frontier_regular_file(
286                resolved.canonical.as_deref(),
287                &default_path,
288                ENGINE_POLICY_DOCUMENT_MAX_BYTES,
289                &reference,
290            )?;
291            if default.is_some() {
292                used_default_path = true;
293            }
294            default.map(|bytes| (default_path, bytes, false))
295        };
296
297        if let Some((path, bytes, declared_in_manifest)) = chosen {
298            let body = std::str::from_utf8(&bytes).map_err(|_| {
299                PolicyLoadError::new(
300                    "document_invalid_utf8",
301                    &reference,
302                    Some(bytes_root(&bytes)),
303                    format!("{reference}: policy document must be UTF-8"),
304                )
305            })?;
306            let (front_matter, title) = parse_front_matter(body, kind);
307            documents.push(PolicyDocumentSummary {
308                kind,
309                path: normalized_path_string(&path),
310                title,
311                body_sha256: format!("sha256:{}", hex::encode(Sha256::digest(body.as_bytes()))),
312                bytes: body.len(),
313                declared_in_manifest,
314                front_matter,
315            });
316        } else {
317            missing_required.push(kind.as_str().to_string());
318        }
319    }
320
321    documents.sort_by(|a, b| a.kind.cmp(&b.kind));
322    missing_required.sort();
323    let configured = has_manifest_refs || !documents.is_empty();
324    let mut summary = FrontierPolicySummary {
325        ok: missing_required.is_empty(),
326        frontier_id,
327        frontier_path: resolved.display.display().to_string(),
328        documents,
329        missing_required,
330        configured,
331        defaults_used: used_default_path,
332        canonical_json_sha256: String::new(),
333    };
334    summary.canonical_json_sha256 = summary_hash(&summary).map_err(|error| {
335        PolicyLoadError::new(
336            "summary_hash_failed",
337            "policy_summary",
338            None,
339            format!("policy_summary: canonical hashing failed ({error})"),
340        )
341    })?;
342    Ok(summary)
343}
344
345pub fn review_requirement_for_operation(
346    summary: Option<&FrontierPolicySummary>,
347    operation_class: &str,
348    proposal_kind: &str,
349    has_downstream_impact: bool,
350) -> OperationReviewRequirement {
351    let review_class =
352        review_class_for_operation(operation_class, proposal_kind, has_downstream_impact);
353    let mut reviewer_roles =
354        policy_roles_for_review_class(summary, &review_class).unwrap_or_else(|| {
355            default_roles_for_review_class(&review_class)
356                .into_iter()
357                .map(ToString::to_string)
358                .collect()
359        });
360    reviewer_roles.sort();
361    reviewer_roles.dedup();
362    if reviewer_roles.is_empty() {
363        reviewer_roles.push("local_reviewer".to_string());
364    }
365
366    let mut required_reason_fields = BTreeSet::new();
367    required_reason_fields.insert("reason".to_string());
368    if matches!(
369        review_class.as_str(),
370        "source_repair" | "clinical_translation" | "retraction_impact"
371    ) || (review_class == "confidence_change"
372        && confidence_policy_requires_source_or_evidence_ref(summary))
373    {
374        required_reason_fields.insert("source_or_evidence_ref".to_string());
375    }
376    if matches!(
377        review_class.as_str(),
378        "clinical_translation" | "retraction_impact" | "decision_impact"
379    ) {
380        required_reason_fields.insert("impact_scope".to_string());
381    }
382
383    let mut policy_sources = BTreeSet::new();
384    let mut allowed_agent_actions = agent_allowed_actions(summary);
385    allowed_agent_actions.sort();
386    allowed_agent_actions.dedup();
387    if summary.is_some() {
388        policy_sources.insert("frontier_policy".to_string());
389    } else {
390        policy_sources.insert("built_in_defaults".to_string());
391    }
392
393    OperationReviewRequirement {
394        review_class,
395        required_reviewer_count: reviewer_roles.len().max(1),
396        reviewer_roles,
397        required_reason_fields: required_reason_fields.into_iter().collect(),
398        allowed_agent_actions,
399        policy_sources: policy_sources.into_iter().collect(),
400    }
401}
402struct ResolvedFrontierRoot {
403    display: PathBuf,
404    canonical: Option<PathBuf>,
405}
406
407fn resolve_frontier_root(path: &Path) -> Result<ResolvedFrontierRoot, PolicyLoadError> {
408    match std::fs::symlink_metadata(path) {
409        Ok(_) => {
410            let canonical = path.canonicalize().map_err(|error| {
411                PolicyLoadError::io("frontier_root_unavailable", "frontier_root", &error)
412            })?;
413            let metadata = std::fs::metadata(&canonical).map_err(|error| {
414                PolicyLoadError::io("frontier_root_unavailable", "frontier_root", &error)
415            })?;
416            let root = if metadata.is_dir() {
417                canonical
418            } else if metadata.is_file() {
419                canonical.parent().map(Path::to_path_buf).ok_or_else(|| {
420                    PolicyLoadError::new(
421                        "frontier_root_invalid",
422                        "frontier_root",
423                        None,
424                        "frontier_root: file has no parent directory",
425                    )
426                })?
427            } else {
428                return Err(PolicyLoadError::new(
429                    "frontier_root_invalid",
430                    "frontier_root",
431                    None,
432                    "frontier_root: expected a directory or regular file",
433                ));
434            };
435            Ok(ResolvedFrontierRoot {
436                display: root.clone(),
437                canonical: Some(root),
438            })
439        }
440        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(ResolvedFrontierRoot {
441            display: path.to_path_buf(),
442            canonical: None,
443        }),
444        Err(error) => Err(PolicyLoadError::io(
445            "frontier_root_unavailable",
446            "frontier_root",
447            &error,
448        )),
449    }
450}
451
452fn parse_manifest(bytes: &[u8]) -> Result<serde_yaml::Value, PolicyLoadError> {
453    let body = std::str::from_utf8(bytes).map_err(|_| {
454        PolicyLoadError::new(
455            "manifest_invalid_utf8",
456            "frontier_manifest",
457            Some(bytes_root(bytes)),
458            "frontier_manifest: manifest must be UTF-8",
459        )
460    })?;
461    serde_yaml::from_str(body).map_err(|_| {
462        PolicyLoadError::new(
463            "manifest_invalid_yaml",
464            "frontier_manifest",
465            Some(bytes_root(bytes)),
466            "frontier_manifest: manifest YAML is invalid",
467        )
468    })
469}
470
471fn read_frontier_regular_file(
472    root: Option<&Path>,
473    relative: &Path,
474    max_bytes: usize,
475    reference: &str,
476) -> Result<Option<Vec<u8>>, PolicyLoadError> {
477    if relative.as_os_str().is_empty()
478        || relative.is_absolute()
479        || !relative
480            .components()
481            .all(|component| matches!(component, Component::Normal(_)))
482    {
483        return Err(PolicyLoadError::new(
484            "path_not_normalized",
485            reference,
486            Some(text_root(&relative.to_string_lossy())),
487            format!("{reference}: path must be normalized and frontier-relative"),
488        ));
489    }
490    let Some(root) = root else {
491        return Ok(None);
492    };
493    let components = relative.components().collect::<Vec<_>>();
494    let mut current = root.to_path_buf();
495    for (index, component) in components.iter().enumerate() {
496        let Component::Normal(component) = component else {
497            unreachable!("relative path was normalized above")
498        };
499        current.push(component);
500        let metadata = match std::fs::symlink_metadata(&current) {
501            Ok(metadata) => metadata,
502            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
503            Err(error) => {
504                return Err(PolicyLoadError::io(
505                    "path_inspection_failed",
506                    reference,
507                    &error,
508                ));
509            }
510        };
511        if metadata.file_type().is_symlink() {
512            return Err(PolicyLoadError::new(
513                "path_symlink",
514                reference,
515                None,
516                format!("{reference}: path must not traverse a symlink"),
517            ));
518        }
519        let is_leaf = index + 1 == components.len();
520        if is_leaf {
521            if !metadata.is_file() {
522                return Err(PolicyLoadError::new(
523                    "path_not_regular_file",
524                    reference,
525                    None,
526                    format!("{reference}: path must name a regular file"),
527                ));
528            }
529            if metadata.len() > max_bytes as u64 {
530                return Err(file_too_large(reference, metadata.len(), max_bytes));
531            }
532        } else if !metadata.is_dir() {
533            return Err(PolicyLoadError::new(
534                "path_ancestor_not_directory",
535                reference,
536                None,
537                format!("{reference}: path ancestor must be a directory"),
538            ));
539        }
540    }
541
542    let file = std::fs::File::open(&current)
543        .map_err(|error| PolicyLoadError::io("file_open_failed", reference, &error))?;
544    let opened = file
545        .metadata()
546        .map_err(|error| PolicyLoadError::io("file_inspection_failed", reference, &error))?;
547    if !opened.is_file() {
548        return Err(PolicyLoadError::new(
549            "path_not_regular_file",
550            reference,
551            None,
552            format!("{reference}: opened descriptor is not a regular file"),
553        ));
554    }
555    if opened.len() > max_bytes as u64 {
556        return Err(file_too_large(reference, opened.len(), max_bytes));
557    }
558    let opened_identity = descriptor_identity(&file, reference)?;
559
560    let linked = std::fs::symlink_metadata(&current)
561        .map_err(|error| PolicyLoadError::io("path_reinspection_failed", reference, &error))?;
562    if linked.file_type().is_symlink() || !linked.is_file() {
563        return Err(PolicyLoadError::new(
564            "path_changed",
565            reference,
566            None,
567            format!("{reference}: path changed while being opened"),
568        ));
569    }
570    let canonical = current
571        .canonicalize()
572        .map_err(|error| PolicyLoadError::io("path_canonicalize_failed", reference, &error))?;
573    if !canonical.starts_with(root) {
574        return Err(PolicyLoadError::new(
575            "path_outside_frontier",
576            reference,
577            None,
578            format!("{reference}: path resolved outside the frontier"),
579        ));
580    }
581    let named = std::fs::File::open(&current)
582        .map_err(|error| PolicyLoadError::io("file_reopen_failed", reference, &error))?;
583    if descriptor_identity(&named, reference)? != opened_identity {
584        return Err(PolicyLoadError::new(
585            "path_changed",
586            reference,
587            None,
588            format!("{reference}: descriptor identity changed while being opened"),
589        ));
590    }
591    let final_linked = std::fs::symlink_metadata(&current)
592        .map_err(|error| PolicyLoadError::io("path_reinspection_failed", reference, &error))?;
593    if final_linked.file_type().is_symlink() || !final_linked.is_file() {
594        return Err(PolicyLoadError::new(
595            "path_changed",
596            reference,
597            None,
598            format!("{reference}: path did not remain a non-symlink regular file"),
599        ));
600    }
601
602    let mut bytes = Vec::new();
603    file.take(max_bytes.saturating_add(1) as u64)
604        .read_to_end(&mut bytes)
605        .map_err(|error| PolicyLoadError::io("file_read_failed", reference, &error))?;
606    if bytes.len() > max_bytes {
607        return Err(file_too_large(reference, bytes.len() as u64, max_bytes));
608    }
609    Ok(Some(bytes))
610}
611
612fn file_too_large(reference: &str, bytes: u64, max_bytes: usize) -> PolicyLoadError {
613    PolicyLoadError::new(
614        "file_too_large",
615        reference,
616        Some(text_root(&bytes.to_string())),
617        format!("{reference}: file exceeds the {max_bytes}-byte input limit"),
618    )
619}
620
621fn descriptor_identity(
622    file: &std::fs::File,
623    reference: &str,
624) -> Result<(u64, u64), PolicyLoadError> {
625    #[cfg(unix)]
626    {
627        use std::os::unix::fs::MetadataExt;
628        let metadata = file
629            .metadata()
630            .map_err(|error| PolicyLoadError::io("file_identity_failed", reference, &error))?;
631        Ok((metadata.dev(), metadata.ino()))
632    }
633    #[cfg(windows)]
634    {
635        windows_descriptor_identity(file)
636            .map_err(|error| PolicyLoadError::io("file_identity_failed", reference, &error))
637    }
638    #[cfg(not(any(unix, windows)))]
639    {
640        let _ = file;
641        Err(PolicyLoadError::new(
642            "file_identity_unsupported",
643            reference,
644            None,
645            format!("{reference}: descriptor identity is unsupported on this platform"),
646        ))
647    }
648}
649
650#[cfg(windows)]
651#[allow(unsafe_code)]
652fn windows_descriptor_identity(file: &std::fs::File) -> Result<(u64, u64), std::io::Error> {
653    use std::ffi::c_void;
654    use std::mem::MaybeUninit;
655    use std::os::windows::io::AsRawHandle;
656
657    #[repr(C)]
658    struct FileTime {
659        low: u32,
660        high: u32,
661    }
662    #[repr(C)]
663    struct ByHandleFileInformation {
664        attributes: u32,
665        creation_time: FileTime,
666        last_access_time: FileTime,
667        last_write_time: FileTime,
668        volume_serial_number: u32,
669        file_size_high: u32,
670        file_size_low: u32,
671        number_of_links: u32,
672        file_index_high: u32,
673        file_index_low: u32,
674    }
675    #[link(name = "kernel32")]
676    unsafe extern "system" {
677        fn GetFileInformationByHandle(
678            handle: *mut c_void,
679            information: *mut ByHandleFileInformation,
680        ) -> i32;
681    }
682
683    let mut information = MaybeUninit::<ByHandleFileInformation>::uninit();
684    // SAFETY: the raw handle is owned by `file`, remains valid for this call,
685    // and Windows initializes the output structure when it reports success.
686    let ok = unsafe {
687        GetFileInformationByHandle(file.as_raw_handle().cast(), information.as_mut_ptr())
688    };
689    if ok == 0 {
690        return Err(std::io::Error::last_os_error());
691    }
692    // SAFETY: a non-zero return guarantees the structure was initialized.
693    let information = unsafe { information.assume_init() };
694    let index =
695        (u64::from(information.file_index_high) << 32) | u64::from(information.file_index_low);
696    Ok((u64::from(information.volume_serial_number), index))
697}
698
699fn policy_refs_from_manifest(
700    manifest: &serde_yaml::Value,
701) -> BTreeMap<PolicyDocumentKind, PathBuf> {
702    let mut out = BTreeMap::new();
703    for kind in PolicyDocumentKind::all() {
704        if let Some(value) = yaml_string_at(manifest, &["policies", "frontier", kind.as_str()]) {
705            out.insert(kind, PathBuf::from(value));
706        }
707    }
708    out
709}
710
711fn review_class_for_operation(
712    operation_class: &str,
713    proposal_kind: &str,
714    has_downstream_impact: bool,
715) -> String {
716    let haystack = format!(
717        "{} {}",
718        operation_class.to_ascii_lowercase(),
719        proposal_kind.to_ascii_lowercase()
720    );
721    if haystack.contains("clinical") || haystack.contains("translation") {
722        return "clinical_translation".to_string();
723    }
724    if haystack.contains("retraction") || haystack.contains("retract") {
725        return "retraction_impact".to_string();
726    }
727    match operation_class {
728        "revise_confidence" => "confidence_change",
729        "mark_contradiction" => "contradiction_change",
730        "repair_locator" | "repair_span" | "add_evidence_atom" => "source_repair",
731        "resolve_entity" => "entity_issue",
732        "request_downstream_review" | "open_gap" => "decision_impact",
733        _ if has_downstream_impact => "decision_impact",
734        _ => "low_risk",
735    }
736    .to_string()
737}
738
739fn default_roles_for_review_class(review_class: &str) -> Vec<&'static str> {
740    match review_class {
741        "confidence_change" | "contradiction_change" | "retraction_impact" => {
742            vec!["domain_reviewer", "method_reviewer"]
743        }
744        "clinical_translation" => vec!["domain_reviewer", "safety_reviewer"],
745        "source_repair" => vec!["source_reviewer"],
746        "entity_issue" => vec!["entity_reviewer"],
747        "decision_impact" => vec!["frontier_reviewer"],
748        _ => vec!["local_reviewer"],
749    }
750}
751
752fn policy_roles_for_review_class(
753    summary: Option<&FrontierPolicySummary>,
754    review_class: &str,
755) -> Option<Vec<String>> {
756    let review_doc = summary?
757        .documents
758        .iter()
759        .find(|doc| doc.kind == PolicyDocumentKind::Review && !doc.front_matter.is_empty())?;
760    let roles = review_doc
761        .front_matter
762        .get("required_roles")?
763        .get(review_class)?
764        .as_array()?
765        .iter()
766        .filter_map(|v| v.as_str().map(ToString::to_string))
767        .collect::<Vec<_>>();
768    if roles.is_empty() { None } else { Some(roles) }
769}
770
771fn confidence_policy_requires_source_or_evidence_ref(
772    summary: Option<&FrontierPolicySummary>,
773) -> bool {
774    summary
775        .and_then(|s| {
776            s.documents
777                .iter()
778                .find(|doc| doc.kind == PolicyDocumentKind::Confidence)
779        })
780        .and_then(|doc| doc.front_matter.get("requires_source_or_evidence_ref"))
781        .and_then(serde_json::Value::as_bool)
782        .unwrap_or(false)
783}
784
785fn agent_allowed_actions(summary: Option<&FrontierPolicySummary>) -> Vec<String> {
786    summary
787        .and_then(|s| {
788            s.documents
789                .iter()
790                .find(|doc| doc.kind == PolicyDocumentKind::Agent)
791        })
792        .and_then(|doc| doc.front_matter.get("agents_may"))
793        .and_then(serde_json::Value::as_array)
794        .map(|arr| {
795            arr.iter()
796                .filter_map(|v| v.as_str().map(ToString::to_string))
797                .collect::<Vec<_>>()
798        })
799        .unwrap_or_default()
800}
801
802fn parse_front_matter(
803    body: &str,
804    kind: PolicyDocumentKind,
805) -> (BTreeMap<String, serde_json::Value>, String) {
806    let mut metadata = BTreeMap::new();
807    if let Some(rest) = body.strip_prefix("---\n")
808        && let Some((front, _body)) = rest.split_once("\n---")
809        && let Ok(yaml) = serde_yaml::from_str::<serde_yaml::Value>(front)
810        && let Some(map) = yaml.as_mapping()
811    {
812        for (key, value) in map {
813            if let Some(key) = key.as_str()
814                && let Ok(json_value) = serde_json::to_value(value)
815            {
816                metadata.insert(key.to_string(), json_value);
817            }
818        }
819    }
820    let title = metadata
821        .get("title")
822        .and_then(|v| v.as_str())
823        .map(ToString::to_string)
824        .unwrap_or_else(|| format!("{} policy", kind.as_str()));
825    (metadata, title)
826}
827
828fn yaml_string_at(value: &serde_yaml::Value, path: &[&str]) -> Option<String> {
829    let mut cur = value;
830    for key in path {
831        cur = cur.get(*key)?;
832    }
833    cur.as_str().map(ToString::to_string)
834}
835
836fn normalized_path_string(path: &Path) -> String {
837    path.components()
838        .filter_map(|component| match component {
839            Component::Normal(component) => Some(component.to_string_lossy()),
840            _ => None,
841        })
842        .collect::<Vec<_>>()
843        .join("/")
844}
845
846fn summary_hash(summary: &FrontierPolicySummary) -> Result<String, String> {
847    let mut value = serde_json::to_value(summary).map_err(|e| format!("serialize policy: {e}"))?;
848    if let Some(obj) = value.as_object_mut() {
849        obj.remove("canonical_json_sha256");
850        obj.remove("frontier_path");
851        obj.remove("frontier_id");
852    }
853    let bytes = canonical::to_canonical_bytes(&value)?;
854    Ok(format!("sha256:{}", hex::encode(Sha256::digest(bytes))))
855}
856
857fn observation_root(
858    state: EnginePolicySummaryState,
859    summary_root: Option<&str>,
860    error_code: Option<&str>,
861    error_root: Option<&str>,
862) -> String {
863    domain_hash(
864        ENGINE_POLICY_SUMMARY_ROOT_DOMAIN,
865        &[
866            Some(ENGINE_POLICY_SUMMARY_OBSERVATION_SCHEMA),
867            Some(state.as_str()),
868            summary_root,
869            error_code,
870            error_root,
871        ],
872    )
873}
874
875fn bytes_root(bytes: &[u8]) -> String {
876    format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
877}
878
879fn text_root(text: &str) -> String {
880    domain_hash("vela.engine-policy-text.v1", &[Some(text)])
881}
882
883fn domain_hash(domain: &str, parts: &[Option<&str>]) -> String {
884    let mut digest = Sha256::new();
885    digest.update(domain.as_bytes());
886    digest.update([0]);
887    for part in parts {
888        match part {
889            Some(part) => {
890                digest.update((part.len() as u64).to_be_bytes());
891                digest.update(part.as_bytes());
892            }
893            None => digest.update(u64::MAX.to_be_bytes()),
894        }
895    }
896    format!("sha256:{}", hex::encode(digest.finalize()))
897}
898
899#[cfg(test)]
900mod tests {
901    use super::*;
902    use tempfile::TempDir;
903
904    /// Write one policy doc to the frontier's default policy dir
905    /// (`.vela/policy/<filename>`), creating the tree as needed.
906    fn write_default_policy(root: &Path, kind: PolicyDocumentKind, body: &str) {
907        let dir = root.join(".vela").join("policy");
908        std::fs::create_dir_all(&dir).unwrap();
909        std::fs::write(dir.join(kind.filename()), body).unwrap();
910    }
911
912    /// A frontier dir with all four required policy docs present at their
913    /// default paths, so the summary is `ok`.
914    fn complete_frontier() -> TempDir {
915        let tmp = TempDir::new().unwrap();
916        for kind in PolicyDocumentKind::all() {
917            write_default_policy(
918                tmp.path(),
919                kind,
920                &format!("---\ntitle: {} rules\n---\nbody\n", kind.as_str()),
921            );
922        }
923        tmp
924    }
925
926    fn write_manifest(root: &Path, policies: &str) {
927        std::fs::write(
928            root.join("frontier.yaml"),
929            format!(
930                "schema: vela.frontier_manifest.v0.1\nfrontier_id: vfr_policy_test\npolicies:\n{policies}"
931            ),
932        )
933        .unwrap();
934    }
935
936    #[test]
937    fn kind_str_and_filename_round_trip() {
938        // Every kind has a distinct str and a filename that embeds it.
939        let kinds = PolicyDocumentKind::all();
940        let strs: BTreeSet<&str> = kinds.iter().map(|k| k.as_str()).collect();
941        assert_eq!(strs.len(), 4, "kinds must have distinct as_str values");
942        for kind in kinds {
943            assert!(
944                kind.filename().starts_with(kind.as_str()),
945                "{} filename {} should embed its str",
946                kind.as_str(),
947                kind.filename()
948            );
949            assert!(kind.filename().ends_with(".md"));
950        }
951    }
952
953    #[test]
954    fn complete_frontier_summary_is_ok_and_titles_parse() {
955        let tmp = complete_frontier();
956        let summary = load_policy_summary(tmp.path()).unwrap();
957        assert!(summary.ok, "all four docs present => ok");
958        assert!(summary.configured);
959        assert!(summary.missing_required.is_empty());
960        assert_eq!(summary.documents.len(), 4);
961        // Front-matter title is lifted verbatim.
962        let review = summary
963            .documents
964            .iter()
965            .find(|d| d.kind == PolicyDocumentKind::Review)
966            .unwrap();
967        assert_eq!(review.title, "review rules");
968        // Default-path docs are not "declared in manifest".
969        assert!(!review.declared_in_manifest);
970        assert!(summary.defaults_used);
971        assert!(summary.canonical_json_sha256.starts_with("sha256:"));
972    }
973
974    #[test]
975    fn missing_documents_are_reported_and_summary_not_ok() {
976        let tmp = TempDir::new().unwrap();
977        // Only two of the four required docs are present.
978        write_default_policy(tmp.path(), PolicyDocumentKind::Evidence, "evidence body");
979        write_default_policy(tmp.path(), PolicyDocumentKind::Review, "review body");
980        let summary = load_policy_summary(tmp.path()).unwrap();
981        assert!(!summary.ok);
982        assert!(summary.configured);
983        assert_eq!(summary.documents.len(), 2);
984        // missing_required is sorted and names exactly the absent kinds.
985        assert_eq!(summary.missing_required, vec!["agent", "confidence"]);
986    }
987
988    #[test]
989    fn declared_missing_documents_do_not_fall_back_or_look_absent() {
990        let tmp = TempDir::new().unwrap();
991        // Even a conventional file with the same kind cannot replace an
992        // explicitly declared path that is missing.
993        write_default_policy(
994            tmp.path(),
995            PolicyDocumentKind::Evidence,
996            "must not be used as a fallback",
997        );
998        write_manifest(
999            tmp.path(),
1000            "  frontier:\n    evidence: policy/missing-evidence.md\n    review: policy/missing-review.md\n    confidence: policy/missing-confidence.md\n    agent: policy/missing-agent.md\n",
1001        );
1002
1003        let summary = load_policy_summary(tmp.path()).unwrap();
1004        assert!(!summary.ok);
1005        assert!(summary.configured);
1006        assert!(summary.documents.is_empty());
1007        assert!(!summary.defaults_used);
1008        assert_eq!(summary.missing_required.len(), 4);
1009        let observation = engine_policy_summary_observation(tmp.path());
1010        assert_eq!(observation.state, EnginePolicySummaryState::Present);
1011    }
1012
1013    #[test]
1014    fn empty_frontier_policy_is_explicitly_unconfigured() {
1015        let tmp = TempDir::new().unwrap();
1016        let summary = load_policy_summary(tmp.path()).unwrap();
1017        assert!(!summary.ok);
1018        assert!(!summary.configured);
1019        assert!(summary.documents.is_empty());
1020        let observation = engine_policy_summary_observation(tmp.path());
1021        assert_eq!(observation.state, EnginePolicySummaryState::Absent);
1022    }
1023
1024    #[test]
1025    fn title_falls_back_when_no_front_matter() {
1026        let tmp = TempDir::new().unwrap();
1027        // A body with no `---` front matter yields the default title.
1028        write_default_policy(
1029            tmp.path(),
1030            PolicyDocumentKind::Confidence,
1031            "plain body, no front matter\n",
1032        );
1033        let summary = load_policy_summary(tmp.path()).unwrap();
1034        let doc = &summary.documents[0];
1035        assert_eq!(doc.kind, PolicyDocumentKind::Confidence);
1036        assert_eq!(doc.title, "confidence policy");
1037        assert!(doc.front_matter.is_empty());
1038        // Body hash and byte count reflect the written body.
1039        assert_eq!(doc.bytes, "plain body, no front matter\n".len());
1040        assert!(doc.body_sha256.starts_with("sha256:"));
1041    }
1042
1043    #[test]
1044    fn summary_hash_is_deterministic_and_excludes_itself() {
1045        let tmp = complete_frontier();
1046        let a = load_policy_summary(tmp.path()).unwrap();
1047        let b = load_policy_summary(tmp.path()).unwrap();
1048        // The canonical hash pins the whole summary and is reproducible.
1049        assert_eq!(a.canonical_json_sha256, b.canonical_json_sha256);
1050        // Recomputing the hash over the summary (which the field excludes)
1051        // reproduces the stored value.
1052        assert_eq!(summary_hash(&a).unwrap(), a.canonical_json_sha256);
1053    }
1054
1055    #[test]
1056    fn engine_policy_observation_is_clone_stable_and_content_bound() {
1057        let first = complete_frontier();
1058        let second = complete_frontier();
1059        let first_observation = engine_policy_summary_observation(first.path());
1060        let second_observation = engine_policy_summary_observation(second.path());
1061        assert_eq!(first_observation.state, EnginePolicySummaryState::Present);
1062        assert_eq!(first_observation.root, second_observation.root);
1063        assert!(
1064            !first_observation
1065                .root
1066                .contains(&first.path().display().to_string())
1067        );
1068
1069        write_default_policy(
1070            second.path(),
1071            PolicyDocumentKind::Review,
1072            "changed review policy",
1073        );
1074        let changed = engine_policy_summary_observation(second.path());
1075        assert_ne!(first_observation.root, changed.root);
1076    }
1077
1078    #[test]
1079    fn manifest_traversal_is_invalid_and_never_read() {
1080        let tmp = TempDir::new().unwrap();
1081        let outside = TempDir::new().unwrap();
1082        std::fs::write(outside.path().join("outside.md"), "must not be read").unwrap();
1083        write_manifest(tmp.path(), "  frontier:\n    evidence: ../outside.md\n");
1084
1085        let error = load_policy_summary(tmp.path()).unwrap_err();
1086        assert!(error.contains("path_not_normalized"), "{error}");
1087        let observation = engine_policy_summary_observation(tmp.path());
1088        assert_eq!(observation.state, EnginePolicySummaryState::Invalid);
1089        assert_eq!(
1090            observation.error_code.as_deref(),
1091            Some("path_not_normalized")
1092        );
1093        assert!(observation.error_root.is_some());
1094        assert!(
1095            !serde_json::to_string(&observation)
1096                .unwrap()
1097                .contains(&outside.path().display().to_string())
1098        );
1099    }
1100
1101    #[cfg(unix)]
1102    #[test]
1103    fn manifest_selected_symlink_leaf_and_ancestor_are_invalid() {
1104        use std::os::unix::fs::symlink;
1105
1106        let outside = TempDir::new().unwrap();
1107        std::fs::write(outside.path().join("review.md"), "outside review").unwrap();
1108
1109        let leaf = TempDir::new().unwrap();
1110        std::fs::create_dir_all(leaf.path().join("policy")).unwrap();
1111        symlink(
1112            outside.path().join("review.md"),
1113            leaf.path().join("policy/review.md"),
1114        )
1115        .unwrap();
1116        write_manifest(leaf.path(), "  frontier:\n    review: policy/review.md\n");
1117        let leaf_observation = engine_policy_summary_observation(leaf.path());
1118        assert_eq!(leaf_observation.state, EnginePolicySummaryState::Invalid);
1119        assert_eq!(leaf_observation.error_code.as_deref(), Some("path_symlink"));
1120
1121        let ancestor = TempDir::new().unwrap();
1122        symlink(outside.path(), ancestor.path().join("linked")).unwrap();
1123        write_manifest(
1124            ancestor.path(),
1125            "  frontier:\n    review: linked/review.md\n",
1126        );
1127        let ancestor_observation = engine_policy_summary_observation(ancestor.path());
1128        assert_eq!(
1129            ancestor_observation.state,
1130            EnginePolicySummaryState::Invalid
1131        );
1132        assert_eq!(
1133            ancestor_observation.error_code.as_deref(),
1134            Some("path_symlink")
1135        );
1136    }
1137
1138    #[test]
1139    fn manifest_and_policy_documents_are_pre_read_bounded() {
1140        let policy = TempDir::new().unwrap();
1141        write_default_policy(
1142            policy.path(),
1143            PolicyDocumentKind::Evidence,
1144            &"x".repeat(ENGINE_POLICY_DOCUMENT_MAX_BYTES + 1),
1145        );
1146        let policy_observation = engine_policy_summary_observation(policy.path());
1147        assert_eq!(policy_observation.state, EnginePolicySummaryState::Invalid);
1148        assert_eq!(
1149            policy_observation.error_code.as_deref(),
1150            Some("file_too_large")
1151        );
1152
1153        let manifest = TempDir::new().unwrap();
1154        std::fs::write(
1155            manifest.path().join("frontier.yaml"),
1156            vec![b'x'; ENGINE_POLICY_MANIFEST_MAX_BYTES + 1],
1157        )
1158        .unwrap();
1159        let manifest_observation = engine_policy_summary_observation(manifest.path());
1160        assert_eq!(
1161            manifest_observation.state,
1162            EnginePolicySummaryState::Invalid
1163        );
1164        assert_eq!(
1165            manifest_observation.error_code.as_deref(),
1166            Some("file_too_large")
1167        );
1168    }
1169
1170    #[test]
1171    fn low_risk_operation_defaults_to_local_reviewer() {
1172        // With no policy summary, an unremarkable operation is low-risk and
1173        // needs one local reviewer, and only a `reason` field.
1174        let req = review_requirement_for_operation(None, "note", "comment", false);
1175        assert_eq!(req.review_class, "low_risk");
1176        assert_eq!(req.reviewer_roles, vec!["local_reviewer"]);
1177        assert_eq!(req.required_reviewer_count, 1);
1178        assert_eq!(req.required_reason_fields, vec!["reason"]);
1179        assert_eq!(req.policy_sources, vec!["built_in_defaults"]);
1180    }
1181
1182    #[test]
1183    fn clinical_translation_escalates_roles_and_reason_fields() {
1184        // A clinical/translation keyword routes to the highest-touch class:
1185        // two reviewer roles and the extra reason fields.
1186        let req = review_requirement_for_operation(None, "revise_confidence", "clinical", false);
1187        assert_eq!(req.review_class, "clinical_translation");
1188        assert_eq!(
1189            req.reviewer_roles,
1190            vec!["domain_reviewer", "safety_reviewer"]
1191        );
1192        assert_eq!(req.required_reviewer_count, 2);
1193        // reason + source_or_evidence_ref + impact_scope, sorted.
1194        assert_eq!(
1195            req.required_reason_fields,
1196            vec!["impact_scope", "reason", "source_or_evidence_ref"]
1197        );
1198    }
1199
1200    #[test]
1201    fn downstream_impact_promotes_unclassified_op_to_decision_impact() {
1202        // An operation with no dedicated class but downstream impact becomes
1203        // decision_impact (frontier_reviewer + impact_scope), whereas without
1204        // impact the same op is low_risk.
1205        let with_impact = review_requirement_for_operation(None, "misc_op", "misc", true);
1206        assert_eq!(with_impact.review_class, "decision_impact");
1207        assert_eq!(with_impact.reviewer_roles, vec!["frontier_reviewer"]);
1208        assert!(
1209            with_impact
1210                .required_reason_fields
1211                .contains(&"impact_scope".to_string())
1212        );
1213
1214        let without = review_requirement_for_operation(None, "misc_op", "misc", false);
1215        assert_eq!(without.review_class, "low_risk");
1216    }
1217
1218    #[test]
1219    fn policy_overrides_default_roles_and_surfaces_agent_actions() {
1220        // A frontier whose review policy declares custom roles for a class,
1221        // and whose agent policy declares allowed actions, is honored over
1222        // the built-in defaults.
1223        let tmp = complete_frontier();
1224        write_default_policy(
1225            tmp.path(),
1226            PolicyDocumentKind::Review,
1227            "---\nrequired_roles:\n  source_repair:\n    - senior_curator\n    - archivist\n---\nbody\n",
1228        );
1229        write_default_policy(
1230            tmp.path(),
1231            PolicyDocumentKind::Agent,
1232            "---\nagents_may:\n  - draft_receipt\n  - run_verifier\n---\nbody\n",
1233        );
1234        let summary = load_policy_summary(tmp.path()).unwrap();
1235
1236        let req = review_requirement_for_operation(Some(&summary), "repair_locator", "fix", false);
1237        assert_eq!(req.review_class, "source_repair");
1238        // Custom roles replace the default `source_reviewer`, and are sorted.
1239        assert_eq!(req.reviewer_roles, vec!["archivist", "senior_curator"]);
1240        // Agent actions from the agent policy are surfaced, sorted.
1241        assert_eq!(
1242            req.allowed_agent_actions,
1243            vec!["draft_receipt", "run_verifier"]
1244        );
1245        // A real summary marks the source as the frontier policy.
1246        assert_eq!(req.policy_sources, vec!["frontier_policy"]);
1247    }
1248
1249    #[test]
1250    fn confidence_change_requires_ref_only_when_policy_opts_in() {
1251        // confidence_change alone does not demand source_or_evidence_ref...
1252        let plain = review_requirement_for_operation(None, "revise_confidence", "update", false);
1253        assert_eq!(plain.review_class, "confidence_change");
1254        assert!(
1255            !plain
1256                .required_reason_fields
1257                .contains(&"source_or_evidence_ref".to_string())
1258        );
1259
1260        // ...but a confidence policy that opts in flips the requirement on.
1261        let tmp = complete_frontier();
1262        write_default_policy(
1263            tmp.path(),
1264            PolicyDocumentKind::Confidence,
1265            "---\nrequires_source_or_evidence_ref: true\n---\nbody\n",
1266        );
1267        let summary = load_policy_summary(tmp.path()).unwrap();
1268        let gated =
1269            review_requirement_for_operation(Some(&summary), "revise_confidence", "update", false);
1270        assert_eq!(gated.review_class, "confidence_change");
1271        assert!(
1272            gated
1273                .required_reason_fields
1274                .contains(&"source_or_evidence_ref".to_string())
1275        );
1276    }
1277}