use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::inspect::source_sha256;
pub(crate) const ENVELOPE_SCHEMA_VERSION: u32 = 1;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
Ok,
Refused,
Error,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Phase {
Inspected,
Generated,
Validated,
Committed,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Effect {
Changed,
Unchanged,
NotApplied,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PredictedEffect {
Changed,
Unchanged,
}
pub mod codes {
pub const NO_CHANGES_REQUESTED: &str = "NO_CHANGES_REQUESTED";
pub const POSTCONDITION_FAILED: &str = "POSTCONDITION_FAILED";
pub const WORKING_BASE_CHANGED: &str = "WORKING_BASE_CHANGED";
pub const AMBIGUOUS_ANCHOR: &str = "AMBIGUOUS_ANCHOR";
pub const STALE_SOURCE: &str = "STALE_SOURCE";
pub const UNSUPPORTED_OPERATION: &str = "UNSUPPORTED_OPERATION";
pub const INVALID_PLAN: &str = "INVALID_PLAN";
pub const RENDER_FIDELITY_FAILED: &str = "RENDER_FIDELITY_FAILED";
pub const RENDERING_FAILED: &str = "RENDERING_FAILED";
pub const DEADLINE_EXCEEDED: &str = "DEADLINE_EXCEEDED";
pub const USAGE: &str = "USAGE";
pub const CHECK_THRESHOLD_EXCEEDED: &str = "CHECK_THRESHOLD_EXCEEDED";
pub const COMPARISON_DIFFERENCE: &str = "COMPARISON_DIFFERENCE";
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommitState {
Committed,
NotCommitted,
Unknown,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MediaRole {
Document,
Plan,
Patch,
Report,
Render,
Other,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Artifact {
pub path: String,
pub media_role: MediaRole,
pub media_type: String,
pub sha256: String,
pub byte_size: u64,
pub committed: bool,
}
impl Artifact {
pub fn new(
path: impl Into<String>,
role: MediaRole,
media_type: impl Into<String>,
payload: &[u8],
) -> Self {
Self {
path: path.into(),
media_role: role,
media_type: media_type.into(),
sha256: source_sha256(payload),
byte_size: payload.len() as u64,
committed: false,
}
}
pub fn committed(
path: impl Into<String>,
role: MediaRole,
media_type: impl Into<String>,
payload: &[u8],
) -> Self {
let mut artifact = Self::new(path, role, media_type, payload);
artifact.committed = true;
artifact
}
#[must_use]
pub fn with_committed(mut self, committed: bool) -> Self {
self.committed = committed;
self
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Context {
pub before: String,
pub matched: String,
pub after: String,
pub truncated: bool,
}
impl Context {
pub fn new(
before: impl Into<String>,
matched: impl Into<String>,
after: impl Into<String>,
) -> Self {
Self {
before: before.into(),
matched: matched.into(),
after: after.into(),
truncated: false,
}
}
#[must_use]
pub fn with_truncated(mut self, truncated: bool) -> Self {
self.truncated = truncated;
self
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct NextAction {
pub argv: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prerequisites: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub purpose: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub destructive: bool,
}
impl NextAction {
pub fn new(argv: Vec<String>) -> Self {
Self {
argv,
prerequisites: None,
purpose: None,
destructive: false,
}
}
#[must_use]
pub fn with_destructive(mut self) -> Self {
self.destructive = true;
self
}
#[must_use]
pub fn with_purpose(mut self, purpose: impl Into<String>) -> Self {
self.purpose = Some(purpose.into());
self
}
#[must_use]
pub fn with_prerequisites(mut self, prerequisites: Vec<String>) -> Self {
self.prerequisites = Some(prerequisites);
self
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Error {
pub code: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_digest: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub matches: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context: Option<Context>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub near: Option<crate::edit::NearMatches>,
pub message: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub next_actions: Vec<NextAction>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retryable: Option<bool>,
pub commit_state: CommitState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expectations: Option<crate::expect::ExpectationReport>,
}
impl Error {
#[must_use]
pub fn with_commit_state(mut self, state: CommitState) -> Self {
self.commit_state = state;
self.normalize_retryable();
self
}
fn normalize_retryable(&mut self) {
if self.commit_state == CommitState::Unknown && self.retryable == Some(true) {
self.retryable = Some(false);
}
}
pub fn new(code: impl Into<String>) -> Self {
Self {
code: code.into(),
operation: None,
source_digest: None,
target: None,
matches: None,
context: None,
near: None,
message: String::new(),
next_actions: Vec::new(),
retryable: None,
commit_state: CommitState::Unknown,
expectations: None,
}
}
#[must_use]
pub fn with_message(mut self, message: impl Into<String>) -> Self {
self.message = message.into();
self
}
#[must_use]
pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
self.operation = Some(operation.into());
self
}
#[must_use]
pub fn with_source(mut self, source: Source) -> Self {
self.source_digest = Some(source.sha256);
self
}
#[must_use]
pub fn with_source_digest(mut self, digest: impl Into<String>) -> Self {
self.source_digest = Some(digest.into());
self
}
#[must_use]
pub fn with_target(mut self, target: impl Into<String>) -> Self {
self.target = Some(target.into());
self
}
#[must_use]
pub fn with_matches(mut self, matches: usize) -> Self {
self.matches = Some(matches);
self
}
#[must_use]
pub fn with_context(mut self, context: Context) -> Self {
self.context = Some(context);
self
}
pub fn set_context(&mut self, context: Context) {
self.context = Some(context);
}
pub fn push_next_action(&mut self, action: NextAction) {
self.next_actions.push(action);
}
#[must_use]
pub fn with_retryable(mut self, retryable: bool) -> Self {
self.retryable = Some(retryable);
self.normalize_retryable();
self
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Source {
pub sha256: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub byte_size: Option<u64>,
}
impl Source {
pub fn new(bytes: &[u8]) -> Self {
Self {
sha256: source_sha256(bytes),
path: None,
byte_size: Some(bytes.len() as u64),
}
}
pub fn from_digest(digest: impl Into<String>) -> Self {
Self {
sha256: digest.into(),
path: None,
byte_size: None,
}
}
#[must_use]
pub fn with_path(mut self, path: impl Into<String>) -> Self {
self.path = Some(path.into());
self
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Runtime {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub build: Option<String>,
}
impl Runtime {
pub fn native() -> Self {
Self {
name: "native".to_string(),
build: None,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Verification {
pub operation_postconditions: String,
pub integrity: String,
pub expectations: String,
pub task_semantics: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub baseline_findings: Option<Vec<crate::validate::Finding>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub introduced_findings: Option<Vec<crate::validate::Finding>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unresolved_findings: Option<Vec<crate::validate::Finding>>,
}
impl Default for Verification {
fn default() -> Self {
Self {
operation_postconditions: "skipped".to_string(),
integrity: "skipped".to_string(),
expectations: "not_requested".to_string(),
task_semantics: "not_assessed".to_string(),
baseline_findings: None,
introduced_findings: None,
unresolved_findings: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct Counts {
#[serde(default, skip_serializing_if = "is_zero")]
pub requested_operations: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub unchanged_operations: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub body_operations_applied: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub review_operations_applied: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub revisions_accepted: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub revisions_rejected: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub logical_revisions: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub revision_xml_entries: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub comment_threads: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub comment_replies: usize,
#[serde(default, skip_serializing_if = "is_zero")]
pub comments_added: usize,
}
impl Counts {
#[must_use]
pub fn total_operations(&self) -> usize {
self.body_operations_applied + self.review_operations_applied
}
}
fn is_zero(value: &usize) -> bool {
*value == 0
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ResultData {
pub phase: Option<Phase>,
pub effect: Effect,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub predicted_effect: Option<PredictedEffect>,
pub counts: Counts,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub removed_comments: Vec<crate::edit::RemovedComment>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub kept_comments: Vec<crate::edit::KeptComment>,
pub verification: Verification,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub generation: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expectations: Option<crate::expect::ExpectationReport>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ResultDataError {
MissingPhase,
FailureRequired,
NotAppliedRequired {
phase: Phase,
effect: Effect,
},
EffectRequired {
phase: Phase,
effect: Effect,
},
PredictedWithoutValidation {
phase: Phase,
},
}
impl std::fmt::Display for ResultDataError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::MissingPhase => write!(f, "a completed phase is required"),
Self::FailureRequired => write!(f, "failure data requires a refused or error status"),
Self::NotAppliedRequired { phase, effect } => write!(
f,
"phase {phase:?} requires effect NotApplied, got {effect:?}"
),
Self::EffectRequired { phase, effect } => write!(
f,
"phase {phase:?} requires effect Changed or Unchanged, got {effect:?}"
),
Self::PredictedWithoutValidation { phase } => write!(
f,
"predicted_effect is only valid with phase Validated, got {phase:?}"
),
}
}
}
impl std::error::Error for ResultDataError {}
impl ResultData {
pub fn failure(phase: Option<Phase>) -> Self {
Self {
phase,
effect: Effect::NotApplied,
predicted_effect: None,
counts: Counts::default(),
removed_comments: Vec::new(),
kept_comments: Vec::new(),
verification: Verification::default(),
generation: None,
expectations: None,
}
}
pub fn new(phase: Phase, effect: Effect) -> Self {
Self {
phase: Some(phase),
effect,
predicted_effect: None,
counts: Counts::default(),
removed_comments: Vec::new(),
kept_comments: Vec::new(),
verification: Verification::default(),
generation: None,
expectations: None,
}
}
pub fn set_predicted(&mut self, predicted: PredictedEffect) {
self.predicted_effect = Some(predicted);
}
pub fn validate(&self) -> Result<(), ResultDataError> {
match self.phase {
Some(phase) => {
if phase == Phase::Committed {
if self.effect == Effect::NotApplied {
return Err(ResultDataError::EffectRequired {
phase,
effect: self.effect,
});
}
} else if self.effect != Effect::NotApplied {
return Err(ResultDataError::NotAppliedRequired {
phase,
effect: self.effect,
});
}
if self.predicted_effect.is_some() && phase != Phase::Validated {
return Err(ResultDataError::PredictedWithoutValidation { phase });
}
}
None if self.effect != Effect::NotApplied || self.predicted_effect.is_some() => {
return Err(ResultDataError::MissingPhase);
}
None => {}
}
Ok(())
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Envelope {
pub schema_version: u32,
pub command: String,
pub engine_version: String,
pub runtime: Runtime,
pub status: Status,
pub source: Source,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<ResultData>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub artifacts: Vec<Artifact>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<Error>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub effective_options: BTreeMap<String, serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub continuation: Option<serde_json::Value>,
}
impl Envelope {
pub fn with_failure_data(mut self, data: ResultData) -> Result<Self, ResultDataError> {
if self.status == Status::Ok {
return Err(ResultDataError::FailureRequired);
}
data.validate()?;
if self.status == Status::Refused && data.phase == Some(Phase::Committed) {
return Err(ResultDataError::FailureRequired);
}
if let Some(error) = &mut self.error {
if data.phase == Some(Phase::Committed) {
error.commit_state = CommitState::Committed;
}
error.normalize_retryable();
}
self.data = Some(data);
Ok(self)
}
pub fn new(command: impl Into<String>, source: Source, runtime: Runtime) -> Self {
Self {
schema_version: ENVELOPE_SCHEMA_VERSION,
command: command.into(),
engine_version: env!("CARGO_PKG_VERSION").to_string(),
runtime,
status: Status::Ok,
source,
data: None,
artifacts: Vec::new(),
warnings: Vec::new(),
error: None,
effective_options: BTreeMap::new(),
continuation: None,
}
}
pub fn ok(
command: impl Into<String>,
source: Source,
data: ResultData,
runtime: Runtime,
) -> Result<Self, ResultDataError> {
data.validate()?;
if data.phase.is_none() {
return Err(ResultDataError::MissingPhase);
}
Ok(Self {
schema_version: ENVELOPE_SCHEMA_VERSION,
command: command.into(),
engine_version: env!("CARGO_PKG_VERSION").to_string(),
runtime,
status: Status::Ok,
source,
data: Some(data),
artifacts: Vec::new(),
warnings: Vec::new(),
error: None,
effective_options: BTreeMap::new(),
continuation: None,
})
}
pub fn refused(command: impl Into<String>, source: Source, error: Error) -> Self {
let error = error.with_commit_state(CommitState::NotCommitted);
Self {
schema_version: ENVELOPE_SCHEMA_VERSION,
command: command.into(),
engine_version: env!("CARGO_PKG_VERSION").to_string(),
runtime: Runtime::native(),
status: Status::Refused,
source,
data: Some(ResultData::failure(None)),
artifacts: Vec::new(),
warnings: Vec::new(),
error: Some(error),
effective_options: BTreeMap::new(),
continuation: None,
}
}
pub fn new_error(command: impl Into<String>, source: Source, mut error: Error) -> Self {
error.normalize_retryable();
Self {
schema_version: ENVELOPE_SCHEMA_VERSION,
command: command.into(),
engine_version: env!("CARGO_PKG_VERSION").to_string(),
runtime: Runtime::native(),
status: Status::Error,
source,
data: Some(ResultData::failure(None)),
artifacts: Vec::new(),
warnings: Vec::new(),
error: Some(error),
effective_options: BTreeMap::new(),
continuation: None,
}
}
pub fn push_artifact(&mut self, artifact: Artifact) {
self.artifacts.push(artifact);
}
pub fn push_warning(&mut self, warning: impl Into<String>) {
self.warnings.push(warning.into());
}
pub fn set_effective_option(&mut self, key: impl Into<String>, value: serde_json::Value) {
self.effective_options.insert(key.into(), value);
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "record", rename = "header")]
pub struct StreamHeader {
pub schema_version: u32,
pub command: String,
pub engine_version: String,
pub source: Source,
}
impl From<&Envelope> for StreamHeader {
fn from(envelope: &Envelope) -> Self {
Self {
schema_version: envelope.schema_version,
command: envelope.command.clone(),
engine_version: envelope.engine_version.clone(),
source: envelope.source.clone(),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProgressEvent {
value: serde_json::Value,
}
impl ProgressEvent {
pub fn new(value: serde_json::Value) -> Self {
Self { value }
}
pub fn value(&self) -> &serde_json::Value {
&self.value
}
}
impl From<serde_json::Value> for ProgressEvent {
fn from(value: serde_json::Value) -> Self {
Self::new(value)
}
}
impl From<ProgressEvent> for serde_json::Value {
fn from(event: ProgressEvent) -> Self {
event.value
}
}
pub fn jsonl_terminal_line(terminal: &Envelope) -> String {
serde_json::to_string(terminal).expect("Envelope serializes")
}
pub fn write_jsonl_stream(events: &[ProgressEvent], terminal: &Envelope) -> String {
let mut out =
serde_json::to_string(&StreamHeader::from(terminal)).expect("StreamHeader serializes");
out.push('\n');
for event in events {
out.push_str(&serde_json::to_string(event.value()).expect("progress serializes"));
out.push('\n');
}
out.push_str(&jsonl_terminal_line(terminal));
out.push('\n');
out
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParsedStream {
pub header: StreamHeader,
pub events: Vec<ProgressEvent>,
pub terminal: Envelope,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StreamError {
MissingHeader,
HeaderParse {
line: usize,
message: String,
},
InvalidLine {
line: usize,
content: String,
},
MissingTerminal,
MultipleTerminals,
TerminalParse {
line: usize,
message: String,
},
}
impl std::fmt::Display for StreamError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::MissingHeader => write!(f, "stream has no initial header record"),
Self::HeaderParse { line, message } => {
write!(f, "line {line}: header record parse error: {message}")
}
Self::InvalidLine { line, content } => {
write!(f, "line {line}: invalid JSONL line: {content}")
}
Self::MissingTerminal => write!(f, "stream has no terminal result line"),
Self::MultipleTerminals => write!(f, "stream carries more than one terminal result"),
Self::TerminalParse { line, message } => {
write!(f, "line {line}: terminal record parse error: {message}")
}
}
}
}
impl std::error::Error for StreamError {}
pub fn read_jsonl_stream(input: &str) -> std::result::Result<ParsedStream, StreamError> {
let mut header: Option<StreamHeader> = None;
let mut events: Vec<ProgressEvent> = Vec::new();
let mut terminal: Option<Envelope> = None;
for (index, raw) in input.lines().enumerate() {
let line = index + 1;
let trimmed = raw.trim();
if trimmed.is_empty() {
continue;
}
let value: serde_json::Value =
serde_json::from_str(trimmed).map_err(|_| StreamError::InvalidLine {
line,
content: trimmed.to_string(),
})?;
if header.is_none() {
if value.get("record").and_then(serde_json::Value::as_str) != Some("header") {
return Err(StreamError::MissingHeader);
}
header = Some(
serde_json::from_value(value).map_err(|e| StreamError::HeaderParse {
line,
message: e.to_string(),
})?,
);
continue;
}
if value.get("record").and_then(serde_json::Value::as_str) == Some("header") {
return Err(StreamError::InvalidLine {
line,
content: trimmed.to_string(),
});
}
if value.get("status").is_some() && value.get("ev").is_none() {
let record: Envelope =
serde_json::from_value(value).map_err(|e| StreamError::TerminalParse {
line,
message: e.to_string(),
})?;
if terminal.is_some() {
return Err(StreamError::MultipleTerminals);
}
terminal = Some(record);
} else {
if terminal.is_some() {
return Err(StreamError::InvalidLine {
line,
content: trimmed.to_string(),
});
}
if value
.get("ev")
.and_then(serde_json::Value::as_str)
.is_none()
{
return Err(StreamError::InvalidLine {
line,
content: trimmed.to_string(),
});
}
events.push(ProgressEvent::new(value));
}
}
let header = header.ok_or(StreamError::MissingHeader)?;
terminal
.map(|terminal| ParsedStream {
header,
events,
terminal,
})
.ok_or(StreamError::MissingTerminal)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ExitStatus(pub u8);
impl ExitStatus {
pub const SUCCESS: Self = Self(0);
pub const INPUT_FAILURE: Self = Self(1);
pub const CHECK_FINDINGS: Self = Self(2);
pub const REFUSED: Self = Self(3);
pub const RENDER_FAILURE: Self = Self(4);
pub const COMPARISON_DIFFERENCE: Self = Self(5);
pub const USAGE: Self = Self(64);
pub const DEADLINE_EXCEEDED: Self = Self(124);
}
impl From<ExitStatus> for u8 {
fn from(value: ExitStatus) -> Self {
value.0
}
}
pub fn exit_status_for(status: Status, error: Option<&Error>) -> ExitStatus {
if let Some(code) = error.map(|e| e.code.as_str()) {
match code {
codes::CHECK_THRESHOLD_EXCEEDED => return ExitStatus::CHECK_FINDINGS,
codes::COMPARISON_DIFFERENCE => return ExitStatus::COMPARISON_DIFFERENCE,
codes::RENDER_FIDELITY_FAILED => return ExitStatus::RENDER_FAILURE,
codes::USAGE => return ExitStatus::USAGE,
codes::DEADLINE_EXCEEDED => return ExitStatus::DEADLINE_EXCEEDED,
_ => {}
}
}
match status {
Status::Ok => ExitStatus::SUCCESS,
Status::Refused => ExitStatus::REFUSED,
Status::Error => ExitStatus::INPUT_FAILURE,
}
}
pub fn exit_status_for_envelope(envelope: &Envelope) -> ExitStatus {
exit_status_for(envelope.status, envelope.error.as_ref())
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture() -> Vec<u8> {
b"fixture-bytes".to_vec()
}
#[test]
fn not_applied_required_for_generated_phase() {
let data = ResultData::new(Phase::Generated, Effect::NotApplied);
assert!(data.validate().is_ok());
let data = ResultData::new(Phase::Generated, Effect::Changed);
assert!(matches!(
data.validate(),
Err(ResultDataError::NotAppliedRequired { .. })
));
}
#[test]
fn not_applied_required_for_validated_phase() {
let data = ResultData::new(Phase::Validated, Effect::NotApplied);
assert!(data.validate().is_ok());
let data = ResultData::new(Phase::Validated, Effect::Changed);
assert!(data.validate().is_err());
}
#[test]
fn committed_phase_may_carry_changed_or_unchanged() {
for effect in [Effect::Changed, Effect::Unchanged] {
let data = ResultData::new(Phase::Committed, effect);
assert!(data.validate().is_ok());
}
}
#[test]
fn committed_phase_with_not_applied_is_rejected() {
let data = ResultData::new(Phase::Committed, Effect::NotApplied);
assert_eq!(
data.validate(),
Err(ResultDataError::EffectRequired {
phase: Phase::Committed,
effect: Effect::NotApplied,
})
);
}
#[test]
fn predicted_effect_requires_validated_phase() {
let mut data = ResultData::new(Phase::Committed, Effect::Changed);
data.set_predicted(PredictedEffect::Unchanged);
assert!(matches!(
data.validate(),
Err(ResultDataError::PredictedWithoutValidation { .. })
));
let mut data = ResultData::new(Phase::Validated, Effect::NotApplied);
data.set_predicted(PredictedEffect::Changed);
assert!(data.validate().is_ok());
}
#[test]
fn exit_status_for_ok_is_success() {
assert_eq!(exit_status_for(Status::Ok, None), ExitStatus::SUCCESS);
}
#[test]
fn exit_status_for_refused_with_no_code_is_refused() {
let err = Error::new("UNKNOWN");
assert_eq!(
exit_status_for(Status::Refused, Some(&err)),
ExitStatus::REFUSED
);
}
#[test]
fn error_status_for_unclassified_code_is_input_failure() {
let err = Error::new("INVALID_PLAN");
assert_eq!(
exit_status_for(Status::Error, Some(&err)),
ExitStatus::INPUT_FAILURE
);
}
#[test]
fn dedicated_exit_codes_win_over_the_status_fallback() {
assert_eq!(
exit_status_for(Status::Refused, Some(&Error::new("USAGE"))),
ExitStatus::USAGE
);
assert_eq!(
exit_status_for(Status::Error, Some(&Error::new("CHECK_THRESHOLD_EXCEEDED"))),
ExitStatus::CHECK_FINDINGS
);
}
#[test]
fn status_serializes_as_lowercase_string() {
let envelope = Envelope::refused(
"edit apply",
Source::new(&fixture()),
Error::new("STALE_SOURCE"),
);
let value: serde_json::Value = serde_json::to_value(&envelope).unwrap();
assert_eq!(value["status"], "refused");
}
#[test]
fn artifact_sha256_matches_source_sha256_helper() {
let payload = b"a payload";
let artifact = Artifact::new("/p", MediaRole::Document, "x", payload);
assert_eq!(artifact.sha256, source_sha256(payload));
}
#[test]
fn jsonl_round_trip_preserves_terminal_record() {
let mut data = ResultData::new(Phase::Validated, Effect::NotApplied);
data.counts.requested_operations = 1;
data.set_predicted(PredictedEffect::Unchanged);
let terminal = Envelope::ok(
"edit apply",
Source::new(&fixture()),
data,
Runtime::native(),
)
.expect("valid result data");
let stream = write_jsonl_stream(&[], &terminal);
let parsed = read_jsonl_stream(&stream).expect("round-trip parses");
assert!(matches!(
parsed.terminal.data.unwrap().phase,
Some(Phase::Validated)
));
assert_eq!(parsed.events.len(), 0);
}
}