merry-tools 0.1.1

Workspace file, search, patch, web fetch, and document tools for the Merry agent runtime.
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use super::*;
use crate::{
    errors::{
        ALL_WORKSPACE_ERROR_CODES, ERROR_FILE_ALREADY_EXISTS, ERROR_FILE_NOT_FOUND,
        ERROR_FILE_TOO_LARGE, ERROR_IMAGE_TOO_LARGE, ERROR_INVALID_ARGUMENTS,
        ERROR_INVALID_DOCUMENT, ERROR_INVALID_IMAGE, ERROR_NOT_DIRECTORY, ERROR_NOT_FILE,
        ERROR_NOT_UTF8, ERROR_PATCH_NOOP, ERROR_PATCH_SYNTAX, ERROR_PATH_DENIED,
        ERROR_PREIMAGE_ABSENT, ERROR_PREIMAGE_AMBIGUOUS, ERROR_PROPOSAL_MISMATCH,
        ERROR_READ_FAILED, ERROR_WRITE_FAILED, WORKSPACE_PATCH_PLAN_CHANGED_MESSAGE,
        WORKSPACE_PATH_CONTRACT,
    },
    patch::{
        ApplyPatchExecutor, ApplyPatchInput, apply_patch_blocking, apply_patch_blocking_checked,
        propose_apply_patch_blocking_checked, stable_content_fingerprint,
    },
    path::validate_workspace_path_argument,
    read::{ReadFileExecutor, ReadFileInput, read_file_blocking},
    trace::{
        TRACE_PATH_MAX_CHARS, bounded_trace_text, install_patch_test_after_write_hook,
        install_patch_test_before_mutation_hook, install_trace_start_test_hook,
    },
};
use merry_core::{
    PendingToolCall, ToolCallArguments, ToolCallId, ToolCallResultStatus, ToolName, ToolOutputKind,
    ToolSpec,
};
use merry_runtime::{ActionExecutionEvidence, ToolConcurrency, ToolExecutionError};
use merry_runtime::{
    ActionProposal, ActionProposalEvidence, ToolActionKind, ToolActionPreflight,
    ToolExecutionContext, ToolExecutionOutcome, ToolExecutor,
};
use serde_json::{Value, json};
use std::{
    cell::Cell,
    env,
    ffi::OsStr,
    fs::{self, File},
    future::Future,
    io::Write,
    sync::{Arc as StdArc, Mutex as StdMutex, OnceLock as StdOnceLock},
    time::{SystemTime, UNIX_EPOCH},
};
use std::{
    path::{Path, PathBuf},
    sync::Arc,
};

#[cfg(unix)]
use std::os::unix::fs::symlink;

fn trace_output_buffer() -> &'static StdArc<StdMutex<Vec<u8>>> {
    #[derive(Clone)]
    struct Buffer(StdArc<StdMutex<Vec<u8>>>);

    impl std::io::Write for Buffer {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0
                .lock()
                .expect("buffer mutex should not be poisoned")
                .extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    static TRACE_OUTPUT: StdOnceLock<StdArc<StdMutex<Vec<u8>>>> = StdOnceLock::new();
    TRACE_OUTPUT.get_or_init(|| {
        use tracing_subscriber::{fmt, prelude::*};

        let bytes = StdArc::new(StdMutex::new(Vec::new()));
        let writer_bytes = StdArc::clone(&bytes);
        let subscriber = tracing_subscriber::registry().with(
            fmt::layer()
                .json()
                .with_writer(move || Buffer(StdArc::clone(&writer_bytes))),
        );
        tracing::subscriber::set_global_default(subscriber)
            .expect("test tracing subscriber should install once");
        bytes
    })
}

async fn capture_traces_for<F, R>(trace_marker: &str, future: F) -> (R, String)
where
    F: Future<Output = R>,
{
    let bytes = StdArc::clone(trace_output_buffer());
    let start = bytes
        .lock()
        .expect("buffer mutex should not be poisoned")
        .len();
    let result = future.await;
    let text = {
        let guard = bytes.lock().expect("buffer mutex should not be poisoned");
        String::from_utf8(guard[start..].to_vec()).expect("trace output should be UTF-8")
    };
    let text = text
        .lines()
        .filter(|line| line.contains(trace_marker))
        .collect::<Vec<_>>()
        .join("\n");
    (result, text)
}

