merry-runtime 0.1.0

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use crate::tool::proposal::ActionProposalError;
use serde::{Deserialize, Serialize};
use std::path::{Component, Path};

/// Per-file metadata for a constrained workspace patch change.
///
/// This stores only file identity, byte counts, and stable non-cryptographic
/// content fingerprints. It does not store old or new text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspacePatchChangeEvidence {
    pub(super) relative_path: String,
    pub(super) preimage_bytes: usize,
    pub(super) replacement_bytes: usize,
    pub(super) file_bytes_before: usize,
    pub(super) file_bytes_after: usize,
    pub(super) file_fingerprint_before: String,
    pub(super) file_fingerprint_after: String,
}

impl WorkspacePatchChangeEvidence {
    /// Creates validated metadata for one file change in a workspace patch.
    pub fn new(
        relative_path: impl Into<String>,
        preimage_bytes: usize,
        replacement_bytes: usize,
        file_bytes_before: usize,
        file_bytes_after: usize,
        file_fingerprint_before: impl Into<String>,
        file_fingerprint_after: impl Into<String>,
    ) -> Result<Self, ActionProposalError> {
        let relative_path = validate_apply_patch_path(relative_path.into())?;
        validate_apply_patch_counts(
            preimage_bytes,
            replacement_bytes,
            file_bytes_before,
            file_bytes_after,
        )?;
        let file_fingerprint_before = validate_apply_patch_fingerprint(
            "file_fingerprint_before",
            file_fingerprint_before.into(),
        )?;
        let file_fingerprint_after = validate_apply_patch_fingerprint(
            "file_fingerprint_after",
            file_fingerprint_after.into(),
        )?;

        Ok(Self {
            relative_path,
            preimage_bytes,
            replacement_bytes,
            file_bytes_before,
            file_bytes_after,
            file_fingerprint_before,
            file_fingerprint_after,
        })
    }

    /// Returns the changed path using `/` separators.
    ///
    /// The value stays workspace-relative while the change is below a configured
    /// root, and is the absolute path the caller named when it is not.
    #[must_use]
    pub fn relative_path(&self) -> &str {
        &self.relative_path
    }

    /// Returns the byte length of the matched preimage.
    #[must_use]
    pub fn preimage_bytes(&self) -> usize {
        self.preimage_bytes
    }

    /// Returns the byte length of the replacement text.
    #[must_use]
    pub fn replacement_bytes(&self) -> usize {
        self.replacement_bytes
    }

    /// Returns the file size immediately before replacement.
    #[must_use]
    pub fn file_bytes_before(&self) -> usize {
        self.file_bytes_before
    }

    /// Returns the file size observed after replacement was written and read back.
    #[must_use]
    pub fn file_bytes_after(&self) -> usize {
        self.file_bytes_after
    }

    /// Returns the stable non-cryptographic fingerprint before replacement.
    #[must_use]
    pub fn file_fingerprint_before(&self) -> &str {
        &self.file_fingerprint_before
    }

    /// Returns the stable non-cryptographic fingerprint after replacement.
    #[must_use]
    pub fn file_fingerprint_after(&self) -> &str {
        &self.file_fingerprint_after
    }
}

/// Execute-time metadata for a constrained workspace patch.
///
/// This stores one or more file changes. It intentionally does not store old or
/// new text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspacePatchExecutionEvidence {
    pub(super) changes: Vec<WorkspacePatchChangeEvidence>,
}

impl WorkspacePatchExecutionEvidence {
    /// Creates validated execute-time metadata for a single workspace patch.
    pub fn new(
        relative_path: impl Into<String>,
        preimage_bytes: usize,
        replacement_bytes: usize,
        file_bytes_before: usize,
        file_bytes_after: usize,
        file_fingerprint_before: impl Into<String>,
        file_fingerprint_after: impl Into<String>,
    ) -> Result<Self, ActionProposalError> {
        Self::from_changes(vec![WorkspacePatchChangeEvidence::new(
            relative_path,
            preimage_bytes,
            replacement_bytes,
            file_bytes_before,
            file_bytes_after,
            file_fingerprint_before,
            file_fingerprint_after,
        )?])
    }

    /// Creates execute-time metadata for a multi-file workspace patch.
    pub fn from_changes(
        changes: Vec<WorkspacePatchChangeEvidence>,
    ) -> Result<Self, ActionProposalError> {
        validate_apply_patch_changes(&changes)?;
        Ok(Self { changes })
    }

