@blackbelt-technology/pi-dashboard-document-converter 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,6 @@
1
1
  ---
2
2
  name: doc-summarizer
3
- description: >-
4
- Summarize documents of any size by extracting them with the document-converter
5
- engine, chunking to fit context, and fanning chunks out to subagents that
6
- produce structured summaries, then synthesizing one unified summary. Handles
7
- PDF, DOCX, PPTX, XLSX, HTML, CSV, TXT, MD and more. Use when the user wants to:
8
- (1) summarize a single document, (2) summarize multiple documents in batch,
9
- (3) condense content from large files that exceed context limits, (4) get a
10
- quick overview of document contents. Triggers on: "summarize this document",
11
- "what's in this PDF", "give me a summary of these files", "extract key points
12
- from", "condense this document", "TL;DR of this file".
3
+ description: 'Summarize documents of any size: extract with the document-converter engine, chunk to fit context, fan out to subagents, then synthesize one unified summary. Handles PDF, DOCX, PPTX, XLSX, HTML, CSV, TXT, MD. Triggers: "summarize this document", "what''s in this PDF", "give me a summary of these files", "extract key points from", "condense this document", "TL;DR of this file".'
13
4
  ---
14
5
 
15
6
  # Document Summarizer
@@ -33,7 +24,11 @@ Call the facade; never invoke Python, docling, or pdftotext directly.
33
24
 
34
25
  ```ts
35
26
  import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-document-converter";
36
- const dc = createDocumentConverter({ image: "pi-doc-engine:0.1.0", stagingDir: "/abs/staging" });
27
+ const dc = createDocumentConverter({
28
+ image: "pi-doc-engine:0.1.0",
29
+ stagingDir: "/abs/staging",
30
+ mounts: ["/docs"], // files outside cwd need a root (mounts or workspaceRoot), else PATH_NOT_ALLOWED
31
+ });
37
32
 
38
33
  const { output } = await dc.convertToMarkdown("<file_path>"); // digital PDF/DOCX/…
39
34
  // scanned PDF: pass OCR explicitly
@@ -42,7 +37,7 @@ await dc.convertToMarkdown("<file_path>", { ocr: { mode: "force", lang: ["englis
42
37
 
43
38
  The result is a provenance-stamped `.md` in `stagingDir`. Read that file to get
44
39
  the document text. On failure the call rejects with `DocConverterError`
45
- (`.code`, `.stderr`) — surface `UNSUPPORTED_FORMAT`, `OCR_LANG_UNSUPPORTED`,
40
+ (`.code`, `.stderr`) — surface `UNSUPPORTED_FORMAT`, `PATH_NOT_ALLOWED`, `OCR_LANG_UNSUPPORTED`,
46
41
  `INGEST_FAILED`, `DOCKER_UNAVAILABLE` rather than retrying blindly.
47
42
 
48
43
  ## Step 2 — Decide direct vs. chunked
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: document-converter
3
- description: Convert documents bidirectionally via the pi-doc-engine facade. Ingest PDF/DOCX/PPTX/XLSX to provenance-stamped Markdown for kb (with selectable OCR). Produce templated DOCX/PDF from Markdown with diagrams (mmdc or styled nano-banana), TOC, cover page, and round-trip extract/edit/merge. Use on requests like "convert this PDF to markdown", "ingest these docs into kb", "make a DOCX from markdown with our template", "render this spec to PDF", "OCR this scanned Hungarian PDF", "edit this DOCX and merge back", "fill frontmatter", "auto-size tables".
3
+ description: 'Convert documents bidirectionally via the pi-doc-engine facade: ingest PDF/DOCX/PPTX/XLSX to provenance-stamped Markdown (with OCR), and produce templated DOCX/PDF from Markdown with diagrams, TOC and round-trip merge. Use on "convert this PDF to markdown", "ingest these docs into kb", "make a DOCX from markdown with our template", "render this spec to PDF", "OCR this scanned PDF".'
4
4
  ---
5
5
 
6
6
  # Document Converter
@@ -17,6 +17,10 @@ Do NOT read the vendored Python under `engine/document_converter/`.
17
17
  ## Prerequisites
18
18
 
19
19
  - Docker available; image built: `cd packages/document-converter && npm run build:image`.
20
+ The `pi.tools` manifest (package root) declares `pi-doc-engine` as a
21
+ `docker-image` probe — `pi-dashboard-ensure <package-root>/package.json`
22
+ reports image presence and the first-party build hint (confirm-gated) via
23
+ the registry's Settings → Tools row.
20
24
  - Styled diagrams (nano-banana) need `GEMINI_API_KEY` at run time; absent or on
21
25
  failure, rendering falls back to mmdc (never hard-fails).
22
26
 
@@ -26,7 +30,11 @@ Do NOT read the vendored Python under `engine/document_converter/`.
26
30
 
27
31
  ```ts
28
32
  import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-document-converter";
29
- const dc = createDocumentConverter({ image: "pi-doc-engine:0.1.0", stagingDir: "/abs/kb-staging" });
33
+ const dc = createDocumentConverter({
34
+ image: "pi-doc-engine:0.1.0",
35
+ stagingDir: "/abs/kb-staging",
36
+ mounts: ["/docs"], // files outside cwd need a root (mounts or workspaceRoot), else PATH_NOT_ALLOWED
37
+ });
30
38
 
31
39
  await dc.convertToMarkdown("/docs/report.pdf"); // digital PDF (auto: native-first)