struct TempWorkspace {
    root: PathBuf,
}

impl TempWorkspace {
    fn new(name: &str) -> Self {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system clock is after unix epoch")
            .as_nanos();
        let root = env::temp_dir().join(format!(
            "merry-tools-{name}-{}-{unique}",
            std::process::id()
        ));
        fs::create_dir_all(&root).expect("temp workspace should be created");
        Self { root }
    }

    fn path(&self) -> &Path {
        &self.root
    }

    fn write_text(&self, relative: &str, content: &str) {
        let path = self.root.join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("parent directory should be created");
        }
        fs::write(path, content).expect("text file should be written");
    }

    fn write_bytes(&self, relative: &str, content: &[u8]) {
        let path = self.root.join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("parent directory should be created");
        }
        let mut file = File::create(path).expect("binary file should be created");
        file.write_all(content)
            .expect("binary file should be written");
    }
}

impl Drop for TempWorkspace {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.root);
    }
}

fn tools_for(root: &Path) -> WorkspaceTools {
    WorkspaceTools::new(WorkspaceToolsConfig::new(root.to_path_buf()))
        .expect("workspace tools should construct")
}

#[test]
fn workspace_tool_schemas_describe_bounded_file_operations() {
    fn assert_fields(spec: ToolSpec, fields: &[&str]) {
        let value = serde_json::to_value(spec.input_schema().as_schema())
            .expect("workspace schema should serialize");
        for field in fields {
            assert!(
                !value["properties"][*field]["description"]
                    .as_str()
                    .unwrap_or_default()
                    .is_empty(),
                "missing workspace field description for {field}"
            );
        }
    }

    assert_fields(
        read_file_spec_default(),
        &["path", "start_line", "max_lines", "pages", "format"],
    );
    assert_fields(apply_patch_spec(), &["patch"]);

    let read_schema = serde_json::to_value(read_file_spec_default().input_schema().as_schema())
        .expect("read schema should serialize");
    let patch_schema = serde_json::to_value(apply_patch_spec().input_schema().as_schema())
        .expect("patch schema should serialize");
    assert_eq!(read_schema["properties"]["path"]["minLength"], 1);
    assert_eq!(read_schema["properties"]["start_line"]["minimum"], 1);
    assert_eq!(read_schema["properties"]["max_lines"]["minimum"], 1);
    assert_eq!(read_schema["properties"]["max_lines"]["maximum"], 2_000);
    assert_eq!(patch_schema["properties"]["patch"]["minLength"], 1);
}

#[test]
fn workspace_schemas_project_session_limits() {
    let temp = TempWorkspace::new("schema-limits");
    let limits = WorkspaceToolLimits {
        max_read_lines: 17,
        max_patch_bytes: 29,
        ..WorkspaceToolLimits::default()
    };
    let tools = WorkspaceTools::new(
        WorkspaceToolsConfig::new(temp.path().to_path_buf()).with_limits(limits),
    )
    .expect("workspace tools should construct");
    let registered = tools.into_registered_tools_with_patch();
    let read = registered
        .iter()
        .find(|tool| tool.spec().name().as_str() == READ_FILE_TOOL)
        .expect("read_file tool should be registered");
    let patch = registered
        .iter()
        .find(|tool| tool.spec().name().as_str() == APPLY_PATCH_TOOL)
        .expect("apply_patch tool should be registered");
    let read_schema = read.spec().input_schema().as_schema().as_value();
    let patch_schema = patch.spec().input_schema().as_schema().as_value();

    fn has_constraint(schema: &Value, keyword: &str, expected: &Value) -> bool {
        if schema.get(keyword) == Some(expected) {
            return true;
        }
        ["anyOf", "oneOf", "allOf"].iter().any(|branch_keyword| {
            schema
                .get(*branch_keyword)
                .and_then(Value::as_array)
                .is_some_and(|branches| {
                    branches
                        .iter()
                        .any(|branch| has_constraint(branch, keyword, expected))
                })
        })
    }

    assert!(has_constraint(
        &read_schema["properties"]["max_lines"],
        "maximum",
        &json!(17)
    ));
    assert_eq!(patch_schema["properties"]["patch"]["maxLength"], 29);
}

