返回 CodeWhale
pandoc.rs
根目录 / crates / engine / src / tools / pandoc.rs
1 //! `pandoc_convert` tool — universal document conversion via the
2 //! `pandoc` binary (<https://pandoc.org>).
3 //!
4 //! Pandoc is the de-facto Swiss Army knife for moving prose between
5 //! the formats writers and engineers actually use: Markdown to HTML,
6 //! HTML to Markdown, anything to LaTeX or DOCX, RST to Markdown,
7 //! ReST imports, etc. Surfacing it as a model-callable tool unblocks
8 //! a large class of "rewrite this report as ..." / "publish this
9 //! changelog as ..." workflows that previously required the user
10 //! to drop into a terminal between turns.
11 //!
12 //! Registration is gated by [`codewhale_dependencies::resolve_pandoc`]
13 //! (see [`crate::tools::registry::ToolRegistryBuilder::with_pandoc_tools`]).
14 //! When pandoc isn't installed the tool simply doesn't appear in the
15 //! catalog, so the model never sees a binary it can't actually use.
16 //!
17 //! ## Format whitelist
18 //!
19 //! Pandoc supports ~30 input and ~50 output formats, and exposing
20 //! every one of them as a free-text string would let the model
21 //! ask for `pdf` (which needs LaTeX installed), `epub3` (works
22 //! everywhere but ambiguous vs. `epub`), or typos like `markown`.
23 //! The whitelist below is the curated subset that a) covers ~95%
24 //! of real document-handling needs and b) doesn't require additional
25 //! system dependencies (LaTeX engines, ImageMagick) beyond pandoc
26 //! itself.
27 //!
28 //! Adding a format: append to [`SUPPORTED_TARGET_FORMATS`] and the
29 //! schema description; the dispatch logic is whitelist-driven so
30 //! anything in the list goes through unchanged.
31
32 use std::ffi::OsString;
33 use std::path::{Path, PathBuf};
34 use std::process::Stdio;
35 use std::time::Duration;
36
37 use async_trait::async_trait;
38 use serde_json::{Value, json};
39 use tokio::process::Command as TokioCommand;
40
41 use super::file::{reject_primitive_unknown, run_blocking_write_atomic};
42 use super::spec::{
43 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
44 optional_str, required_str,
45 };
46
47 /// Curated whitelist of pandoc target formats. Each entry corresponds
48 /// to a `--to=<format>` value pandoc accepts natively without
49 /// additional system tooling. Keep this list short and intentional —
50 /// the schema description below references it verbatim.
51 pub const SUPPORTED_TARGET_FORMATS: &[&str] = &[
52 "markdown", // Pandoc-flavored Markdown (the safe round-trip default)
53 "gfm", // GitHub-Flavored Markdown
54 "commonmark", // strict CommonMark
55 "html", // HTML5
56 "rst", // reStructuredText
57 "latex", // LaTeX source (does not require a TeX install to *generate*)
58 "docx", // Microsoft Word .docx
59 "odt", // OpenDocument Text
60 "epub", // EPUB 2/3
61 "plain", // plain text (formatting stripped)
62 "asciidoc", // AsciiDoc
63 ];
64
65 /// Wall-clock bound for one pandoc conversion: a pathological document
66 /// (giant epub, pathological LaTeX) would otherwise hold the call for as
67 /// long as pandoc felt like taking.
68 const PANDOC_TIMEOUT: Duration = Duration::from_secs(600);
69
70 /// Bound for the one-shot `pandoc --version` probe. A probe that cannot
71 /// finish in 10s means the binary itself is wedged; like an unparseable
72 /// banner, the gate then lets the conversion through and pandoc reports
73 /// any flag it does not know itself.
74 const PANDOC_VERSION_PROBE_TIMEOUT: Duration = Duration::from_secs(10);
75
76 /// Tool implementing `pandoc_convert`. Converts a source file into
77 /// a target format and either writes the output to disk or returns
78 /// the converted text inline.
79 pub struct PandocConvertTool;
80
81 #[async_trait]
82 impl ToolSpec for PandocConvertTool {
83 fn name(&self) -> &'static str {
84 "pandoc_convert"
85 }
86
87 fn description(&self) -> &'static str {
88 "Convert a document between formats via pandoc. Reads `source_path` (any pandoc-supported input format — pandoc autodetects from extension), converts to `target_format`, and either writes the result to `output_path` (when provided) or returns the converted text inline. Supported targets: markdown, gfm, commonmark, html, rst, latex, docx, odt, epub, plain, asciidoc. Use this instead of shelling out to pandoc via `bash` — no approval prompt for output_path-less reads, structured errors, and a curated format whitelist."
89 }
90
91 fn input_schema(&self) -> Value {
92 json!({
93 "type": "object",
94 "properties": {
95 "source_path": {
96 "type": "string",
97 "description": "Path to the source document (relative to workspace or absolute). Pandoc autodetects the input format from the file extension."
98 },
99 "target_format": {
100 "type": "string",
101 "description": "One of: markdown, gfm, commonmark, html, rst, latex, docx, odt, epub, plain, asciidoc.",
102 "enum": SUPPORTED_TARGET_FORMATS,
103 },
104 "output_path": {
105 "type": "string",
106 "description": "Optional path to write the converted document to. When omitted, the converted text is returned inline (text formats only — binary formats like docx/odt/epub require output_path)."
107 }
108 },
109 "required": ["source_path", "target_format"]
110 })
111 }
112
113 fn capabilities(&self) -> Vec<ToolCapability> {
114 vec![
115 ToolCapability::WritesFiles,
116 ToolCapability::Sandboxable,
117 ToolCapability::RequiresApproval,
118 ]
119 }
120
121 fn approval_requirement(&self) -> ApprovalRequirement {
122 ApprovalRequirement::Suggest
123 }
124
125 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
126 reject_primitive_unknown(
127 &input,
128 "pandoc_convert",
129 &["source_path", "target_format", "output_path"],
130 )?;
131 let source_path_str = required_str(&input, "source_path")?;
132 let target_format = required_str(&input, "target_format")?.trim().to_lowercase();
133 let output_path_str = optional_str(&input, "output_path")?;
134
135 if !SUPPORTED_TARGET_FORMATS.contains(&target_format.as_str()) {
136 return Err(ToolError::invalid_input(format!(
137 "unsupported target_format `{target_format}`. Pick one of: {}",
138 SUPPORTED_TARGET_FORMATS.join(", ")
139 )));
140 }
141
142 let plan = crate::tools::file::resolve_read_open_plan(
143 context,
144 source_path_str,
145 "pandoc_convert",
146 false,
147 false,
148 )
149 .await?;
150 let source_path = plan.file_path.clone();
151 let (source_bytes, verified_fd_path) =
152 crate::tools::file::open_and_read_verified_bytes(plan, None, true, "Failed to read")
153 .await?
154 .ok_or_else(|| {
155 ToolError::execution_failed(format!(
156 "source_path does not exist: {}",
157 source_path.display()
158 ))
159 })?;
160
161 let resolved_output_path: Option<PathBuf> = match output_path_str {
162 Some(p) => Some(context.resolve_path(p)?),
163 None => None,
164 };
165
166 // Binary formats can't round-trip through stdout reliably —
167 // require an output_path so the bytes survive the trip.
168 if resolved_output_path.is_none() && format_is_binary(&target_format) {
169 return Err(ToolError::invalid_input(format!(
170 "target_format `{target_format}` is binary; provide an `output_path` to write the converted file."
171 )));
172 }
173
174 // Resolve the pandoc binary at execution time too — registration
175 // gated on resolve_pandoc(), but a concurrent uninstall between
176 // catalog build and the model's call should produce a clear
177 // error rather than the cryptic "program not found" from raw
178 // Command::spawn.
179 let pandoc = codewhale_dependencies::resolve_pandoc().ok_or_else(|| {
180 ToolError::execution_failed(
181 "pandoc_convert: pandoc binary not found on PATH. \
182 Install pandoc 2.15 or newer (macOS: `brew install pandoc`; \
183 Linux: the release package from https://pandoc.org/installing.html, \
184 since older distro packages predate 2.15; \
185 Windows: `winget install JohnMacFarlane.Pandoc`) and restart codewhale.",
186 )
187 })?;
188 require_sandbox_support(&pandoc).await?;
189
190 let staging = if resolved_output_path.is_some() {
191 Some(
192 tempfile::Builder::new()
193 .prefix("codewhale-pandoc-")
194 .tempdir()
195 .map_err(|e| {
196 ToolError::execution_failed(format!(
197 "failed to prepare pandoc output staging: {e}"
198 ))
199 })?,
200 )
201 } else {
202 None
203 };
204 let staged_output = staging.as_ref().map(|dir| dir.path().join("converted"));
205
206 let staged_source_path = source_path.clone();
207 let staged_input = tokio::task::spawn_blocking(move || {
208 stage_pandoc_input_sync(&source_bytes, &verified_fd_path, &staged_source_path)
209 })
210 .await
211 .map_err(|e| {
212 ToolError::execution_failed(format!("pandoc input staging worker failed: {e}"))
213 })??;
214
215 let mut cmd = TokioCommand::new(&pandoc);
216 cmd.args(pandoc_args(
217 &staged_input,
218 &target_format,
219 staged_output.as_deref(),
220 ));
221 // Kill the converter if the timeout below drops the output()
222 // future: pandoc on a pathological document would otherwise keep
223 // running orphaned after the call already failed.
224 cmd.kill_on_drop(true);
225 cmd.stdin(Stdio::null())
226 .stdout(Stdio::piped())
227 .stderr(Stdio::piped());
228
229 let output = tokio::time::timeout(PANDOC_TIMEOUT, cmd.output())
230 .await
231 .map_err(|_| ToolError::Timeout {
232 seconds: PANDOC_TIMEOUT.as_secs(),
233 })?
234 .map_err(|e| ToolError::execution_failed(format!("failed to launch pandoc: {e}")))?;
235
236 if !output.status.success() {
237 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
238 return Err(ToolError::execution_failed(format!(
239 "pandoc failed (exit {:?}): {stderr}",
240 output.status.code()
241 )));
242 }
243
244 let summary = if let Some(out) = resolved_output_path {
245 let staged = staged_output.as_deref().ok_or_else(|| {
246 ToolError::execution_failed("pandoc output staging was not prepared")
247 })?;
248 let converted = tokio::fs::read(staged).await.map_err(|e| {
249 ToolError::execution_failed(format!("failed to read pandoc output: {e}"))
250 })?;
251 run_blocking_write_atomic(&out, converted).await?;
252 format!(
253 "Converted {} → {} via pandoc; wrote {}",
254 source_path.display(),
255 target_format,
256 out.display()
257 )
258 } else {
259 let text = String::from_utf8_lossy(&output.stdout).to_string();
260 return Ok(ToolResult::success(text));
261 };
262 Ok(ToolResult::success(summary))
263 }
264 }
265
266 /// First pandoc release that understands `--sandbox`.
267 const MIN_SANDBOX_VERSION: (u32, u32) = (2, 15);
268
269 /// Arguments for one conversion. `--sandbox` stops readers and writers from
270 /// touching any file but the named source and output: no include
271 /// directives, no embedded images or other resources fetched from disk or
272 /// the network. It is always present; a pandoc without it is refused by
273 /// [`require_sandbox_support`] rather than run without it.
274 fn pandoc_args(source: &Path, target_format: &str, output: Option<&Path>) -> Vec<OsString> {
275 let mut args: Vec<OsString> = vec![
276 "--sandbox".into(),
277 source.as_os_str().to_owned(),
278 "--to".into(),
279 target_format.into(),
280 ];
281 if let Some(out) = output {
282 args.push("--output".into());
283 args.push(out.as_os_str().to_owned());
284 }
285 args
286 }
287
288 /// Parse `major.minor` from the first line of `pandoc --version`
289 /// (`pandoc 3.1.9`, `pandoc.exe 2.9.2.1`).
290 fn parse_pandoc_version(banner: &str) -> Option<(u32, u32)> {
291 let version = banner.lines().next()?.split_whitespace().nth(1)?;
292 let mut parts = version.split('.');
293 let major = parts.next()?.parse().ok()?;
294 let minor = parts.next().map_or(Some(0), |m| m.parse().ok())?;
295 Some((major, minor))
296 }
297
298 /// Refuse a pandoc older than 2.15 with an actionable message instead of
299 /// pandoc's own "Unknown option --sandbox". The version probe runs once per
300 /// process; an unparseable banner — or a probe that outlives its bound — is
301 /// let through, and pandoc itself then rejects the flag if it does not know
302 /// it. The child is async and kill-on-drop so a wedged `--version` can
303 /// neither block the executor nor outlive the probe.
304 async fn require_sandbox_support(pandoc: &str) -> Result<(), ToolError> {
305 static VERSION: tokio::sync::OnceCell<Option<(u32, u32)>> = tokio::sync::OnceCell::const_new();
306 let version = *VERSION
307 .get_or_init(|| async {
308 let mut cmd = TokioCommand::new(pandoc);
309 cmd.arg("--version")
310 .stdin(Stdio::null())
311 .stdout(Stdio::piped())
312 .stderr(Stdio::null())
313 .kill_on_drop(true);
314 let out = tokio::time::timeout(PANDOC_VERSION_PROBE_TIMEOUT, cmd.output())
315 .await
316 .ok()?
317 .ok()?;
318 parse_pandoc_version(&String::from_utf8_lossy(&out.stdout))
319 })
320 .await;
321 match version {
322 Some(found) if found < MIN_SANDBOX_VERSION => Err(ToolError::execution_failed(format!(
323 "pandoc_convert: pandoc {}.{} or newer is required (found {}.{}). \
324 Upgrade from https://pandoc.org/installing.html and restart codewhale.",
325 MIN_SANDBOX_VERSION.0, MIN_SANDBOX_VERSION.1, found.0, found.1
326 ))),
327 _ => Ok(()),
328 }
329 }
330
331 /// Whitelist of target formats whose output is binary (and therefore
332 /// can't be returned as inline text). `docx`, `odt`, and `epub` are
333 /// ZIP archives; everything else in [`SUPPORTED_TARGET_FORMATS`]
334 /// renders to UTF-8 text.
335 pub fn format_is_binary(target_format: &str) -> bool {
336 matches!(target_format, "docx" | "odt" | "epub")
337 }
338
339 fn stage_pandoc_input_sync(
340 source_bytes: &[u8],
341 verified_fd_path: &Path,
342 source_path: &Path,
343 ) -> Result<tempfile::TempPath, ToolError> {
344 use std::io::Write as _;
345
346 let ext_suffix = verified_fd_path
347 .extension()
348 .or_else(|| source_path.extension())
349 .and_then(|ext| ext.to_str())
350 .filter(|ext| {
351 !ext.is_empty()
352 && ext
353 .chars()
354 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
355 })
356 .map(|ext| format!(".{ext}"))
357 .unwrap_or_default();
358 let mut staged = tempfile::Builder::new()
359 .prefix("codewhale-pandoc-in-")
360 .suffix(&ext_suffix)
361 .tempfile()
362 .map_err(|e| {
363 ToolError::execution_failed(format!("failed to prepare pandoc input staging: {e}"))
364 })?;
365 staged.write_all(source_bytes).map_err(|e| {
366 ToolError::execution_failed(format!("failed to write staged pandoc input: {e}"))
367 })?;
368 staged.flush().map_err(|e| {
369 ToolError::execution_failed(format!("failed to flush staged pandoc input: {e}"))
370 })?;
371 Ok(staged.into_temp_path())
372 }
373
374 #[cfg(test)]
375 mod tests {
376 use super::*;
377 use std::fs;
378 use tempfile::tempdir;
379
380 fn pandoc_present() -> bool {
381 codewhale_dependencies::resolve_pandoc().is_some()
382 }
383
384 fn pandoc_environment_unavailable(err: &ToolError) -> bool {
385 let msg = err.to_string();
386 msg.contains("getXdgDirectory") || msg.contains("sHGetFolderPath")
387 }
388
389 // Test-only skip diagnostic; the module-wide print_stderr deny targets prod code.
390 #[allow(clippy::print_stderr)]
391 async fn execute_pandoc_or_skip(input: Value, ctx: &ToolContext) -> Option<ToolResult> {
392 match PandocConvertTool.execute(input, ctx).await {
393 Ok(result) => Some(result),
394 Err(err) if pandoc_environment_unavailable(&err) => {
395 eprintln!("skipping pandoc integration assertion: {err}");
396 None
397 }
398 Err(err) => panic!("execute: {err:?}"),
399 }
400 }
401
402 #[test]
403 fn supported_target_formats_match_schema_enum() {
404 let tool = PandocConvertTool;
405 let schema = tool.input_schema();
406 let enum_vals = schema
407 .get("properties")
408 .and_then(|p| p.get("target_format"))
409 .and_then(|t| t.get("enum"))
410 .and_then(|e| e.as_array())
411 .expect("target_format enum must be present in schema");
412 let from_schema: Vec<&str> = enum_vals.iter().filter_map(|v| v.as_str()).collect();
413 assert_eq!(
414 from_schema, SUPPORTED_TARGET_FORMATS,
415 "schema enum must mirror the SUPPORTED_TARGET_FORMATS constant exactly",
416 );
417 }
418
419 #[test]
420 fn binary_formats_require_output_path() {
421 for fmt in ["docx", "odt", "epub"] {
422 assert!(format_is_binary(fmt));
423 }
424 for fmt in [
425 "markdown",
426 "html",
427 "rst",
428 "latex",
429 "plain",
430 "gfm",
431 "commonmark",
432 ] {
433 assert!(!format_is_binary(fmt));
434 }
435 }
436
437 #[tokio::test]
438 async fn pandoc_convert_refuses_deny_listed_sources() {
439 // `.env` is on the default read deny-list; the refusal comes before
440 // pandoc would run, so this holds with or without pandoc installed.
441 let tmp = tempdir().expect("tempdir");
442 fs::write(tmp.path().join(".env"), "TOKEN=SECRET_PANDOC_VALUE\n").unwrap();
443 #[cfg(unix)]
444 std::os::unix::fs::symlink(tmp.path().join(".env"), tmp.path().join("notes.md")).unwrap();
445 let ctx = ToolContext::new(tmp.path().to_path_buf());
446 let mut sources = vec![".env"];
447 if cfg!(unix) {
448 sources.push("notes.md");
449 }
450 for source in sources {
451 let err = PandocConvertTool
452 .execute(
453 json!({"source_path": source, "target_format": "plain"}),
454 &ctx,
455 )
456 .await
457 .expect_err("a deny-listed source must be refused");
458 assert!(
459 matches!(err, ToolError::PermissionDenied { .. }),
460 "{source}: {err:?}"
461 );
462 assert!(!err.to_string().contains("SECRET_PANDOC_VALUE"));
463 }
464 }
465
466 #[tokio::test]
467 async fn pandoc_convert_does_not_follow_include_directives() {
468 if !pandoc_present() {
469 return;
470 }
471 let outside = tempdir().expect("outside");
472 let secret = outside.path().join("outside.txt");
473 fs::write(&secret, "SECRET_INCLUDED_VALUE\n").unwrap();
474 let tmp = tempdir().expect("tempdir");
475 fs::write(
476 tmp.path().join("p.rst"),
477 format!("Intro\n\n.. include:: {}\n", secret.display()),
478 )
479 .unwrap();
480 let ctx = ToolContext::new(tmp.path().to_path_buf());
481 let result = PandocConvertTool
482 .execute(
483 json!({"source_path": "p.rst", "target_format": "plain"}),
484 &ctx,
485 )
486 .await;
487 if let Err(err) = &result
488 && pandoc_environment_unavailable(err)
489 {
490 return;
491 }
492 if let Ok(result) = result {
493 assert!(
494 !result.content.contains("SECRET_INCLUDED_VALUE"),
495 "include directive must not pull in outside files: {}",
496 result.content
497 );
498 }
499 }
500
501 #[test]
502 fn pandoc_args_always_include_sandbox() {
503 for output in [None, Some(Path::new("/w/out.docx"))] {
504 let args = pandoc_args(Path::new("/w/in.md"), "docx", output);
505 assert_eq!(
506 args.first().map(OsString::as_os_str),
507 Some("--sandbox".as_ref())
508 );
509 assert_eq!(args.iter().filter(|a| *a == "--sandbox").count(), 1);
510 }
511 }
512
513 #[test]
514 fn pandoc_version_gate_matches_sandbox_release() {
515 assert_eq!(
516 parse_pandoc_version("pandoc 2.9.2.1\nCompiled with"),
517 Some((2, 9))
518 );
519 assert_eq!(parse_pandoc_version("pandoc.exe 3.1.9\n"), Some((3, 1)));
520 assert_eq!(parse_pandoc_version("pandoc 3\n"), Some((3, 0)));
521 assert_eq!(parse_pandoc_version("garbage"), None);
522 assert!((2, 9) < MIN_SANDBOX_VERSION);
523 assert!((2, 14) < MIN_SANDBOX_VERSION);
524 assert!((2, 15) >= MIN_SANDBOX_VERSION);
525 assert!((3, 0) >= MIN_SANDBOX_VERSION);
526 }
527
528 // Both invocations are bounded in time; a conversion that outlives its
529 // budget is answered with ToolError::Timeout and its child killed, but
530 // exercising that path would need a wedged `pandoc` injected past the
531 // process-global resolve_pandoc() cache, so the bounds are pinned here
532 // instead.
533 #[test]
534 fn pandoc_invocations_carry_time_bounds() {
535 assert_eq!(PANDOC_TIMEOUT, Duration::from_secs(600));
536 assert_eq!(PANDOC_VERSION_PROBE_TIMEOUT, Duration::from_secs(10));
537 assert!(
538 PANDOC_VERSION_PROBE_TIMEOUT < PANDOC_TIMEOUT,
539 "a wedged version probe must fail fast, not ride the conversion budget"
540 );
541 }
542
543 #[tokio::test]
544 async fn pandoc_convert_rejects_unsupported_target_format() {
545 let tmp = tempdir().expect("tempdir");
546 let src = tmp.path().join("in.md");
547 fs::write(&src, "# hi").unwrap();
548 let ctx = ToolContext::new(tmp.path().to_path_buf());
549 let err = PandocConvertTool
550 .execute(
551 json!({"source_path": "in.md", "target_format": "definitely-not-real"}),
552 &ctx,
553 )
554 .await
555 .expect_err("unsupported target format must reject before pandoc spawn");
556 assert!(
557 err.to_string().contains("unsupported target_format"),
558 "error must call out the unsupported format; got {err}"
559 );
560 }
561
562 #[tokio::test]
563 async fn pandoc_convert_rejects_inline_request_for_binary_format() {
564 let tmp = tempdir().expect("tempdir");
565 let src = tmp.path().join("in.md");
566 fs::write(&src, "# hi").unwrap();
567 let ctx = ToolContext::new(tmp.path().to_path_buf());
568 let err = PandocConvertTool
569 .execute(
570 json!({"source_path": "in.md", "target_format": "docx"}),
571 &ctx,
572 )
573 .await
574 .expect_err("missing output_path for docx must reject");
575 assert!(
576 err.to_string().contains("binary") && err.to_string().contains("output_path"),
577 "error must explain why output_path is required; got {err}"
578 );
579 }
580
581 #[tokio::test]
582 async fn pandoc_convert_roundtrips_markdown_to_html_inline() {
583 if !pandoc_present() {
584 // Tool wouldn't be registered without pandoc; mirror the
585 // catalog-build behaviour.
586 return;
587 }
588 let tmp = tempdir().expect("tempdir");
589 let src = tmp.path().join("note.md");
590 fs::write(&src, "# Title\n\nA paragraph with `inline code`.\n").unwrap();
591 let ctx = ToolContext::new(tmp.path().to_path_buf());
592 let Some(result) = execute_pandoc_or_skip(
593 json!({"source_path": "note.md", "target_format": "html"}),
594 &ctx,
595 )
596 .await
597 else {
598 return;
599 };
600 assert!(result.success);
601 assert!(
602 result.content.contains("<h1") && result.content.contains("Title"),
603 "html output must contain the heading; got {}",
604 result.content
605 );
606 assert!(
607 result.content.contains("<code") || result.content.contains("inline code"),
608 "html output must preserve inline code; got {}",
609 result.content
610 );
611 }
612
613 #[tokio::test]
614 async fn pandoc_convert_writes_output_path_and_reports_summary() {
615 if !pandoc_present() {
616 return;
617 }
618 let tmp = tempdir().expect("tempdir");
619 let src = tmp.path().join("note.md");
620 fs::write(&src, "# Title\n").unwrap();
621 let ctx = ToolContext::new(tmp.path().to_path_buf());
622 let Some(result) = execute_pandoc_or_skip(
623 json!({
624 "source_path": "note.md",
625 "target_format": "html",
626 "output_path": "out.html",
627 }),
628 &ctx,
629 )
630 .await
631 else {
632 return;
633 };
634 assert!(result.success);
635 assert!(result.content.contains("wrote"));
636 let written = fs::read_to_string(tmp.path().join("out.html")).expect("read");
637 assert!(
638 written.contains("Title"),
639 "written file must contain converted body; got {written}"
640 );
641 }
642
643 #[tokio::test]
644 async fn pandoc_convert_surfaces_missing_source_path_clearly() {
645 let tmp = tempdir().expect("tempdir");
646 let ctx = ToolContext::new(tmp.path().to_path_buf());
647 let err = PandocConvertTool
648 .execute(
649 json!({"source_path": "missing.md", "target_format": "html"}),
650 &ctx,
651 )
652 .await
653 .expect_err("nonexistent source must reject");
654 assert!(
655 err.to_string().contains("source_path") && err.to_string().contains("does not exist"),
656 "error must call out missing source; got {err}"
657 );
658 }
659
660 #[test]
661 fn stage_pandoc_input_preserves_extension_and_verified_bytes() {
662 let md =
663 stage_pandoc_input_sync(b"# Hello\n", Path::new("/tmp/doc.md"), Path::new("doc.md"))
664 .expect("stage md");
665 assert_eq!(md.extension().and_then(|e| e.to_str()), Some("md"));
666 assert_eq!(fs::read(&md).expect("read staged md"), b"# Hello\n");
667
668 let rst = stage_pandoc_input_sync(
669 b"Title\n=====\n",
670 Path::new("/tmp/noext"),
671 Path::new("spec.rst"),
672 )
673 .expect("stage rst fallback");
674 assert_eq!(rst.extension().and_then(|e| e.to_str()), Some("rst"));
675 assert_eq!(fs::read(&rst).expect("read staged rst"), b"Title\n=====\n");
676
677 let plain = stage_pandoc_input_sync(b"plain", Path::new("/tmp/plain"), Path::new("plain"))
678 .expect("stage extensionless");
679 assert_eq!(plain.extension(), None);
680 assert_eq!(fs::read(&plain).expect("read staged plain"), b"plain");
681 }
682
683 #[tokio::test]
684 async fn pandoc_convert_refuses_read_only_root_and_outside_hardlink() {
685 let workspace = tempdir().expect("workspace");
686 let ro_root = tempdir().expect("read-only root");
687 let ro_file = ro_root.path().join("guide.md");
688 fs::write(&ro_file, "# guide\n").expect("write ro");
689 let ro_canon = ro_root.path().canonicalize().expect("canon ro");
690 let ctx = ToolContext::new(workspace.path()).with_read_only_roots(vec![ro_canon]);
691 let ro_err = PandocConvertTool
692 .execute(
693 json!({"source_path": ro_file.to_string_lossy(), "target_format": "html"}),
694 &ctx,
695 )
696 .await
697 .expect_err("pandoc_convert must not read from read_only_roots");
698 assert!(matches!(ro_err, ToolError::PathEscape { .. }), "{ro_err:?}");
699
700 #[cfg(unix)]
701 {
702 let outside = tempdir().expect("outside");
703 let original = outside.path().join("orig.md");
704 let linked = outside.path().join("alias.md");
705 fs::write(&original, "# secret\n").expect("write orig");
706 fs::hard_link(&original, &linked).expect("hardlink");
707 let trusted_ctx = ToolContext::new(workspace.path()).with_trust_mode(true);
708 let link_err = PandocConvertTool
709 .execute(
710 json!({"source_path": linked.to_string_lossy(), "target_format": "html"}),
711 &trusted_ctx,
712 )
713 .await
714 .expect_err("outside hardlink must be refused by verified-handle reader");
715 assert!(
716 matches!(link_err, ToolError::PermissionDenied { .. }),
717 "{link_err:?}"
718 );
719 }
720 }
721 }
722
722 lines RUST