Skip to main content

jubarte_edit/
result.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Machine result envelope for the v2 routes (`edit apply`, `edit template`,
6//! `review accept`, and friends).
7//!
8//! The envelope described in `jubarte-cli-proposal-b-revised.md` §11 is one
9//! structure for every outcome: success and failure, with effects, with
10//! artifacts, with terminal records. It is the typed contract that machine
11//! callers (`--json`, `--jsonl`) consume and that the implementations of the
12//! new v2 commands will eventually produce.
13//!
14//! Success requires a phase. Failures carry the last completed phase or
15//! JSON null, with `not_applied` before publication. Post-commit reporting
16//! failures retain the committed phase, actual effect and counts through
17//! [`Envelope::with_failure_data`](crate::result::Envelope::with_failure_data). [`ResultData::validate`](crate::result::ResultData::validate) checks effects
18//! and predictions; [`Envelope::ok`](crate::result::Envelope::ok) also rejects a missing phase. Error
19//! builders never authorize retry when [`CommitState`](crate::result::CommitState) is unknown.
20//!
21//! JSONL starts with a typed [`StreamHeader`](crate::result::StreamHeader) (`"record": "header"`), then
22//! zero or more typed progress records and exactly one terminal [`Envelope`](crate::result::Envelope).
23//! The header carries schema version, command, engine version and source
24//! SHA-256. Readers reject a missing/malformed header and multiple terminals;
25//! a header-bearing stream without its terminal is incomplete. Progress uses
26//! its own `ev` discriminator, so an operation's `status` is not terminal.
27//! Exit status mapping follows proposal §12.
28
29use std::collections::BTreeMap;
30
31use serde::{Deserialize, Serialize};
32
33use crate::inspect::source_sha256;
34
35/// The wire schema version this module emits. Bumped together with any
36/// backwards-incompatible change to the envelope.
37pub(crate) const ENVELOPE_SCHEMA_VERSION: u32 = 1;
38
39/// The terminal status of a v2 result.
40///
41/// The on-the-wire shape is a plain string (`"ok"`, `"refused"`, `"error"`)
42/// so callers can pattern-match on it without descending into a nested
43/// object. The typed error itself lives in the envelope's [`Envelope::error`]
44/// field. All outcomes carry `data`; failures additionally carry `error`.
45#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
46#[serde(rename_all = "lowercase")]
47pub enum Status {
48    /// The command completed; effects and artifacts describe what happened.
49    Ok,
50    /// The command refused the request (`NO_CHANGES_REQUESTED`,
51    /// `AMBIGUOUS_ANCHOR`, `WORKING_BASE_CHANGED`, ...); no primary
52    /// publication.
53    Refused,
54    /// The command could not complete because of an input, operational or
55    /// I/O failure.
56    Error,
57}
58
59/// The stage a result reports.
60#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
61#[serde(rename_all = "lowercase")]
62pub enum Phase {
63    /// Read-only inspection (no edit, no plan, no commit).
64    Inspected,
65    /// A plan artifact was generated and (optionally) saved; the document
66    /// effect is always `not_applied`.
67    Generated,
68    /// A dry-run was validated; nothing was written.
69    Validated,
70    /// A primary publication occurred.
71    Committed,
72}
73
74/// The primary document effect a result reports.
75///
76/// A `generated` or `validated` phase always has [`Effect::NotApplied`],
77/// and a `committed` phase never does — see [`ResultData::validate`](crate::result::ResultData::validate).
78#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80pub enum Effect {
81    /// The primary bytes differ from the source.
82    Changed,
83    /// The primary bytes are an exact byte-identical copy of the source.
84    Unchanged,
85    /// The primary document was not published (generation or dry run).
86    NotApplied,
87}
88
89/// The predicted primary effect of a dry run. Only valid with
90/// [`Phase::Validated`].
91#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
92#[serde(rename_all = "snake_case")]
93pub enum PredictedEffect {
94    /// The dry run predicts a primary effect.
95    Changed,
96    /// The dry run predicts an unchanged primary.
97    Unchanged,
98}
99
100/// Stable error codes the proposal names explicitly. Implementations are
101/// free to use any string; these are the well-known ones.
102pub mod codes {
103    /// `--require-change` requested but the primary effect was zero.
104    pub const NO_CHANGES_REQUESTED: &str = "NO_CHANGES_REQUESTED";
105    /// A required postcondition did not hold after preparation.
106    pub const POSTCONDITION_FAILED: &str = "POSTCONDITION_FAILED";
107    /// The supplied `before_sha256` no longer matches the working baseline.
108    pub const WORKING_BASE_CHANGED: &str = "WORKING_BASE_CHANGED";
109    /// A literal anchor matched more than once without an `--occurrence`.
110    pub const AMBIGUOUS_ANCHOR: &str = "AMBIGUOUS_ANCHOR";
111    /// The source bound to the plan no longer matches the bytes on disk.
112    pub const STALE_SOURCE: &str = "STALE_SOURCE";
113    /// The plan named an operation kind the runtime does not support.
114    pub const UNSUPPORTED_OPERATION: &str = "UNSUPPORTED_OPERATION";
115    /// The JSON plan could not be parsed or validated.
116    pub const INVALID_PLAN: &str = "INVALID_PLAN";
117    /// A requested rendering/fidelity policy failed before publication.
118    pub const RENDER_FIDELITY_FAILED: &str = "RENDER_FIDELITY_FAILED";
119    /// A general rendering failure that is not fidelity-related.
120    pub const RENDERING_FAILED: &str = "RENDERING_FAILED";
121    /// A configured deadline elapsed before commit.
122    pub const DEADLINE_EXCEEDED: &str = "DEADLINE_EXCEEDED";
123    /// Invalid CLI usage or malformed request/schema.
124    pub const USAGE: &str = "USAGE";
125    /// Standalone check/validation findings meet the requested threshold.
126    pub const CHECK_THRESHOLD_EXCEEDED: &str = "CHECK_THRESHOLD_EXCEEDED";
127    /// Comparison differences when `--exit-code` was requested.
128    pub const COMPARISON_DIFFERENCE: &str = "COMPARISON_DIFFERENCE";
129}
130
131/// Publication state known when an error was reported.
132#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
133#[serde(rename_all = "snake_case")]
134pub enum CommitState {
135    /// Primary publication completed.
136    Committed,
137    /// Primary publication did not occur.
138    NotCommitted,
139    /// Primary publication cannot be determined.
140    Unknown,
141}
142
143/// The role of an artifact: which contract slot it fills.
144#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
145#[serde(rename_all = "lowercase")]
146pub enum MediaRole {
147    /// The primary `.docx` publication.
148    Document,
149    /// A generated `PlanV2` JSON file.
150    Plan,
151    /// A unified text/diff patch.
152    Patch,
153    /// A structured report (e.g. `report.json`).
154    Report,
155    /// A rendered PDF or PNG page.
156    Render,
157    /// Any other artifact (test scaffolding, asset, ...).
158    Other,
159}
160
161/// A committed or uncommitted artifact recorded in the result.
162///
163/// `committed` is independent of the document effect: a `Plan` artifact can
164/// be committed with a `generated` phase and a `not_applied` effect, while
165/// a `Document` artifact may remain uncommitted when publication is
166/// refused.
167#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
168pub struct Artifact {
169    /// Absolute path of the artifact on the destination filesystem.
170    pub path: String,
171    /// Role of the artifact (`document`, `plan`, ...).
172    pub media_role: MediaRole,
173    /// IANA media type (e.g. `application/pdf`).
174    pub media_type: String,
175    /// SHA-256 of the artifact's bytes, lowercase hex.
176    pub sha256: String,
177    /// Byte length of the artifact.
178    pub byte_size: u64,
179    /// Whether this artifact was actually written to its path.
180    pub committed: bool,
181}
182
183impl Artifact {
184    /// Build an artifact from `payload`; the digest is computed and
185    /// `committed` defaults to `false`.
186    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    /// Build an artifact and mark it committed.
203    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    /// Override `committed`.
215    #[must_use]
216    pub fn with_committed(mut self, committed: bool) -> Self {
217        self.committed = committed;
218        self
219    }
220}
221
222/// Bounded context around a refused match. `truncated` distinguishes
223/// "complete context shown" from "context bounded by length or column".
224#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
225pub struct Context {
226    /// Text before the matched span (bounded).
227    pub before: String,
228    /// The matched span, verbatim.
229    pub matched: String,
230    /// Text after the matched span (bounded).
231    pub after: String,
232    /// `true` when `before`, `matched` or `after` was bounded; the actual
233    /// context continues past the shown window.
234    pub truncated: bool,
235}
236
237impl Context {
238    /// Build a context with `truncated: false`; the caller sets the flag if
239    /// the window was bounded.
240    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    /// Override the truncation flag.
254    #[must_use]
255    pub fn with_truncated(mut self, truncated: bool) -> Self {
256        self.truncated = truncated;
257        self
258    }
259}
260
261/// A structured next action: an `argv` array (never a shell string) with
262/// prerequisites and purpose.
263#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
264pub struct NextAction {
265    /// Argument array as the caller would pass it to `jubarte`. The first
266    /// entry is the program name.
267    pub argv: Vec<String>,
268    /// Optional human-readable prerequisites (e.g. `source file readable`).
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub prerequisites: Option<Vec<String>>,
271    /// Human-readable purpose.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub purpose: Option<String>,
274    /// The action erases another author's markup. Omitted when it does not.
275    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
276    pub destructive: bool,
277}
278
279impl NextAction {
280    /// Build a next action from a structured argv array.
281    pub fn new(argv: Vec<String>) -> Self {
282        Self {
283            argv,
284            prerequisites: None,
285            purpose: None,
286            destructive: false,
287        }
288    }
289
290    /// Mark the action as erasing another author's markup.
291    #[must_use]
292    pub fn with_destructive(mut self) -> Self {
293        self.destructive = true;
294        self
295    }
296
297    /// Set the purpose string.
298    #[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    /// Set the prerequisites list.
305    #[must_use]
306    pub fn with_prerequisites(mut self, prerequisites: Vec<String>) -> Self {
307        self.prerequisites = Some(prerequisites);
308        self
309    }
310}
311
312/// An error block for a refused or failed result.
313#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
314pub struct Error {
315    /// Stable error code (`NO_CHANGES_REQUESTED`, `AMBIGUOUS_ANCHOR`, ...).
316    pub code: String,
317    /// Operation pointer/id (e.g. `op-2`, `/operations/1`).
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub operation: Option<String>,
320    /// SHA-256 of the source the request bound to.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub source_digest: Option<String>,
323    /// Resolved target pointer (paragraph id or similar).
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub target: Option<String>,
326    /// Number of matches found (1 on success, >1 on ambiguity, 0 on miss).
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub matches: Option<usize>,
329    /// Bounded actual context around the failure point.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub context: Option<Context>,
332    /// Whitespace-only diagnostic occurrences. They never authorize selection.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub near: Option<crate::edit::NearMatches>,
335    /// Human-readable detail.
336    pub message: String,
337    /// Structured argv next actions; never shell strings.
338    #[serde(default, skip_serializing_if = "Vec::is_empty")]
339    pub next_actions: Vec<NextAction>,
340    /// `retryable` hint: `Some(true)` when a retry with the same inputs is
341    /// safe, `Some(false)` when it is not, `None` when the classification
342    /// is unknown. Implementations are free to omit it.
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub retryable: Option<bool>,
345    /// Known primary publication state; unknown never authorizes retry.
346    pub commit_state: CommitState,
347    /// The bounded expectation report behind this failure, when the error
348    /// is an expectation verdict (`EXPECTATION_FAILED`, ...). Kept beside
349    /// the error so a refused envelope still discloses which checks ran,
350    /// refused or stayed unassessed.
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub expectations: Option<crate::expect::ExpectationReport>,
353}
354
355impl Error {
356    /// Set the known publication state.
357    #[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    /// Build an error with unknown publication state and no retry hint.
371    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    /// Set the message.
389    #[must_use]
390    pub fn with_message(mut self, message: impl Into<String>) -> Self {
391        self.message = message.into();
392        self
393    }
394
395    /// Set the operation pointer/id.
396    #[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    /// Bind the source digest.
403    #[must_use]
404    pub fn with_source(mut self, source: Source) -> Self {
405        self.source_digest = Some(source.sha256);
406        self
407    }
408
409    /// Override the source digest directly.
410    #[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    /// Set the resolved target pointer.
417    #[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    /// Set the matches count.
424    #[must_use]
425    pub fn with_matches(mut self, matches: usize) -> Self {
426        self.matches = Some(matches);
427        self
428    }
429
430    /// Set the bounded context.
431    #[must_use]
432    pub fn with_context(mut self, context: Context) -> Self {
433        self.context = Some(context);
434        self
435    }
436
437    /// Set the bounded context (in-place variant for chaining after
438    /// mutating other fields).
439    pub fn set_context(&mut self, context: Context) {
440        self.context = Some(context);
441    }
442
443    /// Push a structured argv next action.
444    pub fn push_next_action(&mut self, action: NextAction) {
445        self.next_actions.push(action);
446    }
447
448    /// Set the retryable hint. Unknown publication coerces `true` to `false`.
449    #[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/// A reference to the bound source. Only `sha256` is mandatory in the
458/// envelope; `path` and `byte_size` may appear when they help the caller.
459#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
460pub struct Source {
461    /// SHA-256 of the source bytes (lowercase hex).
462    pub sha256: String,
463    /// Absolute path of the source, when known.
464    #[serde(default, skip_serializing_if = "Option::is_none")]
465    pub path: Option<String>,
466    /// Source byte size.
467    #[serde(default, skip_serializing_if = "Option::is_none")]
468    pub byte_size: Option<u64>,
469}
470
471impl Source {
472    /// Build a `Source` from raw bytes: the digest is computed and the
473    /// byte size recorded; no path is set.
474    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    /// Build a `Source` from a precomputed digest.
483    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    /// Set the path.
492    #[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/// The runtime that produced the result.
500#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
501pub struct Runtime {
502    /// `native`, `python`, `wasm`, ...
503    pub name: String,
504    /// Optional build identity (e.g. a git sha or release tag).
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub build: Option<String>,
507}
508
509impl Runtime {
510    /// The native CLI runtime.
511    pub fn native() -> Self {
512        Self {
513            name: "native".to_string(),
514            build: None,
515        }
516    }
517}
518
519/// Verification block for an `ok` envelope. Mirrors the proposal's
520/// `data.verification`.
521#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
522pub struct Verification {
523    /// `passed`, `failed`, or `skipped` (operation postconditions).
524    pub operation_postconditions: String,
525    /// `passed`, `failed`, or `skipped` (package/revision/comment integrity).
526    pub integrity: String,
527    /// `passed`, `failed`, `not_requested`, or `unresolved` (typed expectations).
528    pub expectations: String,
529    /// `assessed`, `not_assessed`, `unresolved` (natural-language task semantics).
530    pub task_semantics: String,
531    /// Input findings, separately from candidate findings; absent when unassessed.
532    #[serde(default, skip_serializing_if = "Option::is_none")]
533    pub baseline_findings: Option<Vec<crate::validate::Finding>>,
534    /// Findings newly introduced by the edit, including nonblocking leads.
535    #[serde(default, skip_serializing_if = "Option::is_none")]
536    pub introduced_findings: Option<Vec<crate::validate::Finding>>,
537    /// Findings still present in the checked candidates.
538    #[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/// Counts of operations, revisions and comments. The four categories the
557/// proposal names (operations, logical revisions, revision XML entries,
558/// comments) stay distinct in the schema; aggregate counts are deliberately
559/// absent so a reader cannot accidentally conflate them.
560///
561/// Every field is optional in the JSON; unset zero fields are skipped.
562#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
563pub struct Counts {
564    // Operations
565    /// Total operations the request named.
566    #[serde(default, skip_serializing_if = "is_zero")]
567    pub requested_operations: usize,
568    /// Operations whose effect on the body was a no-op (e.g. a rewrite
569    /// row whose `text` matched the verified baseline exactly).
570    #[serde(default, skip_serializing_if = "is_zero")]
571    pub unchanged_operations: usize,
572    /// Body operations that applied a real edit.
573    #[serde(default, skip_serializing_if = "is_zero")]
574    pub body_operations_applied: usize,
575    /// Review operations that applied (accept, reject, comment, ...).
576    #[serde(default, skip_serializing_if = "is_zero")]
577    pub review_operations_applied: usize,
578
579    // Revisions (logical vs. XML entry)
580    /// Existing revisions accepted by the request.
581    #[serde(default, skip_serializing_if = "is_zero")]
582    pub revisions_accepted: usize,
583    /// Existing revisions rejected by the request.
584    #[serde(default, skip_serializing_if = "is_zero")]
585    pub revisions_rejected: usize,
586    /// Logical revision decisions: a move is one logical decision even
587    /// though it spans two XML entries.
588    #[serde(default, skip_serializing_if = "is_zero")]
589    pub logical_revisions: usize,
590    /// Underlying XML `<w:ins>` / `<w:del>` carrier elements.
591    #[serde(default, skip_serializing_if = "is_zero")]
592    pub revision_xml_entries: usize,
593
594    // Comments
595    /// Root comment threads added or modified by the request.
596    #[serde(default, skip_serializing_if = "is_zero")]
597    pub comment_threads: usize,
598    /// Replies added by the request.
599    #[serde(default, skip_serializing_if = "is_zero")]
600    pub comment_replies: usize,
601    /// Sum of root comments added plus replies added; convenient for a
602    /// reader that does not care about the breakdown.
603    #[serde(default, skip_serializing_if = "is_zero")]
604    pub comments_added: usize,
605}
606
607impl Counts {
608    /// Sum of `body_operations_applied` + `review_operations_applied`.
609    /// Distinct from `requested_operations` (the latter includes
610    /// unchanged and skipped operations).
611    #[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/// Result data for success or failure: phase (null before any completed
622/// stage), effect, optional predicted effect, counts and verification.
623#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
624pub struct ResultData {
625    /// Last completed stage; null when no stage completed. Success requires it.
626    pub phase: Option<Phase>,
627    /// The primary document effect.
628    pub effect: Effect,
629    /// Predicted effect for dry runs; only valid with [`Phase::Validated`].
630    #[serde(default, skip_serializing_if = "Option::is_none")]
631    pub predicted_effect: Option<PredictedEffect>,
632    /// Counts of operations, revisions and comments.
633    pub counts: Counts,
634    /// Threads removed by revision settlement, in the source's ids.
635    #[serde(default, skip_serializing_if = "Vec::is_empty")]
636    pub removed_comments: Vec<crate::edit::RemovedComment>,
637    /// Threads rescued on empty anchors by an edit plan.
638    #[serde(default, skip_serializing_if = "Vec::is_empty")]
639    pub kept_comments: Vec<crate::edit::KeptComment>,
640    /// Verification block.
641    pub verification: Verification,
642    /// Generator-only coverage and bounded working readiness; never plan authority.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub generation: Option<serde_json::Value>,
645    /// The bounded expectation report when `--expect` was evaluated: the
646    /// receipt (path, digest, schema version, checks run/refused/
647    /// unsupported, targets, text view, declared provenance) plus the
648    /// per-check outcomes. Absent when no expectations were supplied.
649    #[serde(default, skip_serializing_if = "Option::is_none")]
650    pub expectations: Option<crate::expect::ExpectationReport>,
651}
652
653/// Invalid combinations of (phase, effect, predicted_effect).
654#[derive(Clone, Debug, Eq, PartialEq)]
655pub enum ResultDataError {
656    /// Success or an actual/predicted effect requires a completed phase.
657    MissingPhase,
658    /// Failure data can only be attached to a failure envelope.
659    FailureRequired,
660    /// A pre-commit phase was paired with a `changed` or `unchanged` effect.
661    NotAppliedRequired {
662        /// The phase that requires `not_applied`.
663        phase: Phase,
664        /// The effect that was supplied.
665        effect: Effect,
666    },
667    /// A committed phase was paired with a `not_applied` effect: only
668    /// actual primary publication reports phase `committed`, and it
669    /// reports an actual effect.
670    EffectRequired {
671        /// The phase that requires an actual effect.
672        phase: Phase,
673        /// The effect that was supplied.
674        effect: Effect,
675    },
676    /// `predicted_effect` was set without a `validated` phase.
677    PredictedWithoutValidation {
678        /// The phase that was supplied.
679        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    /// Build pre-commit failure data with the last completed phase.
708    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    /// Build a result data block. Pre-commit phases require `not_applied`;
723    /// the `predicted_effect` is set with
724    /// [`ResultData::set_predicted`] and only allowed for `validated`.
725    /// [`Envelope::ok`](crate::result::Envelope::ok) enforces both rules through
726    /// [`ResultData::validate`](crate::result::ResultData::validate).
727    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    /// Set the predicted effect (dry runs only). Mutates in place so the
742    /// builder can be called several times before validation.
743    pub fn set_predicted(&mut self, predicted: PredictedEffect) {
744        self.predicted_effect = Some(predicted);
745    }
746
747    /// Validate the (phase, effect, predicted_effect) combination. Returns
748    /// `Ok(())` for a legal combination, `Err(ResultDataError)` otherwise.
749    pub fn validate(&self) -> Result<(), ResultDataError> {
750        match self.phase {
751            Some(phase) => {
752                if phase == Phase::Committed {
753                    // Only actual primary publication reports phase
754                    // `committed`, and it reports an actual effect.
755                    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/// The terminal record of a v2 command. The envelope is one of three
781/// shapes, distinguished by `status`:
782///
783/// - `ok`: `data` carries the phase/effect/counts/verification; `error` is
784///   absent; `artifacts` lists committed (and any uncommitted) outputs.
785/// - `refused`: `error` carries the refusal; `data` records pre-commit state.
786/// - `error`: `error` carries the failure; `data` retains the last completed
787///   phase, including committed publication state after a reporting failure.
788///
789/// The Rust identifier is `Envelope` to avoid shadowing
790/// `std::result::Result` in function signatures.
791#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
792pub struct Envelope {
793    /// Wire schema version; equals `ENVELOPE_SCHEMA_VERSION`.
794    pub schema_version: u32,
795    /// Command identifier (`edit apply`, `edit template`, ...).
796    pub command: String,
797    /// Engine crate version.
798    pub engine_version: String,
799    /// Runtime metadata.
800    pub runtime: Runtime,
801    /// Terminal status (`ok` | `refused` | `error`).
802    pub status: Status,
803    /// Source the request bound to.
804    pub source: Source,
805    /// Result data, including the last completed phase on failures.
806    /// Only the scaffold constructor leaves it absent.
807    #[serde(default, skip_serializing_if = "Option::is_none")]
808    pub data: Option<ResultData>,
809    /// Committed and uncommitted artifacts.
810    #[serde(default, skip_serializing_if = "Vec::is_empty")]
811    pub artifacts: Vec<Artifact>,
812    /// Non-fatal warnings collected during preparation.
813    #[serde(default, skip_serializing_if = "Vec::is_empty")]
814    pub warnings: Vec<String>,
815    /// Error block; present on `refused` and `error`, absent on `ok`.
816    #[serde(default, skip_serializing_if = "Option::is_none")]
817    pub error: Option<Error>,
818    /// Effective option values (resolved flags, defaults, configuration).
819    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
820    pub effective_options: BTreeMap<String, serde_json::Value>,
821    /// Continuation cursor for paginated reads; `None` here means
822    /// exhausted.
823    #[serde(default, skip_serializing_if = "Option::is_none")]
824    pub continuation: Option<serde_json::Value>,
825}
826
827impl Envelope {
828    /// Attach validated phase/effect/counts to a failure envelope. A committed
829    /// phase records known publication; earlier phases preserve the error's
830    /// commit state, including unknown. Refusals cannot report publication.
831    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        // Refusals never publish a primary document.
837        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    /// Build a placeholder envelope with `status: ok` and no data; used by
851    /// tests and scaffold code. Production callers should use
852    /// [`Envelope::ok`](crate::result::Envelope::ok) (with data) or [`Envelope::refused`] /
853    /// [`Envelope::new_error`].
854    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    /// Build a terminal envelope with `status: ok` and the supplied `data`.
872    ///
873    /// Returns [`ResultDataError`] when `data` pairs its phase with an
874    /// effect or predicted effect the envelope rules forbid (see
875    /// [`ResultData::validate`](crate::result::ResultData::validate)), so no contradictory `ok` envelope can be
876    /// built.
877    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    /// Build a terminal envelope with `status: refused` and a typed
904    /// refusal. No stage is assumed complete; use [`Self::with_failure_data`]
905    /// to report a known last completed phase. Refusals are not committed.
906    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    /// Build a terminal envelope with `status: error` and a typed
925    /// failure. No stage is assumed complete; use [`Self::with_failure_data`]
926    /// to retain completed phases, including publication after reporting errors.
927    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    /// Append an artifact to the envelope.
946    pub fn push_artifact(&mut self, artifact: Artifact) {
947        self.artifacts.push(artifact);
948    }
949
950    /// Append a warning to the envelope.
951    pub fn push_warning(&mut self, warning: impl Into<String>) {
952        self.warnings.push(warning.into());
953    }
954
955    /// Set an effective option.
956    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/// First JSONL record. The stable discriminator is `"record": "header"`;
962/// the source block contains the bound source's SHA-256.
963#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
964#[serde(tag = "record", rename = "header")]
965pub struct StreamHeader {
966    /// Envelope schema version.
967    pub schema_version: u32,
968    /// Command identifier.
969    pub command: String,
970    /// Engine crate version.
971    pub engine_version: String,
972    /// Bound source identity.
973    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/// Progress event for JSONL streams: a free-form JSON value so callers can
988/// attach any `ev`/`load`/`op`/`save` line they want. [`read_jsonl_stream`]
989/// requires every progress record to carry a string `ev` discriminator.
990/// The terminal record is a typed [`Envelope`]; see
991/// [`jsonl_terminal_line`] and [`write_jsonl_stream`].
992#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
993#[serde(transparent)]
994pub struct ProgressEvent {
995    /// Free-form JSON.
996    value: serde_json::Value,
997}
998
999impl ProgressEvent {
1000    /// Build a progress event from a JSON value.
1001    pub fn new(value: serde_json::Value) -> Self {
1002        Self { value }
1003    }
1004
1005    /// Borrow the underlying JSON value.
1006    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
1023/// Serialize `terminal` as a single JSONL line (no trailing newline).
1024pub fn jsonl_terminal_line(terminal: &Envelope) -> String {
1025    serde_json::to_string(terminal).expect("Envelope serializes")
1026}
1027
1028/// Serialize a typed header, `events`, then exactly one terminal result.
1029/// Each record occupies its own line; the terminal is always last.
1030pub 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/// A parsed JSONL stream: the progress events and the terminal record.
1044#[derive(Clone, Debug, Eq, PartialEq)]
1045pub struct ParsedStream {
1046    /// Required first record with schema, engine and source identity.
1047    pub header: StreamHeader,
1048    /// Progress events in order.
1049    pub events: Vec<ProgressEvent>,
1050    /// The terminal record.
1051    pub terminal: Envelope,
1052}
1053
1054/// Why a JSONL stream is malformed.
1055#[derive(Clone, Debug, Eq, PartialEq)]
1056pub enum StreamError {
1057    /// The stream did not start with a typed header.
1058    MissingHeader,
1059    /// The header discriminator was present but its fields were malformed.
1060    HeaderParse {
1061        /// 1-based line number.
1062        line: usize,
1063        /// Parse error.
1064        message: String,
1065    },
1066    /// Invalid JSON, a duplicate header, or a record after termination.
1067    InvalidLine {
1068        /// 1-based line number.
1069        line: usize,
1070        /// The line content.
1071        content: String,
1072    },
1073    /// The stream ended without a terminal record.
1074    MissingTerminal,
1075    /// The stream carries more than one terminal record.
1076    MultipleTerminals,
1077    /// A terminal record could not be parsed.
1078    TerminalParse {
1079        /// 1-based line number.
1080        line: usize,
1081        /// Parse error.
1082        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
1107/// Require a typed header first and exactly one terminal result last.
1108/// Progress uses `ev`; its per-operation `status` is not a terminal
1109/// marker. A progress record must carry a string `ev` discriminator:
1110/// JSONL emits typed records, so an untyped line between the header and
1111/// the terminal is malformed. Empty lines are ignored. Missing
1112/// termination is incomplete; missing or malformed headers, duplicate
1113/// terminals and records after termination are malformed.
1114pub 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/// Exit status values per the proposal §12 table.
1188#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1189pub struct ExitStatus(pub u8);
1190
1191impl ExitStatus {
1192    /// Command completed.
1193    pub const SUCCESS: Self = Self(0);
1194    /// Input, operational or I/O failure.
1195    pub const INPUT_FAILURE: Self = Self(1);
1196    /// Standalone check/validation findings meet the requested threshold.
1197    pub const CHECK_FINDINGS: Self = Self(2);
1198    /// Refused stale, ambiguous, unsafe, unsupported request, failed
1199    /// operation/expectation invariant, or unmet require-change condition.
1200    pub const REFUSED: Self = Self(3);
1201    /// Requested rendering/fidelity policy failed before publication.
1202    pub const RENDER_FAILURE: Self = Self(4);
1203    /// Comparison differences when `--exit-code` was requested.
1204    pub const COMPARISON_DIFFERENCE: Self = Self(5);
1205    /// Invalid CLI usage or malformed request/schema.
1206    pub const USAGE: Self = Self(64);
1207    /// Deadline exceeded before commit.
1208    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
1217/// Map a [`Status`] and the optional [`Error`] code to the proposal §12
1218/// exit code.
1219///
1220/// The §12 table is keyed by the code's meaning, not by the envelope
1221/// status: a dedicated code decides whatever status the envelope carries
1222/// (`USAGE`→64, `RENDER_FIDELITY_FAILED`→4, `DEADLINE_EXCEEDED`→124,
1223/// `CHECK_THRESHOLD_EXCEEDED`→2, `COMPARISON_DIFFERENCE`→5). Only
1224/// unclassified codes fall back to the status: `Ok`→0, `Refused`→3,
1225/// `Error`→1.
1226pub 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
1244/// Map an [`Envelope`] to the proposal §12 exit code.
1245pub 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    //! Inline tests covering the type-level invariants the rest of the
1251    //! crate relies on. The full envelope/JSONL contract is covered by the
1252    //! integration suite in `tests/result_envelope.rs`.
1253
1254    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        // Only actual primary publication reports phase committed, and it
1290        // reports an actual effect; not_applied contradicts the phase.
1291        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        // Empty code falls into the default branch.
1322        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        // The exit table is keyed by meaning: the dedicated code decides
1341        // whatever status the envelope carries, and only unclassified
1342        // codes fall back to the status.
1343        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}