fn read_outcome(tools: &WorkspaceTools, path: &str) -> ToolExecutionOutcome {
    read_file_blocking(
        &tools.state,
        ReadFileInput {
            path: path.to_owned(),
            start_line: None,
            max_lines: None,
            pages: None,
            format: None,
        },
    )
}

fn patch_outcome(
    tools: &WorkspaceTools,
    path: &str,
    old_text: &str,
    new_text: &str,
) -> ToolExecutionOutcome {
    apply_patch_blocking(
        &tools.state,
        ApplyPatchInput {
            patch: update_patch(path, old_text, new_text),
        },
    )
}

fn patch_text_outcome(tools: &WorkspaceTools, patch: &str) -> ToolExecutionOutcome {
    apply_patch_blocking(
        &tools.state,
        ApplyPatchInput {
            patch: patch.to_owned(),
        },
    )
}

fn patch_proposal(
    tools: &WorkspaceTools,
    path: &str,
    old_text: &str,
    new_text: &str,
) -> Option<ActionProposal> {
    match patch_preflight(tools, path, old_text, new_text) {
        ToolActionPreflight::Proposal(proposal) => Some(proposal),
        ToolActionPreflight::NoProposal | ToolActionPreflight::Outcome(_) => None,
    }
}

fn patch_preflight(
    tools: &WorkspaceTools,
    path: &str,
    old_text: &str,
    new_text: &str,
) -> ToolActionPreflight {
    let patch = update_patch(path, old_text, new_text);
    let call = pending_call_for(
        APPLY_PATCH_TOOL,
        json!({
            "patch": patch
        }),
    );
    propose_apply_patch_blocking_checked(&tools.state, ApplyPatchInput { patch }, &call, &|| false)
        .expect("uncancelled workspace patch proposal should not return cancellation")
}

fn update_patch(path: &str, old_text: &str, new_text: &str) -> String {
    format!(
        "*** Begin Workspace Patch\n*** Update File: {path}\n-{old_text}\n+{new_text}\n*** End Workspace Patch"
    )
}

fn add_patch(path: &str, lines: &[&str]) -> String {
    let additions = lines
        .iter()
        .map(|line| format!("+{line}"))
        .collect::<Vec<_>>()
        .join("\n");
    format!("*** Begin Workspace Patch\n*** Add File: {path}\n{additions}\n*** End Workspace Patch")
}

fn delete_patch(path: &str) -> String {
    format!("*** Begin Workspace Patch\n*** Delete File: {path}\n*** End Workspace Patch")
}

fn delete_preflight(tools: &WorkspaceTools, path: &str) -> ToolActionPreflight {
    let patch = delete_patch(path);
    let call = pending_call_for(
        APPLY_PATCH_TOOL,
        json!({
            "patch": patch
        }),
    );
    propose_apply_patch_blocking_checked(&tools.state, ApplyPatchInput { patch }, &call, &|| false)
        .expect("uncancelled workspace patch proposal should not return cancellation")
}

fn add_patch_preflight(tools: &WorkspaceTools, path: &str, lines: &[&str]) -> ToolActionPreflight {
    let patch = add_patch(path, lines);
    let call = pending_call_for(
        APPLY_PATCH_TOOL,
        json!({
            "patch": patch
        }),
    );
    propose_apply_patch_blocking_checked(&tools.state, ApplyPatchInput { patch }, &call, &|| false)
        .expect("uncancelled workspace patch proposal should not return cancellation")
}

fn json_content(outcome: &ToolExecutionOutcome) -> Value {
    serde_json::from_str(outcome.content().as_str()).expect("tool outcome should be JSON")
}

fn assert_failed_json(
    outcome: &ToolExecutionOutcome,
    code: &str,
    path: Option<&str>,
    host_root: &Path,
) {
    assert_failed_json_for_tool(outcome, READ_FILE_TOOL, code, path, host_root);
}