    /// Returns all file changes included in this patch.
    #[must_use]
    pub fn changes(&self) -> &[WorkspacePatchChangeEvidence] {
        &self.changes
    }

    pub(super) fn first_change(&self) -> &WorkspacePatchChangeEvidence {
        self.changes
            .first()
            .expect("workspace patch execution evidence always has at least one change")
    }

    /// Returns the first changed path using `/` separators.
    #[must_use]
    pub fn relative_path(&self) -> &str {
        self.first_change().relative_path()
    }

    /// Returns the byte length of the first matched preimage.
    #[must_use]
    pub fn preimage_bytes(&self) -> usize {
        self.first_change().preimage_bytes()
    }

    /// Returns the byte length of the first replacement text.
    #[must_use]
    pub fn replacement_bytes(&self) -> usize {
        self.first_change().replacement_bytes()
    }

    /// Returns the first file size immediately before replacement.
    #[must_use]
    pub fn file_bytes_before(&self) -> usize {
        self.first_change().file_bytes_before()
    }

    /// Returns the first file size observed after replacement was written and read back.
    #[must_use]
    pub fn file_bytes_after(&self) -> usize {
        self.first_change().file_bytes_after()
    }

    /// Returns the first stable non-cryptographic fingerprint before replacement.
    #[must_use]
    pub fn file_fingerprint_before(&self) -> &str {
        self.first_change().file_fingerprint_before()
    }

    /// Returns the first stable non-cryptographic fingerprint after replacement.
    #[must_use]
    pub fn file_fingerprint_after(&self) -> &str {
        self.first_change().file_fingerprint_after()
    }
}

/// Deterministic metadata for a constrained workspace patch proposal.
///
/// This stores one or more file changes needed for a future edit decision. It
/// does not store old text, new text, host absolute paths, or provider wire data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspacePatchProposal {
    pub(super) changes: Vec<WorkspacePatchChangeEvidence>,
}

impl WorkspacePatchProposal {
    /// Creates validated metadata for a workspace patch file change. New-file
    /// changes use an empty preimage and a zero-byte file state before writing.
    pub fn new(
        relative_path: impl Into<String>,
        preimage_bytes: usize,
        replacement_bytes: usize,
        file_bytes_before: usize,
        file_bytes_after: usize,
        file_fingerprint_before: impl Into<String>,
        file_fingerprint_after: impl Into<String>,
    ) -> Result<Self, ActionProposalError> {
        Self::from_changes(vec![WorkspacePatchChangeEvidence::new(
            relative_path,
            preimage_bytes,
            replacement_bytes,
            file_bytes_before,
            file_bytes_after,
            file_fingerprint_before,
            file_fingerprint_after,
        )?])
    }

    /// Creates proposal metadata for a multi-file workspace patch.
    pub fn from_changes(
        changes: Vec<WorkspacePatchChangeEvidence>,
    ) -> Result<Self, ActionProposalError> {
        validate_apply_patch_changes(&changes)?;
        Ok(Self { changes })
    }

    /// Returns all file changes included in this patch.
    #[must_use]
    pub fn changes(&self) -> &[WorkspacePatchChangeEvidence] {
        &self.changes
    }

    pub(super) fn first_change(&self) -> &WorkspacePatchChangeEvidence {
        self.changes
            .first()
            .expect("workspace patch proposal always has at least one change")
    }

    /// Returns the first changed path using `/` separators.
    #[must_use]
    pub fn relative_path(&self) -> &str {
        self.first_change().relative_path()
    }

    /// Returns the byte length of the first matched preimage.
    #[must_use]
    pub fn preimage_bytes(&self) -> usize {
        self.first_change().preimage_bytes()
    }

    /// Returns the byte length of the first replacement text.
    #[must_use]
    pub fn replacement_bytes(&self) -> usize {
        self.first_change().replacement_bytes()
    }

    /// Returns the first file size before replacement.
    #[must_use]
    pub fn file_bytes_before(&self) -> usize {
        self.first_change().file_bytes_before()
    }

    /// Returns the first projected file size after replacement.
    #[must_use]
    pub fn file_bytes_after(&self) -> usize {
        self.first_change().file_bytes_after()
    }

    /// Returns the first stable non-cryptographic fingerprint before replacement.
    #[must_use]
    pub fn file_fingerprint_before(&self) -> &str {
        self.first_change().file_fingerprint_before()
    }

