Skip to main content

merry_runtime/tool/
patch_evidence.rs

1use crate::tool::proposal::ActionProposalError;
2use serde::{Deserialize, Serialize};
3use std::path::{Component, Path};
4
5/// Per-file metadata for a constrained workspace patch change.
6///
7/// This stores only file identity, byte counts, and stable non-cryptographic
8/// content fingerprints. It does not store old or new text.
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(deny_unknown_fields)]
11pub struct WorkspacePatchChangeEvidence {
12    pub(super) relative_path: String,
13    pub(super) preimage_bytes: usize,
14    pub(super) replacement_bytes: usize,
15    pub(super) file_bytes_before: usize,
16    pub(super) file_bytes_after: usize,
17    pub(super) file_fingerprint_before: String,
18    pub(super) file_fingerprint_after: String,
19}
20
21impl WorkspacePatchChangeEvidence {
22    /// Creates validated metadata for one file change in a workspace patch.
23    pub fn new(
24        relative_path: impl Into<String>,
25        preimage_bytes: usize,
26        replacement_bytes: usize,
27        file_bytes_before: usize,
28        file_bytes_after: usize,
29        file_fingerprint_before: impl Into<String>,
30        file_fingerprint_after: impl Into<String>,
31    ) -> Result<Self, ActionProposalError> {
32        let relative_path = validate_apply_patch_path(relative_path.into())?;
33        validate_apply_patch_counts(
34            preimage_bytes,
35            replacement_bytes,
36            file_bytes_before,
37            file_bytes_after,
38        )?;
39        let file_fingerprint_before = validate_apply_patch_fingerprint(
40            "file_fingerprint_before",
41            file_fingerprint_before.into(),
42        )?;
43        let file_fingerprint_after = validate_apply_patch_fingerprint(
44            "file_fingerprint_after",
45            file_fingerprint_after.into(),
46        )?;
47
48        Ok(Self {
49            relative_path,
50            preimage_bytes,
51            replacement_bytes,
52            file_bytes_before,
53            file_bytes_after,
54            file_fingerprint_before,
55            file_fingerprint_after,
56        })
57    }
58
59    /// Returns the changed path using `/` separators.
60    ///
61    /// The value stays workspace-relative while the change is below a configured
62    /// root, and is the absolute path the caller named when it is not.
63    #[must_use]
64    pub fn relative_path(&self) -> &str {
65        &self.relative_path
66    }
67
68    /// Returns the byte length of the matched preimage.
69    #[must_use]
70    pub fn preimage_bytes(&self) -> usize {
71        self.preimage_bytes
72    }
73
74    /// Returns the byte length of the replacement text.
75    #[must_use]
76    pub fn replacement_bytes(&self) -> usize {
77        self.replacement_bytes
78    }
79
80    /// Returns the file size immediately before replacement.
81    #[must_use]
82    pub fn file_bytes_before(&self) -> usize {
83        self.file_bytes_before
84    }
85
86    /// Returns the file size observed after replacement was written and read back.
87    #[must_use]
88    pub fn file_bytes_after(&self) -> usize {
89        self.file_bytes_after
90    }
91
92    /// Returns the stable non-cryptographic fingerprint before replacement.
93    #[must_use]
94    pub fn file_fingerprint_before(&self) -> &str {
95        &self.file_fingerprint_before
96    }
97
98    /// Returns the stable non-cryptographic fingerprint after replacement.
99    #[must_use]
100    pub fn file_fingerprint_after(&self) -> &str {
101        &self.file_fingerprint_after
102    }
103}
104
105/// Execute-time metadata for a constrained workspace patch.
106///
107/// This stores one or more file changes. It intentionally does not store old or
108/// new text.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(deny_unknown_fields)]
111pub struct WorkspacePatchExecutionEvidence {
112    pub(super) changes: Vec<WorkspacePatchChangeEvidence>,
113}
114
115impl WorkspacePatchExecutionEvidence {
116    /// Creates validated execute-time metadata for a single workspace patch.
117    pub fn new(
118        relative_path: impl Into<String>,
119        preimage_bytes: usize,
120        replacement_bytes: usize,
121        file_bytes_before: usize,
122        file_bytes_after: usize,
123        file_fingerprint_before: impl Into<String>,
124        file_fingerprint_after: impl Into<String>,
125    ) -> Result<Self, ActionProposalError> {
126        Self::from_changes(vec![WorkspacePatchChangeEvidence::new(
127            relative_path,
128            preimage_bytes,
129            replacement_bytes,
130            file_bytes_before,
131            file_bytes_after,
132            file_fingerprint_before,
133            file_fingerprint_after,
134        )?])
135    }
136
137    /// Creates execute-time metadata for a multi-file workspace patch.
138    pub fn from_changes(
139        changes: Vec<WorkspacePatchChangeEvidence>,
140    ) -> Result<Self, ActionProposalError> {
141        validate_apply_patch_changes(&changes)?;
142        Ok(Self { changes })
143    }
144
145    /// Returns all file changes included in this patch.
146    #[must_use]
147    pub fn changes(&self) -> &[WorkspacePatchChangeEvidence] {
148        &self.changes
149    }
150
151    pub(super) fn first_change(&self) -> &WorkspacePatchChangeEvidence {
152        self.changes
153            .first()
154            .expect("workspace patch execution evidence always has at least one change")
155    }
156
157    /// Returns the first changed path using `/` separators.
158    #[must_use]
159    pub fn relative_path(&self) -> &str {
160        self.first_change().relative_path()
161    }
162
163    /// Returns the byte length of the first matched preimage.
164    #[must_use]
165    pub fn preimage_bytes(&self) -> usize {
166        self.first_change().preimage_bytes()
167    }
168
169    /// Returns the byte length of the first replacement text.
170    #[must_use]
171    pub fn replacement_bytes(&self) -> usize {
172        self.first_change().replacement_bytes()
173    }
174
175    /// Returns the first file size immediately before replacement.
176    #[must_use]
177    pub fn file_bytes_before(&self) -> usize {
178        self.first_change().file_bytes_before()
179    }
180
181    /// Returns the first file size observed after replacement was written and read back.
182    #[must_use]
183    pub fn file_bytes_after(&self) -> usize {
184        self.first_change().file_bytes_after()
185    }
186
187    /// Returns the first stable non-cryptographic fingerprint before replacement.
188    #[must_use]
189    pub fn file_fingerprint_before(&self) -> &str {
190        self.first_change().file_fingerprint_before()
191    }
192
193    /// Returns the first stable non-cryptographic fingerprint after replacement.
194    #[must_use]
195    pub fn file_fingerprint_after(&self) -> &str {
196        self.first_change().file_fingerprint_after()
197    }
198}
199
200/// Deterministic metadata for a constrained workspace patch proposal.
201///
202/// This stores one or more file changes needed for a future edit decision. It
203/// does not store old text, new text, host absolute paths, or provider wire data.
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205#[serde(deny_unknown_fields)]
206pub struct WorkspacePatchProposal {
207    pub(super) changes: Vec<WorkspacePatchChangeEvidence>,
208}
209
210impl WorkspacePatchProposal {
211    /// Creates validated metadata for a workspace patch file change. New-file
212    /// changes use an empty preimage and a zero-byte file state before writing.
213    pub fn new(
214        relative_path: impl Into<String>,
215        preimage_bytes: usize,
216        replacement_bytes: usize,
217        file_bytes_before: usize,
218        file_bytes_after: usize,
219        file_fingerprint_before: impl Into<String>,
220        file_fingerprint_after: impl Into<String>,
221    ) -> Result<Self, ActionProposalError> {
222        Self::from_changes(vec![WorkspacePatchChangeEvidence::new(
223            relative_path,
224            preimage_bytes,
225            replacement_bytes,
226            file_bytes_before,
227            file_bytes_after,
228            file_fingerprint_before,
229            file_fingerprint_after,
230        )?])
231    }
232
233    /// Creates proposal metadata for a multi-file workspace patch.
234    pub fn from_changes(
235        changes: Vec<WorkspacePatchChangeEvidence>,
236    ) -> Result<Self, ActionProposalError> {
237        validate_apply_patch_changes(&changes)?;
238        Ok(Self { changes })
239    }
240
241    /// Returns all file changes included in this patch.
242    #[must_use]
243    pub fn changes(&self) -> &[WorkspacePatchChangeEvidence] {
244        &self.changes
245    }
246
247    pub(super) fn first_change(&self) -> &WorkspacePatchChangeEvidence {
248        self.changes
249            .first()
250            .expect("workspace patch proposal always has at least one change")
251    }
252
253    /// Returns the first changed path using `/` separators.
254    #[must_use]
255    pub fn relative_path(&self) -> &str {
256        self.first_change().relative_path()
257    }
258
259    /// Returns the byte length of the first matched preimage.
260    #[must_use]
261    pub fn preimage_bytes(&self) -> usize {
262        self.first_change().preimage_bytes()
263    }
264
265    /// Returns the byte length of the first replacement text.
266    #[must_use]
267    pub fn replacement_bytes(&self) -> usize {
268        self.first_change().replacement_bytes()
269    }
270
271    /// Returns the first file size before replacement.
272    #[must_use]
273    pub fn file_bytes_before(&self) -> usize {
274        self.first_change().file_bytes_before()
275    }
276
277    /// Returns the first projected file size after replacement.
278    #[must_use]
279    pub fn file_bytes_after(&self) -> usize {
280        self.first_change().file_bytes_after()
281    }
282
283    /// Returns the first stable non-cryptographic fingerprint before replacement.
284    #[must_use]
285    pub fn file_fingerprint_before(&self) -> &str {
286        self.first_change().file_fingerprint_before()
287    }
288
289    /// Returns the first projected stable non-cryptographic fingerprint after replacement.
290    #[must_use]
291    pub fn file_fingerprint_after(&self) -> &str {
292        self.first_change().file_fingerprint_after()
293    }
294}
295
296pub(super) fn validate_apply_patch_changes(
297    changes: &[WorkspacePatchChangeEvidence],
298) -> Result<(), ActionProposalError> {
299    if changes.is_empty() {
300        return Err(ActionProposalError::InvalidWorkspacePatch {
301            field: "changes",
302            reason: "must contain at least one file change",
303        });
304    }
305    Ok(())
306}
307
308pub(super) fn validate_apply_patch_counts(
309    preimage_bytes: usize,
310    replacement_bytes: usize,
311    file_bytes_before: usize,
312    file_bytes_after: usize,
313) -> Result<(), ActionProposalError> {
314    if preimage_bytes == 0 && file_bytes_before != 0 {
315        return Err(ActionProposalError::InvalidWorkspacePatch {
316            field: "preimage_bytes",
317            reason: "must be greater than zero unless the file is new",
318        });
319    }
320
321    let expected_after = file_bytes_before
322        .checked_sub(preimage_bytes)
323        .and_then(|unchanged| unchanged.checked_add(replacement_bytes))
324        .ok_or(ActionProposalError::InvalidWorkspacePatch {
325            field: "file_bytes_after",
326            reason: "must be consistent with before, preimage, and replacement byte counts",
327        })?;
328    if expected_after != file_bytes_after {
329        return Err(ActionProposalError::InvalidWorkspacePatch {
330            field: "file_bytes_after",
331            reason: "must equal file_bytes_before - preimage_bytes + replacement_bytes",
332        });
333    }
334
335    Ok(())
336}
337
338pub(super) fn validate_apply_patch_fingerprint(
339    field: &'static str,
340    value: String,
341) -> Result<String, ActionProposalError> {
342    if value.trim().is_empty() {
343        return Err(ActionProposalError::InvalidWorkspacePatch {
344            field,
345            reason: "must not be blank",
346        });
347    }
348    if value.len() > 128 {
349        return Err(ActionProposalError::InvalidWorkspacePatch {
350            field,
351            reason: "exceeds the byte limit",
352        });
353    }
354    let Some((algorithm, digest)) = value.split_once(':') else {
355        return Err(ActionProposalError::InvalidWorkspacePatch {
356            field,
357            reason: "must include an algorithm prefix",
358        });
359    };
360    if algorithm != "fnv1a64" {
361        return Err(ActionProposalError::InvalidWorkspacePatch {
362            field,
363            reason: "must use the fnv1a64 fingerprint prefix",
364        });
365    }
366    if digest.len() != 16 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
367        return Err(ActionProposalError::InvalidWorkspacePatch {
368            field,
369            reason: "must include 16 hexadecimal digest characters",
370        });
371    }
372
373    Ok(value)
374}
375
376pub(super) const MAX_WORKSPACE_PATCH_RELATIVE_PATH_BYTES: usize = 4096;
377
378/// Validates the path a patch change reports.
379///
380/// The value is the workspace-relative path of the change, or its absolute path
381/// when the change is outside every configured workspace root. Both forms are
382/// accepted because a patch tool may name a file the sandbox exposes rather than
383/// one below a root. What is rejected is ambiguity: blank text, control
384/// characters, empty segments, and dot segments that would make two different
385/// spellings of one target compare unequal.
386pub(super) fn validate_apply_patch_path(value: String) -> Result<String, ActionProposalError> {
387    if value.trim().is_empty() {
388        return Err(ActionProposalError::InvalidWorkspacePatch {
389            field: "relative_path",
390            reason: "must not be blank",
391        });
392    }
393    if value.len() > MAX_WORKSPACE_PATCH_RELATIVE_PATH_BYTES {
394        return Err(ActionProposalError::InvalidWorkspacePatch {
395            field: "relative_path",
396            reason: "exceeds the byte limit",
397        });
398    }
399    if value.chars().any(char::is_control) {
400        return Err(ActionProposalError::InvalidWorkspacePatch {
401            field: "relative_path",
402            reason: "must not contain control characters",
403        });
404    }
405
406    let path = Path::new(&value);
407    // A leading `/` is the root of an absolute path, not an empty segment.
408    let segments = value.strip_prefix('/').unwrap_or(&value);
409    if segments.split('/').any(str::is_empty) {
410        return Err(ActionProposalError::InvalidWorkspacePatch {
411            field: "relative_path",
412            reason: "must not contain empty path segments",
413        });
414    }
415    if !path.is_absolute() && value.starts_with('\\') {
416        return Err(ActionProposalError::InvalidWorkspacePatch {
417            field: "relative_path",
418            reason: "must use `/` separators",
419        });
420    }
421
422    let mut saw_component = false;
423    for component in path.components() {
424        match component {
425            Component::Normal(value) => {
426                if value.to_str().is_none() {
427                    return Err(ActionProposalError::InvalidWorkspacePatch {
428                        field: "relative_path",
429                        reason: "components must be UTF-8",
430                    });
431                }
432                saw_component = true;
433            }
434            Component::CurDir | Component::ParentDir => {
435                return Err(ActionProposalError::InvalidWorkspacePatch {
436                    field: "relative_path",
437                    reason: "must not contain dot segments",
438                });
439            }
440            // An absolute anchor is how a change outside every configured root
441            // is named, so it is part of a valid path rather than a violation.
442            Component::RootDir | Component::Prefix(_) => {}
443        }
444    }
445
446    if !saw_component {
447        return Err(ActionProposalError::InvalidWorkspacePatch {
448            field: "relative_path",
449            reason: "must name a file",
450        });
451    }
452
453    Ok(value)
454}