1use std::collections::BTreeMap;
30
31use serde::{Deserialize, Serialize};
32
33use crate::inspect::source_sha256;
34
35pub(crate) const ENVELOPE_SCHEMA_VERSION: u32 = 1;
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
46#[serde(rename_all = "lowercase")]
47pub enum Status {
48 Ok,
50 Refused,
54 Error,
57}
58
59#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
61#[serde(rename_all = "lowercase")]
62pub enum Phase {
63 Inspected,
65 Generated,
68 Validated,
70 Committed,
72}
73
74#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80pub enum Effect {
81 Changed,
83 Unchanged,
85 NotApplied,
87}
88
89#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
92#[serde(rename_all = "snake_case")]
93pub enum PredictedEffect {
94 Changed,
96 Unchanged,
98}
99
100pub mod codes {
103 pub const NO_CHANGES_REQUESTED: &str = "NO_CHANGES_REQUESTED";
105 pub const POSTCONDITION_FAILED: &str = "POSTCONDITION_FAILED";
107 pub const WORKING_BASE_CHANGED: &str = "WORKING_BASE_CHANGED";
109 pub const AMBIGUOUS_ANCHOR: &str = "AMBIGUOUS_ANCHOR";
111 pub const STALE_SOURCE: &str = "STALE_SOURCE";
113 pub const UNSUPPORTED_OPERATION: &str = "UNSUPPORTED_OPERATION";
115 pub const INVALID_PLAN: &str = "INVALID_PLAN";
117 pub const RENDER_FIDELITY_FAILED: &str = "RENDER_FIDELITY_FAILED";
119 pub const RENDERING_FAILED: &str = "RENDERING_FAILED";
121 pub const DEADLINE_EXCEEDED: &str = "DEADLINE_EXCEEDED";
123 pub const USAGE: &str = "USAGE";
125 pub const CHECK_THRESHOLD_EXCEEDED: &str = "CHECK_THRESHOLD_EXCEEDED";
127 pub const COMPARISON_DIFFERENCE: &str = "COMPARISON_DIFFERENCE";
129}
130
131#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
133#[serde(rename_all = "snake_case")]
134pub enum CommitState {
135 Committed,
137 NotCommitted,
139 Unknown,
141}
142
143#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
145#[serde(rename_all = "lowercase")]
146pub enum MediaRole {
147 Document,
149 Plan,
151 Patch,
153 Report,
155 Render,
157 Other,
159}
160
161#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
168pub struct Artifact {
169 pub path: String,
171 pub media_role: MediaRole,
173 pub media_type: String,
175 pub sha256: String,
177 pub byte_size: u64,
179 pub committed: bool,
181}
182
183impl Artifact {
184 pub fn new(
187 path: impl Into<String>,
188 role: MediaRole,
189 media_type: impl Into<String>,
190 payload: &[u8],
191 ) -> Self {
192 Self {
193 path: path.into(),
194 media_role: role,
195 media_type: media_type.into(),
196 sha256: source_sha256(payload),
197 byte_size: payload.len() as u64,
198 committed: false,
199 }
200 }
201
202 pub fn committed(
204 path: impl Into<String>,
205 role: MediaRole,
206 media_type: impl Into<String>,
207 payload: &[u8],
208 ) -> Self {
209 let mut artifact = Self::new(path, role, media_type, payload);
210 artifact.committed = true;
211 artifact
212 }
213
214 #[must_use]
216 pub fn with_committed(mut self, committed: bool) -> Self {
217 self.committed = committed;
218 self
219 }
220}
221
222#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
225pub struct Context {
226 pub before: String,
228 pub matched: String,
230 pub after: String,
232 pub truncated: bool,
235}
236
237impl Context {
238 pub fn new(
241 before: impl Into<String>,
242 matched: impl Into<String>,
243 after: impl Into<String>,
244 ) -> Self {
245 Self {
246 before: before.into(),
247 matched: matched.into(),
248 after: after.into(),
249 truncated: false,
250 }
251 }
252
253 #[must_use]
255 pub fn with_truncated(mut self, truncated: bool) -> Self {
256 self.truncated = truncated;
257 self
258 }
259}
260
261#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
264pub struct NextAction {
265 pub argv: Vec<String>,
268 #[serde(default, skip_serializing_if = "Option::is_none")]
270 pub prerequisites: Option<Vec<String>>,
271 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub purpose: Option<String>,
274 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
276 pub destructive: bool,
277}
278
279impl NextAction {
280 pub fn new(argv: Vec<String>) -> Self {
282 Self {
283 argv,
284 prerequisites: None,
285 purpose: None,
286 destructive: false,
287 }
288 }
289
290 #[must_use]
292 pub fn with_destructive(mut self) -> Self {
293 self.destructive = true;
294 self
295 }
296
297 #[must_use]
299 pub fn with_purpose(mut self, purpose: impl Into<String>) -> Self {
300 self.purpose = Some(purpose.into());
301 self
302 }
303
304 #[must_use]
306 pub fn with_prerequisites(mut self, prerequisites: Vec<String>) -> Self {
307 self.prerequisites = Some(prerequisites);
308 self
309 }
310}
311
312#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
314pub struct Error {
315 pub code: String,
317 #[serde(default, skip_serializing_if = "Option::is_none")]
319 pub operation: Option<String>,
320 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub source_digest: Option<String>,
323 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub target: Option<String>,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub matches: Option<usize>,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub context: Option<Context>,
332 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub near: Option<crate::edit::NearMatches>,
335 pub message: String,
337 #[serde(default, skip_serializing_if = "Vec::is_empty")]
339 pub next_actions: Vec<NextAction>,
340 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub retryable: Option<bool>,
345 pub commit_state: CommitState,
347 #[serde(default, skip_serializing_if = "Option::is_none")]
352 pub expectations: Option<crate::expect::ExpectationReport>,
353}
354
355impl Error {
356 #[must_use]
358 pub fn with_commit_state(mut self, state: CommitState) -> Self {
359 self.commit_state = state;
360 self.normalize_retryable();
361 self
362 }
363
364 fn normalize_retryable(&mut self) {
365 if self.commit_state == CommitState::Unknown && self.retryable == Some(true) {
366 self.retryable = Some(false);
367 }
368 }
369
370 pub fn new(code: impl Into<String>) -> Self {
372 Self {
373 code: code.into(),
374 operation: None,
375 source_digest: None,
376 target: None,
377 matches: None,
378 context: None,
379 near: None,
380 message: String::new(),
381 next_actions: Vec::new(),
382 retryable: None,
383 commit_state: CommitState::Unknown,
384 expectations: None,
385 }
386 }
387
388 #[must_use]
390 pub fn with_message(mut self, message: impl Into<String>) -> Self {
391 self.message = message.into();
392 self
393 }
394
395 #[must_use]
397 pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
398 self.operation = Some(operation.into());
399 self
400 }
401
402 #[must_use]
404 pub fn with_source(mut self, source: Source) -> Self {
405 self.source_digest = Some(source.sha256);
406 self
407 }
408
409 #[must_use]
411 pub fn with_source_digest(mut self, digest: impl Into<String>) -> Self {
412 self.source_digest = Some(digest.into());
413 self
414 }
415
416 #[must_use]
418 pub fn with_target(mut self, target: impl Into<String>) -> Self {
419 self.target = Some(target.into());
420 self
421 }
422
423 #[must_use]
425 pub fn with_matches(mut self, matches: usize) -> Self {
426 self.matches = Some(matches);
427 self
428 }
429
430 #[must_use]
432 pub fn with_context(mut self, context: Context) -> Self {
433 self.context = Some(context);
434 self
435 }
436
437 pub fn set_context(&mut self, context: Context) {
440 self.context = Some(context);
441 }
442
443 pub fn push_next_action(&mut self, action: NextAction) {
445 self.next_actions.push(action);
446 }
447
448 #[must_use]
450 pub fn with_retryable(mut self, retryable: bool) -> Self {
451 self.retryable = Some(retryable);
452 self.normalize_retryable();
453 self
454 }
455}
456
457#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
460pub struct Source {
461 pub sha256: String,
463 #[serde(default, skip_serializing_if = "Option::is_none")]
465 pub path: Option<String>,
466 #[serde(default, skip_serializing_if = "Option::is_none")]
468 pub byte_size: Option<u64>,
469}
470
471impl Source {
472 pub fn new(bytes: &[u8]) -> Self {
475 Self {
476 sha256: source_sha256(bytes),
477 path: None,
478 byte_size: Some(bytes.len() as u64),
479 }
480 }
481
482 pub fn from_digest(digest: impl Into<String>) -> Self {
484 Self {
485 sha256: digest.into(),
486 path: None,
487 byte_size: None,
488 }
489 }
490
491 #[must_use]
493 pub fn with_path(mut self, path: impl Into<String>) -> Self {
494 self.path = Some(path.into());
495 self
496 }
497}
498
499#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
501pub struct Runtime {
502 pub name: String,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub build: Option<String>,
507}
508
509impl Runtime {
510 pub fn native() -> Self {
512 Self {
513 name: "native".to_string(),
514 build: None,
515 }
516 }
517}
518
519#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
522pub struct Verification {
523 pub operation_postconditions: String,
525 pub integrity: String,
527 pub expectations: String,
529 pub task_semantics: String,
531 #[serde(default, skip_serializing_if = "Option::is_none")]
533 pub baseline_findings: Option<Vec<crate::validate::Finding>>,
534 #[serde(default, skip_serializing_if = "Option::is_none")]
536 pub introduced_findings: Option<Vec<crate::validate::Finding>>,
537 #[serde(default, skip_serializing_if = "Option::is_none")]
539 pub unresolved_findings: Option<Vec<crate::validate::Finding>>,
540}
541
542impl Default for Verification {
543 fn default() -> Self {
544 Self {
545 operation_postconditions: "skipped".to_string(),
546 integrity: "skipped".to_string(),
547 expectations: "not_requested".to_string(),
548 task_semantics: "not_assessed".to_string(),
549 baseline_findings: None,
550 introduced_findings: None,
551 unresolved_findings: None,
552 }
553 }
554}
555
556#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
563pub struct Counts {
564 #[serde(default, skip_serializing_if = "is_zero")]
567 pub requested_operations: usize,
568 #[serde(default, skip_serializing_if = "is_zero")]
571 pub unchanged_operations: usize,
572 #[serde(default, skip_serializing_if = "is_zero")]
574 pub body_operations_applied: usize,
575 #[serde(default, skip_serializing_if = "is_zero")]
577 pub review_operations_applied: usize,
578
579 #[serde(default, skip_serializing_if = "is_zero")]
582 pub revisions_accepted: usize,
583 #[serde(default, skip_serializing_if = "is_zero")]
585 pub revisions_rejected: usize,
586 #[serde(default, skip_serializing_if = "is_zero")]
589 pub logical_revisions: usize,
590 #[serde(default, skip_serializing_if = "is_zero")]
592 pub revision_xml_entries: usize,
593
594 #[serde(default, skip_serializing_if = "is_zero")]
597 pub comment_threads: usize,
598 #[serde(default, skip_serializing_if = "is_zero")]
600 pub comment_replies: usize,
601 #[serde(default, skip_serializing_if = "is_zero")]
604 pub comments_added: usize,
605}
606
607impl Counts {
608 #[must_use]
612 pub fn total_operations(&self) -> usize {
613 self.body_operations_applied + self.review_operations_applied
614 }
615}
616
617fn is_zero(value: &usize) -> bool {
618 *value == 0
619}
620
621#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
624pub struct ResultData {
625 pub phase: Option<Phase>,
627 pub effect: Effect,
629 #[serde(default, skip_serializing_if = "Option::is_none")]
631 pub predicted_effect: Option<PredictedEffect>,
632 pub counts: Counts,
634 #[serde(default, skip_serializing_if = "Vec::is_empty")]
636 pub removed_comments: Vec<crate::edit::RemovedComment>,
637 #[serde(default, skip_serializing_if = "Vec::is_empty")]
639 pub kept_comments: Vec<crate::edit::KeptComment>,
640 pub verification: Verification,
642 #[serde(default, skip_serializing_if = "Option::is_none")]
644 pub generation: Option<serde_json::Value>,
645 #[serde(default, skip_serializing_if = "Option::is_none")]
650 pub expectations: Option<crate::expect::ExpectationReport>,
651}
652
653#[derive(Clone, Debug, Eq, PartialEq)]
655pub enum ResultDataError {
656 MissingPhase,
658 FailureRequired,
660 NotAppliedRequired {
662 phase: Phase,
664 effect: Effect,
666 },
667 EffectRequired {
671 phase: Phase,
673 effect: Effect,
675 },
676 PredictedWithoutValidation {
678 phase: Phase,
680 },
681}
682
683impl std::fmt::Display for ResultDataError {
684 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
685 match self {
686 Self::MissingPhase => write!(f, "a completed phase is required"),
687 Self::FailureRequired => write!(f, "failure data requires a refused or error status"),
688 Self::NotAppliedRequired { phase, effect } => write!(
689 f,
690 "phase {phase:?} requires effect NotApplied, got {effect:?}"
691 ),
692 Self::EffectRequired { phase, effect } => write!(
693 f,
694 "phase {phase:?} requires effect Changed or Unchanged, got {effect:?}"
695 ),
696 Self::PredictedWithoutValidation { phase } => write!(
697 f,
698 "predicted_effect is only valid with phase Validated, got {phase:?}"
699 ),
700 }
701 }
702}
703
704impl std::error::Error for ResultDataError {}
705
706impl ResultData {
707 pub fn failure(phase: Option<Phase>) -> Self {
709 Self {
710 phase,
711 effect: Effect::NotApplied,
712 predicted_effect: None,
713 counts: Counts::default(),
714 removed_comments: Vec::new(),
715 kept_comments: Vec::new(),
716 verification: Verification::default(),
717 generation: None,
718 expectations: None,
719 }
720 }
721
722 pub fn new(phase: Phase, effect: Effect) -> Self {
728 Self {
729 phase: Some(phase),
730 effect,
731 predicted_effect: None,
732 counts: Counts::default(),
733 removed_comments: Vec::new(),
734 kept_comments: Vec::new(),
735 verification: Verification::default(),
736 generation: None,
737 expectations: None,
738 }
739 }
740
741 pub fn set_predicted(&mut self, predicted: PredictedEffect) {
744 self.predicted_effect = Some(predicted);
745 }
746
747 pub fn validate(&self) -> Result<(), ResultDataError> {
750 match self.phase {
751 Some(phase) => {
752 if phase == Phase::Committed {
753 if self.effect == Effect::NotApplied {
756 return Err(ResultDataError::EffectRequired {
757 phase,
758 effect: self.effect,
759 });
760 }
761 } else if self.effect != Effect::NotApplied {
762 return Err(ResultDataError::NotAppliedRequired {
763 phase,
764 effect: self.effect,
765 });
766 }
767 if self.predicted_effect.is_some() && phase != Phase::Validated {
768 return Err(ResultDataError::PredictedWithoutValidation { phase });
769 }
770 }
771 None if self.effect != Effect::NotApplied || self.predicted_effect.is_some() => {
772 return Err(ResultDataError::MissingPhase);
773 }
774 None => {}
775 }
776 Ok(())
777 }
778}
779
780#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
792pub struct Envelope {
793 pub schema_version: u32,
795 pub command: String,
797 pub engine_version: String,
799 pub runtime: Runtime,
801 pub status: Status,
803 pub source: Source,
805 #[serde(default, skip_serializing_if = "Option::is_none")]
808 pub data: Option<ResultData>,
809 #[serde(default, skip_serializing_if = "Vec::is_empty")]
811 pub artifacts: Vec<Artifact>,
812 #[serde(default, skip_serializing_if = "Vec::is_empty")]
814 pub warnings: Vec<String>,
815 #[serde(default, skip_serializing_if = "Option::is_none")]
817 pub error: Option<Error>,
818 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
820 pub effective_options: BTreeMap<String, serde_json::Value>,
821 #[serde(default, skip_serializing_if = "Option::is_none")]
824 pub continuation: Option<serde_json::Value>,
825}
826
827impl Envelope {
828 pub fn with_failure_data(mut self, data: ResultData) -> Result<Self, ResultDataError> {
832 if self.status == Status::Ok {
833 return Err(ResultDataError::FailureRequired);
834 }
835 data.validate()?;
836 if self.status == Status::Refused && data.phase == Some(Phase::Committed) {
838 return Err(ResultDataError::FailureRequired);
839 }
840 if let Some(error) = &mut self.error {
841 if data.phase == Some(Phase::Committed) {
842 error.commit_state = CommitState::Committed;
843 }
844 error.normalize_retryable();
845 }
846 self.data = Some(data);
847 Ok(self)
848 }
849
850 pub fn new(command: impl Into<String>, source: Source, runtime: Runtime) -> Self {
855 Self {
856 schema_version: ENVELOPE_SCHEMA_VERSION,
857 command: command.into(),
858 engine_version: env!("CARGO_PKG_VERSION").to_string(),
859 runtime,
860 status: Status::Ok,
861 source,
862 data: None,
863 artifacts: Vec::new(),
864 warnings: Vec::new(),
865 error: None,
866 effective_options: BTreeMap::new(),
867 continuation: None,
868 }
869 }
870
871 pub fn ok(
878 command: impl Into<String>,
879 source: Source,
880 data: ResultData,
881 runtime: Runtime,
882 ) -> Result<Self, ResultDataError> {
883 data.validate()?;
884 if data.phase.is_none() {
885 return Err(ResultDataError::MissingPhase);
886 }
887 Ok(Self {
888 schema_version: ENVELOPE_SCHEMA_VERSION,
889 command: command.into(),
890 engine_version: env!("CARGO_PKG_VERSION").to_string(),
891 runtime,
892 status: Status::Ok,
893 source,
894 data: Some(data),
895 artifacts: Vec::new(),
896 warnings: Vec::new(),
897 error: None,
898 effective_options: BTreeMap::new(),
899 continuation: None,
900 })
901 }
902
903 pub fn refused(command: impl Into<String>, source: Source, error: Error) -> Self {
907 let error = error.with_commit_state(CommitState::NotCommitted);
908 Self {
909 schema_version: ENVELOPE_SCHEMA_VERSION,
910 command: command.into(),
911 engine_version: env!("CARGO_PKG_VERSION").to_string(),
912 runtime: Runtime::native(),
913 status: Status::Refused,
914 source,
915 data: Some(ResultData::failure(None)),
916 artifacts: Vec::new(),
917 warnings: Vec::new(),
918 error: Some(error),
919 effective_options: BTreeMap::new(),
920 continuation: None,
921 }
922 }
923
924 pub fn new_error(command: impl Into<String>, source: Source, mut error: Error) -> Self {
928 error.normalize_retryable();
929 Self {
930 schema_version: ENVELOPE_SCHEMA_VERSION,
931 command: command.into(),
932 engine_version: env!("CARGO_PKG_VERSION").to_string(),
933 runtime: Runtime::native(),
934 status: Status::Error,
935 source,
936 data: Some(ResultData::failure(None)),
937 artifacts: Vec::new(),
938 warnings: Vec::new(),
939 error: Some(error),
940 effective_options: BTreeMap::new(),
941 continuation: None,
942 }
943 }
944
945 pub fn push_artifact(&mut self, artifact: Artifact) {
947 self.artifacts.push(artifact);
948 }
949
950 pub fn push_warning(&mut self, warning: impl Into<String>) {
952 self.warnings.push(warning.into());
953 }
954
955 pub fn set_effective_option(&mut self, key: impl Into<String>, value: serde_json::Value) {
957 self.effective_options.insert(key.into(), value);
958 }
959}
960
961#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
964#[serde(tag = "record", rename = "header")]
965pub struct StreamHeader {
966 pub schema_version: u32,
968 pub command: String,
970 pub engine_version: String,
972 pub source: Source,
974}
975
976impl From<&Envelope> for StreamHeader {
977 fn from(envelope: &Envelope) -> Self {
978 Self {
979 schema_version: envelope.schema_version,
980 command: envelope.command.clone(),
981 engine_version: envelope.engine_version.clone(),
982 source: envelope.source.clone(),
983 }
984 }
985}
986
987#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
993#[serde(transparent)]
994pub struct ProgressEvent {
995 value: serde_json::Value,
997}
998
999impl ProgressEvent {
1000 pub fn new(value: serde_json::Value) -> Self {
1002 Self { value }
1003 }
1004
1005 pub fn value(&self) -> &serde_json::Value {
1007 &self.value
1008 }
1009}
1010
1011impl From<serde_json::Value> for ProgressEvent {
1012 fn from(value: serde_json::Value) -> Self {
1013 Self::new(value)
1014 }
1015}
1016
1017impl From<ProgressEvent> for serde_json::Value {
1018 fn from(event: ProgressEvent) -> Self {
1019 event.value
1020 }
1021}
1022
1023pub fn jsonl_terminal_line(terminal: &Envelope) -> String {
1025 serde_json::to_string(terminal).expect("Envelope serializes")
1026}
1027
1028pub fn write_jsonl_stream(events: &[ProgressEvent], terminal: &Envelope) -> String {
1031 let mut out =
1032 serde_json::to_string(&StreamHeader::from(terminal)).expect("StreamHeader serializes");
1033 out.push('\n');
1034 for event in events {
1035 out.push_str(&serde_json::to_string(event.value()).expect("progress serializes"));
1036 out.push('\n');
1037 }
1038 out.push_str(&jsonl_terminal_line(terminal));
1039 out.push('\n');
1040 out
1041}
1042
1043#[derive(Clone, Debug, Eq, PartialEq)]
1045pub struct ParsedStream {
1046 pub header: StreamHeader,
1048 pub events: Vec<ProgressEvent>,
1050 pub terminal: Envelope,
1052}
1053
1054#[derive(Clone, Debug, Eq, PartialEq)]
1056pub enum StreamError {
1057 MissingHeader,
1059 HeaderParse {
1061 line: usize,
1063 message: String,
1065 },
1066 InvalidLine {
1068 line: usize,
1070 content: String,
1072 },
1073 MissingTerminal,
1075 MultipleTerminals,
1077 TerminalParse {
1079 line: usize,
1081 message: String,
1083 },
1084}
1085
1086impl std::fmt::Display for StreamError {
1087 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1088 match self {
1089 Self::MissingHeader => write!(f, "stream has no initial header record"),
1090 Self::HeaderParse { line, message } => {
1091 write!(f, "line {line}: header record parse error: {message}")
1092 }
1093 Self::InvalidLine { line, content } => {
1094 write!(f, "line {line}: invalid JSONL line: {content}")
1095 }
1096 Self::MissingTerminal => write!(f, "stream has no terminal result line"),
1097 Self::MultipleTerminals => write!(f, "stream carries more than one terminal result"),
1098 Self::TerminalParse { line, message } => {
1099 write!(f, "line {line}: terminal record parse error: {message}")
1100 }
1101 }
1102 }
1103}
1104
1105impl std::error::Error for StreamError {}
1106
1107pub fn read_jsonl_stream(input: &str) -> std::result::Result<ParsedStream, StreamError> {
1115 let mut header: Option<StreamHeader> = None;
1116 let mut events: Vec<ProgressEvent> = Vec::new();
1117 let mut terminal: Option<Envelope> = None;
1118 for (index, raw) in input.lines().enumerate() {
1119 let line = index + 1;
1120 let trimmed = raw.trim();
1121 if trimmed.is_empty() {
1122 continue;
1123 }
1124 let value: serde_json::Value =
1125 serde_json::from_str(trimmed).map_err(|_| StreamError::InvalidLine {
1126 line,
1127 content: trimmed.to_string(),
1128 })?;
1129 if header.is_none() {
1130 if value.get("record").and_then(serde_json::Value::as_str) != Some("header") {
1131 return Err(StreamError::MissingHeader);
1132 }
1133 header = Some(
1134 serde_json::from_value(value).map_err(|e| StreamError::HeaderParse {
1135 line,
1136 message: e.to_string(),
1137 })?,
1138 );
1139 continue;
1140 }
1141 if value.get("record").and_then(serde_json::Value::as_str) == Some("header") {
1142 return Err(StreamError::InvalidLine {
1143 line,
1144 content: trimmed.to_string(),
1145 });
1146 }
1147 if value.get("status").is_some() && value.get("ev").is_none() {
1148 let record: Envelope =
1149 serde_json::from_value(value).map_err(|e| StreamError::TerminalParse {
1150 line,
1151 message: e.to_string(),
1152 })?;
1153 if terminal.is_some() {
1154 return Err(StreamError::MultipleTerminals);
1155 }
1156 terminal = Some(record);
1157 } else {
1158 if terminal.is_some() {
1159 return Err(StreamError::InvalidLine {
1160 line,
1161 content: trimmed.to_string(),
1162 });
1163 }
1164 if value
1165 .get("ev")
1166 .and_then(serde_json::Value::as_str)
1167 .is_none()
1168 {
1169 return Err(StreamError::InvalidLine {
1170 line,
1171 content: trimmed.to_string(),
1172 });
1173 }
1174 events.push(ProgressEvent::new(value));
1175 }
1176 }
1177 let header = header.ok_or(StreamError::MissingHeader)?;
1178 terminal
1179 .map(|terminal| ParsedStream {
1180 header,
1181 events,
1182 terminal,
1183 })
1184 .ok_or(StreamError::MissingTerminal)
1185}
1186
1187#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1189pub struct ExitStatus(pub u8);
1190
1191impl ExitStatus {
1192 pub const SUCCESS: Self = Self(0);
1194 pub const INPUT_FAILURE: Self = Self(1);
1196 pub const CHECK_FINDINGS: Self = Self(2);
1198 pub const REFUSED: Self = Self(3);
1201 pub const RENDER_FAILURE: Self = Self(4);
1203 pub const COMPARISON_DIFFERENCE: Self = Self(5);
1205 pub const USAGE: Self = Self(64);
1207 pub const DEADLINE_EXCEEDED: Self = Self(124);
1209}
1210
1211impl From<ExitStatus> for u8 {
1212 fn from(value: ExitStatus) -> Self {
1213 value.0
1214 }
1215}
1216
1217pub fn exit_status_for(status: Status, error: Option<&Error>) -> ExitStatus {
1227 if let Some(code) = error.map(|e| e.code.as_str()) {
1228 match code {
1229 codes::CHECK_THRESHOLD_EXCEEDED => return ExitStatus::CHECK_FINDINGS,
1230 codes::COMPARISON_DIFFERENCE => return ExitStatus::COMPARISON_DIFFERENCE,
1231 codes::RENDER_FIDELITY_FAILED => return ExitStatus::RENDER_FAILURE,
1232 codes::USAGE => return ExitStatus::USAGE,
1233 codes::DEADLINE_EXCEEDED => return ExitStatus::DEADLINE_EXCEEDED,
1234 _ => {}
1235 }
1236 }
1237 match status {
1238 Status::Ok => ExitStatus::SUCCESS,
1239 Status::Refused => ExitStatus::REFUSED,
1240 Status::Error => ExitStatus::INPUT_FAILURE,
1241 }
1242}
1243
1244pub fn exit_status_for_envelope(envelope: &Envelope) -> ExitStatus {
1246 exit_status_for(envelope.status, envelope.error.as_ref())
1247}
1248#[cfg(test)]
1249mod tests {
1250 use super::*;
1255
1256 fn fixture() -> Vec<u8> {
1257 b"fixture-bytes".to_vec()
1258 }
1259
1260 #[test]
1261 fn not_applied_required_for_generated_phase() {
1262 let data = ResultData::new(Phase::Generated, Effect::NotApplied);
1263 assert!(data.validate().is_ok());
1264 let data = ResultData::new(Phase::Generated, Effect::Changed);
1265 assert!(matches!(
1266 data.validate(),
1267 Err(ResultDataError::NotAppliedRequired { .. })
1268 ));
1269 }
1270
1271 #[test]
1272 fn not_applied_required_for_validated_phase() {
1273 let data = ResultData::new(Phase::Validated, Effect::NotApplied);
1274 assert!(data.validate().is_ok());
1275 let data = ResultData::new(Phase::Validated, Effect::Changed);
1276 assert!(data.validate().is_err());
1277 }
1278
1279 #[test]
1280 fn committed_phase_may_carry_changed_or_unchanged() {
1281 for effect in [Effect::Changed, Effect::Unchanged] {
1282 let data = ResultData::new(Phase::Committed, effect);
1283 assert!(data.validate().is_ok());
1284 }
1285 }
1286
1287 #[test]
1288 fn committed_phase_with_not_applied_is_rejected() {
1289 let data = ResultData::new(Phase::Committed, Effect::NotApplied);
1292 assert_eq!(
1293 data.validate(),
1294 Err(ResultDataError::EffectRequired {
1295 phase: Phase::Committed,
1296 effect: Effect::NotApplied,
1297 })
1298 );
1299 }
1300
1301 #[test]
1302 fn predicted_effect_requires_validated_phase() {
1303 let mut data = ResultData::new(Phase::Committed, Effect::Changed);
1304 data.set_predicted(PredictedEffect::Unchanged);
1305 assert!(matches!(
1306 data.validate(),
1307 Err(ResultDataError::PredictedWithoutValidation { .. })
1308 ));
1309 let mut data = ResultData::new(Phase::Validated, Effect::NotApplied);
1310 data.set_predicted(PredictedEffect::Changed);
1311 assert!(data.validate().is_ok());
1312 }
1313
1314 #[test]
1315 fn exit_status_for_ok_is_success() {
1316 assert_eq!(exit_status_for(Status::Ok, None), ExitStatus::SUCCESS);
1317 }
1318
1319 #[test]
1320 fn exit_status_for_refused_with_no_code_is_refused() {
1321 let err = Error::new("UNKNOWN");
1323 assert_eq!(
1324 exit_status_for(Status::Refused, Some(&err)),
1325 ExitStatus::REFUSED
1326 );
1327 }
1328
1329 #[test]
1330 fn error_status_for_unclassified_code_is_input_failure() {
1331 let err = Error::new("INVALID_PLAN");
1332 assert_eq!(
1333 exit_status_for(Status::Error, Some(&err)),
1334 ExitStatus::INPUT_FAILURE
1335 );
1336 }
1337
1338 #[test]
1339 fn dedicated_exit_codes_win_over_the_status_fallback() {
1340 assert_eq!(
1344 exit_status_for(Status::Refused, Some(&Error::new("USAGE"))),
1345 ExitStatus::USAGE
1346 );
1347 assert_eq!(
1348 exit_status_for(Status::Error, Some(&Error::new("CHECK_THRESHOLD_EXCEEDED"))),
1349 ExitStatus::CHECK_FINDINGS
1350 );
1351 }
1352
1353 #[test]
1354 fn status_serializes_as_lowercase_string() {
1355 let envelope = Envelope::refused(
1356 "edit apply",
1357 Source::new(&fixture()),
1358 Error::new("STALE_SOURCE"),
1359 );
1360 let value: serde_json::Value = serde_json::to_value(&envelope).unwrap();
1361 assert_eq!(value["status"], "refused");
1362 }
1363
1364 #[test]
1365 fn artifact_sha256_matches_source_sha256_helper() {
1366 let payload = b"a payload";
1367 let artifact = Artifact::new("/p", MediaRole::Document, "x", payload);
1368 assert_eq!(artifact.sha256, source_sha256(payload));
1369 }
1370
1371 #[test]
1372 fn jsonl_round_trip_preserves_terminal_record() {
1373 let mut data = ResultData::new(Phase::Validated, Effect::NotApplied);
1374 data.counts.requested_operations = 1;
1375 data.set_predicted(PredictedEffect::Unchanged);
1376 let terminal = Envelope::ok(
1377 "edit apply",
1378 Source::new(&fixture()),
1379 data,
1380 Runtime::native(),
1381 )
1382 .expect("valid result data");
1383 let stream = write_jsonl_stream(&[], &terminal);
1384 let parsed = read_jsonl_stream(&stream).expect("round-trip parses");
1385 assert!(matches!(
1386 parsed.terminal.data.unwrap().phase,
1387 Some(Phase::Validated)
1388 ));
1389 assert_eq!(parsed.events.len(), 0);
1390 }
1391}