    /// Returns the first projected stable non-cryptographic fingerprint after replacement.
    #[must_use]
    pub fn file_fingerprint_after(&self) -> &str {
        self.first_change().file_fingerprint_after()
    }
}

pub(super) fn validate_apply_patch_changes(
    changes: &[WorkspacePatchChangeEvidence],
) -> Result<(), ActionProposalError> {
    if changes.is_empty() {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field: "changes",
            reason: "must contain at least one file change",
        });
    }
    Ok(())
}

pub(super) fn validate_apply_patch_counts(
    preimage_bytes: usize,
    replacement_bytes: usize,
    file_bytes_before: usize,
    file_bytes_after: usize,
) -> Result<(), ActionProposalError> {
    if preimage_bytes == 0 && file_bytes_before != 0 {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field: "preimage_bytes",
            reason: "must be greater than zero unless the file is new",
        });
    }

    let expected_after = file_bytes_before
        .checked_sub(preimage_bytes)
        .and_then(|unchanged| unchanged.checked_add(replacement_bytes))
        .ok_or(ActionProposalError::InvalidWorkspacePatch {
            field: "file_bytes_after",
            reason: "must be consistent with before, preimage, and replacement byte counts",
        })?;
    if expected_after != file_bytes_after {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field: "file_bytes_after",
            reason: "must equal file_bytes_before - preimage_bytes + replacement_bytes",
        });
    }

    Ok(())
}

pub(super) fn validate_apply_patch_fingerprint(
    field: &'static str,
    value: String,
) -> Result<String, ActionProposalError> {
    if value.trim().is_empty() {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field,
            reason: "must not be blank",
        });
    }
    if value.len() > 128 {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field,
            reason: "exceeds the byte limit",
        });
    }
    let Some((algorithm, digest)) = value.split_once(':') else {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field,
            reason: "must include an algorithm prefix",
        });
    };
    if algorithm != "fnv1a64" {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field,
            reason: "must use the fnv1a64 fingerprint prefix",
        });
    }
    if digest.len() != 16 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field,
            reason: "must include 16 hexadecimal digest characters",
        });
    }

    Ok(value)
}

pub(super) const MAX_WORKSPACE_PATCH_RELATIVE_PATH_BYTES: usize = 4096;

/// Validates the path a patch change reports.
///
/// The value is the workspace-relative path of the change, or its absolute path
/// when the change is outside every configured workspace root. Both forms are
/// accepted because a patch tool may name a file the sandbox exposes rather than
/// one below a root. What is rejected is ambiguity: blank text, control
/// characters, empty segments, and dot segments that would make two different
/// spellings of one target compare unequal.
pub(super) fn validate_apply_patch_path(value: String) -> Result<String, ActionProposalError> {
    if value.trim().is_empty() {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field: "relative_path",
            reason: "must not be blank",
        });
    }
    if value.len() > MAX_WORKSPACE_PATCH_RELATIVE_PATH_BYTES {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field: "relative_path",
            reason: "exceeds the byte limit",
        });
    }
    if value.chars().any(char::is_control) {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field: "relative_path",
            reason: "must not contain control characters",
        });
    }

    let path = Path::new(&value);
    // A leading `/` is the root of an absolute path, not an empty segment.
    let segments = value.strip_prefix('/').unwrap_or(&value);
    if segments.split('/').any(str::is_empty) {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field: "relative_path",
            reason: "must not contain empty path segments",
        });
    }
    if !path.is_absolute() && value.starts_with('\\') {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field: "relative_path",
            reason: "must use `/` separators",
        });
    }

    let mut saw_component = false;
    for component in path.components() {
        match component {
            Component::Normal(value) => {
                if value.to_str().is_none() {
                    return Err(ActionProposalError::InvalidWorkspacePatch {
                        field: "relative_path",
                        reason: "components must be UTF-8",
                    });
                }
                saw_component = true;
            }
            Component::CurDir | Component::ParentDir => {
                return Err(ActionProposalError::InvalidWorkspacePatch {
                    field: "relative_path",
                    reason: "must not contain dot segments",
                });
            }
            // An absolute anchor is how a change outside every configured root
            // is named, so it is part of a valid path rather than a violation.
            Component::RootDir | Component::Prefix(_) => {}
        }
    }

    if !saw_component {
        return Err(ActionProposalError::InvalidWorkspacePatch {
            field: "relative_path",
            reason: "must name a file",
        });
    }

    Ok(value)
}