fn assert_failed_json_for_tool(
    outcome: &ToolExecutionOutcome,
    tool: &str,
    code: &str,
    path: Option<&str>,
    host_root: &Path,
) {
    assert_eq!(outcome.status(), ToolCallResultStatus::Failed);
    assert_eq!(outcome.content().kind(), ToolOutputKind::Json);
    assert_eq!(outcome.diagnostic().expect("diagnostic").code(), code);

    let payload = json_content(outcome);
    assert_eq!(payload["ok"], false);
    assert_eq!(payload["tool"], tool);
    assert_eq!(payload["error"]["code"], code);
    let expected_recovery = expected_recovery_for_code(code)
        .unwrap_or_else(|| panic!("{code} must declare its expected recovery"));
    if expected_recovery.path_contract {
        assert_eq!(
            payload["recovery"]["path_contract"],
            WORKSPACE_PATH_CONTRACT
        );
    } else {
        assert!(
            payload.get("recovery").is_none(),
            "patch-text failures must not repeat the workspace path contract"
        );
    }
    if let Some(expected_guidance_kind) = expected_recovery.guidance_kind {
        assert_eq!(payload["guidance"]["kind"], expected_guidance_kind);
        assert!(
            payload["guidance"]["message"]
                .as_str()
                .expect("guidance should be text")
                .len()
                > 20,
            "guidance should contain an actionable model hint"
        );
    } else {
        assert!(
            payload.get("guidance").is_none(),
            "unexpected guidance for {code}"
        );
    }
    if let Some(path) = path {
        assert_eq!(payload["path"], path);
    } else {
        assert!(
            payload.get("path").is_none(),
            "failure payload should omit path"
        );
    }

    assert!(
        !outcome
            .content()
            .as_str()
            .contains(host_root.to_str().expect("temp path utf8")),
        "tool output must not include absolute host roots"
    );
}

/// Model-facing recovery block a failure code must produce.
///
/// The expectation lives here as data per code. Restating it instead of
/// re-running the production classifier keeps the assertion able to fail: a
/// classifier that moved a code into the wrong class would still agree with
/// itself.
struct ExpectedRecovery {
    path_contract: bool,
    guidance_kind: Option<&'static str>,
}

/// Returns the declared expectation for one code, or `None` when none exists.
///
/// The match names constants instead of literals, so an expectation for a code
/// that no longer exists cannot compile. The `None` arm is what makes
/// `every_workspace_error_code_declares_its_recovery` fail when a new code is
/// declared without its own expectation.
fn expected_recovery_for_code(code: &str) -> Option<ExpectedRecovery> {
    match code {
        ERROR_INVALID_ARGUMENTS => Some(ExpectedRecovery {
            path_contract: true,
            guidance_kind: Some("workspace_invalid_arguments"),
        }),
        ERROR_PATCH_SYNTAX => Some(ExpectedRecovery {
            path_contract: false,
            guidance_kind: Some("apply_patch_syntax"),
        }),
        ERROR_PATCH_NOOP => Some(ExpectedRecovery {
            path_contract: false,
            guidance_kind: Some("apply_patch_noop"),
        }),
        ERROR_PREIMAGE_ABSENT | ERROR_PREIMAGE_AMBIGUOUS => Some(ExpectedRecovery {
            path_contract: false,
            guidance_kind: Some("apply_patch_preimage_mismatch"),
        }),
        ERROR_PROPOSAL_MISMATCH => Some(ExpectedRecovery {
            path_contract: true,
            guidance_kind: Some("apply_patch_plan_changed"),
        }),
        ERROR_PATH_DENIED
        | ERROR_FILE_NOT_FOUND
        | ERROR_FILE_ALREADY_EXISTS
        | ERROR_NOT_FILE
        | ERROR_NOT_DIRECTORY => Some(ExpectedRecovery {
            path_contract: true,
            guidance_kind: Some("workspace_path_recovery"),
        }),
        ERROR_FILE_TOO_LARGE => Some(ExpectedRecovery {
            path_contract: true,
            guidance_kind: Some("workspace_file_too_large"),
        }),
        ERROR_IMAGE_TOO_LARGE => Some(ExpectedRecovery {
            path_contract: true,
            guidance_kind: Some("workspace_image_too_large"),
        }),
        // These codes explain the path contract without guidance text of their
        // own, because a failure can be about where a path points and a failed
        // read or write has no model-facing recovery step beyond retrying.
        ERROR_NOT_UTF8
        | ERROR_INVALID_IMAGE
        | ERROR_INVALID_DOCUMENT
        | ERROR_READ_FAILED
        | ERROR_WRITE_FAILED => Some(ExpectedRecovery {
            path_contract: true,
            guidance_kind: None,
        }),
        _ => None,
    }
}

