Skip to main content

taskfleet_core/
report.rs

1//! §7.3 terminal-report payload validation (design.md §7.3).
2//!
3//! Validates the structural shape of a `node.report` payload — `success`
4//! required; optional `summary`, `cancelled`/`reason`, `discussion_items`,
5//! `spinoff_proposals`, `wrap_up_recommendations` — before the reducer
6//! ever projects it. Lives in `taskfleet-core` (not the CLI) so the supervisor
7//! can validate child reports with the same rules it would consume
8//! (design.md §7.3 step 3), rather than copying the validator or depending
9//! on the CLI crate.
10//!
11//! Errors are domain-typed ([`ReportValidationError`]); the CLI maps them
12//! to its `CliError` envelope at the boundary.
13//!
14//! # Two validation modes
15//!
16//! - **Strict** ([`validate_report_payload`]) — the whole payload passes or
17//!   the first schema violation is returned. Used by `node report` (an agent
18//!   self-submission) and merge-recovery's synthesized report, where the caller
19//!   controls the shape and a malformed field is a real bug to surface.
20//! - **Lenient advisory** ([`sanitize_report_advisory`]) — the REQUIRED and
21//!   correctness-bearing fields (`success`, `cancelled`/`reason`) are still
22//!   validated strictly, but the *advisory* sections (`summary`,
23//!   `discussion_items`, `spinoff_proposals`, `wrap_up_recommendations`) degrade
24//!   gracefully: a malformed element is dropped and reported as a machine-readable
25//!   [`AdvisoryWarning`] rather than rejecting the whole payload. Used by
26//!   `run merge --report-file` so an advisory-field typo can no longer block a
27//!   clean, already-committed code merge (issue `merge-report-schema-lenience`).
28
29use serde::{Deserialize, Serialize};
30use serde_json::Value;
31
32use crate::schema::Kind;
33
34/// The report-payload key under which a typed [`ReportOrigin`] is serialized
35/// (issue `typed-report-origin`).
36pub const REPORT_ORIGIN_KEY: &str = "origin";
37
38/// The legacy `via` marker `run merge` stamps on the terminal `node.report` it
39/// appends after a clean merge, alongside the typed [`ReportOrigin::RunMerge`].
40/// This is the taskfleet/taskfleet-core contract point: the CLI
41/// (`crates/taskfleet/src/run/merge.rs`) writes it, and — for a legacy on-disk
42/// report carrying NO `origin` field — [`ReportOrigin::report_is_confirmed_merge`]
43/// reads it as the fallback merge signal. Retained for backward compatibility with
44/// pre-typed-origin runs and downgrade-reading older CLIs; the typed origin is the
45/// authority for a report that carries one (issue `retire-via-string`). Lives here
46/// beside [`REPORT_ORIGIN_KEY`] as a wire-protocol constant, and is re-exported at
47/// the crate root (`taskfleet_core::VIA_EXPLICIT_MERGE`) for the CLI writers.
48pub const VIA_EXPLICIT_MERGE: &str = "explicit-merge";
49
50/// The typed provenance of a `node.report` — WHO authored it (issue
51/// `typed-report-origin`).
52///
53/// Before this field, `supervise::outcome` split a terminal report's outcome by
54/// sniffing string conventions: a `reason` that `starts_with("agent-")` or is one
55/// of a hard-coded set meant "supervisor failure", and `via: "explicit-merge"`
56/// from *any* author meant "merged". Those conventions are brittle (a new
57/// supervisor reason silently misclassifies) and conflate the report's AUTHOR with
58/// its content. `ReportOrigin` records the author explicitly on the event, so the
59/// outcome table can read a typed fact instead of pattern-matching prose.
60///
61/// The origin is stamped by the code path that appends the report, never accepted
62/// from an untrusted payload: `run merge` stamps [`ReportOrigin::RunMerge`] (the
63/// SOLE merge authority — an agent's `node report` cannot assert it; that path
64/// normalizes any supplied origin back to [`ReportOrigin::Agent`]), the supervisor
65/// stamps [`ReportOrigin::Supervisor`] on every report it synthesizes, and an
66/// agent self-submission is [`ReportOrigin::Agent`]. This keeps merge authorization
67/// tied to the run-merge path exactly as the legacy `via` marker did — the typed
68/// origin is a parallel, higher-fidelity signal, not a new trust boundary.
69///
70/// Serialized under [`REPORT_ORIGIN_KEY`] with an internal `kind` tag, e.g.
71/// `{"kind": "agent"}`, `{"kind": "supervisor"}`,
72/// `{"kind": "run-merge", "op_id": "…", "worker_oid": "…"}`.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(tag = "kind", rename_all = "kebab-case")]
75pub enum ReportOrigin {
76    /// The worker agent authored this report itself — a `node report`
77    /// self-submission (a success handoff, or a blocked `success: false` handoff).
78    Agent,
79    /// The supervisor/launcher synthesized this report: a told worker-exit
80    /// failure, the crash backstop, or a re-spawn-exhausted failure.
81    Supervisor,
82    /// Stamped by the `run merge` transaction (or its crash recovery) — the ONLY
83    /// authority for a merge/success outcome. The immutable transaction OIDs are
84    /// carried for provenance/forensics; they are absent only on the legacy
85    /// unguarded merge path (no concrete source branch / stubbed git) where no
86    /// transaction was recorded, but the discriminant alone still identifies the
87    /// report as a genuine `run merge`.
88    RunMerge {
89        /// The merge transaction's `op_id`, when a transaction was recorded.
90        #[serde(default, skip_serializing_if = "Option::is_none")]
91        op_id: Option<String>,
92        /// The pre-rebase worker tip, when a transaction was recorded.
93        #[serde(default, skip_serializing_if = "Option::is_none")]
94        worker_oid: Option<String>,
95        /// Exact post-rebase tip integrated by a native merge. Absent on legacy,
96        /// caller-owned, or unverifiable recovery evidence; never a current tip guess.
97        #[serde(default, skip_serializing_if = "Option::is_none")]
98        integrated_oid: Option<String>,
99    },
100}
101
102impl ReportOrigin {
103    /// Read the typed origin from a report payload, returning `None` for BOTH an
104    /// absent `origin` field (a legacy report written before this field existed)
105    /// AND a present-but-malformed one (corrupt / hand-edited / a future variant).
106    ///
107    /// IMPORTANT — `None` does NOT mean "fall back to the legacy `via`/`reason`
108    /// string path". That fallback is gated on the `origin` KEY being genuinely
109    /// ABSENT (`report.get(REPORT_ORIGIN_KEY).is_none()`), NOT on this returning
110    /// `None`. A present-but-malformed origin is "typed, but unknown authority":
111    /// it must NEVER re-unlock the forgeable legacy path (a merge on a forged
112    /// `via`, a supervisor failure on a spoofed `reason`). Every consumer
113    /// (`report_is_confirmed_merge`, `supervise::outcome::classify` /
114    /// `is_supervisor_failure`) checks key presence separately for exactly this
115    /// reason — do not collapse the two. See `report_is_confirmed_merge`.
116    #[must_use]
117    pub fn from_report(report: &Value) -> Option<Self> {
118        let raw = report.get(REPORT_ORIGIN_KEY)?;
119        serde_json::from_value(raw.clone()).ok()
120    }
121
122    /// True when a terminal `node.report` payload is a CONFIRMED, SUCCESSFUL
123    /// `run merge` — the sole authority for a merge/success outcome (issue
124    /// `retire-via-string`).
125    ///
126    /// The typed [`ReportOrigin::RunMerge`] (stamped only by the `run merge`
127    /// transaction / its crash recovery — an agent's `node report` is normalized
128    /// to [`ReportOrigin::Agent`]) is the authoritative marker. The legacy
129    /// `via: "explicit-merge"` string is honored ONLY as a fallback for a report
130    /// that carries NO `origin` field at all — a legacy on-disk report written
131    /// before the typed origin existed. Gating the `via` fallback on a genuinely
132    /// ABSENT origin (not on [`from_report`](Self::from_report) returning `None`)
133    /// is what makes the typed field strictly stronger: a report that DOES carry
134    /// an `origin` field — parsed or malformed/hand-edited — never earns merge
135    /// status on a forged `via` string alone. This mirrors
136    /// `supervise::outcome::classify`'s merge gate exactly, so the reducer, the
137    /// `landed` fallback, and `run wait`'s `merged` flag all agree on the one
138    /// merge truth.
139    ///
140    /// Requires `success == true` and `cancelled` absent/`false`: a payload
141    /// carrying the merge marker but `success: false` (malformed/spoofed) or a
142    /// cancel is NOT a merge. Boolean typing is strict — a non-boolean `success`
143    /// / `cancelled` reads as not-a-merge rather than erroring, so a replay of
144    /// such a dead event stays a clean no-op.
145    #[must_use]
146    pub fn report_is_confirmed_merge(report: &Value) -> bool {
147        let success = matches!(report.get("success"), Some(Value::Bool(true)));
148        let not_cancelled = matches!(
149            report.get("cancelled"),
150            None | Some(Value::Null | Value::Bool(false))
151        );
152        if !(success && not_cancelled) {
153            return false;
154        }
155        // Prefer the typed origin; the legacy `via` string is authority ONLY when
156        // no `origin` field is present (a pre-typed-origin on-disk report).
157        let is_run_merge_origin = matches!(
158            Self::from_report(report),
159            Some(ReportOrigin::RunMerge { .. })
160        );
161        let origin_present = report.get(REPORT_ORIGIN_KEY).is_some();
162        let legacy_via_merge = !origin_present
163            && report.get("via").and_then(Value::as_str) == Some(VIA_EXPLICIT_MERGE);
164        is_run_merge_origin || legacy_via_merge
165    }
166
167    /// Whether a confirmed merge report may replace a node's settled outcome.
168    ///
169    /// This is the single transition predicate shared by projection reduction
170    /// and log-derived status replay. A confirmed `run merge` may repair a
171    /// failed node (or refresh an already-done node's authoritative report),
172    /// but it never overrides cancellation or any future deliberate terminal
173    /// outcome.
174    #[must_use]
175    pub fn permits_terminal_merge_recovery(status: crate::Status, report: &Value) -> bool {
176        matches!(status, crate::Status::Failed | crate::Status::Done)
177            && Self::report_is_confirmed_merge(report)
178    }
179
180    /// Stamp this origin into a report payload under [`REPORT_ORIGIN_KEY`],
181    /// overwriting any existing value. A no-op if `report` is not a JSON object
182    /// (callers always pass an object — the §7.3 validator rejects non-objects
183    /// before this point).
184    pub fn stamp(&self, report: &mut Value) {
185        if let Some(obj) = report.as_object_mut() {
186            // Serializing a tagged enum with only `Option::None` extra fields
187            // yields a plain object, so this never fails for these variants.
188            if let Ok(v) = serde_json::to_value(self) {
189                obj.insert(REPORT_ORIGIN_KEY.to_string(), v);
190            }
191        }
192    }
193}
194
195/// A §7.3 report payload failed structural validation.
196///
197/// Every variant describes one schema violation. The CLI renders these as
198/// a `schema_violation` error; [`ReportValidationError::expected`] supplies
199/// the machine-readable `expected` hint for the variants that carry one.
200#[derive(Debug, thiserror::Error)]
201pub enum ReportValidationError {
202    /// The payload root was not a JSON object.
203    #[error("report payload must be a JSON object")]
204    NotObject,
205
206    /// The required `success` field was absent.
207    #[error("report payload missing required field `success`")]
208    MissingSuccess,
209
210    /// `success` was present but not a boolean.
211    #[error("field `success` must be a boolean")]
212    SuccessNotBoolean,
213
214    /// `summary` was present but not a string (or null).
215    #[error("field `summary` must be a string")]
216    SummaryNotString,
217
218    /// `cancelled` was present but not a boolean.
219    #[error("field `cancelled` must be a boolean")]
220    CancelledNotBoolean,
221
222    /// `reason` was present but not a string.
223    #[error("field `reason` must be a string")]
224    ReasonNotString,
225
226    /// `cancelled: true` was paired with `success: true` (§7.7 forbids it).
227    #[error("`cancelled: true` requires `success: false`")]
228    CancelledRequiresSuccessFalse,
229
230    /// `cancelled: true` lacked a non-empty `reason` string (§7.7).
231    #[error("`cancelled: true` requires a non-empty `reason` string")]
232    CancelledRequiresReason,
233
234    /// `discussion_items` was present but not an array.
235    #[error("field `discussion_items` must be an array")]
236    DiscussionItemsNotArray,
237
238    /// A `discussion_items` element was not a JSON object.
239    #[error("discussion_items[{index}] must be a JSON object")]
240    DiscussionItemNotObject {
241        /// Index of the offending element.
242        index: usize,
243    },
244
245    /// A `discussion_items` element lacked a non-empty `topic` string.
246    #[error("discussion_items[{index}].topic must be a non-empty string")]
247    DiscussionItemTopicMissing {
248        /// Index of the offending element.
249        index: usize,
250    },
251
252    /// A `discussion_items` element's `severity` was not a string.
253    #[error("discussion_items[{index}].severity must be a string")]
254    DiscussionItemSeverityNotString {
255        /// Index of the offending element.
256        index: usize,
257    },
258
259    /// `spinoff_proposals` was present but not an array.
260    #[error("field `spinoff_proposals` must be an array")]
261    SpinoffProposalsNotArray,
262
263    /// A `spinoff_proposals` element was not a JSON object.
264    #[error("spinoff_proposals[{index}] must be a JSON object")]
265    SpinoffProposalNotObject {
266        /// Index of the offending element.
267        index: usize,
268    },
269
270    /// A `spinoff_proposals` element lacked a non-empty `proposed_title`.
271    #[error("spinoff_proposals[{index}].proposed_title must be a non-empty string")]
272    SpinoffProposalTitleMissing {
273        /// Index of the offending element.
274        index: usize,
275    },
276
277    /// A `spinoff_proposals` element's `proposed_kind` was not a string.
278    #[error("spinoff_proposals[{index}].proposed_kind must be a string")]
279    SpinoffProposalKindNotString {
280        /// Index of the offending element.
281        index: usize,
282    },
283
284    /// A `spinoff_proposals` element's `proposed_kind` was not a known [`Kind`].
285    #[error("spinoff_proposals[{index}].proposed_kind `{kind}` is not a known kind")]
286    SpinoffProposalKindUnknown {
287        /// Index of the offending element.
288        index: usize,
289        /// The rejected kind string.
290        kind: String,
291    },
292
293    /// A `spinoff_proposals` element's `rationale` was not a string (or null).
294    #[error("spinoff_proposals[{index}].rationale must be a string")]
295    SpinoffProposalRationaleNotString {
296        /// Index of the offending element.
297        index: usize,
298    },
299
300    /// A declared string-array field was not an array.
301    #[error("field `{field}` must be an array")]
302    FieldNotArray {
303        /// The offending field name.
304        field: String,
305    },
306
307    /// An element of a declared string-array field was not a string.
308    #[error("{field}[{index}] must be a string")]
309    FieldElementNotString {
310        /// The offending field name.
311        field: String,
312        /// Index of the offending element.
313        index: usize,
314    },
315
316    /// A nested path expected to hold a string array was not an array.
317    #[error("{path} must be an array")]
318    PathNotArray {
319        /// Dotted/indexed path to the offending value.
320        path: String,
321    },
322
323    /// An element at a nested string-array path was not a string.
324    #[error("{path}[{index}] must be a string")]
325    PathElementNotString {
326        /// Dotted/indexed path to the offending array.
327        path: String,
328        /// Index of the offending element.
329        index: usize,
330    },
331}
332
333impl ReportValidationError {
334    /// The machine-readable `expected` hint for this error, if any.
335    ///
336    /// Mirrors the `with_expected(...)` payloads the CLI previously
337    /// attached inline, so callers can surface the same structured hint.
338    #[must_use]
339    pub fn expected(&self) -> Option<Value> {
340        match self {
341            Self::MissingSuccess | Self::SuccessNotBoolean => {
342                Some(serde_json::json!({"field": "success", "type": "boolean"}))
343            }
344            // Source the accepted kinds from the enum so the hint can never
345            // drift from what the validator actually accepts (see
346            // `Kind::WIRE_NAMES` and its serde round-trip test).
347            Self::SpinoffProposalKindUnknown { .. } => Some(serde_json::json!(Kind::WIRE_NAMES)),
348            _ => None,
349        }
350    }
351}
352
353/// Validate a §7.3 report payload's structural shape.
354///
355/// Rejects anything obviously not a report before the reducer ever sees
356/// it, so the caller can name the offending field instead of bubbling a
357/// generic `CorruptEventLog`. Keeps the current validation logic verbatim;
358/// this is a relocation, not a tightening.
359///
360/// # Errors
361///
362/// Returns a [`ReportValidationError`] describing the first schema
363/// violation found.
364pub fn validate_report_payload(data: &Value) -> Result<(), ReportValidationError> {
365    let obj = data.as_object().ok_or(ReportValidationError::NotObject)?;
366
367    validate_required_fields(obj)?;
368
369    if let Some(v) = obj.get("summary") {
370        if !v.is_string() && !v.is_null() {
371            return Err(ReportValidationError::SummaryNotString);
372        }
373    }
374
375    validate_discussion_items(obj.get("discussion_items"))?;
376    validate_spinoff_proposals(obj.get("spinoff_proposals"))?;
377    validate_string_array(
378        obj.get("wrap_up_recommendations"),
379        "wrap_up_recommendations",
380    )?;
381    Ok(())
382}
383
384/// Validate the REQUIRED, correctness-bearing fields — `success` and the
385/// `cancelled`/`reason` §7.7 cross-constraints. These are strict in BOTH
386/// validation modes: they gate the terminal outcome and teardown, so a malformed
387/// one is never degraded to a warning (issue `merge-report-schema-lenience`).
388fn validate_required_fields(
389    obj: &serde_json::Map<String, Value>,
390) -> Result<(), ReportValidationError> {
391    // `success` is the one strictly required field per §7.3. A cancel-
392    // synthesized report (§7.7) may carry `cancelled: true` AND
393    // `success: false` — both are still booleans on the wire.
394    let success = obj
395        .get("success")
396        .ok_or(ReportValidationError::MissingSuccess)?;
397    if !success.is_boolean() {
398        return Err(ReportValidationError::SuccessNotBoolean);
399    }
400
401    let cancelled = match obj.get("cancelled") {
402        None | Some(Value::Null) => false,
403        Some(v) => v
404            .as_bool()
405            .ok_or(ReportValidationError::CancelledNotBoolean)?,
406    };
407    let reason = match obj.get("reason") {
408        None | Some(Value::Null) => None,
409        Some(v) => Some(v.as_str().ok_or(ReportValidationError::ReasonNotString)?),
410    };
411
412    // §7.7: a cancel-synthesized report carries `cancelled: true,
413    // success: false, reason: <non-empty>`. Allowing `success: true`
414    // alongside `cancelled: true` would persist a contradiction (the
415    // reducer prioritizes `cancelled`, so the node would be cancelled
416    // while `last_report.success == true`).
417    if cancelled {
418        // `success` was confirmed a boolean above, so this never panics;
419        // `expect` documents that invariant rather than masking a reorder
420        // bug behind `unwrap_or(false)`.
421        if success
422            .as_bool()
423            .expect("success validated as boolean above")
424        {
425            return Err(ReportValidationError::CancelledRequiresSuccessFalse);
426        }
427        match reason {
428            Some(s) if !s.trim().is_empty() => {}
429            _ => return Err(ReportValidationError::CancelledRequiresReason),
430        }
431    }
432    Ok(())
433}
434
435fn validate_discussion_items(v: Option<&Value>) -> Result<(), ReportValidationError> {
436    let arr = match v {
437        Some(Value::Array(a)) => a,
438        Some(_) => return Err(ReportValidationError::DiscussionItemsNotArray),
439        None => return Ok(()),
440    };
441    for (i, item) in arr.iter().enumerate() {
442        validate_discussion_item(item, i)?;
443    }
444    Ok(())
445}
446
447/// Validate ONE `discussion_items` element. Extracted so both the strict
448/// validator (first error wins) and the lenient sanitizer (drop the offending
449/// element, keep the rest) share the exact same per-element rules.
450fn validate_discussion_item(item: &Value, index: usize) -> Result<(), ReportValidationError> {
451    let obj = item
452        .as_object()
453        .ok_or(ReportValidationError::DiscussionItemNotObject { index })?;
454    let topic = obj.get("topic").and_then(Value::as_str);
455    if topic.is_none_or(|t| t.trim().is_empty()) {
456        return Err(ReportValidationError::DiscussionItemTopicMissing { index });
457    }
458    if let Some(sev) = obj.get("severity") {
459        if !sev.is_string() {
460            return Err(ReportValidationError::DiscussionItemSeverityNotString { index });
461        }
462        // §7.3 example lists "discuss|critical" but the design
463        // calls for forward-compatibility — accept any string and
464        // let the supervisor interpret unknown severities. (A
465        // CLI-side closed-set check would deadlock agents shipped
466        // ahead of a CLI release; see review #2/DeepSeek and #15
467        // /Claude.)
468    }
469    if let Some(opts) = obj.get("options") {
470        validate_string_array_at(opts, &format!("discussion_items[{index}].options"))?;
471    }
472    Ok(())
473}
474
475fn validate_spinoff_proposals(v: Option<&Value>) -> Result<(), ReportValidationError> {
476    let arr = match v {
477        Some(Value::Array(a)) => a,
478        Some(_) => return Err(ReportValidationError::SpinoffProposalsNotArray),
479        None => return Ok(()),
480    };
481    for (i, item) in arr.iter().enumerate() {
482        validate_spinoff_proposal(item, i)?;
483    }
484    Ok(())
485}
486
487/// Validate ONE `spinoff_proposals` element. Extracted so both the strict
488/// validator and the lenient sanitizer share the exact same per-element rules —
489/// including the `proposed_title`/`proposed_kind` field names whose intuitive
490/// typos (`title`/`detail`) motivated the lenient mode (issue
491/// `merge-report-schema-lenience`).
492fn validate_spinoff_proposal(item: &Value, index: usize) -> Result<(), ReportValidationError> {
493    let obj = item
494        .as_object()
495        .ok_or(ReportValidationError::SpinoffProposalNotObject { index })?;
496    let title = obj.get("proposed_title").and_then(Value::as_str);
497    if title.is_none_or(|t| t.trim().is_empty()) {
498        return Err(ReportValidationError::SpinoffProposalTitleMissing { index });
499    }
500    let kind_str = obj
501        .get("proposed_kind")
502        .and_then(Value::as_str)
503        .ok_or(ReportValidationError::SpinoffProposalKindNotString { index })?;
504    // Reject unknown kinds at the boundary so the supervisor never
505    // has to translate a generic `CorruptEventLog` for the user. The
506    // accepted set is the enum's *creatable* wire names — the read-only
507    // `Kind::Unknown` catch-all is deliberately excluded (a proposal must
508    // name a live kind), so this checks membership rather than round-tripping
509    // through serde (which would silently map any unknown string to
510    // `Kind::Unknown`).
511    if !Kind::WIRE_NAMES.contains(&kind_str) {
512        return Err(ReportValidationError::SpinoffProposalKindUnknown {
513            index,
514            kind: kind_str.to_string(),
515        });
516    }
517    if let Some(rationale) = obj.get("rationale") {
518        if !rationale.is_string() && !rationale.is_null() {
519            return Err(ReportValidationError::SpinoffProposalRationaleNotString { index });
520        }
521    }
522    Ok(())
523}
524
525/// Path-aware string-array validator. Used for nested fields where the
526/// caller wants to embed an index in the error message.
527fn validate_string_array_at(v: &Value, path: &str) -> Result<(), ReportValidationError> {
528    let arr = v
529        .as_array()
530        .ok_or_else(|| ReportValidationError::PathNotArray {
531            path: path.to_string(),
532        })?;
533    for (i, item) in arr.iter().enumerate() {
534        if !item.is_string() {
535            return Err(ReportValidationError::PathElementNotString {
536                path: path.to_string(),
537                index: i,
538            });
539        }
540    }
541    Ok(())
542}
543
544fn validate_string_array(v: Option<&Value>, field: &str) -> Result<(), ReportValidationError> {
545    let arr = match v {
546        Some(Value::Array(a)) => a,
547        Some(_) => {
548            return Err(ReportValidationError::FieldNotArray {
549                field: field.to_string(),
550            })
551        }
552        None => return Ok(()),
553    };
554    for (i, item) in arr.iter().enumerate() {
555        if !item.is_string() {
556            return Err(ReportValidationError::FieldElementNotString {
557                field: field.to_string(),
558                index: i,
559            });
560        }
561    }
562    Ok(())
563}
564
565/// A machine-readable warning that one advisory report field (or one element of
566/// an advisory array) was dropped during lenient sanitization
567/// (issue `merge-report-schema-lenience`).
568///
569/// Emitted by [`sanitize_report_advisory`] and surfaced in `run merge`'s JSON
570/// envelope so an agent reads a structured record of what was discarded instead
571/// of regex-parsing prose. The dropped data was never correctness-bearing (see
572/// [`sanitize_report_advisory`] for the strict/advisory split), so a warning —
573/// not a rejected merge — is the right severity.
574#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
575pub struct AdvisoryWarning {
576    /// The advisory field the drop applies to, e.g. `spinoff_proposals`.
577    pub field: String,
578    /// The element index dropped, when the field itself was kept but one element
579    /// was invalid. Absent (`None`) when the entire field was dropped (e.g. it was
580    /// present but not an array).
581    #[serde(skip_serializing_if = "Option::is_none")]
582    pub index: Option<usize>,
583    /// Human-readable reason — the underlying [`ReportValidationError`] rendered.
584    pub reason: String,
585}
586
587impl AdvisoryWarning {
588    /// Render as a single human-readable line for the CLI's `warnings` string list,
589    /// e.g. `dropped spinoff_proposals[0]: … must be a non-empty string`.
590    #[must_use]
591    pub fn to_message(&self) -> String {
592        match self.index {
593            Some(i) => format!("dropped {}[{i}]: {}", self.field, self.reason),
594            None => format!("dropped advisory field `{}`: {}", self.field, self.reason),
595        }
596    }
597}
598
599/// The result of [`sanitize_report_advisory`]: a report with malformed *advisory*
600/// sections removed, plus the machine-readable [`AdvisoryWarning`]s describing
601/// every drop.
602#[derive(Debug, Clone)]
603pub struct SanitizedReport {
604    /// The report with malformed advisory fields/elements dropped. Required and
605    /// correctness-bearing fields are untouched (they were validated strictly).
606    pub report: Value,
607    /// One entry per dropped advisory field or element; empty when nothing was
608    /// dropped (the report validated cleanly).
609    pub warnings: Vec<AdvisoryWarning>,
610}
611
612/// Validate a §7.3 report payload with **lenient advisory handling** — the
613/// merge-first posture of `run merge --report-file` (issue
614/// `merge-report-schema-lenience`).
615///
616/// The REQUIRED, correctness-bearing fields are still strict — a violation here
617/// returns `Err` exactly as [`validate_report_payload`] would:
618/// - the payload root must be a JSON object,
619/// - `success` must be present and boolean, and
620/// - the `cancelled`/`reason` §7.7 cross-constraints must hold.
621///
622/// These gate the node's terminal outcome and the supervisor's teardown, so a
623/// malformed one is never silently degraded — that would risk mis-terminalizing a
624/// node or stranding teardown.
625///
626/// Everything else is **advisory** and degrades gracefully: a malformed value is
627/// dropped from the returned [`SanitizedReport::report`] and recorded as an
628/// [`AdvisoryWarning`] instead of failing the call. This covers:
629/// - `summary` (a non-string/non-null scalar → field dropped),
630/// - `discussion_items` / `spinoff_proposals` (a non-array → whole field dropped;
631///   an invalid element → that WHOLE element dropped, valid siblings kept),
632/// - `wrap_up_recommendations` (a non-array → field dropped; a non-string element
633///   → that element dropped).
634///
635/// **Element granularity is coarse by design:** an element is validated as a unit,
636/// so a malformed *nested* value (e.g. a non-string inside a `discussion_items[i].
637/// options` array, or a bad `spinoff_proposals[i].proposed_kind`) drops the entire
638/// containing element — its valid siblings like `topic` go with it. This keeps the
639/// lenient rules byte-identical to the strict per-element validators (no rule
640/// drift) at the cost of not salvaging partial elements; salvaging a typo is what
641/// motivated leniency, and dropping one malformed proposal is an acceptable price.
642///
643/// This is what stops an advisory-field typo (the recurring `title`/`detail`
644/// instead of `proposed_title`/`proposed_kind`/`rationale`) from rejecting the
645/// whole terminal report and blocking a clean, already-committed code merge.
646///
647/// **Provenance is NOT validated here — the caller owns it.** This function
648/// touches only the required and advisory fields above; every OTHER top-level key
649/// (`origin`, `via`, and any unknown agent key) is preserved verbatim from the
650/// input. It deliberately does NOT establish provenance trust: a caller that
651/// persists the result MUST stamp the authoritative [`ReportOrigin`] itself (as
652/// `run merge` does after this returns) — never trust a payload-supplied `origin`
653/// / `via`. See [`ReportOrigin`]'s "never accepted from an untrusted payload"
654/// contract; this sanitizer is a shape check, not a trust boundary.
655///
656/// # Errors
657///
658/// Returns a [`ReportValidationError`] only for a violation of a required field
659/// (root shape, `success`, `cancelled`/`reason`). Advisory violations never error.
660pub fn sanitize_report_advisory(data: &Value) -> Result<SanitizedReport, ReportValidationError> {
661    let obj = data.as_object().ok_or(ReportValidationError::NotObject)?;
662
663    // Required/correctness-bearing fields stay strict.
664    validate_required_fields(obj)?;
665
666    let mut out = obj.clone();
667    let mut warnings = Vec::new();
668
669    // `summary` — advisory descriptive scalar. Drop a malformed one.
670    if let Some(v) = obj.get("summary") {
671        if !v.is_string() && !v.is_null() {
672            out.remove("summary");
673            warnings.push(AdvisoryWarning {
674                field: "summary".to_string(),
675                index: None,
676                reason: ReportValidationError::SummaryNotString.to_string(),
677            });
678        }
679    }
680
681    sanitize_element_array(
682        &mut out,
683        "discussion_items",
684        ReportValidationError::DiscussionItemsNotArray,
685        validate_discussion_item,
686        &mut warnings,
687    );
688    sanitize_element_array(
689        &mut out,
690        "spinoff_proposals",
691        ReportValidationError::SpinoffProposalsNotArray,
692        validate_spinoff_proposal,
693        &mut warnings,
694    );
695    sanitize_string_array_field(&mut out, "wrap_up_recommendations", &mut warnings);
696
697    Ok(SanitizedReport {
698        report: Value::Object(out),
699        warnings,
700    })
701}
702
703/// Leniently sanitize one advisory array-of-objects field in place: a
704/// present-but-non-array field is dropped whole; each element that fails
705/// `validate` is dropped, valid siblings retained. Every drop appends an
706/// [`AdvisoryWarning`]. Indices in the warnings are the ORIGINAL element
707/// positions, so they line up with what the agent wrote.
708fn sanitize_element_array(
709    obj: &mut serde_json::Map<String, Value>,
710    field: &str,
711    not_array_err: ReportValidationError,
712    validate: fn(&Value, usize) -> Result<(), ReportValidationError>,
713    warnings: &mut Vec<AdvisoryWarning>,
714) {
715    let Some(v) = obj.get(field) else { return };
716    let Some(arr) = v.as_array() else {
717        obj.remove(field);
718        warnings.push(AdvisoryWarning {
719            field: field.to_string(),
720            index: None,
721            reason: not_array_err.to_string(),
722        });
723        return;
724    };
725    let mut kept = Vec::with_capacity(arr.len());
726    for (i, item) in arr.iter().enumerate() {
727        match validate(item, i) {
728            Ok(()) => kept.push(item.clone()),
729            Err(e) => warnings.push(AdvisoryWarning {
730                field: field.to_string(),
731                index: Some(i),
732                reason: e.to_string(),
733            }),
734        }
735    }
736    obj.insert(field.to_string(), Value::Array(kept));
737}
738
739/// Leniently sanitize one advisory string-array field in place: a
740/// present-but-non-array field is dropped whole; each non-string element is
741/// dropped, string siblings retained.
742fn sanitize_string_array_field(
743    obj: &mut serde_json::Map<String, Value>,
744    field: &str,
745    warnings: &mut Vec<AdvisoryWarning>,
746) {
747    let Some(v) = obj.get(field) else { return };
748    let Some(arr) = v.as_array() else {
749        obj.remove(field);
750        warnings.push(AdvisoryWarning {
751            field: field.to_string(),
752            index: None,
753            reason: ReportValidationError::FieldNotArray {
754                field: field.to_string(),
755            }
756            .to_string(),
757        });
758        return;
759    };
760    let mut kept = Vec::with_capacity(arr.len());
761    for (i, item) in arr.iter().enumerate() {
762        if item.is_string() {
763            kept.push(item.clone());
764        } else {
765            warnings.push(AdvisoryWarning {
766                field: field.to_string(),
767                index: Some(i),
768                reason: ReportValidationError::FieldElementNotString {
769                    field: field.to_string(),
770                    index: i,
771                }
772                .to_string(),
773            });
774        }
775    }
776    obj.insert(field.to_string(), Value::Array(kept));
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782    use serde_json::json;
783
784    // --- valid payloads ---
785
786    #[test]
787    fn validates_minimal_success_payload() {
788        let v = json!({"success": true});
789        assert!(validate_report_payload(&v).is_ok());
790    }
791
792    #[test]
793    fn validates_full_success_payload() {
794        let v = json!({
795            "success": true,
796            "summary": "did the thing",
797            "discussion_items": [
798                {"topic": "naming", "severity": "discuss", "options": ["a", "b"]},
799            ],
800            "spinoff_proposals": [
801                {"proposed_title": "follow-up", "proposed_kind": "spinoff", "rationale": "later"},
802            ],
803            "wrap_up_recommendations": ["rebase", "squash"],
804        });
805        assert!(validate_report_payload(&v).is_ok());
806    }
807
808    #[test]
809    fn discussion_item_unknown_severity_accepted_for_forward_compat() {
810        // Forward-compat: a supervisor may add new severities without a
811        // CLI release. The validator only enforces severity is a string.
812        let v = json!({
813            "success": true,
814            "discussion_items": [{"topic": "x", "severity": "info"}],
815        });
816        assert!(validate_report_payload(&v).is_ok());
817    }
818
819    #[test]
820    fn cancel_synthesized_report_shape_ok() {
821        // Mirror of run cancel's synthesized payload (run/cancel.rs).
822        let v = json!({
823            "success": false,
824            "cancelled": true,
825            "reason": "cancelled by user",
826            "summary": "Run cancelled before agent reported.",
827            "discussion_items": [],
828            "spinoff_proposals": [],
829            "wrap_up_recommendations": [],
830        });
831        assert!(validate_report_payload(&v).is_ok());
832    }
833
834    // --- invalid payloads ---
835
836    #[test]
837    fn non_object_root_rejected() {
838        let v = json!([1, 2, 3]);
839        assert!(matches!(
840            validate_report_payload(&v),
841            Err(ReportValidationError::NotObject)
842        ));
843    }
844
845    #[test]
846    fn missing_success_rejected() {
847        let v = json!({"summary": "no success field"});
848        let err = validate_report_payload(&v).unwrap_err();
849        assert!(matches!(err, ReportValidationError::MissingSuccess));
850        // Missing `success` carries the structured `expected` hint.
851        assert_eq!(
852            err.expected(),
853            Some(json!({"field": "success", "type": "boolean"}))
854        );
855    }
856
857    #[test]
858    fn success_variants_carry_field_type_hint() {
859        // Both `success` errors reproduce the exact CLI hint, byte-for-byte.
860        let hint = Some(json!({"field": "success", "type": "boolean"}));
861        assert_eq!(ReportValidationError::MissingSuccess.expected(), hint);
862        assert_eq!(ReportValidationError::SuccessNotBoolean.expected(), hint);
863    }
864
865    #[test]
866    fn summary_must_be_string() {
867        let v = json!({"success": true, "summary": 42});
868        assert!(matches!(
869            validate_report_payload(&v),
870            Err(ReportValidationError::SummaryNotString)
871        ));
872    }
873
874    #[test]
875    fn discussion_item_options_non_array_rejected() {
876        let v = json!({
877            "success": true,
878            "discussion_items": [{"topic": "x", "options": "not-an-array"}],
879        });
880        assert!(matches!(
881            validate_report_payload(&v),
882            Err(ReportValidationError::PathNotArray { .. })
883        ));
884    }
885
886    #[test]
887    fn cancelled_requires_non_whitespace_reason() {
888        let v = json!({"success": false, "cancelled": true, "reason": "   "});
889        assert!(matches!(
890            validate_report_payload(&v),
891            Err(ReportValidationError::CancelledRequiresReason)
892        ));
893    }
894
895    #[test]
896    fn non_boolean_success_rejected() {
897        let v = json!({"success": "yes"});
898        assert!(matches!(
899            validate_report_payload(&v),
900            Err(ReportValidationError::SuccessNotBoolean)
901        ));
902    }
903
904    #[test]
905    fn discussion_item_missing_topic_rejected() {
906        let v = json!({
907            "success": true,
908            "discussion_items": [{"severity": "discuss"}],
909        });
910        assert!(matches!(
911            validate_report_payload(&v),
912            Err(ReportValidationError::DiscussionItemTopicMissing { index: 0 })
913        ));
914    }
915
916    #[test]
917    fn discussion_item_non_string_severity_rejected() {
918        let v = json!({
919            "success": true,
920            "discussion_items": [{"topic": "x", "severity": 42}],
921        });
922        assert!(matches!(
923            validate_report_payload(&v),
924            Err(ReportValidationError::DiscussionItemSeverityNotString { index: 0 })
925        ));
926    }
927
928    #[test]
929    fn discussion_item_options_must_be_strings() {
930        let v = json!({
931            "success": true,
932            "discussion_items": [{"topic": "x", "options": [1, 2]}],
933        });
934        assert!(matches!(
935            validate_report_payload(&v),
936            Err(ReportValidationError::PathElementNotString { index: 0, .. })
937        ));
938    }
939
940    #[test]
941    fn spinoff_unknown_proposed_kind_rejected() {
942        let v = json!({
943            "success": true,
944            "spinoff_proposals": [{"proposed_title": "x", "proposed_kind": "not-a-kind"}],
945        });
946        let err = validate_report_payload(&v).unwrap_err();
947        assert!(matches!(
948            err,
949            ReportValidationError::SpinoffProposalKindUnknown { index: 0, .. }
950        ));
951        // Unknown kind surfaces the exact closed-set of known kinds, and
952        // that set is the enum's own wire names (no drift).
953        assert_eq!(err.expected(), Some(json!(crate::schema::Kind::WIRE_NAMES)));
954        assert_eq!(
955            err.expected(),
956            Some(json!([
957                "spinoff",
958                "research",
959                "technical-decision",
960                "fan-out"
961            ]))
962        );
963    }
964
965    #[test]
966    fn spinoff_missing_kind_rejected() {
967        let v = json!({
968            "success": true,
969            "spinoff_proposals": [{"proposed_title": "x"}],
970        });
971        assert!(matches!(
972            validate_report_payload(&v),
973            Err(ReportValidationError::SpinoffProposalKindNotString { index: 0 })
974        ));
975    }
976
977    #[test]
978    fn cancelled_requires_success_false() {
979        let v = json!({"success": true, "cancelled": true, "reason": "x"});
980        assert!(matches!(
981            validate_report_payload(&v),
982            Err(ReportValidationError::CancelledRequiresSuccessFalse)
983        ));
984    }
985
986    #[test]
987    fn cancelled_requires_reason() {
988        let v = json!({"success": false, "cancelled": true});
989        assert!(matches!(
990            validate_report_payload(&v),
991            Err(ReportValidationError::CancelledRequiresReason)
992        ));
993    }
994
995    // --- ReportOrigin (issue `typed-report-origin`) ---
996
997    #[test]
998    fn report_origin_round_trips_through_a_report() {
999        let cases = [
1000            ReportOrigin::Agent,
1001            ReportOrigin::Supervisor,
1002            ReportOrigin::RunMerge {
1003                op_id: Some("op-123".into()),
1004                worker_oid: Some("deadbeef".into()),
1005                integrated_oid: None,
1006            },
1007            ReportOrigin::RunMerge {
1008                op_id: None,
1009                worker_oid: None,
1010                integrated_oid: None,
1011            },
1012        ];
1013        for origin in cases {
1014            let mut report = json!({ "success": true });
1015            origin.stamp(&mut report);
1016            assert_eq!(
1017                ReportOrigin::from_report(&report),
1018                Some(origin.clone()),
1019                "round-trip: {origin:?}"
1020            );
1021        }
1022    }
1023
1024    #[test]
1025    fn legacy_merge_origin_decodes_without_exact_integrated_evidence() {
1026        let report = json!({"origin": {"kind":"run-merge", "op_id":"old", "worker_oid":"old-tip"}});
1027        assert!(matches!(
1028            ReportOrigin::from_report(&report),
1029            Some(ReportOrigin::RunMerge {
1030                integrated_oid: None,
1031                ..
1032            })
1033        ));
1034        let mut modern = report.clone();
1035        modern["origin"]["integrated_oid"] = json!("post-rebase-tip");
1036        let origin = ReportOrigin::from_report(&modern).unwrap();
1037        origin.stamp(&mut modern);
1038        assert_eq!(modern["origin"]["integrated_oid"], "post-rebase-tip");
1039    }
1040
1041    #[test]
1042    fn report_origin_serializes_with_kind_tag() {
1043        let mut report = json!({ "success": true });
1044        ReportOrigin::Agent.stamp(&mut report);
1045        assert_eq!(report["origin"], json!({ "kind": "agent" }));
1046
1047        let mut merge = json!({ "success": true });
1048        ReportOrigin::RunMerge {
1049            op_id: Some("op-9".into()),
1050            worker_oid: Some("abc123".into()),
1051            integrated_oid: None,
1052        }
1053        .stamp(&mut merge);
1054        assert_eq!(
1055            merge["origin"],
1056            json!({ "kind": "run-merge", "op_id": "op-9", "worker_oid": "abc123" })
1057        );
1058
1059        // A bare run-merge (legacy unguarded path) omits the null OID fields.
1060        let mut bare = json!({ "success": true });
1061        ReportOrigin::RunMerge {
1062            op_id: None,
1063            worker_oid: None,
1064            integrated_oid: None,
1065        }
1066        .stamp(&mut bare);
1067        assert_eq!(bare["origin"], json!({ "kind": "run-merge" }));
1068    }
1069
1070    #[test]
1071    fn report_origin_absent_or_malformed_is_none() {
1072        // A legacy report with no origin field.
1073        assert_eq!(ReportOrigin::from_report(&json!({ "success": true })), None);
1074        // A malformed origin is treated as absent (conservative fallback), never
1075        // an error that could brick classification.
1076        assert_eq!(
1077            ReportOrigin::from_report(&json!({ "origin": "not-an-object" })),
1078            None
1079        );
1080        assert_eq!(
1081            ReportOrigin::from_report(&json!({ "origin": { "kind": "bogus" } })),
1082            None
1083        );
1084    }
1085
1086    #[test]
1087    fn report_origin_stamp_overwrites_a_supplied_value() {
1088        // The enforcement `node report` relies on: stamping Agent discards any
1089        // caller-supplied merge/supervisor origin.
1090        let mut report = json!({
1091            "success": true,
1092            "origin": { "kind": "run-merge", "op_id": "spoofed" }
1093        });
1094        ReportOrigin::Agent.stamp(&mut report);
1095        assert_eq!(
1096            ReportOrigin::from_report(&report),
1097            Some(ReportOrigin::Agent)
1098        );
1099    }
1100
1101    #[test]
1102    fn report_is_confirmed_merge_prefers_typed_origin() {
1103        // A RunMerge origin authorizes a merge even with NO legacy `via` string.
1104        let mut merged = json!({ "success": true });
1105        ReportOrigin::RunMerge {
1106            op_id: Some("op-1".into()),
1107            worker_oid: Some("abc".into()),
1108            integrated_oid: None,
1109        }
1110        .stamp(&mut merged);
1111        assert!(ReportOrigin::report_is_confirmed_merge(&merged));
1112
1113        // A bare RunMerge origin (legacy unguarded path, no OIDs) still counts.
1114        let mut bare = json!({ "success": true });
1115        ReportOrigin::RunMerge {
1116            op_id: None,
1117            worker_oid: None,
1118            integrated_oid: None,
1119        }
1120        .stamp(&mut bare);
1121        assert!(ReportOrigin::report_is_confirmed_merge(&bare));
1122    }
1123
1124    #[test]
1125    fn report_is_confirmed_merge_legacy_via_only_when_origin_absent() {
1126        // Legacy report (no origin field): the `via` marker is honored.
1127        assert!(ReportOrigin::report_is_confirmed_merge(&json!({
1128            "success": true, "via": "explicit-merge"
1129        })));
1130
1131        // Present-but-Agent origin + a forged `via`: NOT a merge. Merge authority
1132        // is the run-merge path; an agent report can't fabricate one on `via`.
1133        let mut agent = json!({ "success": true, "via": "explicit-merge" });
1134        ReportOrigin::Agent.stamp(&mut agent);
1135        assert!(
1136            !ReportOrigin::report_is_confirmed_merge(&agent),
1137            "an Agent-origin report must not be a merge even with a forged via"
1138        );
1139
1140        // Present-but-MALFORMED origin + a forged `via`: NOT a merge — a corrupt
1141        // origin field must not re-unlock the legacy via path.
1142        assert!(!ReportOrigin::report_is_confirmed_merge(&json!({
1143            "success": true, "via": "explicit-merge", "origin": "garbage-not-an-object"
1144        })));
1145        assert!(!ReportOrigin::report_is_confirmed_merge(&json!({
1146            "success": true, "via": "explicit-merge", "origin": { "kind": "bogus" }
1147        })));
1148    }
1149
1150    #[test]
1151    fn report_is_confirmed_merge_requires_success_and_not_cancelled() {
1152        // success:false with a merge marker is not a merge (malformed/spoofed).
1153        assert!(!ReportOrigin::report_is_confirmed_merge(&json!({
1154            "success": false, "via": "explicit-merge"
1155        })));
1156        // A RunMerge origin on a success:false report is likewise not a merge.
1157        let mut neg = json!({ "success": false });
1158        ReportOrigin::RunMerge {
1159            op_id: None,
1160            worker_oid: None,
1161            integrated_oid: None,
1162        }
1163        .stamp(&mut neg);
1164        assert!(!ReportOrigin::report_is_confirmed_merge(&neg));
1165        // A cancelled report never counts, even with a RunMerge origin riding along.
1166        let mut cancelled = json!({ "success": false, "cancelled": true, "reason": "x" });
1167        ReportOrigin::RunMerge {
1168            op_id: None,
1169            worker_oid: None,
1170            integrated_oid: None,
1171        }
1172        .stamp(&mut cancelled);
1173        assert!(!ReportOrigin::report_is_confirmed_merge(&cancelled));
1174        // Non-boolean success (strict typing) is not a merge.
1175        assert!(!ReportOrigin::report_is_confirmed_merge(&json!({
1176            "success": "true", "via": "explicit-merge"
1177        })));
1178    }
1179
1180    #[test]
1181    fn report_origin_stamp_on_non_object_is_noop() {
1182        let mut not_obj = json!([1, 2, 3]);
1183        ReportOrigin::Agent.stamp(&mut not_obj);
1184        assert_eq!(not_obj, json!([1, 2, 3]));
1185    }
1186
1187    #[test]
1188    fn wrap_up_must_be_string_array() {
1189        let v = json!({
1190            "success": true,
1191            "wrap_up_recommendations": ["ok", 42],
1192        });
1193        assert!(matches!(
1194            validate_report_payload(&v),
1195            Err(ReportValidationError::FieldElementNotString { index: 1, .. })
1196        ));
1197    }
1198
1199    // --- lenient advisory sanitization (issue `merge-report-schema-lenience`) ---
1200
1201    #[test]
1202    fn sanitize_clean_report_has_no_warnings() {
1203        let v = json!({
1204            "success": true,
1205            "summary": "did the thing",
1206            "discussion_items": [{"topic": "naming", "severity": "discuss"}],
1207            "spinoff_proposals": [
1208                {"proposed_title": "follow-up", "proposed_kind": "spinoff", "rationale": "later"},
1209            ],
1210            "wrap_up_recommendations": ["rebase"],
1211        });
1212        let out = sanitize_report_advisory(&v).unwrap();
1213        assert_eq!(out.warnings.len(), 0);
1214        assert_eq!(out.report, v);
1215    }
1216
1217    #[test]
1218    fn sanitize_drops_typoed_spinoff_proposal_with_warning() {
1219        // The exact glasspad-stint foot-gun: `title`/`detail` instead of the
1220        // schema's `proposed_title`/`proposed_kind`/`rationale`. Strict validation
1221        // would reject the whole report and block the merge; lenient drops the
1222        // proposal and warns.
1223        let v = json!({
1224            "success": true,
1225            "summary": "green, reviewed, committed",
1226            "spinoff_proposals": [{"title": "do X later", "detail": "because Y"}],
1227        });
1228        // Strict path rejects it (the behavior the issue is fixing).
1229        assert!(validate_report_payload(&v).is_err());
1230        // Lenient path merges: no error, proposal dropped, one warning.
1231        let out = sanitize_report_advisory(&v).unwrap();
1232        assert_eq!(out.warnings.len(), 1);
1233        assert_eq!(out.warnings[0].field, "spinoff_proposals");
1234        assert_eq!(out.warnings[0].index, Some(0));
1235        assert_eq!(out.report["spinoff_proposals"], json!([]));
1236        // Required + descriptive fields survive untouched.
1237        assert_eq!(out.report["success"], json!(true));
1238        assert_eq!(out.report["summary"], json!("green, reviewed, committed"));
1239    }
1240
1241    #[test]
1242    fn sanitize_keeps_valid_siblings_drops_only_bad_element() {
1243        let v = json!({
1244            "success": true,
1245            "spinoff_proposals": [
1246                {"proposed_title": "keep me", "proposed_kind": "spinoff"},
1247                {"title": "typo, drop me"},
1248                {"proposed_title": "keep me too", "proposed_kind": "research"},
1249            ],
1250        });
1251        let out = sanitize_report_advisory(&v).unwrap();
1252        assert_eq!(out.warnings.len(), 1);
1253        assert_eq!(out.warnings[0].index, Some(1));
1254        let kept = out.report["spinoff_proposals"].as_array().unwrap();
1255        assert_eq!(kept.len(), 2);
1256        assert_eq!(kept[0]["proposed_title"], json!("keep me"));
1257        assert_eq!(kept[1]["proposed_title"], json!("keep me too"));
1258    }
1259
1260    #[test]
1261    fn sanitize_drops_non_array_advisory_field_whole() {
1262        let v = json!({
1263            "success": true,
1264            "discussion_items": "not-an-array",
1265            "wrap_up_recommendations": {"oops": true},
1266        });
1267        let out = sanitize_report_advisory(&v).unwrap();
1268        assert_eq!(out.warnings.len(), 2);
1269        // Both malformed fields removed entirely.
1270        assert!(out.report.get("discussion_items").is_none());
1271        assert!(out.report.get("wrap_up_recommendations").is_none());
1272        let fields: Vec<&str> = out.warnings.iter().map(|w| w.field.as_str()).collect();
1273        assert!(fields.contains(&"discussion_items"));
1274        assert!(fields.contains(&"wrap_up_recommendations"));
1275        // A whole-field drop carries no element index.
1276        assert!(out.warnings.iter().all(|w| w.index.is_none()));
1277    }
1278
1279    #[test]
1280    fn sanitize_drops_non_string_wrap_up_element() {
1281        let v = json!({
1282            "success": true,
1283            "wrap_up_recommendations": ["rebase", 42, "squash"],
1284        });
1285        let out = sanitize_report_advisory(&v).unwrap();
1286        assert_eq!(out.warnings.len(), 1);
1287        assert_eq!(out.warnings[0].index, Some(1));
1288        assert_eq!(
1289            out.report["wrap_up_recommendations"],
1290            json!(["rebase", "squash"])
1291        );
1292    }
1293
1294    #[test]
1295    fn sanitize_drops_malformed_summary() {
1296        let v = json!({"success": true, "summary": 42});
1297        let out = sanitize_report_advisory(&v).unwrap();
1298        assert_eq!(out.warnings.len(), 1);
1299        assert_eq!(out.warnings[0].field, "summary");
1300        assert!(out.report.get("summary").is_none());
1301    }
1302
1303    #[test]
1304    fn sanitize_still_rejects_missing_required_success() {
1305        // Required-field strictness is preserved: no `success` → error, no merge.
1306        let v = json!({"summary": "no success field"});
1307        assert!(matches!(
1308            sanitize_report_advisory(&v),
1309            Err(ReportValidationError::MissingSuccess)
1310        ));
1311    }
1312
1313    #[test]
1314    fn sanitize_still_rejects_non_boolean_success() {
1315        let v = json!({"success": "yes", "spinoff_proposals": [{"title": "x"}]});
1316        assert!(matches!(
1317            sanitize_report_advisory(&v),
1318            Err(ReportValidationError::SuccessNotBoolean)
1319        ));
1320    }
1321
1322    #[test]
1323    fn sanitize_still_rejects_cancelled_contradiction() {
1324        // The §7.7 cross-constraint is correctness-bearing (it drives terminal
1325        // outcome), so it stays strict even in lenient mode.
1326        let v = json!({"success": true, "cancelled": true, "reason": "x"});
1327        assert!(matches!(
1328            sanitize_report_advisory(&v),
1329            Err(ReportValidationError::CancelledRequiresSuccessFalse)
1330        ));
1331    }
1332
1333    #[test]
1334    fn sanitize_rejects_non_object_root() {
1335        let v = json!([1, 2, 3]);
1336        assert!(matches!(
1337            sanitize_report_advisory(&v),
1338            Err(ReportValidationError::NotObject)
1339        ));
1340    }
1341
1342    #[test]
1343    fn sanitize_preserves_unknown_and_provenance_fields() {
1344        // The sanitizer is a SHAPE check, not a trust boundary: it must pass
1345        // through `origin`, `via`, and unknown agent keys untouched. (`run merge`
1346        // re-stamps the authoritative origin/via afterward — provenance trust is
1347        // the caller's job, per the doc contract.)
1348        let v = json!({
1349            "success": true,
1350            "origin": {"kind": "agent"},
1351            "via": "explicit-merge",
1352            "custom_agent_key": {"nested": [1, 2, 3]},
1353            "spinoff_proposals": [{"title": "typo, drop me"}],
1354        });
1355        let out = sanitize_report_advisory(&v).unwrap();
1356        assert_eq!(out.warnings.len(), 1, "only the bad proposal is dropped");
1357        assert_eq!(out.report["origin"], json!({"kind": "agent"}));
1358        assert_eq!(out.report["via"], json!("explicit-merge"));
1359        assert_eq!(out.report["custom_agent_key"], json!({"nested": [1, 2, 3]}));
1360    }
1361
1362    #[test]
1363    fn sanitize_nested_options_drops_whole_discussion_item() {
1364        // A malformed nested `options` drops the ENTIRE element (coarse by design),
1365        // taking the otherwise-valid `topic` with it. Documented behavior.
1366        let v = json!({
1367            "success": true,
1368            "discussion_items": [
1369                {"topic": "keep", "severity": "discuss"},
1370                {"topic": "drop me", "options": ["ok", 42]},
1371            ],
1372        });
1373        let out = sanitize_report_advisory(&v).unwrap();
1374        assert_eq!(out.warnings.len(), 1);
1375        assert_eq!(out.warnings[0].index, Some(1));
1376        let kept = out.report["discussion_items"].as_array().unwrap();
1377        assert_eq!(kept.len(), 1);
1378        assert_eq!(kept[0]["topic"], json!("keep"));
1379    }
1380
1381    #[test]
1382    fn advisory_warning_message_shapes() {
1383        let elem = AdvisoryWarning {
1384            field: "spinoff_proposals".to_string(),
1385            index: Some(2),
1386            reason: "boom".to_string(),
1387        };
1388        assert_eq!(elem.to_message(), "dropped spinoff_proposals[2]: boom");
1389        let whole = AdvisoryWarning {
1390            field: "discussion_items".to_string(),
1391            index: None,
1392            reason: "not an array".to_string(),
1393        };
1394        assert_eq!(
1395            whole.to_message(),
1396            "dropped advisory field `discussion_items`: not an array"
1397        );
1398    }
1399}