32
40
  await dc.convertToMarkdown("/docs/scan.pdf", { // scanned HU PDF
@@ -75,5 +83,5 @@ All stages read/write one unified schema (`./schema`): template vars ·
75
83
  ## Errors
76
84
 
77
85
  Every method rejects with `DocConverterError` (`.code`, `.stderr`, `.exitCode`):
78
- `UNSUPPORTED_FORMAT`, `OCR_LANG_UNSUPPORTED`, `INGEST_FAILED`, `PRODUCE_FAILED`,
86
+ `UNSUPPORTED_FORMAT`, `PATH_NOT_ALLOWED`, `OCR_LANG_UNSUPPORTED`, `INGEST_FAILED`, `PRODUCE_FAILED`,
79
87
  `DOCKER_UNAVAILABLE`, … Surface `.code` + `.stderr`; do not retry blindly.
package/README.md CHANGED
@@ -16,6 +16,8 @@ import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-docu
16
16
  const dc = createDocumentConverter({
17
17
  image: "pi-doc-engine:0.1.0",
18
18
  stagingDir: "/abs/kb-staging",
19
+ // Files outside process.cwd() must sit under a configured root:
20
+ mounts: ["/docs", "/out"], // or workspaceRoot: "/abs/project"
19
21
  });
20
22
 
21
23
  // Ingest -> Markdown with provenance frontmatter (written into stagingDir).
@@ -68,10 +70,23 @@ The `provenance` frontmatter (`source_path`, `sha256`, `doc_type`,
68
70
  originating file. Re-ingesting an unchanged file yields the same `sha256`, so
69
71
  staging output is byte-stable (idempotent by hash).
70
72
 
73
+ ## Path confinement
74
+
75
+ Every absolute path in a request must lie under a configured root:
76
+ `stagingDir` (mounted read-write), `mounts`, or `workspaceRoot` (default
77
+ `process.cwd()`). Comparison uses real paths, so a symlink cannot escape a root.
78
+ Sensitive dirs (`/etc`, `/root`, `/var/run`, `/proc`, `/sys`, `/dev`, `~/.ssh`,
79
+ `~/.aws`, `~/.gnupg`, `~/.config`, `~/.pi`, `~/.docker`, `~/.kube`) are refused
80
+ unless a root containing the path is itself inside that dir. A root of `/` is
81
+ refused. Violations reject with `DocConverterError` code `PATH_NOT_ALLOWED`
82
+ before docker runs. Inputs of `convertToMarkdown`, `renderPdf`, and
83
+ `fillFrontmatter`/`profileTables` with `apply:false` mount read-only.
84
+
71
85
  ## Templates (runtime-mounted, not baked)
72
86
 
73
87
  DOCX templates are NOT baked into the image — pass `templatesDir` (an absolute
74
- host dir containing `<template>/template.docx`); the facade bind-mounts it. Keeps
88
+ host dir containing `<template>/template.docx`, under a configured root — add it
89
+ to `mounts`); the facade bind-mounts it. Keeps
75
90
  branded/template assets out of the image and the repo.
76
91
 
77
92
  ## Engine image
@@ -383,6 +383,33 @@ def cmd_list_templates(args: argparse.Namespace) -> int:
383
383
  return 0
384
384
 
385
385
 
386
+ def resolve_pdf_output(
387
+ inputs: list, output: str | None, output_dir: str | None
388
+ ) -> tuple:
389
+ """Split a trailing positional output path off `inputs`.
390
+
391
+ `inputs` is `nargs='+'`, so argparse cannot own an optional positional
392
+ output — it swallows both paths and leaves `output=None` (issue #507).
393
+ The documented single-file form `convert-pdf in.docx out.pdf` is recovered
394
+ here, under rules narrow enough that a genuine batch never loses an input:
395
+
396
+ * an explicit `--output` / `--output-dir` always wins;
397
+ * at least two positionals must remain;
398
+ * the last one must look like a PDF and must NOT already exist
399
+ (an existing `.pdf` is an input someone asked to convert).
400
+
401
+ Returns `(inputs, output)`.
402
+ """
403
+ if output is not None or output_dir is not None or len(inputs) < 2:
404
+ return list(inputs), output
405
+
406
+ tail = inputs[-1]
407
+ if not tail.lower().endswith('.pdf') or Path(tail).exists():
408
+ return list(inputs), output
409
+
410
+ return list(inputs[:-1]), tail
411
+
412
+
386
413
  def cmd_convert_pdf(args: argparse.Namespace) -> int:
387
414
  """Handle the convert-pdf command."""
388
415
  from .pdf_converter import (
@@ -395,7 +422,9 @@ def cmd_convert_pdf(args: argparse.Namespace) -> int:
395
422
  # Collect input files
396
423
  input_files = []
397
424
 
398
- for pattern in args.inputs:
425
+ patterns, output = resolve_pdf_output(args.inputs, args.output, args.output_dir)
426
+
427
+ for pattern in patterns:
399
428
  # Check if it's a glob pattern
400
429
  if '*' in pattern or '?' in pattern:
401
430
  matches = glob.glob(pattern, recursive=True)
@@ -471,8 +500,8 @@ def cmd_convert_pdf(args: argparse.Namespace) -> int:
471
500
  input_path = input_files[0]
472
501
 
473
502
  # Determine output path
474
- if args.output:
475
- output_path = Path(args.output)
503
+ if output:
504
+ output_path = Path(output)
476
505
  else:
477
506
  output_path = input_path.with_suffix('.pdf')
478
507
 
@@ -524,8 +553,9 @@ def cmd_convert_pdf(args: argparse.Namespace) -> int:
524
553
  return 1
525
554
 
526
555
 
527
- def main():
528
- """Main CLI entry point."""
556
+ def build_parser() -> argparse.ArgumentParser:
557
+ """Build the top-level parser. Split out of `main()` so tests can parse an
558
+ argv vector without executing a command (see tests/test_convert_pdf_output.py)."""
529
559
  parser = argparse.ArgumentParser(
530
560
  description='Document Converter - Convert between Markdown and DOCX formats',
531
561
  formatter_class=argparse.RawDescriptionHelpFormatter
@@ -694,8 +724,12 @@ Examples:
694
724
  """
695
725
  )
696
726
  pdf_parser.add_argument('inputs', nargs='+',
697
- help='Input file(s) or glob pattern (e.g., "*.docx")')
698
- pdf_parser.add_argument('output', nargs='?', default=None,
727
+ help='Input file(s), glob pattern (e.g., "*.docx"), '
728
+ 'optionally followed by the output PDF file')
729
+ # NOT a positional: `inputs` is nargs='+' and would greedily swallow it,
730
+ # leaving output=None (issue #507). The documented positional form is
731
+ # recovered by `resolve_pdf_output` instead.
732
+ pdf_parser.add_argument('-o', '--output', type=str, default=None,
699
733
  help='Output PDF file (for single file conversion)')
700
734
  pdf_parser.add_argument('--output-dir', type=str, default=None,
701
735
  help='Output directory for batch conversion')
@@ -712,6 +746,13 @@ Examples:
712
746
  help='Diagram output format (default: png)')
713
747
  add_common_args(pdf_parser)
714
748
 
749
+ return parser
750
+
751
+
752
+ def main():
753
+ """Main CLI entry point."""
754
+ parser = build_parser()
755
+
715
756
  # Parse arguments
716
757
  args = parser.parse_args()
717
758
 
@@ -357,6 +357,83 @@ def add_cover_page(
357
357
  doc.save(docx_path)
358
358
 
359
359
 
360
+ R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
361
+ W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
362
+ _SECTION_REF_TAGS = (f'{{{W_NS}}}headerReference', f'{{{W_NS}}}footerReference')
363
+
364
+
365
+ def _rel_targets(doc) -> dict:
366
+ """`{rId: target_ref}` for a document's own relationship part."""
367
+ return {rid: rel.target_ref for rid, rel in doc.part.rels.items()}
368
+
369
+
370
+ def remap_relationship_ids(elements: list, template_doc, output_doc) -> list:
371
+ """Rewrite template-local `r:id`s on copied elements to the OUTPUT's ids.
372
+
373
+ Elements copied out of a template carry that template's relationship ids.
374
+ The output package was produced independently (pandoc `--reference-doc`)
375
+ and numbered its own rels, so those ids are at best a different part and at
376
+ worst absent entirely — the dangling `rId15` that makes Word and
377
+ LibreOffice reject the file with no useful diagnostic (issue #506).
378
+
379
+ Ids are matched by TARGET, never by number: matching by number is what
380
+ silently repoints `headerReference type="first"` at *footer3*.
381
+
382
+ A header/footer reference the output package cannot satisfy is DROPPED — a
383
+ missing header renders fine, a dangling id does not. Any other unresolvable
384
+ reference is returned to the caller to fail on.
385
+
386
+ Returns the list of unresolvable non-section ids (empty when all resolved).
387
+ """
388
+
389
+ template_targets = _rel_targets(template_doc)
390
+ output_ids_by_target = {}
391
+ for rid, target in _rel_targets(output_doc).items():
392
+ output_ids_by_target.setdefault(target, rid)
393
+
394
+ unresolvable = []
395
+
396
+ for root in elements:
397
+ for el in list(root.iter()):
398
+ for key, old_id in list(el.attrib.items()):
399
+ if not key.startswith(f'{{{R_NS}}}'):
400
+ continue
401
+
402
+ target = template_targets.get(old_id)
403
+ new_id = output_ids_by_target.get(target) if target else None
404
+
405
+ if new_id is not None:
406
+ el.set(key, new_id)
407
+ continue
408
+
409
+ if el.tag in _SECTION_REF_TAGS:
410
+ parent = el.getparent()
411
+ if parent is not None:
412
+ parent.remove(el)
413
+ break # element is gone; stop reading its attributes
414
+
415
+ unresolvable.append(old_id)
416
+
417
+ return unresolvable
418
+
419
+
420
+ def find_dangling_relationship_ids(doc) -> list:
421
+ """Every `r:*` id in the body that no relationship backs.
422
+
423
+ A dangling id costs nothing at write time and everything at read time: the
424
+ package unzips, every part is well-formed, and Word/LibreOffice still
425
+ refuse it. Checking here turns silent corruption into a diagnosable error
426
+ (issue #506).
427
+ """
428
+ known = set(_rel_targets(doc))
429
+ dangling = []
430
+ for el in doc.element.body.iter():
431
+ for key, value in el.attrib.items():
432
+ if key.startswith(f'{{{R_NS}}}') and value not in known:
433
+ dangling.append(value)
434
+ return dangling
435
+
436
+
360
437
  def copy_template_cover_page(
361
438
  output_path: Path,
362
439
  template_path: Path
@@ -405,6 +482,18 @@ def copy_template_cover_page(
405
482
  if not cover_elements:
406
483
  return False
407
484
 
485
+ # The copied XML still speaks the TEMPLATE's relationship ids. Translate
486
+ # them before they reach the output package, and refuse to write a package
487
+ # whose references cannot be satisfied rather than emitting a file Word
488
+ # rejects as "source file could not be loaded". See issue #506.
489
+ unresolvable = remap_relationship_ids(cover_elements, template_doc, output_doc)
490
+ if unresolvable:
491
+ raise RuntimeError(
492
+ "Cover page references relationships absent from the output package: "
493
+ f"{', '.join(sorted(set(unresolvable)))}. "
494
+ f"Template: {template_path}"
495
+ )
496
+
408
497
  # Get the first element in output to insert before
409
498
  first_output = output_body[0] if len(output_body) > 0 else None
410
499
 
@@ -444,5 +533,13 @@ def copy_template_cover_page(
444
533
  else:
445
534
  output_body.append(page_break_para)
446
535
 
536
+ dangling = find_dangling_relationship_ids(output_doc)
537
+ if dangling:
538
+ raise RuntimeError(
539
+ "Refusing to write a DOCX with unresolvable relationship ids: "
540
+ f"{', '.join(sorted(set(dangling)))}. "
541
+ f"Output: {output_path}"
542
+ )
543
+
447
544
  output_doc.save(output_path)
448
545
  return True # Always return True if we copied something
@@ -256,7 +256,9 @@ def cmd_render_docx(req: dict) -> dict:
256
256
  def cmd_render_pdf(req: dict) -> dict:
257
257
  inp = Path(req["input"])
258
258
  out = req["output"]
259
- args = ["convert-pdf", str(inp), out]
259
+ # `--output`, never a positional: `convert-pdf`'s `inputs` is nargs='+' and
260
+ # swallows a trailing positional output. See issue #507.
261
+ args = ["convert-pdf", str(inp), "--output", out]
260
262
  if req.get("pageSize"):
261
263
  args += ["--page-size", req["pageSize"]]
262
264
  if req.get("template"):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-document-converter",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "TypeScript facade over a Dockerized Python document engine (pi-doc-engine). Bidirectional: ingest any format to provenance-stamped Markdown for kb, produce templated DOCX/PDF with diagrams. Engine quarantined in Docker; TS is the only call surface.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -16,6 +16,12 @@
16
16
  "skills": [
17
17
  ".pi/skills/document-converter",
18
18
  ".pi/skills/doc-summarizer"
19
+ ],
20
+ "tools": [
21
+ {
22
+ "id": "pi-doc-engine",
23
+ "probe": "docker-image"
24
+ }
19
25
  ]
20
26
  },
21
27
  "exports": {
@@ -30,13 +36,19 @@
30
36
  "test": "vitest run"
31
37
  },
32
38
  "dependencies": {
33
- "@blackbelt-technology/pi-dashboard-shared": "^0.7.0"
39
+ "@blackbelt-technology/pi-dashboard-shared": "^0.9.0"
34
40
  },
35
41
  "files": [
36
42
  "dist",
37
43
  "src",
38
44
  "engine",
39
- ".pi/skills/"
45
+ ".pi/skills/",
46
+ "!**/AGENTS.md",
47
+ "!**/*.AGENTS.md",
48
+ "!engine/tests",
49
+ "!**/__tests__",
50
+ "!**/*.test.ts",
51
+ "!**/*.test.tsx"
40
52
  ],
41
53
  "keywords": [
42
54
  "pi-package",
package/src/engine.ts CHANGED
@@ -3,14 +3,22 @@
3
3
  *
4
4
  * Spawns `docker run -i pi-doc-engine`, pipes one JSON request to stdin, reads
5
5
  * one JSON response from stdout, and maps exit codes + the response envelope to
6
- * typed errors. Mounts are **path-identical** (`-v dir:dir -w dir`) so host
7
- * paths equal container paths — no path rewriting needed.
6
+ * typed errors. Mount *targets* keep the lexical request path so container
7
+ * paths equal request paths — no path rewriting needed; mount *sources* are the
8
+ * realpath'd host dir that is actually exposed.
9
+ *
10
+ * Confinement (change: harden-untrusted-content-ingestion, D1): every absolute
11
+ * request path must lie under a configured root (`writable` ∪ `mounts` ∪
12
+ * `workspaceRoot`), outside the sensitive denylist, before docker is spawned.
8
13
  *
9
14
  * The raw runner is injectable so unit tests can mock the Docker boundary
10
15
  * without a container.
11
16
  */
17
+
18
+ import { mkdir, realpath, stat } from "node:fs/promises";
19
+ import { homedir } from "node:os";
20
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
12
21
  import { spawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
13
- import { dirname } from "node:path";
14
22
  import { DocConverterError } from "./errors.js";
15
23
 
16
24
  /** One JSON request to the engine. `command` selects the handler. */
@@ -49,8 +57,12 @@ export type EngineRunner = (argv: string[], stdin: string) => Promise<RunnerResu
49
57
  export interface EngineConfig {
50
58
  /** Image tag, e.g. `pi-doc-engine:0.1.0`. */
51
59
  image: string;
52
- /** Host dirs to bind-mount path-identically (parents of all referenced files). */
60
+ /** Roots always mounted read-write (the facade puts `stagingDir` here). Created on demand. */
61
+ writable?: string[];
62
+ /** Extra caller-configured roots. Request paths under them are admitted. */
53
63
  mounts?: string[];
64
+ /** Workspace root admitting request paths (default `process.cwd()`). */
65
+ workspaceRoot?: string;
54
66
  /** Passed through to `docker run -e GEMINI_API_KEY` when set in env. */
55
67
  passEnv?: string[];
56
68
  /** Override the process runner (tests). */
@@ -88,10 +100,18 @@ const defaultRunner: EngineRunner = (argv, stdin) =>
88
100
  child.stdin.end(stdin);
89
101
  });
90
102
 
103
+ /** One planned bind mount, keyed by its (lexical) container target. */
104
+ interface PlannedMount {
105
+ source: string;
106
+ mode: "ro" | "rw";
107
+ }
108
+
91
109
  /** Build the `docker run` argv for a request. */
92
- function buildArgv(cfg: EngineConfig, mounts: Set<string>): string[] {
110
+ function buildArgv(cfg: EngineConfig, mounts: Map<string, PlannedMount>): string[] {
93
111
  const argv = [cfg.dockerBin ?? "docker", "run", "--rm", "-i"];
94
- for (const m of mounts) argv.push("-v", `${m}:${m}`);
112
+ for (const [target, { source, mode }] of mounts) {
113
+ argv.push("-v", mode === "ro" ? `${source}:${target}:ro` : `${source}:${target}`);
114
+ }
95
115
  for (const key of cfg.passEnv ?? ["GEMINI_API_KEY"]) {
96
116
  if (process.env[key] !== undefined) argv.push("-e", key);
97
117
  }
@@ -99,18 +119,136 @@ function buildArgv(cfg: EngineConfig, mounts: Set<string>): string[] {
99
119
  return argv;
100
120
  }
101
121
 
102
- /** Collect every filesystem path referenced by a request so we can mount its dir. */
103
- function collectMountDirs(cfg: EngineConfig, req: EngineRequest): Set<string> {
104
- const dirs = new Set<string>(cfg.mounts ?? []);
105
- const add = (p: unknown) => {
106
- if (typeof p === "string" && p.startsWith("/")) dirs.add(dirname(p));
122
+ /** Sensitive host dirs never mounted unless a containing root opts in. `~` = homedir at call time. */
123
+ const DENYLIST = ["/etc", "/root", "/var/run", "/proc", "/sys", "/dev"];
124
+ const HOME_DENYLIST = [".ssh", ".aws", ".gnupg", ".config", ".pi", ".docker", ".kube"];
125
+
126
+ /**
127
+ * Write keys per command (mounted rw), and whether the command's other paths
128
+ * are verified read-only. Unknown commands mount everything rw (within
129
+ * confinement). Engine write sites: design D1 table.
130
+ */
131
+ function modeFor(req: EngineRequest): { writeKeys: Set<string>; othersRo: boolean } {
132
+ const apply = req.apply !== false;
133
+ switch (req.command) {
134
+ case "convertToMarkdown":
135
+ return { writeKeys: new Set(), othersRo: true };
136
+ case "renderPdf":
137
+ return { writeKeys: new Set(["output"]), othersRo: true };
138
+ case "renderDocx":
139
+ return { writeKeys: new Set(["output", "cacheDir"]), othersRo: false };
140
+ case "extractForEdit":
141
+ case "mergeBack":
142
+ return { writeKeys: new Set(["output"]), othersRo: false };
143
+ case "fillFrontmatter":
144
+ case "profileTables":
145
+ return apply ? { writeKeys: new Set(["paths"]), othersRo: false } : { writeKeys: new Set(), othersRo: true };
146
+ default:
147
+ return { writeKeys: new Set(), othersRo: false };
148
+ }
149
+ }
150
+
151
+ const isUnder = (p: string, root: string) => p === root || p.startsWith(root.endsWith(sep) ? root : root + sep);
152
+
153
+ /** realpath of the nearest existing ancestor, with the non-existent remainder re-appended. */
154
+ async function realpathLoose(p: string): Promise<string> {
155
+ let cur = resolve(p);
156
+ const rest: string[] = [];
157
+ for (;;) {
158
+ try {
159
+ return join(await realpath(cur), ...rest.reverse());
160
+ } catch {
161
+ const parent = dirname(cur);
162
+ if (parent === cur) return resolve(p);
163
+ rest.push(basename(cur));
164
+ cur = parent;
165
+ }
166
+ }
167
+ }
168
+
169
+ async function isDir(p: string): Promise<boolean> {
170
+ try {
171
+ return (await stat(p)).isDirectory();
172
+ } catch {
173
+ return false;
174
+ }
175
+ }
176
+
177
+ function notAllowed(path: string, why: string, roots: string[]): DocConverterError {
178
+ return new DocConverterError({
179
+ code: "PATH_NOT_ALLOWED",
180
+ message:
181
+ `path not allowed: ${path} (${why}). Configured roots: ${roots.join(", ") || "(none)"}. ` +
182
+ `Pass \`mounts:[dir]\` or \`workspaceRoot\` to admit files outside the workspace.`,
183
+ });
184
+ }
185
+
186
+ /**
187
+ * Plan the bind mounts for a request, enforcing confinement + denylist.
188
+ * Throws `PATH_NOT_ALLOWED` before anything is spawned.
189
+ */
190
+ async function planMounts(cfg: EngineConfig, req: EngineRequest): Promise<Map<string, PlannedMount>> {
191
+ const configured = [...(cfg.writable ?? []), ...(cfg.mounts ?? []), cfg.workspaceRoot ?? process.cwd()];
192
+ // Materialise roots: create writable ones, then realpath every root.
193
+ for (const w of cfg.writable ?? []) await mkdir(w, { recursive: true });
194
+ const roots: string[] = [];
195
+ for (const r of configured) {
196
+ const real = await realpathLoose(r);
197
+ if (real === sep || resolve(r) === sep) throw notAllowed(r, "`/` cannot be a root", configured);
198
+ roots.push(real);
199
+ }
200
+
201
+ // Denylist entries, lexical + realpath (e.g. /var/run → /run, symlinked ~/.pi).
202
+ const home = homedir();
203
+ const deny: string[][] = [];
204
+ for (const d of [...DENYLIST, ...HOME_DENYLIST.map((h) => join(home, h))]) {
205
+ deny.push([...new Set([d, await realpathLoose(d)])]);
206
+ }
207
+
208
+ const plan = new Map<string, PlannedMount>();
209
+ const addMount = (target: string, source: string, mode: "ro" | "rw") => {
210
+ const prev = plan.get(target);
211
+ plan.set(target, { source, mode: prev?.mode === "rw" ? "rw" : mode });
107
212
  };
213
+ for (const w of cfg.writable ?? []) addMount(resolve(w), await realpathLoose(w), "rw");
214
+
215
+ const { writeKeys, othersRo } = modeFor(req);
216
+ const check = async (p: string, mode: "ro" | "rw") => {
217
+ if (!isAbsolute(p)) return; // engine has no host cwd: relative paths never hit host files
218
+ if (p.split(/[\\/]/).includes("..")) throw notAllowed(p, "`..` segment", configured);
219
+ if (p.includes(":")) throw notAllowed(p, "`:` breaks the bind-mount spec", configured);
220
+ const lexical = resolve(p);
221
+ const globAt = lexical.search(/[*?[]/);
222
+ let target: string;
223
+ if (globAt >= 0) target = dirname(lexical.slice(0, globAt + 1));
224
+ else if (await isDir(lexical)) target = lexical;
225
+ else target = dirname(lexical);
226
+ const realPath = await realpathLoose(lexical.slice(0, globAt >= 0 ? globAt : undefined));
227
+ const source = await realpathLoose(target);
228
+
229
+ const containing = roots.filter((r) => isUnder(realPath, r) && isUnder(source, r));
230
+ if (containing.length === 0) throw notAllowed(p, "outside every configured root", configured);
231
+ for (const variants of deny) {
232
+ const hit = variants.some((d) => isUnder(source, d) || isUnder(realPath, d) || (globAt >= 0 && isUnder(d, source)));
233
+ if (!hit) continue;
234
+ const optedIn = containing.some((r) => variants.some((d) => isUnder(r, d)));
235
+ if (!optedIn) throw notAllowed(p, `sensitive directory ${variants[0]}`, configured);
236
+ }
237
+ addMount(target, source, mode);
238
+ };
239
+
108
240
  for (const [k, v] of Object.entries(req)) {
109
241
  if (k === "command") continue;
110
- if (Array.isArray(v)) v.forEach(add);
111
- else add(v);
242
+ const mode = writeKeys.has(k) || !othersRo ? "rw" : "ro";
243
+ for (const item of Array.isArray(v) ? v : [v]) {
244
+ if (typeof item === "string") await check(item, mode);
245
+ }
246
+ }
247
+ // Only after every path passed: create missing rw dirs (else docker creates them as root).
248
+ for (const { source, mode } of plan.values()) {
249
+ if (mode === "rw" && !(await isDir(source))) await mkdir(source, { recursive: true });
112
250
  }
113
- return dirs;
251
+ return plan;
114
252
  }
115
253
 
116
254
  /**
@@ -122,7 +260,7 @@ export async function runEngine<T = Record<string, unknown>>(
122
260
  req: EngineRequest,
123
261
  ): Promise<T> {
124
262
  const runner = cfg.runner ?? defaultRunner;
125
- const argv = buildArgv(cfg, collectMountDirs(cfg, req));
263
+ const argv = buildArgv(cfg, await planMounts(cfg, req));
126
264
  const { stdout, stderr, exitCode } = await runner(argv, JSON.stringify(req));
127
265
 
128
266
  let parsed: EngineResponse | undefined;
package/src/errors.ts CHANGED
@@ -12,6 +12,7 @@ export type DocConverterErrorCode =
12
12
  | "OCR_LANG_UNSUPPORTED" // canonical lang not supported by chosen engine
13
13
  | "OCR_ENGINE_UNKNOWN" // unknown OCR engine
14
14
  | "UNSUPPORTED_FORMAT" // extension not routable to a command
15
+ | "PATH_NOT_ALLOWED" // request path outside configured roots or in a sensitive dir
15
16
  | "INGEST_FAILED"
16
17
  | "PRODUCE_FAILED"
17
18
  | "FILL_FAILED"
package/src/index.ts CHANGED
@@ -7,14 +7,14 @@
7
7
  */
8
8
  import { mkdir, writeFile } from "node:fs/promises";
9
9
  import { basename, join } from "node:path";
10
- import { runEngine, type EngineConfig } from "./engine.js";
10
+ import { type EngineConfig, runEngine } from "./engine.js";
11
11
  import { mapOcrCodes } from "./ocr.js";
12
- import { ingestDocType } from "./routing.js";
13
12
  import {
14
13
  buildProvenance,
15
14
  sha256File,
16
15
  stampProvenance,
17
16
  } from "./provenance.js";
17
+ import { ingestDocType } from "./routing.js";
18
18
  import type {
19
19
  ConvertToMarkdownOptions,
20
20
  ConvertToMarkdownResult,
@@ -32,8 +32,10 @@ export interface DocumentConverterConfig {
32
32
  image: string;
33
33
  /** Staging dir where ingest writes `.md` for kb. Created on demand. */
34
34
  stagingDir: string;
35
- /** Extra host dirs to bind-mount path-identically. */
35
+ /** Extra host roots: request paths under them are admitted (mounted on demand). */
36
36
  mounts?: string[];
37
+ /** Workspace root admitting request paths (default `process.cwd()`). */
38
+ workspaceRoot?: string;
37
39
  /** Test hook: inject the engine config (e.g. a fake runner). */
38
40
  engine?: Partial<EngineConfig>;
39
41
  }
@@ -42,7 +44,9 @@ export interface DocumentConverterConfig {
42
44
  export function createDocumentConverter(config: DocumentConverterConfig) {
43
45
  const engineCfg = (extraMounts: string[] = []): EngineConfig => ({
44
46
  image: config.image,
45
- mounts: [config.stagingDir, ...(config.mounts ?? []), ...extraMounts],
47
+ writable: [config.stagingDir],
48
+ mounts: [...(config.mounts ?? []), ...extraMounts],
49
+ workspaceRoot: config.workspaceRoot,
46
50
  ...config.engine,
47
51
  });
48
52
 
@@ -164,16 +168,16 @@ function replaceExt(name: string, ext: string): string {
164
168
  return name.replace(/\.[^.]+$/, "") + ext;
165
169
  }
166
170
 
167
- export { DocConverterError } from "./errors.js";
168
171
  export type { DocConverterErrorCode } from "./errors.js";
169
- export * from "./types.js";
172
+ export { DocConverterError } from "./errors.js";
173
+ export { mapOcrCodes, SUPPORTED_LANGUAGES } from "./ocr.js";
174
+ export { buildProvenance, provenanceFrontmatter, sha256File, stampProvenance } from "./provenance.js";
175
+ export { docTypeOf, ingestDocType, isIngestable } from "./routing.js";
170
176
  export type {
171
177
  DocumentFrontmatter,
172
- Provenance,
173
178
  NanoBananaConfig,
174
- TableProfiles,
179
+ Provenance,
175
180
  TableProfile,
181
+ TableProfiles,
176
182
  } from "./schema.js";
177
- export { mapOcrCodes, SUPPORTED_LANGUAGES } from "./ocr.js";
178
- export { docTypeOf, isIngestable, ingestDocType } from "./routing.js";
179
- export { buildProvenance, stampProvenance, provenanceFrontmatter, sha256File } from "./provenance.js";
183
+ export * from "./types.js";
@@ -1,109 +0,0 @@
1
- """Engine-internal unit tests: styled-diagram md5 cache + mmdc fallback.
2
-
3
- These cover logic that lives below the TS↔engine JSON boundary (the TS suite
4
- mocks the boundary and cannot reach it). Pure stdlib + monkeypatch; no docling,
5
- no Docker. Run:
6
-
7
- python -m pytest packages/document-converter/engine/tests -q
8
- """
9
- import hashlib
10
- import sys
11
- from pathlib import Path
12
-
13
- import pytest
14
-
15
- ENGINE_DIR = Path(__file__).resolve().parent.parent
16
- sys.path.insert(0, str(ENGINE_DIR))
17
-
18
- import engine_cli # noqa: E402
19
-
20
- MERMAID_DOC = "intro\n\n```mermaid\ngraph TD; A-->B\n```\n\noutro\n"
21
-
22
-
23
- def _write_md(tmp_path: Path) -> Path:
24
- md = tmp_path / "doc.md"
25
- md.write_text(MERMAID_DOC, encoding="utf-8")
26
- return md
27
-
28
-
29
- def test_cache_hit_skips_generation(tmp_path, monkeypatch):
30
- md = _write_md(tmp_path)
31
- cache = tmp_path / ".mermaid-cache"
32
- cache.mkdir()
33
- # Pre-seed the cache with the exact md5 key.
34
- digest = hashlib.md5("graph TD; A-->B".encode()).hexdigest()
35
- (cache / f"{digest}.png").write_bytes(b"PNG")
36
-
37
- calls = {"nano": 0, "mmdc": 0}
38
- monkeypatch.setattr(engine_cli, "_nano_banana", lambda *a, **k: calls.__setitem__("nano", calls["nano"] + 1) or True)
39
- monkeypatch.setattr(engine_cli, "_mmdc", lambda *a, **k: calls.__setitem__("mmdc", calls["mmdc"] + 1))
40
-
41
- out = engine_cli._render_styled_diagrams(md, "ros-3d", cache)
42
-
43
- assert calls == {"nano": 0, "mmdc": 0} # cache hit -> neither called
44
- text = out.read_text(encoding="utf-8")
45
- assert f"{digest}.png" in text
46
- assert "```mermaid" not in text
47
-
48
-
49
- def test_cache_miss_generates_via_nano_banana(tmp_path, monkeypatch):
50
- md = _write_md(tmp_path)
51
- cache = tmp_path / ".mermaid-cache"
52
- monkeypatch.setenv("GEMINI_API_KEY", "k")
53
-
54
- def fake_nano(source, style, png):
55
- png.write_bytes(b"PNG")
56
- return True
57
-
58
- calls = {"mmdc": 0}
59
- monkeypatch.setattr(engine_cli, "_nano_banana", fake_nano)
60
- monkeypatch.setattr(engine_cli, "_mmdc", lambda *a, **k: calls.__setitem__("mmdc", calls["mmdc"] + 1))
61
-
62
- engine_cli._render_styled_diagrams(md, "ros-3d", cache)
63
- assert calls["mmdc"] == 0 # nano-banana succeeded; no fallback
64
-
65
-
66
- def test_falls_back_to_mmdc_when_nano_fails(tmp_path, monkeypatch):
67
- md = _write_md(tmp_path)
68
- cache = tmp_path / ".mermaid-cache"
69
- monkeypatch.setenv("GEMINI_API_KEY", "k")
70
-
71
- monkeypatch.setattr(engine_cli, "_nano_banana", lambda *a, **k: False)
72
-
73
- def fake_mmdc(source, png):
74
- png.write_bytes(b"PNG")
75
-
76
- fallback = {"n": 0}
77
- monkeypatch.setattr(engine_cli, "_mmdc", lambda s, p: (fallback.__setitem__("n", fallback["n"] + 1), fake_mmdc(s, p)))
78
-
79
- engine_cli._render_styled_diagrams(md, "ros-3d", cache)
80
- assert fallback["n"] == 1 # fell back to mmdc exactly once
81
-
82
-
83
- def test_missing_key_uses_mmdc(tmp_path, monkeypatch):
84
- md = _write_md(tmp_path)
85
- cache = tmp_path / ".mermaid-cache"
86
- monkeypatch.delenv("GEMINI_API_KEY", raising=False)
87
-
88
- nano = {"n": 0}
89
- monkeypatch.setattr(engine_cli, "_nano_banana", lambda *a, **k: nano.__setitem__("n", nano["n"] + 1) or True)
90
- monkeypatch.setattr(engine_cli, "_mmdc", lambda s, p: p.write_bytes(b"PNG"))
91
-
92
- engine_cli._render_styled_diagrams(md, "ros-3d", cache)
93
- assert nano["n"] == 0 # no key -> nano-banana never attempted, mmdc used
94
-
95
-
96
- def test_unknown_command_envelope():
97
- import io
98
- import json
99
-
100
- monkey_stdin = io.StringIO(json.dumps({"command": "nope"}))
101
- out = io.StringIO()
102
- old_in, old_out = sys.stdin, sys.stdout
103
- sys.stdin, sys.stdout = monkey_stdin, out
104
- try:
105
- rc = engine_cli.main()
106
- finally:
107
- sys.stdin, sys.stdout = old_in, old_out
108
- assert rc == 2
109
- assert json.loads(out.getvalue())["error"]["code"] == "UNKNOWN_COMMAND"
package/src/AGENTS.md DELETED
@@ -1,14 +0,0 @@
1
- # DOX — packages/document-converter/src
2
-
3
- Files in this directory. One row per source file.
4
-
5
- | File | Purpose |
6
- |------|---------|
7
- | `engine.ts` | Docker invocation layer. `runEngine(cfg, req)` spawns `docker run --rm -i <image>`, pipes JSON request stdin, reads JSON response stdout. Path-identical mounts (`-v dir:dir`). Maps exit codes + envelope to `DocConverterError`. Injectable `EngineRunner`. |
8
- | `errors.ts` | `DocConverterError` class + `DocConverterErrorCode` union. Single error type facade rejects with. Codes: DOCKER_UNAVAILABLE, ENGINE_NONZERO, BAD_RESPONSE, INPUT_NOT_FOUND, OCR_*, UNSUPPORTED_FORMAT, INGEST/PRODUCE/FILL/PROFILE_FAILED, INTERNAL. |
9
- | `index.ts` | Facade entry. `createDocumentConverter(config)` returns object with convertToMarkdown, renderDocx, renderPdf, extractForEdit, mergeBack, fillFrontmatter, profileTables. Only call surface. Re-exports errors, types, schema, ocr, routing, provenance. `renderPdf` input widened to accept `.pptx` (engine `convert_to_pdf` routes pptx via LibreOffice Impress export filter) — no facade validation, engine-only change. See change: render-pptx-preview. |
10
- | `ocr.ts` | Canonical language name→per-engine OCR code. `mapOcrCodes(langs, engine)`. EasyOCR `hu` vs Tesseract `hun`. rapidocr returns `[]`. Unsupported throws `OCR_LANG_UNSUPPORTED`. `SUPPORTED_LANGUAGES`. |
11
- | `provenance.ts` | Provenance frontmatter writer. `sha256File`, `buildProvenance`, `provenanceFrontmatter`, `stampProvenance`. Stamps ingested `.md` with origin metadata. Byte-stable by hash. |
12
- | `routing.ts` | Extension routing. `EXT_TO_DOCTYPE` map. `docTypeOf`, `isIngestable`, `ingestDocType`. Ingestable set = pdf/docx/pptx/xlsx. Throws `UNSUPPORTED_FORMAT`. |
13
- | `schema.ts` | Unified document-frontmatter schema. Shared bus contract across stages. Types: `DocumentFrontmatter`, `Provenance`, `NanoBananaConfig`, `TableProfiles`, `TemplateVars`, `DocType`, `DiagramFormat`. Key consts. Mirrors `schema.json`. |
14
- | `types.ts` | Facade option + result types. `OcrEngine`, `OcrMode`, `OcrOptions`, `ConvertToMarkdown*`, `RenderDocx/PdfOptions`, `Produce/Extract/MergeBack`, `FillFrontmatter/ProfileTablesOptions`. |
@@ -1,72 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { runEngine, type EngineRunner } from "../engine.js";
3
- import { DocConverterError } from "../errors.js";
4
-
5
- const okRunner =
6
- (payload: object): EngineRunner =>
7
- async () => ({ stdout: JSON.stringify({ ok: true, ...payload }), stderr: "", exitCode: 0 });
8
-
9
- describe("runEngine envelope handling", () => {
10
- it("returns the ok envelope minus the ok flag", async () => {
11
- const res = await runEngine(
12
- { image: "pi-doc-engine:test", runner: okRunner({ output: "/out.docx" }) },
13
- { command: "renderDocx", input: "/in.md", output: "/out.docx" },
14
- );
15
- expect(res).toEqual({ output: "/out.docx" });
16
- });
17
-
18
- it("maps an error envelope to a typed DocConverterError", async () => {
19
- const runner: EngineRunner = async () => ({
20
- stdout: JSON.stringify({
21
- ok: false,
22
- error: { code: "INGEST_FAILED", message: "boom", stderr: "trace" },
23
- }),
24
- stderr: "",
25
- exitCode: 1,
26
- });
27
- await expect(
28
- runEngine({ image: "x", runner }, { command: "convertToMarkdown", input: "/a.pdf" }),
29
- ).rejects.toMatchObject({ code: "INGEST_FAILED", message: "boom", stderr: "trace" });
30
- });
31
-
32
- it("rejects non-JSON stdout with BAD_RESPONSE on clean exit", async () => {
33
- const runner: EngineRunner = async () => ({ stdout: "not json", stderr: "", exitCode: 0 });
34
- await expect(
35
- runEngine({ image: "x", runner }, { command: "renderPdf", input: "/a.md", output: "/a.pdf" }),
36
- ).rejects.toMatchObject({ code: "BAD_RESPONSE" });
37
- });
38
-
39
- it("rejects non-JSON stdout with ENGINE_NONZERO on bad exit", async () => {
40
- const runner: EngineRunner = async () => ({ stdout: "", stderr: "docker: not found", exitCode: 127 });
41
- await expect(
42
- runEngine({ image: "x", runner }, { command: "renderPdf", input: "/a.md", output: "/a.pdf" }),
43
- ).rejects.toMatchObject({ code: "ENGINE_NONZERO", exitCode: 127 });
44
- });
45
-
46
- it("builds path-identical bind mounts for every referenced path", async () => {
47
- const runner = vi.fn<EngineRunner>(async () => ({
48
- stdout: JSON.stringify({ ok: true }),
49
- stderr: "",
50
- exitCode: 0,
51
- }));
52
- await runEngine(
53
- { image: "pi-doc-engine:test", runner, mounts: [] },
54
- { command: "renderDocx", input: "/work/in.md", output: "/work/out.docx" },
55
- );
56
- const argv = runner.mock.calls[0][0];
57
- expect(argv).toContain("-v");
58
- expect(argv).toContain("/work:/work");
59
- expect(argv).toContain("pi-doc-engine:test");
60
- // mount appears once even though two paths share /work
61
- expect(argv.filter((a) => a === "/work:/work")).toHaveLength(1);
62
- });
63
-
64
- it("surfaces DOCKER_UNAVAILABLE when the runner cannot spawn", async () => {
65
- const runner: EngineRunner = async () => {
66
- throw new DocConverterError({ code: "DOCKER_UNAVAILABLE", message: "no docker" });
67
- };
68
- await expect(
69
- runEngine({ image: "x", runner }, { command: "renderPdf", input: "/a.md", output: "/a.pdf" }),
70
- ).rejects.toMatchObject({ code: "DOCKER_UNAVAILABLE" });
71
- });
72
- });
@@ -1,120 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { createDocumentConverter } from "../index.js";
6
- import type { EngineRunner } from "../engine.js";
7
-
8
- const tmps: string[] = [];
9
- async function workdir(): Promise<string> {
10
- const d = await mkdtemp(join(tmpdir(), "docconv-"));
11
- tmps.push(d);
12
- return d;
13
- }
14
- afterEach(async () => {
15
- await Promise.all(tmps.splice(0).map((d) => rm(d, { recursive: true, force: true })));
16
- });
17
-
18
- /** Fake runner that records the parsed request and returns a canned ok payload. */
19
- function recordingRunner(payload: object): { runner: EngineRunner; reqs: any[] } {
20
- const reqs: any[] = [];
21
- const runner: EngineRunner = async (_argv, stdin) => {
22
- reqs.push(JSON.parse(stdin));
23
- return { stdout: JSON.stringify({ ok: true, ...payload }), stderr: "", exitCode: 0 };
24
- };
25
- return { runner, reqs };
26
- }
27
-
28
- describe("facade: convertToMarkdown", () => {
29
- it("stamps provenance and writes markdown to the staging dir", async () => {
30
- const dir = await workdir();
31
- const staging = join(dir, "staging");
32
- const pdf = join(dir, "report.pdf");
33
- await writeFile(pdf, "fake-pdf-bytes");
34
-
35
- const { runner, reqs } = recordingRunner({ markdown: "# Report\n\ncontent" });
36
- const dc = createDocumentConverter({
37
- image: "pi-doc-engine:test",
38
- stagingDir: staging,
39
- engine: { runner },
40
- });
41
-
42
- const res = await dc.convertToMarkdown(pdf, { ocr: { lang: ["hungarian"], engine: "tesseract" } });
43
-
44
- // OCR canonical name was mapped to the per-engine code before the engine saw it.
45
- expect(reqs[0].command).toBe("convertToMarkdown");
46
- expect(reqs[0].ocr).toEqual({ mode: "auto", engine: "tesseract", codes: ["hun"] });
47
-
48
- const written = await readFile(res.output, "utf-8");
49
- expect(written).toContain("provenance:");
50
- expect(written).toContain("doc_type: pdf");
51
- expect(written).toContain(`source_path: ${pdf}`);
52
- expect(written).toContain("# Report");
53
- expect(res.provenance.sha256).toMatch(/^[0-9a-f]{64}$/);
54
- expect(res.output).toBe(join(staging, "report.md"));
55
- });
56
-
57
- it("rejects unsupported input formats before calling the engine", async () => {
58
- const dir = await workdir();
59
- const { runner, reqs } = recordingRunner({ markdown: "x" });
60
- const dc = createDocumentConverter({
61
- image: "x",
62
- stagingDir: join(dir, "staging"),
63
- engine: { runner },
64
- });
65
- await expect(dc.convertToMarkdown(join(dir, "a.txt"))).rejects.toMatchObject({
66
- code: "UNSUPPORTED_FORMAT",
67
- });
68
- expect(reqs).toHaveLength(0);
69
- });
70
-
71
- it("rejects an unsupported OCR language before calling the engine", async () => {
72
- const dir = await workdir();
73
- const pdf = join(dir, "a.pdf");
74
- await writeFile(pdf, "x");
75
- const { runner, reqs } = recordingRunner({ markdown: "x" });
76
- const dc = createDocumentConverter({
77
- image: "x",
78
- stagingDir: join(dir, "staging"),
79
- engine: { runner },
80
- });
81
- await expect(
82
- dc.convertToMarkdown(pdf, { ocr: { lang: ["klingon"], engine: "easyocr" } }),
83
- ).rejects.toMatchObject({ code: "OCR_LANG_UNSUPPORTED" });
84
- expect(reqs).toHaveLength(0);
85
- });
86
- });
87
-
88
- describe("facade: produce", () => {
89
- it("forwards the nano_banana flag and template to the engine on renderDocx", async () => {
90
- const { runner, reqs } = recordingRunner({ output: "/out.docx" });
91
- const dc = createDocumentConverter({
92
- image: "x",
93
- stagingDir: "/staging",
94
- engine: { runner },
95
- });
96
- await dc.renderDocx("/in.md", {
97
- output: "/out.docx",
98
- template: "default",
99
- nanoBanana: { enabled: true, style: "ros-3d" },
100
- });
101
- expect(reqs[0]).toMatchObject({
102
- command: "renderDocx",
103
- input: "/in.md",
104
- output: "/out.docx",
105
- template: "default",
106
- nano_banana: { enabled: true, style: "ros-3d" },
107
- });
108
- });
109
-
110
- it("returns the extract result with a document_meta path", async () => {
111
- const { runner } = recordingRunner({ output: "/edit.md", meta: "/document_meta.xml" });
112
- const dc = createDocumentConverter({
113
- image: "x",
114
- stagingDir: "/staging",
115
- engine: { runner },
116
- });
117
- const res = await dc.extractForEdit("/in.docx", "/edit.md");
118
- expect(res).toEqual({ output: "/edit.md", meta: "/document_meta.xml" });
119
- });
120
- });
@@ -1,122 +0,0 @@
1
- /**
2
- * Integration test — one real conversion per direction against the built image.
3
- * VERIFIED green against `pi-doc-engine:0.1.0` (ingest PDF→md→kb; produce
4
- * md→DOCX with template + mmdc diagram).
5
- *
6
- * Opt-in only (heavy image: docling ML models + LibreOffice + pandoc). Skipped
7
- * unless `docker` is on PATH and these env vars are set:
8
- * DOC_ENGINE_IMAGE=pi-doc-engine:0.1.0 built + loadable image tag
9
- * DOC_ENGINE_PDF=/abs/sample.pdf a digital PDF fixture (ingest case)
10
- * DOC_ENGINE_TEMPLATES=/abs/templates dir with <template>/template.docx (produce case)
11
- * DOC_ENGINE_PPTX=/abs/deck.pptx a real .pptx deck (pptx→PDF case)
12
- * Never runs in the default `npm test`.
13
- *
14
- * DOC_ENGINE_IMAGE=pi-doc-engine:0.1.0 DOC_ENGINE_PDF=… DOC_ENGINE_TEMPLATES=… \
15
- * npx vitest run integration
16
- */
17
- import { execFileSync } from "node:child_process";
18
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
19
- import { tmpdir } from "node:os";
20
- import { join } from "node:path";
21
- import { afterAll, beforeAll, describe, expect, it } from "vitest";
22
- import { createDocumentConverter } from "../index.js";
23
-
24
- const IMAGE = process.env.DOC_ENGINE_IMAGE;
25
-
26
- function dockerOk(): boolean {
27
- if (!IMAGE) return false;
28
- try {
29
- execFileSync("docker", ["image", "inspect", IMAGE], { stdio: "ignore" });
30
- return true;
31
- } catch {
32
- return false;
33
- }
34
- }
35
-
36
- const ENABLED = dockerOk();
37
- let work: string;
38
-
39
- beforeAll(async () => {
40
- if (!ENABLED) return;
41
- work = await mkdtemp(join(tmpdir(), "docconv-it-"));
42
- });
43
- afterAll(async () => {
44
- if (work) await rm(work, { recursive: true, force: true });
45
- });
46
-
47
- describe.skipIf(!ENABLED)("pi-doc-engine integration", () => {
48
- it("ingest: PDF -> Markdown with provenance, indexable by kb", async () => {
49
- const dc = createDocumentConverter({ image: IMAGE!, stagingDir: join(work, "staging") });
50
- // A trivial single-page PDF fixture must exist; integration fixtures are
51
- // provided alongside the built image. Point at it via DOC_ENGINE_PDF.
52
- const pdf = process.env.DOC_ENGINE_PDF;
53
- expect(pdf, "set DOC_ENGINE_PDF to a sample PDF").toBeTruthy();
54
-
55
- const { output, provenance } = await dc.convertToMarkdown(pdf!);
56
- const md = await readFile(output, "utf-8");
57
- expect(md).toContain("provenance:");
58
- expect(provenance.doc_type).toBe("pdf");
59
- expect(provenance.sha256).toMatch(/^[0-9a-f]{64}$/);
60
- }, 120_000);
61
-
62
- it("produce: Markdown -> DOCX with template + diagram", async () => {
63
- // Templates are runtime-mounted, not baked into the image (design Q4). Point
64
- // DOC_ENGINE_TEMPLATES at a dir containing `<template>/template.docx`.
65
- const templatesDir = process.env.DOC_ENGINE_TEMPLATES;
66
- expect(templatesDir, "set DOC_ENGINE_TEMPLATES to a templates dir").toBeTruthy();
67
-
68
- const dc = createDocumentConverter({
69
- image: IMAGE!,
70
- stagingDir: join(work, "staging"),
71
- mounts: [templatesDir!],
72
- });
73
- const md = join(work, "spec.md");
74
- await writeFile(
75
- md,
76
- [
77
- "---",
78
- "template: default",
79
- "---",
80
- "",
81
- "# Spec",
82
- "",
83
- "Hello world.",
84
- "",
85
- "```mermaid",
86
- "graph TD; A-->B",
87
- "```",
88
- "",
89
- ].join("\n"),
90
- "utf-8",
91
- );
92
- const out = join(work, "spec.docx");
93
- const res = await dc.renderDocx(md, {
94
- output: out,
95
- template: "default",
96
- templatesDir: templatesDir!,
97
- });
98
- expect(res.output).toBe(out);
99
- const bytes = await readFile(out);
100
- expect(bytes.byteLength).toBeGreaterThan(1000); // non-trivial DOCX
101
- }, 180_000);
102
-
103
- it("produce: PPTX -> PDF via renderPdf (fidelity path; change: render-pptx-preview)", async () => {
104
- // Verifies the engine input-type widening: renderPdf accepts .pptx and the
105
- // LibreOffice Impress export filter produces a valid PDF. Point DOC_ENGINE_PPTX
106
- // at a real deck.
107
- const pptx = process.env.DOC_ENGINE_PPTX;
108
- expect(pptx, "set DOC_ENGINE_PPTX to a sample .pptx deck").toBeTruthy();
109
-
110
- const dc = createDocumentConverter({
111
- image: IMAGE!,
112
- stagingDir: join(work, "staging"),
113
- mounts: [join(pptx!, "..")],
114
- });
115
- const out = join(work, "deck.pdf");
116
- const res = await dc.renderPdf(pptx!, { output: out });
117
- expect(res.output).toBe(out);
118
- const bytes = await readFile(out);
119
- expect(bytes.subarray(0, 5).toString()).toBe("%PDF-"); // valid PDF header
120
- expect(bytes.byteLength).toBeGreaterThan(1000);
121
- }, 180_000);
122
- });
@@ -1,34 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { mapOcrCodes, SUPPORTED_LANGUAGES } from "../ocr.js";
3
- import { DocConverterError } from "../errors.js";
4
-
5
- describe("OCR canonical-name -> per-engine-code mapping", () => {
6
- it("maps the same language to different codes per engine", () => {
7
- expect(mapOcrCodes(["hungarian"], "easyocr")).toEqual(["hu"]);
8
- expect(mapOcrCodes(["hungarian"], "tesseract")).toEqual(["hun"]);
9
- });
10
-
11
- it("is case- and whitespace-insensitive", () => {
12
- expect(mapOcrCodes([" English ", "GERMAN"], "tesseract")).toEqual(["eng", "deu"]);
13
- });
14
-
15
- it("rapidocr ignores language codes", () => {
16
- expect(mapOcrCodes(["hungarian"], "rapidocr")).toEqual([]);
17
- });
18
-
19
- it("throws OCR_LANG_UNSUPPORTED for an unknown language", () => {
20
- try {
21
- mapOcrCodes(["klingon"], "easyocr");
22
- throw new Error("should have thrown");
23
- } catch (e) {
24
- expect(e).toBeInstanceOf(DocConverterError);
25
- expect((e as DocConverterError).code).toBe("OCR_LANG_UNSUPPORTED");
26
- }
27
- });
28
-
29
- it("throws when a known language is unsupported by the chosen engine path", () => {
30
- // ocrmac has no italian entry mapping? It does; use a language absent for ocrmac.
31
- expect(() => mapOcrCodes(["hungarian"], "easyocr")).not.toThrow();
32
- expect(SUPPORTED_LANGUAGES).toContain("hungarian");
33
- });
34
- });
@@ -1,89 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- buildProvenance,
4
- provenanceFrontmatter,
5
- stampProvenance,
6
- } from "../provenance.js";
7
-
8
- const FIXED = "2026-06-24T00:00:00.000Z";
9
-
10
- describe("provenance frontmatter", () => {
11
- it("builds a deterministic record with a fixed timestamp", () => {
12
- const prov = buildProvenance({
13
- sourcePath: "/docs/a.pdf",
14
- sha256: "abc123",
15
- docType: "pdf",
16
- convertedAt: FIXED,
17
- });
18
- expect(prov).toEqual({
19
- source_path: "/docs/a.pdf",
20
- sha256: "abc123",
21
- doc_type: "pdf",
22
- converted_at: FIXED,
23
- });
24
- });
25
-
26
- it("includes page/slide only when provided", () => {
27
- const prov = buildProvenance({
28
- sourcePath: "/a.pptx",
29
- sha256: "x",
30
- docType: "pptx",
31
- convertedAt: FIXED,
32
- slide: 3,
33
- });
34
- expect(prov.slide).toBe(3);
35
- expect(prov.page).toBeUndefined();
36
- });
37
-
38
- it("prepends a frontmatter block to a bare body", () => {
39
- const prov = buildProvenance({
40
- sourcePath: "/a.pdf",
41
- sha256: "deadbeef",
42
- docType: "pdf",
43
- convertedAt: FIXED,
44
- });
45
- const out = stampProvenance("# Title\n\nbody", prov);
46
- expect(out.startsWith("---\nprovenance:\n")).toBe(true);
47
- expect(out).toContain("sha256: deadbeef");
48
- expect(out.trimEnd().endsWith("body")).toBe(true);
49
- });
50
-
51
- it("injects into existing frontmatter without clobbering keys", () => {
52
- const prov = buildProvenance({
53
- sourcePath: "/a.pdf",
54
- sha256: "h",
55
- docType: "pdf",
56
- convertedAt: FIXED,
57
- });
58
- const existing = "---\ntitle: Hello\n---\n\nbody\n";
59
- const out = stampProvenance(existing, prov);
60
- expect(out).toContain("provenance:");
61
- expect(out).toContain("title: Hello");
62
- // Single opening fence only.
63
- expect(out.match(/^---\n/)).toBeTruthy();
64
- expect(out.indexOf("---", 4)).toBeGreaterThan(0);
65
- });
66
-
67
- it("re-stamping the same hash is byte-identical (idempotent)", () => {
68
- const prov = buildProvenance({
69
- sourcePath: "/a.pdf",
70
- sha256: "same",
71
- docType: "pdf",
72
- convertedAt: FIXED,
73
- });
74
- const a = stampProvenance("body", prov);
75
- const b = stampProvenance("body", prov);
76
- expect(a).toBe(b);
77
- });
78
-
79
- it("quotes scalars that could be misparsed", () => {
80
- const prov = buildProvenance({
81
- sourcePath: "/path with spaces/a.pdf",
82
- sha256: "h",
83
- docType: "pdf",
84
- convertedAt: FIXED,
85
- });
86
- const fm = provenanceFrontmatter(prov);
87
- expect(fm).toContain('"/path with spaces/a.pdf"');
88
- });
89
- });
@@ -1,40 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { docTypeOf, ingestDocType, isIngestable } from "../routing.js";
3
- import { DocConverterError } from "../errors.js";
4
-
5
- describe("routing", () => {
6
- it("maps known extensions to doc types", () => {
7
- expect(docTypeOf("/a/b.pdf")).toBe("pdf");
8
- expect(docTypeOf("/a/b.DOCX")).toBe("docx");
9
- expect(docTypeOf("report.pptx")).toBe("pptx");
10
- expect(docTypeOf("sheet.xlsx")).toBe("xlsx");
11
- expect(docTypeOf("notes.md")).toBe("md");
12
- expect(docTypeOf("notes.markdown")).toBe("md");
13
- });
14
-
15
- it("throws UNSUPPORTED_FORMAT for unknown extensions", () => {
16
- expect(() => docTypeOf("/a/b.txt")).toThrowError(DocConverterError);
17
- try {
18
- docTypeOf("/a/b");
19
- } catch (e) {
20
- expect((e as DocConverterError).code).toBe("UNSUPPORTED_FORMAT");
21
- }
22
- });
23
-
24
- it("classifies ingestable formats", () => {
25
- expect(isIngestable("a.pdf")).toBe(true);
26
- expect(isIngestable("a.docx")).toBe(true);
27
- expect(isIngestable("a.md")).toBe(false); // md is not ingested, it IS the target
28
- expect(isIngestable("a.txt")).toBe(false);
29
- });
30
-
31
- it("ingestDocType rejects markdown", () => {
32
- expect(ingestDocType("a.pdf")).toBe("pdf");
33
- try {
34
- ingestDocType("a.md");
35
- throw new Error("should have thrown");
36
- } catch (e) {
37
- expect((e as DocConverterError).code).toBe("UNSUPPORTED_FORMAT");
38
- }
39
- });
40
- });