#[test]
fn every_workspace_error_code_declares_its_recovery() {
    for declared in ALL_WORKSPACE_ERROR_CODES {
        assert!(
            expected_recovery_for_code(declared.code).is_some(),
            "{} ({}) needs an explicit expected recovery entry",
            declared.name,
            declared.code
        );
    }
}

fn assert_no_provider_visible_patch_metadata(outcome: &ToolExecutionOutcome) {
    let text = outcome.content().as_str();
    for forbidden in [
        "approved workspace patch",
        "fingerprint",
        "proposal",
        "fnv1a64",
        "file_fingerprint_before",
        "file_fingerprint_after",
    ] {
        assert!(
            !text.contains(forbidden),
            "provider-visible patch output leaked {forbidden}: {text}"
        );
    }
    if let Some(diagnostic) = outcome.diagnostic() {
        assert_eq!(
            diagnostic.message(),
            WORKSPACE_PATCH_PLAN_CHANGED_MESSAGE,
            "patch mismatch diagnostic should stay neutral"
        );
        let diagnostic_text = format!("{} {}", diagnostic.code(), diagnostic.message());
        for forbidden in [
            "approved workspace patch",
            "fingerprint",
            "proposal",
            "fnv1a64",
            "file_fingerprint_before",
            "file_fingerprint_after",
        ] {
            assert!(
                !diagnostic_text.contains(forbidden),
                "provider-visible patch diagnostic leaked {forbidden}: {diagnostic_text}"
            );
        }
    }
}

fn pending_call(arguments: Value) -> PendingToolCall {
    pending_call_for(READ_FILE_TOOL, arguments)
}

fn pending_call_with_id(tool: &str, call_id: &str, arguments: Value) -> PendingToolCall {
    let arguments = ToolCallArguments::try_from(arguments).expect("arguments object");
    PendingToolCall::new(
        ToolCallId::new(call_id).expect("valid call id"),
        ToolName::new(tool).expect("valid tool name"),
        arguments,
    )
}

fn pending_call_for(tool: &str, arguments: Value) -> PendingToolCall {
    pending_call_with_id(tool, "call-1", arguments)
}

fn assert_invalid_arguments_trace(
    outcome: ToolExecutionOutcome,
    logs: &str,
    tool_name: &str,
    tool_call_id: &str,
) {
    assert_eq!(outcome.status(), ToolCallResultStatus::Failed);
    assert_eq!(
        outcome.diagnostic().expect("diagnostic").code(),
        ERROR_INVALID_ARGUMENTS
    );
    assert!(logs.contains("\"event\":\"runtime.workspace_tool.finish\""));
    assert!(logs.contains("\"status\":\"failed\""));
    assert!(logs.contains("\"diagnostic_code\":\"workspace_invalid_arguments\""));
    assert!(logs.contains(&format!("\"tool_name\":\"{tool_name}\"")));
    assert!(logs.contains(&format!("\"tool_call_id\":\"{tool_call_id}\"")));
    assert!(!logs.contains("sensitive invalid payload"));
}

fn read_text(path: &Path) -> String {
    fs::read_to_string(path).expect("workspace text file should be readable")
}

static TRACE_START_CANCEL_TOKEN: StdOnceLock<
    StdMutex<Option<tokio_util::sync::CancellationToken>>,
> = StdOnceLock::new();

fn install_trace_start_cancellation_token(token: tokio_util::sync::CancellationToken) {
    TRACE_START_CANCEL_TOKEN
        .get_or_init(|| StdMutex::new(None))
        .lock()
        .expect("trace start cancel token mutex should not be poisoned")
        .replace(token);
}

fn cancel_trace_start_token() {
    let Some(slot) = TRACE_START_CANCEL_TOKEN.get() else {
        return;
    };
    let token = slot
        .lock()
        .expect("trace start cancel token mutex should not be poisoned")
        .take();
    if let Some(token) = token {
        token.cancel();
    }
}

mod config;
mod model_content;
mod office;
mod patch;
mod patch_policy;
mod read;
mod trace;
mod workspace_path;

fn read_file_spec_default() -> ToolSpec {
    crate::read::spec(&WorkspaceToolLimits::default()).expect("valid read tool schema")
}

fn apply_patch_spec() -> ToolSpec {
    crate::patch::spec(&WorkspaceToolLimits::default()).expect("valid patch tool schema")
}