#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add document preparation for engine ingestion (#7983)
Anthony Stirling382a054624f5
diff --git a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.javaindex de96ad7b36..d4cab51648 100644--- a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java+++ b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java@@ -451,6 +451,9 @@ public class EndpointConfiguration {addEndpointToGroup("Automation", "automate"); // Alias for handleData (user-friendly name)addEndpointToGroup("Automation", "pipeline");+ // Adding endpoints to "DocParse" group (ingestion: chunk + index + export)+ addEndpointToGroup("DocParse", "ingest");+// Adding endpoints to "DeveloperTools" groupaddEndpointToGroup("DeveloperTools", "show-javascript");diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex 4a49f61dd7..2689de35cb 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -80,6 +80,7 @@ public class ApplicationProperties {private PdfEditor pdfEditor = new PdfEditor();private AiEngine aiEngine = new AiEngine();private FormDetection formDetection = new FormDetection();+ private Docparse docparse = new Docparse();private Mcp mcp = new Mcp();private InternalApi internalApi = new InternalApi();private Cluster cluster = new Cluster();@@ -481,6 +482,17 @@ public class ApplicationProperties {private String preinstalledModelDir = "";}+ /**+ * DocParse settings (top-level {@code docparse.*}): document understanding for ingestion+ * pipelines.+ */+ @Data+ public static class Docparse {++ /** Master switch; hides the DocParse endpoints when false. */+ private boolean enabled = true;+ }+/*** Model Context Protocol (MCP) server configuration. All keys live under the top-level {@code* mcp.*} prefix. {@link #enabled} defaults to {@code false}: when off, no MCP beans are wired,diff --git a/app/common/src/main/java/stirling/software/common/model/tool/ToolFormat.java b/app/common/src/main/java/stirling/software/common/model/tool/ToolFormat.javaindex 3e83c94a39..e7a9a13f5d 100644--- a/app/common/src/main/java/stirling/software/common/model/tool/ToolFormat.java+++ b/app/common/src/main/java/stirling/software/common/model/tool/ToolFormat.java@@ -33,7 +33,7 @@ public enum ToolFormat {CSV("csv"),HTML("html", "htm", "xhtml"),XML("xml", "xsd", "xsl"),- JSON("json"),+ JSON("json", "jsonl"),TEXT("txt", "text", "md", "markdown"),MARKDOWN("md", "markdown"),JAVASCRIPT("js", "jsx"),diff --git a/app/common/src/main/java/stirling/software/common/pdf/BasicPdfMarkdownExtractor.java b/app/common/src/main/java/stirling/software/common/pdf/BasicPdfMarkdownExtractor.javaindex 51cdc90368..f8dcf56037 100644--- a/app/common/src/main/java/stirling/software/common/pdf/BasicPdfMarkdownExtractor.java+++ b/app/common/src/main/java/stirling/software/common/pdf/BasicPdfMarkdownExtractor.java@@ -1,6 +1,7 @@package stirling.software.common.pdf;import java.io.IOException;+import java.util.List;import org.springframework.stereotype.Service;@@ -11,7 +12,7 @@ import stirling.software.jpdfium.PdfDocument;public class BasicPdfMarkdownExtractor implements PdfMarkdownExtractor {@Override- public String convert(PdfDocument doc) throws IOException {- return new PdfMarkdownConverter().convert(doc);+ public List<MarkdownBlock> extractBlocks(PdfDocument doc) throws IOException {+ return new PdfMarkdownConverter().extractBlocks(doc);}}diff --git a/app/common/src/main/java/stirling/software/common/pdf/MarkdownBlock.java b/app/common/src/main/java/stirling/software/common/pdf/MarkdownBlock.javanew file mode 100644index 0000000000..f56926ac95--- /dev/null+++ b/app/common/src/main/java/stirling/software/common/pdf/MarkdownBlock.java@@ -0,0 +1,26 @@+package stirling.software.common.pdf;++import java.util.List;++/**+ * One rendered Markdown element with the pages it came from. Page numbers are 1-based and differ+ * only for content stitched across a page break.+ */+public record MarkdownBlock(String markdown, int pageStart, int pageEnd, List<String> headingPath) {++ public MarkdownBlock {+ headingPath = headingPath == null ? List.of() : List.copyOf(headingPath);+ }++ public MarkdownBlock(String markdown, int pageStart, int pageEnd) {+ this(markdown, pageStart, pageEnd, List.of());+ }++ public MarkdownBlock withMarkdown(String replacement) {+ return new MarkdownBlock(replacement, pageStart, pageEnd, headingPath);+ }++ public MarkdownBlock withHeadingPath(List<String> path) {+ return new MarkdownBlock(markdown, pageStart, pageEnd, path);+ }+}diff --git a/app/common/src/main/java/stirling/software/common/pdf/MarkdownBlocks.java b/app/common/src/main/java/stirling/software/common/pdf/MarkdownBlocks.javanew file mode 100644index 0000000000..b42345c563--- /dev/null+++ b/app/common/src/main/java/stirling/software/common/pdf/MarkdownBlocks.java@@ -0,0 +1,137 @@+package stirling.software.common.pdf;++import java.util.ArrayDeque;+import java.util.ArrayList;+import java.util.Deque;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.TreeSet;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++/** Document-wide passes over a block list: joining, heading-level rebasing, heading paths. */+public final class MarkdownBlocks {++ private MarkdownBlocks() {}++ /** Separator between blocks; it ends in a newline, so every block starts at a line start. */+ public static final String SEPARATOR = "\n\n";++ /** A Markdown ATX heading at the start of a line, with its level in group 1. */+ private static final Pattern ATX_HEADING = Pattern.compile("(?m)^(#{1,6}) (?=\\S)");++ /** The same heading shape anchored at a block's own first character. */+ private static final Pattern BLOCK_HEADING = Pattern.compile("^(#{1,6}) (?=\\S)");++ /** Every character escapeMarkdown may have backslash-escaped, so unescaping is exact. */+ private static final String ESCAPABLE = "\\`*_[]<>|~#-+.)";++ /** Opening marker of the placeholder both converters emit in place of an image's bytes. */+ public static final String IMAGE_PLACEHOLDER = "<image redacted";++ public static String join(List<MarkdownBlock> blocks) {+ List<String> parts = new ArrayList<>(blocks.size());+ for (MarkdownBlock block : blocks) {+ parts.add(block.markdown());+ }+ return String.join(SEPARATOR, parts);+ }++ /**+ * Rebases headings so the strongest is level 1 and no level is skipped: levels only mean+ * anything against the other headings in the same document. The set is collected over the whole+ * list, so the decision is made once and then applied block by block.+ */+ public static List<MarkdownBlock> normaliseHeadingLevels(List<MarkdownBlock> blocks) {+ Set<Integer> levels = new TreeSet<>();+ for (MarkdownBlock block : blocks) {+ Matcher m = ATX_HEADING.matcher(block.markdown());+ while (m.find()) {+ levels.add(m.group(1).length());+ }+ }+ if (levels.isEmpty() || (levels.contains(1) && levels.size() == maxOf(levels))) {+ return blocks;+ }+ Map<Integer, String> rebased = rebaseMap(levels);+ List<MarkdownBlock> out = new ArrayList<>(blocks.size());+ for (MarkdownBlock block : blocks) {+ out.add(+ block.withMarkdown(+ ATX_HEADING+ .matcher(block.markdown())+ .replaceAll(r -> rebased.get(r.group(1).length()) + " ")));+ }+ return out;+ }++ /** Each block's enclosing heading chain; a heading block includes itself. */+ public static List<MarkdownBlock> withHeadingPaths(List<MarkdownBlock> blocks) {+ Deque<Heading> open = new ArrayDeque<>();+ List<MarkdownBlock> out = new ArrayList<>(blocks.size());+ for (MarkdownBlock block : blocks) {+ int level = headingLevel(block.markdown());+ if (level > 0) {+ while (!open.isEmpty() && open.peekLast().level() >= level) {+ open.removeLast();+ }+ open.addLast(new Heading(level, headingText(block.markdown(), level)));+ }+ List<String> path = new ArrayList<>(open.size());+ for (Heading h : open) {+ path.add(h.text());+ }+ out.add(block.withHeadingPath(List.copyOf(path)));+ }+ return out;+ }++ /** ATX level of a block's own first line, or 0 when the block is not a heading. */+ public static int headingLevel(String markdown) {+ Matcher m = BLOCK_HEADING.matcher(markdown);+ return m.lookingAt() ? m.group(1).length() : 0;+ }++ /** True when a block is nothing but an image placeholder, so it carries no readable text. */+ public static boolean isImagePlaceholder(String markdown) {+ return markdown.strip().startsWith(IMAGE_PLACEHOLDER);+ }++ /** Reverses escapeMarkdown so a heading path reads as the page does. */+ public static String unescape(String text) {+ StringBuilder sb = new StringBuilder(text.length());+ for (int i = 0; i < text.length(); i++) {+ char c = text.charAt(i);+ if (c == '\\' && i + 1 < text.length() && ESCAPABLE.indexOf(text.charAt(i + 1)) >= 0) {+ continue;+ }+ sb.append(c);+ }+ return sb.toString();+ }++ private static String headingText(String markdown, int level) {+ return unescape(markdown.substring(level + 1)).strip();+ }++ private static Map<Integer, String> rebaseMap(Set<Integer> levels) {+ Map<Integer, String> rebased = new HashMap<>();+ int rank = 1;+ for (int level : levels) {+ rebased.put(level, "#".repeat(rank++));+ }+ return rebased;+ }++ private static int maxOf(Set<Integer> levels) {+ int max = 0;+ for (int level : levels) {+ max = Math.max(max, level);+ }+ return max;+ }++ private record Heading(int level, String text) {}+}diff --git a/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownConverter.java b/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownConverter.javaindex a9932582f2..19f3092b77 100644--- a/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownConverter.java+++ b/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownConverter.java@@ -15,9 +15,7 @@ import stirling.software.jpdfium.doc.ExtractedImage;import stirling.software.jpdfium.doc.PdfImageExtractor;import stirling.software.jpdfium.model.Rect;import stirling.software.jpdfium.text.PageText;-import stirling.software.jpdfium.text.PdfTableExtractor;import stirling.software.jpdfium.text.PdfTextExtractor;-import stirling.software.jpdfium.text.Table;import stirling.software.jpdfium.text.TextLine;import stirling.software.jpdfium.text.TextWord;@@ -38,6 +36,21 @@ public class PdfMarkdownConverter {private static final float GLYPH_WIDTH = 7.5f;public String convert(PdfDocument doc) throws IOException {+ return MarkdownBlocks.join(extractBlocks(doc));+ }++ /** Page-attributed Markdown elements in reading order; {@link #convert} is these joined. */+ public List<MarkdownBlock> extractBlocks(PdfDocument doc) throws IOException {+ List<Element> stitched = stitchTables(buildElements(doc));+ List<MarkdownBlock> blocks = new ArrayList<>(stitched.size());+ for (Element e : stitched) {+ String md = e.value() instanceof TableBlock tb ? tb.render() : (String) e.value();+ blocks.add(new MarkdownBlock(md, e.pageStart(), e.pageEnd()));+ }+ return MarkdownBlocks.withHeadingPaths(blocks);+ }++ private List<Element> buildElements(PdfDocument doc) throws IOException {List<PageText> allPageText = PdfTextExtractor.extractAll(doc);float medianSize = HeadingDetector.medianFontSize(allPageText);float medianHeight = HeadingDetector.medianLineHeight(allPageText);@@ -46,7 +59,7 @@ public class PdfMarkdownConverter {// Elements are either rendered text (String) or a structured TableBlock. Tables stay// structured until after the page loop so a table split across a page break can be stitched// back together before rendering.- List<Object> output = new ArrayList<>();+ List<Element> output = new ArrayList<>();// Header text of a table that ended the previous page, used to spot a continuation whose// header repeats at the top of the current page. Null when the previous page did not end in// a table.@@ -60,7 +73,7 @@ public class PdfMarkdownConverter {// their host lines so paragraph assembly sees faithful, complete lines.List<Line> lines = stitchGlyphs(rawLines);if (lines.isEmpty()) {- emitImages(doc, pageIndex, output);+ emitImages(doc, pageIndex, pageIndex + 1, output);prevPageTrailingTableHeader = null;continue;}@@ -99,12 +112,14 @@ public class PdfMarkdownConverter {}}- List<Object> pageItems = new ArrayList<>();+ List<Element> pageItems = new ArrayList<>();if (twoColumn) {for (List<Line> col : splitIntoColumns(lines)) {List<String> paras = new ArrayList<>();assembleParagraphs(col, medianSize, medianHeight, paras, tableRowTexts);- pageItems.addAll(paras);+ for (String p : paras) {+ pageItems.add(new Element(p, pageIndex + 1, pageIndex + 1));+ }}} else {// Interleave tables with surrounding text by vertical position. Each block sits in@@ -131,14 +146,16 @@ public class PdfMarkdownConverter {List<String> paras = new ArrayList<>();assembleParagraphs(segments.get(s), medianSize, medianHeight, paras, tableRowTexts);- pageItems.addAll(paras);+ for (String p : paras) {+ pageItems.add(new Element(p, pageIndex + 1, pageIndex + 1));+ }if (s < blocks.size()) {- pageItems.add(blocks.get(s));+ pageItems.add(new Element(blocks.get(s), pageIndex + 1, pageIndex + 1));}}}- emitImages(doc, pageIndex, pageItems);+ emitImages(doc, pageIndex, pageIndex + 1, pageItems);if (pageItems.isEmpty()) {continue;@@ -149,13 +166,7 @@ public class PdfMarkdownConverter {prevPageTrailingTableHeader = trailingTableHeader(pageItems);}- // Stitch tables split across page breaks, then render every element to Markdown.- List<Object> stitched = stitchTables(output);- List<String> rendered = new ArrayList<>();- for (Object e : stitched) {- rendered.add(e instanceof TableBlock tb ? tb.render() : (String) e);- }- return String.join("\n\n", rendered);+ return output;}// --- Glyph stitching ---------------------------------------------------@@ -465,6 +476,11 @@ public class PdfMarkdownConverter {}}+ /**+ * An element plus the 1-based pages it came from; pageEnd widens when a page break is joined.+ */+ private record Element(Object value, int pageStart, int pageEnd) {}+/*** Detects table blocks on a page. Anchor rows (lines with table-like column gaps) are grouped* into vertically-contiguous runs separated by large vertical gaps, so multiple separate tables@@ -853,13 +869,13 @@ public class PdfMarkdownConverter {// --- Page-level emission helpers ---------------------------------------- private static void emitImages(PdfDocument doc, int pageIndex, List<Object> pageItems)- throws IOException {+ private static void emitImages(+ PdfDocument doc, int pageIndex, int pageNumber, List<Element> sink) throws IOException {try (PdfPage page = doc.page(pageIndex)) {List<ExtractedImage> images =PdfImageExtractor.extract(page.rawDocHandle(), page.rawHandle(), pageIndex);for (ExtractedImage img : images) {- pageItems.add(describeImage(img));+ sink.add(new Element(describeImage(img), pageNumber, pageNumber));}}}@@ -896,7 +912,7 @@ public class PdfMarkdownConverter {parts.add(img.bitsPerPixel() + "bpp");}- StringBuilder sb = new StringBuilder("<image redacted");+ StringBuilder sb = new StringBuilder(MarkdownBlocks.IMAGE_PLACEHOLDER);if (!parts.isEmpty()) {sb.append(": ").append(String.join(", ", parts));}@@ -904,20 +920,24 @@ public class PdfMarkdownConverter {return sb.toString();}- private static void mergeAcrossPageBoundary(List<Object> output, List<Object> pageItems) {+ private static void mergeAcrossPageBoundary(List<Element> output, List<Element> pageItems) {if (output.isEmpty() || pageItems.isEmpty()) {return;}// Only merge a sentence continuation between two text paragraphs, never into/out of a// table.- if (!(output.getLast() instanceof String last)- || !(pageItems.getFirst() instanceof String first)) {+ if (!(output.getLast().value() instanceof String last)+ || !(pageItems.getFirst().value() instanceof String first)) {return;}if (!first.isEmpty()&& Character.isLowerCase(first.charAt(0))&& !endsWithSentencePunctuation(last)) {- output.set(output.size() - 1, last + " " + first);+ Element head = output.getLast();+ Element tail = pageItems.getFirst();+ output.set(+ output.size() - 1,+ new Element(last + " " + first, head.pageStart(), tail.pageEnd()));pageItems.remove(0);}}@@ -927,12 +947,12 @@ public class PdfMarkdownConverter {* them — i.e. one ended a page and the next began the following page) are merged when their* column layouts match; a repeated header row on the continuation is dropped.*/- private static List<Object> stitchTables(List<Object> elements) {- List<Object> out = new ArrayList<>();- for (Object e : elements) {- if (e instanceof TableBlock tb+ private static List<Element> stitchTables(List<Element> elements) {+ List<Element> out = new ArrayList<>();+ for (Element e : elements) {+ if (e.value() instanceof TableBlock tb&& !out.isEmpty()- && out.getLast() instanceof TableBlock prev+ && out.getLast().value() instanceof TableBlock prev&& columnsMatch(flatten(prev.rows()), flatten(tb.rows()))) {List<List<Line>> merged = new ArrayList<>(prev.rows());List<List<Line>> tail = tb.rows();@@ -942,7 +962,13 @@ public class PdfMarkdownConverter {tail = tail.subList(1, tail.size());}merged.addAll(tail);- out.set(out.size() - 1, new TableBlock(merged, prev.top(), tb.bottom()));+ Element prevEl = out.getLast();+ out.set(+ out.size() - 1,+ new Element(+ new TableBlock(merged, prev.top(), tb.bottom()),+ prevEl.pageStart(),+ Math.max(prevEl.pageEnd(), e.pageEnd())));} else {out.add(e);}@@ -964,10 +990,10 @@ public class PdfMarkdownConverter {* Trailing image placeholders are skipped; any other text after a table means it did not run to* the page bottom and so is not a continuation candidate.*/- private static String trailingTableHeader(List<Object> pageItems) {+ private static String trailingTableHeader(List<Element> pageItems) {for (int i = pageItems.size() - 1; i >= 0; i--) {- Object e = pageItems.get(i);- if (e instanceof String s && s.strip().startsWith("<image redacted")) {+ Object e = pageItems.get(i).value();+ if (e instanceof String s && MarkdownBlocks.isImagePlaceholder(s)) {continue;}if (e instanceof TableBlock tb && !tb.rows().isEmpty()) {@@ -1026,18 +1052,4 @@ public class PdfMarkdownConverter {char last = s.charAt(s.length() - 1);return last == '.' || last == '?' || last == '!' || last == ':';}-- // --- Methods used by other components / tests ---------------------------- List<PageText> extractAllPageText(PdfDocument doc) throws IOException {- return PdfTextExtractor.extractAll(doc);- }-- List<Table> extractTables(PdfDocument doc, int pageIndex) throws IOException {- return PdfTableExtractor.extract(doc, pageIndex);- }-- List<String> renderTables(List<Table> tables) {- return tables.stream().map(TableRenderer::render).toList();- }}diff --git a/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownExtractor.java b/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownExtractor.javaindex 960a1443dc..1d3995f0f1 100644--- a/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownExtractor.java+++ b/app/common/src/main/java/stirling/software/common/pdf/PdfMarkdownExtractor.java@@ -1,6 +1,7 @@package stirling.software.common.pdf;import java.io.IOException;+import java.util.List;import stirling.software.jpdfium.PdfDocument;@@ -10,5 +11,10 @@ import stirling.software.jpdfium.PdfDocument;*/public interface PdfMarkdownExtractor {- String convert(PdfDocument doc) throws IOException;+ /** Page-attributed Markdown elements in reading order; the one source of truth. */+ List<MarkdownBlock> extractBlocks(PdfDocument doc) throws IOException;++ default String convert(PdfDocument doc) throws IOException {+ return MarkdownBlocks.join(extractBlocks(doc));+ }}diff --git a/app/common/src/main/java/stirling/software/common/pdf/TableRenderer.java b/app/common/src/main/java/stirling/software/common/pdf/TableRenderer.javadeleted file mode 100644index 3f468699fb..0000000000--- a/app/common/src/main/java/stirling/software/common/pdf/TableRenderer.java+++ /dev/null@@ -1,82 +0,0 @@-package stirling.software.common.pdf;--import stirling.software.jpdfium.text.Table;--final class TableRenderer {- private TableRenderer() {}-- /** Renders a Table as a GitHub-Flavoured Markdown table string. */- static String render(Table table) {- if (table.rowCount() == 0) {- return "";- }-- String[][] grid = table.asGrid();-- if (table.rowCount() < 2) {- // No separator row possible — return plain lines- StringBuilder sb = new StringBuilder();- for (int c = 0; c < grid[0].length; c++) {- if (c > 0) sb.append('\n');- sb.append(escape(grid[0][c].trim()));- }- return sb.toString();- }-- int cols = grid[0].length;-- // Compute column widths: max(3, max content length across all rows)- int[] widths = new int[cols];- for (int c = 0; c < cols; c++) {- widths[c] = 3;- }- for (String[] row : grid) {- for (int c = 0; c < cols; c++) {- String cell = c < row.length ? row[c].trim() : "";- widths[c] = Math.max(widths[c], escape(cell).length());- }- }-- StringBuilder sb = new StringBuilder();-- // Header row- sb.append(buildRow(grid[0], widths, cols));- sb.append('\n');-- // Separator row- sb.append('|');- for (int c = 0; c < cols; c++) {- sb.append('-').append("-".repeat(widths[c])).append('-').append('|');- }- sb.append('\n');-- // Data rows- for (int r = 1; r < grid.length; r++) {- sb.append(buildRow(grid[r], widths, cols));- if (r < grid.length - 1) {- sb.append('\n');- }- }-- return sb.toString();- }-- private static String buildRow(String[] row, int[] widths, int cols) {- StringBuilder sb = new StringBuilder();- sb.append('|');- for (int c = 0; c < cols; c++) {- String cell = c < row.length ? escape(row[c].trim()) : "";- sb.append(' ').append(padRight(cell, widths[c])).append(' ').append('|');- }- return sb.toString();- }-- private static String escape(String cell) {- return cell.replace("|", "\\|");- }-- private static String padRight(String s, int width) {- if (s.length() >= width) return s;- return s + " ".repeat(width - s.length());- }-}diff --git a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.javaindex 4cb859eedf..d3f3ee102d 100644--- a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java+++ b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java@@ -53,7 +53,7 @@ public class InternalApiClient {// ApiConnectionResolver.private static final Pattern ALLOWED_ENDPOINT_PATH =Pattern.compile(- "^/api/v1/(general|misc|security|convert|filter|integration)(/[A-Za-z0-9_-]+)+$"+ "^/api/v1/(general|misc|security|convert|filter|integration|docparse)(/[A-Za-z0-9_-]+)+$"+ "|^/api/v1/ai/tools(/[A-Za-z0-9_-]+)+$");/**diff --git a/app/common/src/test/java/stirling/software/common/pdf/MarkdownBlocksTest.java b/app/common/src/test/java/stirling/software/common/pdf/MarkdownBlocksTest.javanew file mode 100644index 0000000000..8c1b5850e9--- /dev/null+++ b/app/common/src/test/java/stirling/software/common/pdf/MarkdownBlocksTest.java@@ -0,0 +1,214 @@+package stirling.software.common.pdf;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;++import java.util.ArrayList;+import java.util.List;++import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Nested;+import org.junit.jupiter.api.Test;++/** Document-wide block passes: joining, heading-level rebasing, heading paths and unescaping. */+class MarkdownBlocksTest {++ private static MarkdownBlock block(String markdown) {+ return new MarkdownBlock(markdown, 1, 1);+ }++ private static List<MarkdownBlock> blocks(String... markdown) {+ List<MarkdownBlock> out = new ArrayList<>(markdown.length);+ for (String md : markdown) {+ out.add(block(md));+ }+ return out;+ }++ private static List<String> markdownOf(List<MarkdownBlock> blocks) {+ return blocks.stream().map(MarkdownBlock::markdown).toList();+ }++ @Nested+ @DisplayName("join")+ class Join {++ @Test+ void separatesBlocksWithABlankLine() {+ assertEquals("a\n\nb\n\nc", MarkdownBlocks.join(blocks("a", "b", "c")));+ }++ @Test+ void keepsEmptyBlocksSoTheSeparatorRunSurvives() {+ assertEquals("a\n\n\n\nb", MarkdownBlocks.join(blocks("a", "", "b")));+ }++ @Test+ void joinsNothingToAnEmptyString() {+ assertEquals("", MarkdownBlocks.join(List.of()));+ }+ }++ @Nested+ @DisplayName("heading-level rebasing over a block list")+ class Rebasing {++ @Test+ void rebasesTheStrongestHeadingToLevelOne() {+ List<MarkdownBlock> out =+ MarkdownBlocks.normaliseHeadingLevels(blocks("### CONTENTS", "body"));+ assertEquals(List.of("# CONTENTS", "body"), markdownOf(out));+ }++ @Test+ void closesTheGapBetweenLevelsThatAreKept() {+ List<MarkdownBlock> out =+ MarkdownBlocks.normaliseHeadingLevels(+ blocks("# Title", "text", "### Section", "more"));+ assertEquals(List.of("# Title", "text", "## Section", "more"), markdownOf(out));+ }++ @Test+ void leavesAnAlreadyRootedGaplessDocumentAlone() {+ List<MarkdownBlock> input = blocks("# Title", "## Section", "body");+ assertSame(input, MarkdownBlocks.normaliseHeadingLevels(input));+ }++ @Test+ void decidesOnceOverTheWholeDocumentRatherThanPerBlock() {+ // In isolation "### Deep" would rebase to "#"; against the document's own level 1 it+ // must only close the gap.+ List<MarkdownBlock> out =+ MarkdownBlocks.normaliseHeadingLevels(blocks("# Top", "### Deep"));+ assertEquals(List.of("# Top", "## Deep"), markdownOf(out));+ }++ @Test+ void keepsPagesAndHeadingPathsWhileRewritingTheMarkdown() {+ MarkdownBlock in = new MarkdownBlock("### Deep", 4, 5, List.of("kept"));+ MarkdownBlock out = MarkdownBlocks.normaliseHeadingLevels(List.of(in)).getFirst();+ assertEquals("# Deep", out.markdown());+ assertEquals(4, out.pageStart());+ assertEquals(5, out.pageEnd());+ assertEquals(List.of("kept"), out.headingPath());+ }+ }++ @Nested+ @DisplayName("headingLevel")+ class HeadingLevel {++ @Test+ void readsTheLevelOfABlocksOwnFirstLine() {+ assertEquals(1, MarkdownBlocks.headingLevel("# Title"));+ assertEquals(6, MarkdownBlocks.headingLevel("###### Deep"));+ }++ @Test+ void rejectsAnythingThatIsNotAHeadingAtTheVeryStart() {+ assertEquals(0, MarkdownBlocks.headingLevel("body\n# Not a heading block"));+ assertEquals(0, MarkdownBlocks.headingLevel("####### Seven is not a level"));+ assertEquals(0, MarkdownBlocks.headingLevel("#NoSpace"));+ assertEquals(0, MarkdownBlocks.headingLevel("# "));+ assertEquals(0, MarkdownBlocks.headingLevel("| Name | Qty |"));+ assertEquals(0, MarkdownBlocks.headingLevel("\\# escaped body text"));+ assertEquals(0, MarkdownBlocks.headingLevel(""));+ }+ }++ @Nested+ @DisplayName("heading paths")+ class HeadingPaths {++ @Test+ void aHeadingIncludesItselfAndBodyInheritsTheOpenChain() {+ List<MarkdownBlock> out =+ MarkdownBlocks.withHeadingPaths(+ blocks("preamble", "# Top", "body", "## Sub", "more body"));+ assertEquals(List.of(), out.get(0).headingPath());+ assertEquals(List.of("Top"), out.get(1).headingPath());+ assertEquals(List.of("Top"), out.get(2).headingPath());+ assertEquals(List.of("Top", "Sub"), out.get(3).headingPath());+ assertEquals(List.of("Top", "Sub"), out.get(4).headingPath());+ }++ @Test+ void aSiblingReplacesAndAShallowerHeadingPopsTheChain() {+ List<MarkdownBlock> out =+ MarkdownBlocks.withHeadingPaths(+ blocks("# A", "## A1", "### A1a", "## A2", "# B", "tail"));+ assertEquals(List.of("A", "A1", "A1a"), out.get(2).headingPath());+ assertEquals(List.of("A", "A2"), out.get(3).headingPath());+ assertEquals(List.of("B"), out.get(4).headingPath());+ assertEquals(List.of("B"), out.get(5).headingPath());+ }++ @Test+ void readsHeadingTextAsThePageDoesRatherThanAsMarkdown() {+ List<MarkdownBlock> out =+ MarkdownBlocks.withHeadingPaths(blocks("# Q3 \\*net\\* revenue \\[USD\\]"));+ assertEquals(List.of("Q3 *net* revenue [USD]"), out.getFirst().headingPath());+ }++ @Test+ void leavesTheMarkdownAndPagesUntouched() {+ MarkdownBlock in = new MarkdownBlock("# Title", 2, 3);+ MarkdownBlock out = MarkdownBlocks.withHeadingPaths(List.of(in)).getFirst();+ assertEquals("# Title", out.markdown());+ assertEquals(2, out.pageStart());+ assertEquals(3, out.pageEnd());+ }+ }++ @Nested+ @DisplayName("unescape")+ class Unescape {++ @Test+ void dropsTheBackslashBeforeEveryCharacterEscapingAdds() {+ assertEquals("*_[]<>|~`", MarkdownBlocks.unescape("\\*\\_\\[\\]\\<\\>\\|\\~\\`"));+ assertEquals("# leading", MarkdownBlocks.unescape("\\# leading"));+ assertEquals("1. item", MarkdownBlocks.unescape("1\\. item"));+ assertEquals("2) item", MarkdownBlocks.unescape("2\\) item"));+ }++ @Test+ void restoresAGenuineBackslashFromItsEscapedPair() {+ assertEquals("C:\\path", MarkdownBlocks.unescape("C:\\\\path"));+ }++ @Test+ void keepsABackslashThatNeverCameFromEscaping() {+ assertEquals("\\q", MarkdownBlocks.unescape("\\q"));+ assertEquals("ends with \\", MarkdownBlocks.unescape("ends with \\"));+ }+ }++ @Nested+ @DisplayName("MarkdownBlock")+ class Block {++ @Test+ void defaultsAMissingHeadingPathToEmptyAndCopiesTheOneGiven() {+ assertEquals(List.of(), new MarkdownBlock("x", 1, 1, null).headingPath());+ List<String> source = new ArrayList<>(List.of("Top"));+ MarkdownBlock block = new MarkdownBlock("x", 1, 1, source);+ source.add("mutated after construction");+ assertEquals(List.of("Top"), block.headingPath());+ assertThrows(+ UnsupportedOperationException.class, () -> block.headingPath().add("nope"));+ }++ @Test+ void withersReplaceOneFieldAndKeepTheRest() {+ MarkdownBlock block = new MarkdownBlock("original", 2, 4, List.of("Top"));+ assertEquals(+ new MarkdownBlock("replaced", 2, 4, List.of("Top")),+ block.withMarkdown("replaced"));+ assertEquals(+ new MarkdownBlock("original", 2, 4, List.of("Other")),+ block.withHeadingPath(List.of("Other")));+ }+ }+}diff --git a/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterMoreTest.java b/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterMoreTest.javaindex 4dc43f7772..a99bdaa4db 100644--- a/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterMoreTest.java+++ b/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterMoreTest.java@@ -16,8 +16,6 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;import stirling.software.jpdfium.PdfDocument;-import stirling.software.jpdfium.text.PageText;-import stirling.software.jpdfium.text.Table;import stirling.software.jpdfium.text.TextChar;import stirling.software.jpdfium.text.TextLine;import stirling.software.jpdfium.text.TextWord;@@ -149,53 +147,6 @@ class PdfMarkdownConverterMoreTest {}}- // ---- package-private extraction helpers ----------------------------------- @Nested- @DisplayName("extraction helpers")- class ExtractionHelpers {-- @Test- @DisplayName("extractAllPageText returns one PageText per page")- void extractAllPageText() throws IOException {- Path pdf = fixture("bordered-table-test_widget.pdf");- try (PdfDocument doc = PdfDocument.open(pdf)) {- List<PageText> pages = new PdfMarkdownConverter().extractAllPageText(doc);- assertThat(pages).isNotNull();- assertThat(pages).hasSize(doc.pageCount());- }- }-- @Test- @DisplayName("extractTables returns a non-null list for the first page")- void extractTables() throws IOException {- Path pdf = fixture("bordered-table-test_widget.pdf");- try (PdfDocument doc = PdfDocument.open(pdf)) {- List<Table> tables = new PdfMarkdownConverter().extractTables(doc, 0);- assertThat(tables).isNotNull();- }- }-- @Test- @DisplayName("renderTables maps each extracted table to a markdown string")- void renderTables() throws IOException {- Path pdf = fixture("bordered-table-test_widget.pdf");- PdfMarkdownConverter converter = new PdfMarkdownConverter();- try (PdfDocument doc = PdfDocument.open(pdf)) {- List<Table> tables = converter.extractTables(doc, 0);- List<String> rendered = converter.renderTables(tables);- assertThat(rendered).isNotNull();- assertThat(rendered).hasSameSizeAs(tables);- }- }-- @Test- @DisplayName("renderTables on an empty table list returns an empty list")- void renderTablesEmpty() {- assertThat(new PdfMarkdownConverter().renderTables(List.of())).isEmpty();- }- }-// ---- full conversion of additional fixtures -----------------------------@Nesteddiff --git a/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterTest.java b/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterTest.javaindex 7e1d3d2e35..c6756e7a57 100644--- a/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterTest.java+++ b/app/common/src/test/java/stirling/software/common/pdf/PdfMarkdownConverterTest.java@@ -1,6 +1,8 @@package stirling.software.common.pdf;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.junit.jupiter.api.Assertions.fail;@@ -11,6 +13,8 @@ import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;+import java.util.Set;+import java.util.TreeSet;import java.util.stream.Stream;import org.junit.jupiter.api.Disabled;@@ -97,7 +101,82 @@ class PdfMarkdownConverterTest {"implausible page span should disable column detection, not allocate from it");}- private void assertConversionMatchesGolden(String pdfName, String mdName) throws IOException {+ /**+ * The block list carries the pages a reader would cite, so it must survive a page break: this+ * fixture's third table runs off page 2 and is stitched back together on page 3.+ */+ @Test+ void blocksCarryPagesAndAStitchedTableSpansThePageBreak() throws IOException {+ Path pdfPath = copyFixture("many-tables-test_stress.pdf");++ List<MarkdownBlock> blocks;+ int pageCount;+ try (PdfDocument doc = PdfDocument.open(pdfPath)) {+ pageCount = doc.pageCount();+ blocks = new PdfMarkdownConverter().extractBlocks(doc);+ }++ assertFalse(blocks.isEmpty(), "the fixture has text on every page");+ Set<Integer> covered = new TreeSet<>();+ int previousStart = 0;+ for (MarkdownBlock block : blocks) {+ assertTrue(block.pageStart() >= 1, "page numbers are 1-based: " + block.pageStart());+ assertTrue(block.pageEnd() >= block.pageStart(), "pageEnd cannot precede pageStart");+ assertTrue(block.pageEnd() <= pageCount, "pageEnd cannot exceed the document");+ assertTrue(block.pageStart() >= previousStart, "blocks come out in reading order");+ previousStart = block.pageStart();+ for (int p = block.pageStart(); p <= block.pageEnd(); p++) {+ covered.add(p);+ }+ }+ assertEquals(pageCount, covered.size(), "every page of the fixture contributes a block");++ List<MarkdownBlock> spanning =+ blocks.stream().filter(b -> b.pageEnd() > b.pageStart()).toList();+ assertEquals(1, spanning.size(), "only the stitched table spans a page break");+ MarkdownBlock stitched = spanning.getFirst();+ assertEquals(2, stitched.pageStart());+ assertEquals(3, stitched.pageEnd());+ assertTrue(stitched.markdown().startsWith("|"), "the stitched block is the GFM table");+ }++ @Test+ void headingPathsFollowTheHeadingStack() throws IOException {+ Path pdfPath = copyFixture("many-tables-test_stress.pdf");++ List<MarkdownBlock> blocks;+ try (PdfDocument doc = PdfDocument.open(pdfPath)) {+ blocks = new PdfMarkdownConverter().extractBlocks(doc);+ }++ int subIndex = indexOfMarkdown(blocks, "## Section 3 Heading");+ assertEquals(+ List.of("Section 2 Heading", "Section 3 Heading"),+ blocks.get(subIndex).headingPath(),+ "a heading includes itself under its parent");+ assertEquals(+ blocks.get(subIndex).headingPath(),+ blocks.get(subIndex + 1).headingPath(),+ "the block under a heading inherits its chain");++ int topIndex = indexOfMarkdown(blocks, "# Section 5 Heading");+ assertEquals(+ List.of("Section 5 Heading"),+ blocks.get(topIndex).headingPath(),+ "a top-level heading pops everything below it");+ }++ private static int indexOfMarkdown(List<MarkdownBlock> blocks, String markdown) {+ for (int i = 0; i < blocks.size(); i++) {+ if (blocks.get(i).markdown().equals(markdown)) {+ return i;+ }+ }+ fail("No block rendered as '" + markdown + "'");+ return -1;+ }++ private Path copyFixture(String pdfName) throws IOException {Path pdfPath = tmp.resolve(pdfName);try (InputStream in =getClass().getResourceAsStream("/pdf-ingestion-fixtures/" + pdfName)) {@@ -106,6 +185,11 @@ class PdfMarkdownConverterTest {}Files.copy(in, pdfPath);}+ return pdfPath;+ }++ private void assertConversionMatchesGolden(String pdfName, String mdName) throws IOException {+ Path pdfPath = copyFixture(pdfName);String actual;try (PdfDocument doc = PdfDocument.open(pdfPath)) {diff --git a/app/common/src/test/java/stirling/software/common/pdf/TableRendererTest.java b/app/common/src/test/java/stirling/software/common/pdf/TableRendererTest.javadeleted file mode 100644index 89bcb45760..0000000000--- a/app/common/src/test/java/stirling/software/common/pdf/TableRendererTest.java+++ /dev/null@@ -1,152 +0,0 @@-package stirling.software.common.pdf;--import static org.assertj.core.api.Assertions.assertThat;--import java.util.List;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--import stirling.software.jpdfium.text.Table;--/**- * Unit tests for {@link TableRenderer}. Tables are built directly from the {@link Table} record so- * the renderer can be exercised without any PDF parsing, fixtures, or native calls.- */-class TableRendererTest {-- /** Builds a Table from raw rows; geometry is irrelevant to rendering so it is set to zero. */- private static Table table(List<List<String>> rows) {- return new Table(rows, 0f, 0f, 0f, 0f);- }-- @Nested- @DisplayName("Degenerate tables")- class Degenerate {-- @Test- @DisplayName("zero rows renders the empty string")- void zeroRows() {- assertThat(TableRenderer.render(table(List.of()))).isEmpty();- }-- @Test- @DisplayName("single row with one column has no separator and is a plain line")- void singleRowOneColumn() {- String md = TableRenderer.render(table(List.of(List.of("only"))));- assertThat(md).isEqualTo("only");- assertThat(md).doesNotContain("|");- }-- @Test- @DisplayName("single row with several columns becomes newline-separated plain lines")- void singleRowManyColumns() {- String md = TableRenderer.render(table(List.of(List.of("a", "b", "c"))));- // No separator row is possible with a single row, so cells are emitted as lines.- assertThat(md).isEqualTo("a\nb\nc");- }-- @Test- @DisplayName("single-row cell content is trimmed and escaped")- void singleRowTrimsAndEscapes() {- String md = TableRenderer.render(table(List.of(List.of(" a|b "))));- assertThat(md).isEqualTo("a\\|b");- }- }-- @Nested- @DisplayName("GFM rendering")- class GfmRendering {-- @Test- @DisplayName("two rows produce a header, a separator and a data row")- void headerSeparatorData() {- String md =- TableRenderer.render(- table(List.of(List.of("Name", "Age"), List.of("Alice", "30"))));- String[] lines = md.split("\n");- assertThat(lines).hasSize(3);- assertThat(lines[0]).startsWith("|").contains("Name").contains("Age");- // Separator row is made only of pipes and dashes.- assertThat(lines[1].chars().allMatch(c -> c == '|' || c == '-')).isTrue();- assertThat(lines[2]).contains("Alice").contains("30");- }-- @Test- @DisplayName("column widths grow to fit the widest cell in each column")- void columnWidthsFitContent() {- String md =- TableRenderer.render(- table(- List.of(- List.of("h", "header2"),- List.of("averylongvalue", "x"))));- String[] lines = md.split("\n");- // Every rendered row (header, separator, data) is the same total width.- int width = lines[0].length();- for (String line : lines) {- assertThat(line.length()).isEqualTo(width);- }- }-- @Test- @DisplayName("minimum column width of three dashes is honoured for tiny cells")- void minimumWidthThree() {- String md = TableRenderer.render(table(List.of(List.of("a", "b"), List.of("c", "d"))));- String separator = md.split("\n")[1];- // Each column is padded to a minimum of 3, fenced by a dash either side: |-----|-----|.- assertThat(separator).isEqualTo("|-----|-----|");- }-- @Test- @DisplayName("pipe characters in cells are escaped in every rendered row")- void escapesPipes() {- String md =- TableRenderer.render(table(List.of(List.of("a|b", "c"), List.of("d", "e|f"))));- // Two literal pipes escaped; the structural pipes are not.- assertThat(md).contains("a\\|b").contains("e\\|f");- }-- @Test- @DisplayName("cells are trimmed before measuring and rendering")- void trimsCells() {- String md =- TableRenderer.render(- table(List.of(List.of(" Name ", " Age "), List.of("Al", "30"))));- assertThat(md).contains("| Name").contains("Age ");- assertThat(md).doesNotContain(" Name ");- }-- @Test- @DisplayName("three rows emit two data rows after the separator")- void multipleDataRows() {- String md =- TableRenderer.render(- table(- List.of(- List.of("c1", "c2"),- List.of("a", "b"),- List.of("x", "y"))));- String[] lines = md.split("\n");- assertThat(lines).hasSize(4);- assertThat(lines[2]).contains("a").contains("b");- assertThat(lines[3]).contains("x").contains("y");- }-- @Test- @DisplayName("a short trailing row is padded out to the column count from asGrid")- void shortRowPaddedByGrid() {- // colCount comes from the first row; a shorter later row is padded with empty cells by- // Table.asGrid, so rendering must not throw and the grid stays rectangular.- String md =- TableRenderer.render(table(List.of(List.of("a", "b", "c"), List.of("only"))));- String[] lines = md.split("\n");- assertThat(lines).hasSize(3);- int width = lines[0].length();- for (String line : lines) {- assertThat(line.length()).isEqualTo(width);- }- }- }-}diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex f096b0ad72..bc2a80486d 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -414,6 +414,11 @@ aiEngine:pdfComment: true # AI-authored PDF comments/annotationsclassify: true # Automatic document classification/labelling+# DocParse: document understanding for ingestion pipelines (chunking + knowledge-base+# indexing).+docparse:+ enabled: true # Master switch; hides the DocParse endpoints when false+formDetection:enabled: true # Master on/off switch for the Auto Form Detection featureactiveModelId: "" # Id of the installed Auto Form Detection model (set automatically after an admin installs one)diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/DocParseController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/DocParseController.javanew file mode 100644index 0000000000..be5795430a--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/DocParseController.java@@ -0,0 +1,212 @@+package stirling.software.proprietary.controller.api;++import java.io.BufferedOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.util.zip.ZipEntry;+import java.util.zip.ZipOutputStream;++import org.springframework.core.io.Resource;+import org.springframework.http.HttpHeaders;+import org.springframework.http.MediaType;+import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.ModelAttribute;+import org.springframework.web.bind.annotation.RequestMapping;+import org.springframework.web.bind.annotation.RestController;+import org.springframework.web.multipart.MultipartFile;++import io.swagger.v3.oas.annotations.Operation;+import io.swagger.v3.oas.annotations.tags.Tag;++import lombok.RequiredArgsConstructor;++import stirling.software.common.annotations.AutoJobPostMapping;+import stirling.software.common.enumeration.ResourceWeight;+import stirling.software.common.model.tool.ToolArity;+import stirling.software.common.model.tool.ToolFormat;+import stirling.software.common.model.tool.ToolIO;+import stirling.software.common.model.tool.ToolIOCase;+import stirling.software.common.model.tool.ToolIOWhen;+import stirling.software.common.util.TempFile;+import stirling.software.common.util.TempFileManager;+import stirling.software.common.util.WebResponseUtils;+import stirling.software.proprietary.model.api.docparse.IngestApiRequest;+import stirling.software.proprietary.model.docparse.DocChunk;+import stirling.software.proprietary.model.docparse.IngestOutcome;+import stirling.software.proprietary.service.AiToolResponseHeaders;+import stirling.software.proprietary.service.DocParseService;++import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.node.ObjectNode;++/**+ * Public DocParse ingestion API. Thin HTTP layer over {@link DocParseService}, which owns the+ * engine wire contract; this class owns the pipeline step shape (report header, export ZIP).+ */+@RestController+@RequestMapping("/api/v1/docparse")+@RequiredArgsConstructor+@Tag(+ name = "DocParse",+ description =+ "Document ingestion: chunk, embed, and index documents into the searchable"+ + " knowledge base, or export the parsed content (markdown, chunks JSONL)"+ + " for external systems.")+public class DocParseController {++ private final DocParseService docParseService;+ private final ObjectMapper objectMapper;+ private final TempFileManager tempFileManager;++ @AutoJobPostMapping(+ consumes = MediaType.MULTIPART_FORM_DATA_VALUE,+ value = "/ingest",+ resourceWeight = ResourceWeight.LARGE_WEIGHT)+ @ToolIO(+ produces = ToolFormat.PDF,+ arity = ToolArity.SIMO,+ cases = {+ @ToolIOCase(+ when = {+ @ToolIOWhen(param = "includeOriginal", matches = "false"),+ @ToolIOWhen(param = "exportMarkdown", matches = "false")+ },+ produces = ToolFormat.JSON,+ arity = ToolArity.SIMO),+ @ToolIOCase(+ when = {+ @ToolIOWhen(param = "includeOriginal", matches = "false"),+ @ToolIOWhen(param = "exportChunksJsonl", matches = "false")+ },+ produces = ToolFormat.MARKDOWN,+ arity = ToolArity.SIMO),+ @ToolIOCase(+ when = {+ @ToolIOWhen(param = "includeOriginal", matches = "false"),+ @ToolIOWhen(param = "exportMarkdown", matches = "true"),+ @ToolIOWhen(param = "exportChunksJsonl", matches = "true")+ },+ produces = ToolFormat.ANY,+ arity = ToolArity.SIMO)+ })+ @Operation(+ summary = "Chunk, embed, and index a document into the knowledge base (pipeline shape)",+ description =+ "Ingests the document into the engine's knowledge base under a stable documentId"+ + " (default: content hash). Returns a ZIP containing the original PDF"+ + " when includeOriginal is true and any selected markdown or chunks"+ + " JSONL exports. Pipelines unpack the ZIP for the next step. The"+ + " X-Stirling-Tool-Report header contains the ingest summary JSON.")+ public ResponseEntity<Resource> ingest(@ModelAttribute IngestApiRequest request)+ throws IOException {+ if (!request.isIncludeOriginal()+ && !request.isExportMarkdown()+ && !request.isExportChunksJsonl()) {+ throw new IllegalArgumentException(+ "Select at least one corpus export when excluding the original PDF");+ }+ IngestOutcome outcome = docParseService.ingest(request);++ // The report header must stay small: summary fields only, never the parsed content.+ ObjectNode report = objectMapper.createObjectNode();+ report.put("documentId", outcome.documentId());+ report.put("chunksIndexed", outcome.chunksIndexed());+ report.put("pages", outcome.pages());+ report.put("sourcePages", outcome.sourcePages());+ // Without this a capped ingest is indistinguishable from a complete one.+ report.put("truncated", outcome.truncated());+ report.put("indexed", request.isIndex());+ String reportJson = objectMapper.writeValueAsString(report);++ MultipartFile file = request.getFileInput();+ String fileName = DocParseService.fileName(file);++ // Stream the archive to disk: a 2 GB upload must never be held in heap, and this endpoint+ // is not queued, so several can run at once.+ TempFile zip = tempFileManager.createManagedTempFile(".zip");+ try {+ writeZip(zip, fileName, file, outcome, request);+ } catch (IOException e) {+ zip.close();+ throw e;+ }++ // fileToWebResponse streams the temp file and deletes it once the response body is closed.+ ResponseEntity<Resource> response =+ WebResponseUtils.fileToWebResponse(+ zip,+ baseName(fileName) + "-ingested.zip",+ MediaType.parseMediaType("application/zip"));+ HttpHeaders headers = new HttpHeaders();+ headers.addAll(response.getHeaders());+ headers.set(AiToolResponseHeaders.TOOL_REPORT, reportJson);+ return new ResponseEntity<>(response.getBody(), headers, response.getStatusCode());+ }++ /** Original + requested corpus files in one ZIP, so destinations receive them together. */+ private void writeZip(+ TempFile target,+ String fileName,+ MultipartFile file,+ IngestOutcome outcome,+ IngestApiRequest request)+ throws IOException {+ String base = baseName(fileName);+ try (ZipOutputStream zip =+ new ZipOutputStream(+ new BufferedOutputStream(Files.newOutputStream(target.getPath())))) {+ if (request.isIncludeOriginal()) {+ zip.putNextEntry(new ZipEntry(fileName));+ // Copied from the upload's stream (disk-backed for large files) rather than+ // getBytes(), so the original is never materialised in heap.+ try (InputStream original = file.getInputStream()) {+ original.transferTo(zip);+ }+ zip.closeEntry();+ }+ if (request.isExportMarkdown()) {+ zip.putNextEntry(new ZipEntry(base + ".md"));+ zip.write(+ (outcome.markdown() == null ? "" : outcome.markdown())+ .getBytes(StandardCharsets.UTF_8));+ zip.closeEntry();+ }+ if (request.isExportChunksJsonl()) {+ zip.putNextEntry(new ZipEntry(base + ".chunks.jsonl"));+ zip.write(chunksJsonl(outcome).getBytes(StandardCharsets.UTF_8));+ zip.closeEntry();+ }+ }+ }++ /** One chunk per line, each self-describing: the documentId travels on every line. */+ private String chunksJsonl(IngestOutcome outcome) {+ if (outcome.chunks() == null) {+ return "";+ }+ StringBuilder lines = new StringBuilder();+ for (DocChunk chunk : outcome.chunks()) {+ ObjectNode line = objectMapper.createObjectNode();+ line.put("documentId", outcome.documentId());+ line.put("index", chunk.index());+ line.put("text", chunk.text());+ if (chunk.pageStart() != null) {+ line.put("pageStart", chunk.pageStart());+ }+ if (chunk.pageEnd() != null) {+ line.put("pageEnd", chunk.pageEnd());+ }+ var headings = line.putArray("headingPath");+ chunk.headingPath().forEach(headings::add);+ lines.append(objectMapper.writeValueAsString(line)).append('\n');+ }+ return lines.toString();+ }++ private static String baseName(String fileName) {+ int dot = fileName.lastIndexOf('.');+ return dot > 0 ? fileName.substring(0, dot) : fileName;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/docparse/IngestApiRequest.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/docparse/IngestApiRequest.javanew file mode 100644index 0000000000..87b5600505--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/docparse/IngestApiRequest.java@@ -0,0 +1,51 @@+package stirling.software.proprietary.model.api.docparse;++import io.swagger.v3.oas.annotations.media.Schema;++import lombok.Data;+import lombok.EqualsAndHashCode;++import stirling.software.common.model.api.PDFFile;++@Data+@EqualsAndHashCode(callSuper = true)+public class IngestApiRequest extends PDFFile {++ @Schema(+ description =+ "Stable identifier for the ingested document; re-ingesting the same id replaces"+ + " its chunks. Defaults to a content hash of the uploaded bytes.")+ private String documentId;++ @Schema(+ description = "Include the input PDF alongside the requested corpus files",+ defaultValue = "true")+ private boolean includeOriginal = true;++ @Schema(description = "Target chunk size in characters (64-32768)", defaultValue = "512")+ private int chunkSize = 512;++ @Schema(+ description = "Overlap between adjacent chunks in characters (0-4096)",+ defaultValue = "64")+ private int overlap = 64;++ @Schema(+ description = "Index the document into the built-in knowledge base",+ defaultValue = "true")+ private boolean index = true;++ @Schema(+ description =+ "Also return the parsed document as a markdown file, for delivery to external"+ + " systems (vector DBs, training corpora)",+ defaultValue = "false")+ private boolean exportMarkdown = false;++ @Schema(+ description =+ "Also return the chunks as a JSONL file (one chunk per line with page span and"+ + " heading breadcrumb), ready for external embedding or indexing",+ defaultValue = "false")+ private boolean exportChunksJsonl = false;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/DocChunk.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/DocChunk.javanew file mode 100644index 0000000000..3468a0d460--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/DocChunk.java@@ -0,0 +1,12 @@+package stirling.software.proprietary.model.docparse;++import java.util.List;++/** One chunk with page span and heading breadcrumb. Mirrors {@code docparse.py DocChunk}. */+public record DocChunk(+ int index, String text, Integer pageStart, Integer pageEnd, List<String> headingPath) {++ public DocChunk {+ headingPath = headingPath == null ? List.of() : headingPath;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/IngestOutcome.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/IngestOutcome.javanew file mode 100644index 0000000000..b4dda02bae--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/IngestOutcome.java@@ -0,0 +1,13 @@+package stirling.software.proprietary.model.docparse;++import java.util.List;++/** Everything the controller needs to build the report header and the export ZIP. */+public record IngestOutcome(+ String documentId,+ int chunksIndexed,+ List<DocChunk> chunks,+ String markdown,+ int pages,+ int sourcePages,+ boolean truncated) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/IngestRequest.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/IngestRequest.javanew file mode 100644index 0000000000..fcf04f604f--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/IngestRequest.java@@ -0,0 +1,26 @@+package stirling.software.proprietary.model.docparse;++import java.time.Instant;+import java.util.List;++import stirling.software.common.pdf.MarkdownBlock;++/**+ * Engine request for {@code POST /api/v1/docparse/ingest}. Java converts the PDF to page-attributed+ * Markdown blocks; the engine packs them into chunks, embeds and indexes them. Owner semantics+ * mirror {@code POST /api/v1/documents}: {@code ownerId} is the tenant, {@code readPrincipals} the+ * explicit readers, and a null {@code expiresAt} keeps the ingested content until an explicit+ * delete. {@code index} false skips the store (export-only); {@code includeChunks} returns the+ * chunks so the caller can emit a corpus file.+ */+public record IngestRequest(+ String documentId,+ String source,+ String ownerId,+ List<String> readPrincipals,+ Instant expiresAt,+ List<MarkdownBlock> blocks,+ int chunkSize,+ int overlap,+ boolean index,+ boolean includeChunks) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/IngestResponse.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/IngestResponse.javanew file mode 100644index 0000000000..bd9962bd70--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/docparse/IngestResponse.java@@ -0,0 +1,9 @@+package stirling.software.proprietary.model.docparse;++import java.util.List;++/**+ * Engine response for {@code POST /api/v1/docparse/ingest}. {@code chunks} is only present when the+ * request asked for it via includeChunks.+ */+public record IngestResponse(String documentId, int chunksIndexed, List<DocChunk> chunks) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/AdvancedPdfMarkdownConverter.java b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/AdvancedPdfMarkdownConverter.javaindex 95762d85bb..0ee3e53646 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/AdvancedPdfMarkdownConverter.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/AdvancedPdfMarkdownConverter.java@@ -12,6 +12,8 @@ import org.springframework.stereotype.Service;import lombok.extern.slf4j.Slf4j;+import stirling.software.common.pdf.MarkdownBlock;+import stirling.software.common.pdf.MarkdownBlocks;import stirling.software.common.pdf.PdfMarkdownExtractor;import stirling.software.jpdfium.PdfDocument;import stirling.software.jpdfium.PdfPage;@@ -29,15 +31,17 @@ import stirling.software.jpdfium.text.TextLine;public class AdvancedPdfMarkdownConverter implements PdfMarkdownExtractor {@Override- public String convert(PdfDocument doc) throws IOException {- List<String> rendered = new ArrayList<>();- for (Object e : buildElements(doc)) {- rendered.add(e instanceof TableBlock tb ? tb.render() : (String) e);+ public List<MarkdownBlock> extractBlocks(PdfDocument doc) throws IOException {+ List<Element> elements = buildElements(doc);+ List<MarkdownBlock> blocks = new ArrayList<>(elements.size());+ for (Element e : elements) {+ String md = e.value() instanceof TableBlock tb ? tb.render() : (String) e.value();+ blocks.add(new MarkdownBlock(md, e.pageStart(), e.pageEnd()));}- return MarkdownText.normaliseHeadingLevels(String.join("\n\n", rendered));+ return MarkdownBlocks.withHeadingPaths(MarkdownBlocks.normaliseHeadingLevels(blocks));}- private List<Object> buildElements(PdfDocument doc) throws IOException {+ private List<Element> buildElements(PdfDocument doc) throws IOException {List<PageText> allPageText = PdfTextExtractor.extractAll(doc);float medianSize = HeadingDetector.medianFontSize(allPageText);float medianHeight = HeadingDetector.medianLineHeight(allPageText);@@ -46,7 +50,7 @@ public class AdvancedPdfMarkdownConverter implements PdfMarkdownExtractor {int pageCount = doc.pageCount();// Tables stay structured until after the page loop so one split across a page break can// be stitched back together before rendering.- List<Object> output = new ArrayList<>();+ List<Element> output = new ArrayList<>();// Header of a table that ended the previous page, for spotting a continuation; null if// none.String prevPageTrailingTableHeader = null;@@ -54,12 +58,12 @@ public class AdvancedPdfMarkdownConverter implements PdfMarkdownExtractor {for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {PageLines page = pageLines(doc, allPageText, pageIndex);if (page.lines().isEmpty()) {- PageImages.emit(doc, pageIndex, output);+ PageImages.emit(doc, pageIndex, pageIndex + 1, output);prevPageTrailingTableHeader = null;continue;}- List<Object> pageItems =+ List<Element> pageItems =buildPageItems(doc,page,@@ -107,7 +111,7 @@ public class AdvancedPdfMarkdownConverter implements PdfMarkdownExtractor {* One page's elements: paragraph strings interleaved with {@link TableBlock}s in reading order.* {@code continuationHeader} is the previous page's trailing table header, or null.*/- private List<Object> buildPageItems(+ private List<Element> buildPageItems(PdfDocument doc,PageLines page,int pageIndex,@@ -191,7 +195,7 @@ public class AdvancedPdfMarkdownConverter implements PdfMarkdownExtractor {}}- List<Object> pageItems = new ArrayList<>();+ List<Element> pageItems = new ArrayList<>();List<List<Line>> segments = segmentsAround(lines, blocks, tableLines);if (twoColumn) {// A full-width table interrupts both columns, so splitting at its own vertical band@@ -205,10 +209,12 @@ public class AdvancedPdfMarkdownConverter implements PdfMarkdownExtractor {List<String> paras = new ArrayList<>();ParagraphAssembler.assembleParagraphs(col, medianSize, medianHeight, bodyFont, paras, tableRowTexts);- pageItems.addAll(paras);+ for (String p : paras) {+ pageItems.add(new Element(p, pageIndex + 1, pageIndex + 1));+ }}if (s < blocks.size()) {- pageItems.add(blocks.get(s));+ pageItems.add(new Element(blocks.get(s), pageIndex + 1, pageIndex + 1));}}} else {@@ -218,14 +224,16 @@ public class AdvancedPdfMarkdownConverter implements PdfMarkdownExtractor {List<String> paras = new ArrayList<>();ParagraphAssembler.assembleParagraphs(segments.get(s), medianSize, medianHeight, bodyFont, paras, tableRowTexts);- pageItems.addAll(paras);+ for (String p : paras) {+ pageItems.add(new Element(p, pageIndex + 1, pageIndex + 1));+ }if (s < blocks.size()) {- pageItems.add(blocks.get(s));+ pageItems.add(new Element(blocks.get(s), pageIndex + 1, pageIndex + 1));}}}- PageImages.emit(doc, pageIndex, pageItems);+ PageImages.emit(doc, pageIndex, pageIndex + 1, pageItems);return pageItems;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/Element.java b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/Element.javanew file mode 100644index 0000000000..137f1188e4--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/Element.java@@ -0,0 +1,4 @@+package stirling.software.proprietary.pdf;++/** An element plus the 1-based pages it came from; pageEnd widens when a page break is joined. */+record Element(Object value, int pageStart, int pageEnd) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/MarkdownText.java b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/MarkdownText.javaindex 316650eefc..1663608a5c 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/MarkdownText.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/MarkdownText.java@@ -1,53 +1,12 @@package stirling.software.proprietary.pdf;-import java.util.HashMap;import java.util.List;-import java.util.Map;-import java.util.Set;-import java.util.TreeSet;-import java.util.regex.Matcher;-import java.util.regex.Pattern;-/**- * Markdown text utilities: escaping extracted text and rebasing the finished document's heading- * levels.- */+/** Markdown text utilities for escaping extracted text so it is emitted literally. */final class MarkdownText {private MarkdownText() {}- /** A Markdown ATX heading at the start of a line, with its level in group 1. */- private static final Pattern ATX_HEADING = Pattern.compile("(?m)^(#{1,6}) (?=\\S)");-- /**- * Rebases headings so the strongest is level 1 and no level is skipped: levels only mean- * anything against the other headings in the same document.- */- static String normaliseHeadingLevels(String markdown) {- Set<Integer> levels = new TreeSet<>();- Matcher m = ATX_HEADING.matcher(markdown);- while (m.find()) {- levels.add(m.group(1).length());- }- if (levels.isEmpty() || (levels.contains(1) && levels.size() == maxOf(levels))) {- return markdown;- }- Map<Integer, String> rebased = new HashMap<>();- int rank = 1;- for (int level : levels) {- rebased.put(level, "#".repeat(rank++));- }- return m.reset().replaceAll(r -> rebased.get(r.group(1).length()) + " ");- }-- private static int maxOf(Set<Integer> levels) {- int max = 0;- for (int level : levels) {- max = Math.max(max, level);- }- return max;- }-static int wordCount(String text) {return text.isBlank() ? 0 : text.strip().split("\\s+").length;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/PageImages.java b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/PageImages.javaindex 932f83c50d..3631f92042 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/PageImages.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/PageImages.java@@ -5,6 +5,7 @@ import java.util.ArrayList;import java.util.List;import java.util.Locale;+import stirling.software.common.pdf.MarkdownBlocks;import stirling.software.jpdfium.PdfDocument;import stirling.software.jpdfium.PdfPage;import stirling.software.jpdfium.doc.ExtractedImage;@@ -19,12 +20,13 @@ final class PageImages {private PageImages() {}- static void emit(PdfDocument doc, int pageIndex, List<Object> pageItems) throws IOException {+ static void emit(PdfDocument doc, int pageIndex, int pageNumber, List<Element> sink)+ throws IOException {try (PdfPage page = doc.page(pageIndex)) {List<ExtractedImage> images =PdfImageExtractor.extract(page.rawDocHandle(), page.rawHandle(), pageIndex);for (ExtractedImage img : images) {- pageItems.add(describe(img));+ sink.add(new Element(describe(img), pageNumber, pageNumber));}}}@@ -60,7 +62,7 @@ final class PageImages {parts.add(img.bitsPerPixel() + "bpp");}- StringBuilder sb = new StringBuilder("<image redacted");+ StringBuilder sb = new StringBuilder(MarkdownBlocks.IMAGE_PLACEHOLDER);if (!parts.isEmpty()) {sb.append(": ").append(String.join(", ", parts));}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/PageStitcher.java b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/PageStitcher.javaindex 31a8a77381..00b7f5fe8b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/PageStitcher.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/PageStitcher.java@@ -5,6 +5,8 @@ import java.util.Comparator;import java.util.List;import java.util.stream.Collectors;+import stirling.software.common.pdf.MarkdownBlocks;+/*** Joins what a page break split: a sentence running into the next page, and a table whose rows* continue on it.@@ -13,20 +15,24 @@ final class PageStitcher {private PageStitcher() {}- static void mergeAcrossPageBoundary(List<Object> output, List<Object> pageItems) {+ static void mergeAcrossPageBoundary(List<Element> output, List<Element> pageItems) {if (output.isEmpty() || pageItems.isEmpty()) {return;}// Only merge a sentence continuation between two text paragraphs, never into/out of a// table.- if (!(output.getLast() instanceof String last)- || !(pageItems.getFirst() instanceof String first)) {+ if (!(output.getLast().value() instanceof String last)+ || !(pageItems.getFirst().value() instanceof String first)) {return;}if (!first.isEmpty()&& Character.isLowerCase(first.charAt(0))&& !MarkdownText.endsWithSentencePunctuation(last)) {- output.set(output.size() - 1, last + " " + first);+ Element head = output.getLast();+ Element tail = pageItems.getFirst();+ output.set(+ output.size() - 1,+ new Element(last + " " + first, head.pageStart(), tail.pageEnd()));pageItems.remove(0);}}@@ -35,18 +41,18 @@ final class PageStitcher {* Joins tables split across a page break: two consecutive blocks with no text between them* merge when their column layouts match, dropping a repeated header.*/- static List<Object> stitchTables(List<Object> elements) {- List<Object> out = new ArrayList<>();+ static List<Element> stitchTables(List<Element> elements) {+ List<Element> out = new ArrayList<>();// Column geometry of the trailing TableBlock in `out`, carried forward across merges so a// table running page-to-page is not re-projected from every accumulated row at each break.ColumnAccumulator acc = null;// Row list we own and may append to in place; null while the trailing block still holds a// list belonging to `elements`.List<List<Line>> ownedRows = null;- for (Object e : elements) {- if (e instanceof TableBlock tb+ for (Element e : elements) {+ if (e.value() instanceof TableBlock tb&& !out.isEmpty()- && out.getLast() instanceof TableBlock prev) {+ && out.getLast().value() instanceof TableBlock prev) {if (acc == null) {acc = ColumnAccumulator.of(prev.rows());}@@ -72,16 +78,20 @@ final class PageStitcher {merged.addAll(tail);// A stitched table belongs to where it started, so keep the earlier block's// page and columns; its ruling lines are dropped as they are one page's only.+ Element prevEl = out.getLast();out.set(out.size() - 1,- new TableBlock(- merged,- prev.top(),- tb.bottom(),- prev.cols(),- prev.ruled(),- prev.rowSource(),- prev.page()));+ new Element(+ new TableBlock(+ merged,+ prev.top(),+ tb.bottom(),+ prev.cols(),+ prev.ruled(),+ prev.rowSource(),+ prev.page()),+ prevEl.pageStart(),+ Math.max(prevEl.pageEnd(), e.pageEnd())));continue;}}@@ -100,10 +110,10 @@ final class PageStitcher {* Header text of a table at the very bottom of a page, or null. Trailing image placeholders are* skipped; any other text means it is not a continuation.*/- static String trailingTableHeader(List<Object> pageItems) {+ static String trailingTableHeader(List<Element> pageItems) {for (int i = pageItems.size() - 1; i >= 0; i--) {- Object e = pageItems.get(i);- if (e instanceof String s && s.strip().startsWith("<image redacted")) {+ Object e = pageItems.get(i).value();+ if (e instanceof String s && MarkdownBlocks.isImagePlaceholder(s)) {continue;}if (e instanceof TableBlock tb && !tb.rows().isEmpty()) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.javaindex 5b302e5987..95fb7adb86 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java@@ -78,6 +78,7 @@ public class PolicyValidator {inputSourceFor(spec).validate(spec);}validateRoutingRules(policy);+ validateEditorOutput(policy);validateSteps(policy.steps());validateAssetReferences(policy);validateChain(policy.steps());@@ -188,6 +189,27 @@ public class PolicyValidator {return toolChainValidator.validate(chain, sourceFormat);}+ /** Corpus files must be delivered to a destination, never imported into the editor. */+ public void validateEditorOutput(Policy policy) {+ if (!policy.editor().allowed()+ || !policy.outputIds().isEmpty()+ || !"inline".equals(policy.output().type())) {+ return;+ }+ for (PipelineStep step : policy.steps()) {+ if (!"/api/v1/docparse/ingest".equals(step.operation())) {+ continue;+ }+ Map<String, Object> params = step.parameters();+ if (Boolean.parseBoolean(String.valueOf(params.get("exportChunksJsonl")))+ || Boolean.parseBoolean(String.valueOf(params.get("exportMarkdown")))+ || "false".equalsIgnoreCase(String.valueOf(params.get("includeOriginal")))) {+ throw new IllegalArgumentException(+ "Choose a file or database destination for chunk and Markdown exports. These files cannot be returned to the editor.");+ }+ }+ }+/*** Validate each step against every registered {@link PipelineStepValidator}. Must be called on* a request thread (caller's principal present) for the same reason as {@linkdiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.javanew file mode 100644index 0000000000..c2e47c22c9--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java@@ -0,0 +1,235 @@+package stirling.software.proprietary.service;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.StandardCopyOption;+import java.util.ArrayList;+import java.util.List;+import java.util.Set;+import java.util.TreeSet;++import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.http.HttpStatus;+import org.springframework.stereotype.Service;+import org.springframework.web.multipart.MultipartFile;+import org.springframework.web.server.ResponseStatusException;++import io.github.pixee.security.Filenames;++import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.pdf.MarkdownBlock;+import stirling.software.common.pdf.MarkdownBlocks;+import stirling.software.common.pdf.PdfMarkdownExtractor;+import stirling.software.common.service.UserServiceInterface;+import stirling.software.common.util.TempFile;+import stirling.software.common.util.TempFileManager;+import stirling.software.jpdfium.PdfDocument;+import stirling.software.proprietary.model.api.docparse.IngestApiRequest;+import stirling.software.proprietary.model.docparse.DocChunk;+import stirling.software.proprietary.model.docparse.IngestOutcome;+import stirling.software.proprietary.model.docparse.IngestRequest;+import stirling.software.proprietary.model.docparse.IngestResponse;++import tools.jackson.databind.ObjectMapper;++/**+ * DocParse ingestion: layout-aware Markdown conversion (the same {@link PdfMarkdownExtractor} that+ * backs {@code /pdf/markdown}) plus engine dispatch for chunk + embed + index. The engine owns+ * chunking, embedding, and the document store; Java owns identity, limits, and the wire contract+ * from {@code engine/src/stirling/contracts/docparse.py}.+ *+ * <p>jpdfium serialises natively (NativeGuard's process-wide lock); a LARGE_WEIGHT ingest holds it+ * for the whole document, so concurrent ingests queue behind each other and behind /pdf/markdown.+ */+@Slf4j+@Service+public class DocParseService {++ private static final String INGEST_ENDPOINT = "/api/v1/docparse/ingest";++ private final AiEngineClient aiEngineClient;+ private final PdfMarkdownExtractor markdownExtractor;+ private final TempFileManager tempFileManager;+ private final ApplicationProperties applicationProperties;+ private final ObjectMapper objectMapper;+ private final FileIdStrategy fileIdStrategy;+ private final UserServiceInterface userService;++ public DocParseService(+ AiEngineClient aiEngineClient,+ PdfMarkdownExtractor markdownExtractor,+ TempFileManager tempFileManager,+ ApplicationProperties applicationProperties,+ ObjectMapper objectMapper,+ FileIdStrategy fileIdStrategy,+ @Autowired(required = false) UserServiceInterface userService) {+ this.aiEngineClient = aiEngineClient;+ this.markdownExtractor = markdownExtractor;+ this.tempFileManager = tempFileManager;+ this.applicationProperties = applicationProperties;+ this.objectMapper = objectMapper;+ this.fileIdStrategy = fileIdStrategy;+ this.userService = userService;+ }++ /** Throws 503 when the docparse.enabled master switch is off. */+ public void requireEnabled() {+ if (!applicationProperties.getDocparse().isEnabled()) {+ throw new ResponseStatusException(+ HttpStatus.SERVICE_UNAVAILABLE, "DocParse is disabled");+ }+ }++ /**+ * Convert the document to Markdown blocks, then chunk, embed, and index them into the engine's+ * knowledge base and/or hand them back for corpus export.+ */+ public IngestOutcome ingest(IngestApiRequest apiRequest) throws IOException {+ requireEnabled();+ MultipartFile file = apiRequest.getFileInput();+ boolean index = apiRequest.isIndex();+ boolean includeChunks = apiRequest.isExportChunksJsonl();+ if (!index && !apiRequest.isExportMarkdown() && !includeChunks) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST,+ "Nothing to do: enable index, exportMarkdown, or exportChunksJsonl");+ }+ String documentId = apiRequest.getDocumentId();+ // Content hash default: re-ingesting identical bytes dedupes to the same document.+ String docId =+ (documentId == null || documentId.isBlank())+ ? fileIdStrategy.idFor(file)+ : documentId.trim();+ int size = Math.clamp(apiRequest.getChunkSize(), 64, 32_768);+ // Both bounds are satisfiable independently, so a caller can pass overlap >= chunkSize and+ // reach the engine's chunker with a zero or negative stride.+ int step = Math.clamp(apiRequest.getOverlap(), 0, 4_096);+ if (step >= size) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST,+ "overlap (" + step + ") must be smaller than chunkSize (" + size + ")");+ }++ List<MarkdownBlock> all;+ int sourcePages;+ try (TempFile tempInput = new TempFile(tempFileManager, ".pdf")) {+ // Copy rather than transferTo: transferTo moves the servlet part's backing file away,+ // and the controller still reads the upload afterwards to build the export ZIP.+ Files.copy(+ file.getInputStream(),+ tempInput.getPath(),+ StandardCopyOption.REPLACE_EXISTING);+ try (PdfDocument doc = PdfDocument.open(tempInput.getPath())) {+ sourcePages = doc.pageCount();+ all = markdownExtractor.extractBlocks(doc);+ }+ }++ Capped capped = applyLimits(all, sourcePages);+ List<MarkdownBlock> blocks = capped.blocks();+ if (hasNoText(blocks)) {+ // Caught here rather than at the engine: Java is what found no text, and the engine+ // cannot tell a scan from a genuinely empty file.+ throw new ResponseStatusException(+ HttpStatus.UNPROCESSABLE_ENTITY,+ "No extractable text: this document has no text layer. OCR it before ingesting.");+ }+ String markdown = MarkdownBlocks.join(blocks);+ int pages = pagesCovered(blocks);++ int chunksIndexed = 0;+ List<DocChunk> chunks = null;+ // Chunking lives in the engine, so an export-markdown-only run needs no round trip at all.+ if (index || includeChunks) {+ String callerId = currentUserId();+ // Null expiresAt = persistent until explicit delete; ingest here is a deliberate+ // knowledge-base action, unlike the TTL'd auto-ingest in AiWorkflowService.+ IngestRequest request =+ new IngestRequest(+ docId,+ fileName(file),+ callerId,+ // Engine forbids an empty list here (min_length=1); null means+ // "default to the owner" on the engine side.+ callerId == null ? null : List.of(callerId),+ null,+ blocks,+ size,+ step,+ index,+ includeChunks);+ String responseJson =+ aiEngineClient.postLongRunning(+ INGEST_ENDPOINT, objectMapper.writeValueAsString(request), callerId);+ IngestResponse response = objectMapper.readValue(responseJson, IngestResponse.class);+ chunksIndexed = response.chunksIndexed();+ chunks = response.chunks();+ }+ if (capped.truncated()) {+ log.warn("Ingest of {} reached the configured extraction limits", docId);+ }+ return new IngestOutcome(+ docId, chunksIndexed, chunks, markdown, pages, sourcePages, capped.truncated());+ }++ /** Apply the shared aiEngine caps over the block list, keeping whole blocks. */+ Capped applyLimits(List<MarkdownBlock> all, int sourcePages) {+ ApplicationProperties.AiEngine.Limits limits =+ applicationProperties.getAiEngine().getLimits();+ int maxPages = limits.getMaxPages();+ int remaining = limits.getMaxCharacters();+ boolean truncated = sourcePages > maxPages;+ List<MarkdownBlock> kept = new ArrayList<>();+ for (MarkdownBlock block : all) {+ // Blocks come out in reading order, so pageStart never goes backwards.+ if (block.pageStart() > maxPages) {+ truncated = true;+ break;+ }+ String md = block.markdown();+ if (md.isBlank()) {+ continue;+ }+ if (remaining == 0) {+ truncated = true;+ break;+ }+ if (md.length() > remaining) {+ truncated = true;+ md = md.substring(0, remaining);+ }+ kept.add(block.withMarkdown(md));+ remaining -= md.length();+ }+ return new Capped(kept, truncated);+ }++ record Capped(List<MarkdownBlock> blocks, boolean truncated) {}++ /** A scan converts to image placeholders rather than to nothing, so emptiness misses it. */+ private static boolean hasNoText(List<MarkdownBlock> blocks) {+ return blocks.stream()+ .allMatch(block -> MarkdownBlocks.isImagePlaceholder(block.markdown()));+ }++ private static int pagesCovered(List<MarkdownBlock> blocks) {+ Set<Integer> covered = new TreeSet<>();+ for (MarkdownBlock block : blocks) {+ for (int p = block.pageStart(); p <= block.pageEnd(); p++) {+ covered.add(p);+ }+ }+ return covered.size();+ }++ public static String fileName(MultipartFile file) {+ String name = Filenames.toSimpleFileName(file.getOriginalFilename());+ return (name == null || name.isBlank()) ? "document.pdf" : name;+ }++ private String currentUserId() {+ return userService != null ? userService.getCurrentUsername() : null;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/PdfContentExtractor.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/PdfContentExtractor.javaindex 9dccb91f38..0d3b921434 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/PdfContentExtractor.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/PdfContentExtractor.java@@ -94,6 +94,7 @@ public class PdfContentExtractor {*/public String extractPageTextRaw(PDDocument document, int pageNumber) throws IOException {PDFTextStripper stripper = new PDFTextStripper();+ stripper.setSortByPosition(true);stripper.setStartPage(pageNumber);stripper.setEndPage(pageNumber);String text = stripper.getText(document).trim();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/DocParseControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/DocParseControllerTest.javanew file mode 100644index 0000000000..a9bb565eb9--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/DocParseControllerTest.java@@ -0,0 +1,180 @@+package stirling.software.proprietary.controller.api;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.spy;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.zip.ZipEntry;+import java.util.zip.ZipInputStream;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.core.io.Resource;+import org.springframework.http.ResponseEntity;+import org.springframework.mock.web.MockMultipartFile;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.util.TempFileManager;+import stirling.software.common.util.TempFileRegistry;+import stirling.software.proprietary.model.api.docparse.IngestApiRequest;+import stirling.software.proprietary.model.docparse.DocChunk;+import stirling.software.proprietary.model.docparse.IngestOutcome;+import stirling.software.proprietary.service.AiToolResponseHeaders;+import stirling.software.proprietary.service.DocParseService;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.json.JsonMapper;++/**+ * The pipeline-facing shape of the ingest endpoint: the ZIP body the policy executor unpacks, and+ * the summary header it records as the step report.+ */+@ExtendWith(MockitoExtension.class)+class DocParseControllerTest {++ private static final byte[] PDF_BYTES = "%PDF-1.7 original".getBytes(StandardCharsets.UTF_8);++ @Mock private DocParseService docParseService;++ private final JsonMapper jsonMapper = JsonMapper.builder().build();++ private DocParseController controller() {+ return new DocParseController(+ docParseService,+ jsonMapper,+ new TempFileManager(new TempFileRegistry(), new ApplicationProperties()));+ }++ private static IngestApiRequest request(boolean markdown, boolean chunksJsonl) {+ IngestApiRequest request = new IngestApiRequest();+ request.setFileInput(+ new MockMultipartFile("fileInput", "invoice.pdf", "application/pdf", PDF_BYTES));+ request.setExportMarkdown(markdown);+ request.setExportChunksJsonl(chunksJsonl);+ return request;+ }++ private static IngestOutcome outcome(int pages, int sourcePages) {+ return new IngestOutcome(+ "doc-1",+ 3,+ List.of(new DocChunk(0, "body text", 1, 1, List.of("Invoice"))),+ "# Invoice\n\nbody text",+ pages,+ sourcePages,+ sourcePages > pages);+ }++ private void stubService(IngestOutcome result) throws IOException {+ when(docParseService.ingest(any())).thenReturn(result);+ }++ private static Map<String, String> unzip(Resource body) throws IOException {+ Map<String, String> entries = new HashMap<>();+ try (ZipInputStream zip = new ZipInputStream(body.getInputStream())) {+ ZipEntry entry;+ while ((entry = zip.getNextEntry()) != null) {+ entries.put(+ entry.getName(), new String(zip.readAllBytes(), StandardCharsets.UTF_8));+ }+ }+ return entries;+ }++ private JsonNode report(ResponseEntity<Resource> response) {+ String raw = response.getHeaders().getFirst(AiToolResponseHeaders.TOOL_REPORT);+ assertNotNull(raw, "the step report header must always be present");+ return jsonMapper.readTree(raw);+ }++ @Test+ void chunksOnlyStillReturnsAOneEntryZip() throws IOException {+ stubService(outcome(2, 2));+ IngestApiRequest request = request(false, true);+ request.setIncludeOriginal(false);+ var file = spy(request.getFileInput());+ request.setFileInput(file);+ Map<String, String> entries = unzip(controller().ingest(request).getBody());+ assertEquals(List.of("invoice.chunks.jsonl"), new ArrayList<>(entries.keySet()));+ verify(file, never()).getBytes();+ }++ @Test+ void excludingTheOriginalRequiresAnExport() {+ IngestApiRequest request = request(false, false);+ request.setIncludeOriginal(false);+ org.junit.jupiter.api.Assertions.assertThrows(+ IllegalArgumentException.class, () -> controller().ingest(request));+ }++ @Test+ void indexOnlyStillReturnsAZipSoTheResponseShapeNeverVaries() throws IOException {+ stubService(outcome(2, 2));++ ResponseEntity<Resource> response = controller().ingest(request(false, false));++ // A varying body would have to be declared as both SISO and SIMO; the executor reads one+ // doc-type per endpoint, so an index-only run returns the original inside a ZIP too.+ Map<String, String> entries = unzip(response.getBody());+ assertEquals(List.of("invoice.pdf"), new ArrayList<>(entries.keySet()));+ assertEquals(new String(PDF_BYTES, StandardCharsets.UTF_8), entries.get("invoice.pdf"));+ }++ @Test+ void exportsRideAlongsideTheUntouchedOriginal() throws IOException {+ stubService(outcome(2, 2));++ ResponseEntity<Resource> response = controller().ingest(request(true, true));++ Map<String, String> entries = unzip(response.getBody());+ assertEquals(3, entries.size());+ assertEquals(new String(PDF_BYTES, StandardCharsets.UTF_8), entries.get("invoice.pdf"));+ assertTrue(entries.get("invoice.md").contains("# Invoice"));++ JsonNode line = jsonMapper.readTree(entries.get("invoice.chunks.jsonl").strip());+ assertEquals("doc-1", line.get("documentId").asString());+ assertEquals("body text", line.get("text").asString());+ assertEquals(1, line.get("pageStart").asInt());+ assertEquals("Invoice", line.get("headingPath").get(0).asString());+ }++ @Test+ void theReportCarriesTheIngestSummary() throws IOException {+ stubService(outcome(2, 2));++ JsonNode report = report(controller().ingest(request(false, false)));++ assertEquals("doc-1", report.get("documentId").asString());+ assertEquals(3, report.get("chunksIndexed").asInt());+ assertEquals(2, report.get("pages").asInt());+ assertTrue(report.get("indexed").asBoolean());+ assertFalse(report.get("truncated").asBoolean());+ }++ @Test+ void aCappedIngestIsReportedAsTruncatedRatherThanComplete() throws IOException {+ // The aiEngine page and character caps stop extraction early; without this flag a+ // partially-indexed document is indistinguishable from a fully-indexed one.+ stubService(outcome(50, 900));++ JsonNode report = report(controller().ingest(request(false, false)));++ assertTrue(report.get("truncated").asBoolean());+ assertEquals(50, report.get("pages").asInt());+ assertEquals(900, report.get("sourcePages").asInt());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/model/docparse/DocparseWireContractTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/model/docparse/DocparseWireContractTest.javanew file mode 100644index 0000000000..55b7bb282a--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/model/docparse/DocparseWireContractTest.java@@ -0,0 +1,85 @@+package stirling.software.proprietary.model.docparse;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.util.List;++import org.junit.jupiter.api.Test;++import stirling.software.common.pdf.MarkdownBlock;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.json.JsonMapper;++/**+ * The Java DTOs must serialize to exactly the camelCase wire shapes defined in {@code+ * engine/src/stirling/contracts/docparse.py}; a drift here breaks ingestion silently.+ */+class DocparseWireContractTest {++ private final JsonMapper mapper = JsonMapper.builder().build();++ @Test+ void ingestRequestSerializesTheEngineContract() {+ IngestRequest request =+ new IngestRequest(+ "doc-1",+ "report.pdf",+ "user:alice",+ List.of("user:alice"),+ null,+ List.of(new MarkdownBlock("# Title", 1, 2, List.of("Title"))),+ 512,+ 64,+ true,+ true);++ JsonNode json = mapper.readTree(mapper.writeValueAsString(request));++ assertEquals("doc-1", json.get("documentId").asString());+ assertEquals("report.pdf", json.get("source").asString());+ assertEquals("user:alice", json.get("ownerId").asString());+ assertEquals("user:alice", json.get("readPrincipals").get(0).asString());+ JsonNode block = json.get("blocks").get(0);+ assertEquals("# Title", block.get("markdown").asString());+ assertEquals(1, block.get("pageStart").asInt());+ assertEquals(2, block.get("pageEnd").asInt());+ assertEquals("Title", block.get("headingPath").get(0).asString());+ assertEquals(512, json.get("chunkSize").asInt());+ assertEquals(64, json.get("overlap").asInt());+ assertTrue(json.get("index").asBoolean());+ assertTrue(json.get("includeChunks").asBoolean());+ // The engine rejects unknown keys (extra="forbid"), so the retired fields must be gone.+ assertNull(json.get("fileName"));+ assertNull(json.get("pages"));+ assertNull(json.get("mode"));+ assertNull(json.get("includeMarkdown"));+ }++ @Test+ void ingestResponseReadsTheEngineShapeIncludingEchoedChunks() {+ String engineJson =+ "{\"documentId\":\"doc-1\",\"chunksIndexed\":2,"+ + "\"chunks\":[{\"index\":0,\"text\":\"t\",\"pageStart\":1,\"pageEnd\":2,"+ + "\"headingPath\":[\"Intro\"]}]}";++ IngestResponse response = mapper.readValue(engineJson, IngestResponse.class);++ assertEquals("doc-1", response.documentId());+ assertEquals(2, response.chunksIndexed());+ assertEquals(1, response.chunks().size());+ assertEquals(List.of("Intro"), response.chunks().get(0).headingPath());+ }++ @Test+ void ingestResponseToleratesAbsentChunks() {+ String engineJson = "{\"documentId\":\"d\",\"chunksIndexed\":0}";++ IngestResponse response = mapper.readValue(engineJson, IngestResponse.class);++ assertNull(response.chunks());+ assertEquals(0, response.chunksIndexed());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/pdf/AdvancedPdfMarkdownConverterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/pdf/AdvancedPdfMarkdownConverterTest.javaindex 5cbf57bd11..5c98e4b550 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/pdf/AdvancedPdfMarkdownConverterTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/pdf/AdvancedPdfMarkdownConverterTest.java@@ -13,8 +13,16 @@ import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;+import java.util.Set;+import java.util.TreeSet;import java.util.stream.Stream;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.PDPageContentStream;+import org.apache.pdfbox.pdmodel.common.PDRectangle;+import org.apache.pdfbox.pdmodel.font.PDType1Font;+import org.apache.pdfbox.pdmodel.font.Standard14Fonts;import org.junit.jupiter.api.Disabled;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.Timeout;@@ -23,6 +31,8 @@ import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.Arguments;import org.junit.jupiter.params.provider.MethodSource;+import stirling.software.common.pdf.MarkdownBlock;+import stirling.software.common.pdf.MarkdownBlocks;import stirling.software.jpdfium.PdfDocument;import stirling.software.jpdfium.text.TextChar;import stirling.software.jpdfium.text.TextLine;@@ -160,20 +170,6 @@ class AdvancedPdfMarkdownConverterTest {assertEquals("he said ' hello", WordGeometry.rejoinContractions("he said ' hello"));}- @Test- void headingLevelsAreRebasedOnTheStrongestHeadingPresent() {- // A document whose headings are body-size and bold scores every one of them level 3;- // relative to each other they are its top level, so they must render as level 1.- assertEquals("# CONTENTS\n", MarkdownText.normaliseHeadingLevels("### CONTENTS\n"));- // A real two-level document keeps two levels, with no gap between them.- assertEquals(- "# Title\n\ntext\n\n## Section\n",- MarkdownText.normaliseHeadingLevels("# Title\n\ntext\n\n### Section\n"));- // Already rooted at level 1 with no gaps: left alone.- String unchanged = "# Title\n\n## Section\n";- assertEquals(unchanged, MarkdownText.normaliseHeadingLevels(unchanged));- }-/** A line of Han text has no spaces, so the word-count heading guard cannot measure it. */private static List<TextWord> cjkWords(String text, String font) {List<TextChar> chars = new ArrayList<>(text.length());@@ -367,7 +363,152 @@ class AdvancedPdfMarkdownConverterTest {"a rule flood should disable ruled-table detection, not scan it");}- private void assertConversionMatchesGolden(String pdfName, String mdName) throws IOException {+ /**+ * The block list carries the pages a reader would cite, so it must survive a page break: this+ * fixture's third table runs off page 2 and is stitched back together on page 3.+ */+ @Test+ void blocksCarryPagesAndAStitchedTableSpansThePageBreak() throws IOException {+ Path pdfPath = copyFixture("many-tables-test_stress.pdf");++ List<MarkdownBlock> blocks;+ int pageCount;+ try (PdfDocument doc = PdfDocument.open(pdfPath)) {+ pageCount = doc.pageCount();+ blocks = new AdvancedPdfMarkdownConverter().extractBlocks(doc);+ }++ assertFalse(blocks.isEmpty(), "the fixture has text on every page");+ Set<Integer> covered = new TreeSet<>();+ int previousStart = 0;+ for (MarkdownBlock block : blocks) {+ assertTrue(block.pageStart() >= 1, "page numbers are 1-based: " + block.pageStart());+ assertTrue(block.pageEnd() >= block.pageStart(), "pageEnd cannot precede pageStart");+ assertTrue(block.pageEnd() <= pageCount, "pageEnd cannot exceed the document");+ assertTrue(block.pageStart() >= previousStart, "blocks come out in reading order");+ previousStart = block.pageStart();+ for (int p = block.pageStart(); p <= block.pageEnd(); p++) {+ covered.add(p);+ }+ }+ assertEquals(pageCount, covered.size(), "every page of the fixture contributes a block");++ List<MarkdownBlock> spanning =+ blocks.stream().filter(b -> b.pageEnd() > b.pageStart()).toList();+ assertEquals(1, spanning.size(), "only the stitched table spans a page break");+ MarkdownBlock stitched = spanning.getFirst();+ assertEquals(2, stitched.pageStart());+ assertEquals(3, stitched.pageEnd());+ assertTrue(stitched.markdown().startsWith("|"), "the stitched block is the GFM table");+ }++ @Test+ void headingPathsFollowTheHeadingStack() throws IOException {+ Path pdfPath = copyFixture("many-tables-test_stress.pdf");++ List<MarkdownBlock> blocks;+ try (PdfDocument doc = PdfDocument.open(pdfPath)) {+ blocks = new AdvancedPdfMarkdownConverter().extractBlocks(doc);+ }++ int subIndex = indexOfMarkdown(blocks, "## Section 3 Heading");+ assertEquals(+ List.of("Section 2 Heading", "Section 3 Heading"),+ blocks.get(subIndex).headingPath(),+ "a heading includes itself under its parent");+ assertEquals(+ blocks.get(subIndex).headingPath(),+ blocks.get(subIndex + 1).headingPath(),+ "the block under a heading inherits its chain");++ int topIndex = indexOfMarkdown(blocks, "# Section 5 Heading");+ assertEquals(+ List.of("Section 5 Heading"),+ blocks.get(topIndex).headingPath(),+ "a top-level heading pops everything below it");+ }++ /**+ * Heading and body are both 12pt here, so the detector cannot have scored a heading level 1 on+ * size: bold body-size headings score level 3, and only the document-wide rebase makes them 1.+ */+ @Test+ void headingLevelsAreRebasedBeforeBlocksAreHandedOut() throws IOException {+ Path pdfPath = boldBodySizeHeadingsPdf();++ List<MarkdownBlock> blocks;+ try (PdfDocument doc = PdfDocument.open(pdfPath)) {+ blocks = new AdvancedPdfMarkdownConverter().extractBlocks(doc);+ }++ List<String> headings =+ blocks.stream()+ .map(MarkdownBlock::markdown)+ .filter(md -> MarkdownBlocks.headingLevel(md) > 0)+ .toList();+ assertEquals(List.of("# Overview", "# Retention"), headings);+ assertEquals(+ List.of("Overview"),+ blocks.get(1).headingPath(),+ "heading paths are derived after the rebase");+ }++ private static final List<String> OVERVIEW_BODY =+ List.of(+ "The widget service records every request it receives.",+ "Each record keeps the caller, the outcome and the time taken.");++ private static final List<String> RETENTION_BODY =+ List.of(+ "Records are kept for ninety days and then deleted.",+ "A deletion is itself recorded so the audit trail stays whole.");++ /** Two sections whose headings are set in the body size, bold, each on its own block. */+ private Path boldBodySizeHeadingsPdf() throws IOException {+ Path pdfPath = tmp.resolve("bold-body-size-headings.pdf");+ try (PDDocument doc = new PDDocument()) {+ PDPage page = new PDPage(PDRectangle.LETTER);+ doc.addPage(page);+ PDType1Font body = new PDType1Font(Standard14Fonts.FontName.HELVETICA);+ PDType1Font bold = new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD);+ try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {+ // The extra leading is what makes each heading isolated enough to be detected.+ float y = writeLine(cs, bold, "Overview", 720f) - 24f;+ for (String line : OVERVIEW_BODY) {+ y = writeLine(cs, body, line, y);+ }+ y = writeLine(cs, bold, "Retention", y - 30f) - 24f;+ for (String line : RETENTION_BODY) {+ y = writeLine(cs, body, line, y);+ }+ }+ doc.save(pdfPath.toFile());+ }+ return pdfPath;+ }++ /** Writes one 12pt line at the left margin and returns the next baseline. */+ private static float writeLine(PDPageContentStream cs, PDType1Font font, String text, float y)+ throws IOException {+ cs.beginText();+ cs.setFont(font, 12f);+ cs.newLineAtOffset(72f, y);+ cs.showText(text);+ cs.endText();+ return y - 15f;+ }++ private static int indexOfMarkdown(List<MarkdownBlock> blocks, String markdown) {+ for (int i = 0; i < blocks.size(); i++) {+ if (blocks.get(i).markdown().equals(markdown)) {+ return i;+ }+ }+ fail("No block rendered as '" + markdown + "'");+ return -1;+ }++ private Path copyFixture(String pdfName) throws IOException {Path pdfPath = tmp.resolve(pdfName);try (InputStream in =getClass().getResourceAsStream("/pdf-ingestion-fixtures/" + pdfName)) {@@ -376,6 +517,11 @@ class AdvancedPdfMarkdownConverterTest {}Files.copy(in, pdfPath);}+ return pdfPath;+ }++ private void assertConversionMatchesGolden(String pdfName, String mdName) throws IOException {+ Path pdfPath = copyFixture(pdfName);String actual;try (PdfDocument doc = PdfDocument.open(pdfPath)) {diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.javaindex b14c51dca8..cbc9715c37 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java@@ -15,6 +15,8 @@ import java.util.Set;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;@@ -30,6 +32,7 @@ import stirling.software.proprietary.policy.asset.PolicyAsset;import stirling.software.proprietary.policy.asset.PolicyAssetRefs;import stirling.software.proprietary.policy.asset.PolicyAssetStore;import stirling.software.proprietary.policy.input.InputSource;+import stirling.software.proprietary.policy.model.EditorConfig;import stirling.software.proprietary.policy.model.InputSpec;import stirling.software.proprietary.policy.model.OutputSpec;import stirling.software.proprietary.policy.model.PipelineInput;@@ -69,6 +72,81 @@ class PolicyValidatorTest {new ToolChainValidator(path -> java.util.Optional.empty()));}+ @ParameterizedTest+ @ValueSource(strings = {"upload", "export"})+ void rejectsCorpusExportsFromEditorPolicies(String runOn) {+ for (Map<String, Object> params :+ List.<Map<String, Object>>of(+ Map.of("exportChunksJsonl", true),+ Map.of("exportChunksJsonl", "true", "index", true),+ Map.of("exportMarkdown", true),+ Map.of("exportMarkdown", "true"),+ Map.of("includeOriginal", false))) {+ Policy policy = ingestionPolicy(params, new EditorConfig(true, runOn));+ IllegalArgumentException error =+ assertThrows(IllegalArgumentException.class, () -> validator.validate(policy));+ assertTrue(error.getMessage().contains("Choose a file or database destination"));+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"upload", "export"})+ void allowsEditorCorpusExportsToSavedDestinations(String runOn) {+ Policy policy =+ ingestionPolicy(+ Map.of(+ "index",+ false,+ "exportChunksJsonl",+ true,+ "includeOriginal",+ false),+ new EditorConfig(true, runOn))+ .withOutputIds(List.of("destination"));+ validator.validateEditorOutput(policy);+ }++ @Test+ void allowsEditorIndexingWithoutCorpusFiles() {+ when(outputSink.supports(any())).thenReturn(true);+ validator.validate(ingestionPolicy(Map.of("index", true), EditorConfig.onUpload()));+ validator.validate(+ ingestionPolicy(+ Map.of(+ "index",+ true,+ "includeOriginal",+ true,+ "exportChunksJsonl",+ false,+ "exportMarkdown",+ "false"),+ EditorConfig.onExport()));+ }++ @Test+ void keepsCorpusExportsAvailableOutsideEditorPolicies() {+ when(outputSink.supports(any())).thenReturn(true);+ validator.validate(+ ingestionPolicy(+ Map.of("index", false, "exportChunksJsonl", true),+ EditorConfig.disabled()));+ }++ private Policy ingestionPolicy(Map<String, Object> params, EditorConfig editor) {+ return new Policy(+ "ingestion",+ "Ingestion",+ "owner",+ true,+ List.of(),+ List.of(new PipelineStep("/api/v1/docparse/ingest", params, Map.of())),+ OutputSpec.inline(),+ List.of(),+ null,+ editor);+ }+@Testvoid delegatesEachFacetToItsHandler() {when(trigger.type()).thenReturn("schedule");diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.javanew file mode 100644index 0000000000..3fc1605cc3--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.java@@ -0,0 +1,352 @@+package stirling.software.proprietary.service;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.ArgumentMatchers.isNull;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.io.ByteArrayOutputStream;+import java.io.File;+import java.io.FileNotFoundException;+import java.io.IOException;+import java.io.InputStream;+import java.nio.file.Path;+import java.util.List;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.api.io.TempDir;+import org.mockito.ArgumentCaptor;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.http.HttpStatus;+import org.springframework.mock.web.MockMultipartFile;+import org.springframework.web.multipart.MultipartFile;+import org.springframework.web.server.ResponseStatusException;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.pdf.MarkdownBlock;+import stirling.software.common.pdf.MarkdownBlocks;+import stirling.software.common.pdf.PdfMarkdownExtractor;+import stirling.software.common.util.TempFileManager;+import stirling.software.proprietary.model.api.docparse.IngestApiRequest;+import stirling.software.proprietary.model.docparse.IngestOutcome;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.json.JsonMapper;++/** Wire-building, limit capping, and the engine round trip for the ingestion path. */+@ExtendWith(MockitoExtension.class)+class DocParseServiceTest {++ private static final String ENGINE_RESPONSE =+ "{\"documentId\":\"doc-1\",\"chunksIndexed\":3,\"chunks\":null}";++ private static final List<MarkdownBlock> BLOCKS =+ List.of(+ new MarkdownBlock("# Invoice", 1, 1, List.of("Invoice")),+ new MarkdownBlock("body text", 1, 2, List.of("Invoice")));++ @Mock private AiEngineClient aiEngineClient;+ @Mock private PdfMarkdownExtractor markdownExtractor;+ @Mock private TempFileManager tempFileManager;+ @Mock private FileIdStrategy fileIdStrategy;++ @TempDir Path tmp;++ private ApplicationProperties properties;+ private DocParseService service;+ private final JsonMapper jsonMapper = JsonMapper.builder().build();++ @BeforeEach+ void setUp() {+ properties = new ApplicationProperties();+ service =+ new DocParseService(+ aiEngineClient,+ markdownExtractor,+ tempFileManager,+ properties,+ jsonMapper,+ fileIdStrategy,+ null);+ }++ private static byte[] pdfBytes(int pages) throws IOException {+ try (PDDocument document = new PDDocument();+ ByteArrayOutputStream out = new ByteArrayOutputStream()) {+ for (int page = 0; page < pages; page++) {+ document.addPage(new PDPage());+ }+ document.save(out);+ return out.toByteArray();+ }+ }++ private MultipartFile pdfFile() throws IOException {+ return new MockMultipartFile("fileInput", "invoice.pdf", "application/pdf", pdfBytes(2));+ }++ /** The conversion seam is stubbed; opening the temp copy is the real jpdfium path. */+ private void stubConversion(List<MarkdownBlock> blocks) throws IOException {+ when(tempFileManager.createTempFile(".pdf")).thenReturn(tmp.resolve("ingest.pdf").toFile());+ when(markdownExtractor.extractBlocks(any())).thenReturn(blocks);+ }++ private static IngestApiRequest apiRequest(+ MultipartFile file,+ String documentId,+ boolean index,+ boolean markdown,+ boolean chunks) {+ IngestApiRequest request = new IngestApiRequest();+ request.setFileInput(file);+ request.setDocumentId(documentId);+ request.setIndex(index);+ request.setExportMarkdown(markdown);+ request.setExportChunksJsonl(chunks);+ return request;+ }++ private IngestOutcome ingest(String documentId, boolean index, boolean markdown, boolean chunks)+ throws IOException {+ return service.ingest(apiRequest(pdfFile(), documentId, index, markdown, chunks));+ }++ private JsonNode ingestAndCaptureRequest(+ String documentId, boolean index, boolean markdown, boolean chunks) throws IOException {+ stubConversion(BLOCKS);+ ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);+ when(aiEngineClient.postLongRunning(+ eq("/api/v1/docparse/ingest"), body.capture(), isNull()))+ .thenReturn(ENGINE_RESPONSE);++ IngestOutcome outcome = ingest(documentId, index, markdown, chunks);+ assertEquals(3, outcome.chunksIndexed());+ return jsonMapper.readTree(body.getValue());+ }++ @Test+ void ingestSendsTheMarkdownBlocksAsTheWireContract() throws IOException {+ JsonNode request = ingestAndCaptureRequest("doc-1", true, false, false);++ assertEquals("doc-1", request.get("documentId").asString());+ assertEquals("invoice.pdf", request.get("source").asString());+ assertEquals(2, request.get("blocks").size());+ JsonNode heading = request.get("blocks").get(0);+ assertEquals("# Invoice", heading.get("markdown").asString());+ assertEquals(1, heading.get("pageStart").asInt());+ assertEquals("Invoice", heading.get("headingPath").get(0).asString());+ assertEquals(2, request.get("blocks").get(1).get("pageEnd").asInt());+ assertEquals(512, request.get("chunkSize").asInt());+ assertEquals(64, request.get("overlap").asInt());+ assertTrue(request.get("index").asBoolean());+ assertFalse(request.get("includeChunks").asBoolean());+ // Page text, the parse tier and the markdown echo are gone from the contract.+ assertNull(request.get("pages"));+ assertNull(request.get("mode"));+ assertNull(request.get("fileName"));+ assertNull(request.get("includeMarkdown"));+ }++ @Test+ void ingestDefaultsDocumentIdToContentHash() throws IOException {+ when(fileIdStrategy.idFor(any(MultipartFile.class))).thenReturn("sha-abc");+ JsonNode request = ingestAndCaptureRequest(" ", true, false, false);+ assertEquals("sha-abc", request.get("documentId").asString());+ }++ @Test+ void ingestForwardsTheChunkExportFlag() throws IOException {+ JsonNode request = ingestAndCaptureRequest("doc-1", false, true, true);+ assertFalse(request.get("index").asBoolean());+ assertTrue(request.get("includeChunks").asBoolean());+ }++ @Test+ void theOutcomeCarriesTheJoinedMarkdownAndThePagesItCovers() throws IOException {+ stubConversion(BLOCKS);++ IngestOutcome outcome = ingest("doc-1", false, true, false);++ assertEquals("# Invoice\n\nbody text", outcome.markdown());+ // The second block was stitched across the page break, so it covers both pages.+ assertEquals(2, outcome.pages());+ assertEquals(2, outcome.sourcePages());+ assertFalse(outcome.truncated());+ }++ @Test+ void markdownOnlyExportNeverCallsTheEngine() throws IOException {+ stubConversion(BLOCKS);++ IngestOutcome outcome = ingest("doc-1", false, true, false);++ assertEquals(0, outcome.chunksIndexed());+ assertNull(outcome.chunks());+ verifyNoInteractions(aiEngineClient);+ }++ @Test+ void aDocumentWithNoTextLayerIs422() throws IOException {+ stubConversion(List.of(new MarkdownBlock(" ", 1, 1)));+ ResponseStatusException error =+ assertThrows(+ ResponseStatusException.class, () -> ingest("doc-1", true, false, false));+ assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, error.getStatusCode());+ verifyNoInteractions(aiEngineClient);+ }++ @Test+ void aScanThatConvertsToNothingButImagePlaceholdersIs422() throws IOException {+ // A scanned page has no text but does have an image, so the converter emits a placeholder;+ // without this the placeholders would be embedded and indexed as if they were content.+ stubConversion(+ List.of(+ new MarkdownBlock(+ MarkdownBlocks.IMAGE_PLACEHOLDER + ": 2480x3508px, JPG>", 1, 1)));+ ResponseStatusException error =+ assertThrows(+ ResponseStatusException.class, () -> ingest("doc-1", true, false, false));+ assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, error.getStatusCode());+ verifyNoInteractions(aiEngineClient);+ }++ @Test+ void theUploadIsStillReadableAfterIngest() throws IOException {+ // The controller reads the upload after this returns, to put the original in the export+ // ZIP; consuming the part here 500s every default-configuration ingest.+ stubConversion(BLOCKS);+ SpendableMultipartFile file = new SpendableMultipartFile(pdfBytes(2));++ service.ingest(apiRequest(file, "doc-1", false, true, false));++ assertEquals(pdfBytes(2).length, file.getBytes().length);+ }++ /** A servlet part spooled to disk: transferTo moves the backing file, leaving it unreadable. */+ private static final class SpendableMultipartFile extends MockMultipartFile {++ private boolean spent;++ SpendableMultipartFile(byte[] content) {+ super("fileInput", "invoice.pdf", "application/pdf", content);+ }++ @Override+ public void transferTo(File dest) throws IOException {+ super.transferTo(dest);+ spent = true;+ }++ @Override+ public byte[] getBytes() throws IOException {+ requireUnspent();+ return super.getBytes();+ }++ @Override+ public InputStream getInputStream() throws IOException {+ requireUnspent();+ return super.getInputStream();+ }++ private void requireUnspent() throws IOException {+ if (spent) {+ throw new FileNotFoundException("the part's backing file was already transferred");+ }+ }+ }++ @Test+ void ingestWithNothingToDoIs400() throws IOException {+ ResponseStatusException error =+ assertThrows(+ ResponseStatusException.class, () -> ingest("doc", false, false, false));+ assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());+ verifyNoInteractions(aiEngineClient);+ }++ @Test+ void ingestWhenDisabledIs503() throws IOException {+ properties.getDocparse().setEnabled(false);+ ResponseStatusException error =+ assertThrows(+ ResponseStatusException.class, () -> ingest("doc", true, false, false));+ assertEquals(HttpStatus.SERVICE_UNAVAILABLE, error.getStatusCode());+ verifyNoInteractions(aiEngineClient);+ }++ @Test+ void fileNameFallsBackWhenMissing() throws IOException {+ MultipartFile nameless =+ new MockMultipartFile("fileInput", "", "application/pdf", new byte[] {1});+ assertEquals("document.pdf", DocParseService.fileName(nameless));+ assertEquals("invoice.pdf", DocParseService.fileName(pdfFile()));+ }++ // --- applyLimits: the shared aiEngine caps, applied over whole blocks ---++ @Test+ void applyLimitsSkipsBlankBlocksAndCapsCharacters() {+ properties.getAiEngine().getLimits().setMaxCharacters(12);+ List<MarkdownBlock> all =+ List.of(+ new MarkdownBlock("0123456789", 1, 1),+ new MarkdownBlock(" ", 2, 2),+ new MarkdownBlock("abcdef", 3, 3));++ DocParseService.Capped capped = service.applyLimits(all, 3);++ assertTrue(capped.truncated());+ assertEquals(2, capped.blocks().size());+ // The last block is cut to the remaining budget (12 - 10 = 2 chars).+ assertEquals("ab", capped.blocks().get(1).markdown());+ }++ @Test+ void reportsCharacterTruncationEvenOnTheOnlyBlock() {+ properties.getAiEngine().getLimits().setMaxCharacters(4);++ DocParseService.Capped capped =+ service.applyLimits(List.of(new MarkdownBlock("more than four", 1, 1)), 1);++ assertTrue(capped.truncated());+ assertEquals("more", capped.blocks().getFirst().markdown());+ }++ @Test+ void aBlankTrailingBlockIsNotTruncation() {+ DocParseService.Capped capped =+ service.applyLimits(+ List.of(new MarkdownBlock("text", 1, 1), new MarkdownBlock(" ", 2, 2)),+ 2);+ assertFalse(capped.truncated());+ }++ @Test+ void applyLimitsStopsAtThePageCapButKeepsAStraddlingBlockWhole() {+ properties.getAiEngine().getLimits().setMaxPages(2);+ List<MarkdownBlock> all =+ List.of(+ new MarkdownBlock("page one", 1, 1),+ // Stitched across the cap: kept whole, because its content is all here.+ new MarkdownBlock("straddles", 2, 3),+ new MarkdownBlock("past the cap", 3, 3));++ DocParseService.Capped capped = service.applyLimits(all, 3);++ assertTrue(capped.truncated());+ assertEquals(2, capped.blocks().size());+ assertEquals(3, capped.blocks().get(1).pageEnd());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/PdfContentExtractorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/PdfContentExtractorTest.javaindex 1bb042f882..f4f8a71553 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/PdfContentExtractorTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/PdfContentExtractorTest.java@@ -151,6 +151,29 @@ class PdfContentExtractorTest {@DisplayName("extractPageTextRaw")class ExtractPageTextRaw {+ @Test+ @DisplayName("orders OCR words by position instead of content stream order")+ void restoresReadingOrder() throws IOException {+ extractor = newExtractor();+ try (PDDocument doc = blankDocument(1)) {+ String[][] lines = {{"Solar", "panels", "shine"}, {"Wind", "turbines", "turn"}};+ try (PDPageContentStream content = new PDPageContentStream(doc, doc.getPage(0))) {+ for (int column = 0; column < 3; column++) {+ for (int row = 0; row < 2; row++) {+ content.beginText();+ content.setFont(+ new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);+ content.newLineAtOffset(72 + column * 70, 700 - row * 30);+ content.showText(lines[row][column]);+ content.endText();+ }+ }+ }+ assertThat(extractor.extractPageTextRaw(doc, 1))+ .contains("Solar panels shine", "Wind turbines turn");+ }+ }+@Test@DisplayName("returns trimmed page text")void returnsText() throws IOException {diff --git a/engine/src/stirling/api/app.py b/engine/src/stirling/api/app.pyindex 60de81360f..a5f1cb716f 100644--- a/engine/src/stirling/api/app.py+++ b/engine/src/stirling/api/app.py@@ -17,6 +17,7 @@ from stirling.api.routes import (agent_capabilities_router,agent_draft_router,config_router,+ docparse_router,document_classifier_router,document_router,execution_router,@@ -217,6 +218,7 @@ app.include_router(ledger_router, dependencies=_user_gate)app.include_router(pdf_comments_router, dependencies=_user_gate)app.include_router(agent_capabilities_router, dependencies=_user_gate)app.include_router(document_classifier_router, dependencies=_user_gate)+app.include_router(docparse_router, dependencies=_user_gate)# Config push is a system sync with no X-User-Id, so it is guarded by the shared secret# and allow_config_push flag only, deliberately NOT the per-user identity gate.app.include_router(config_router)diff --git a/engine/src/stirling/api/routes/__init__.py b/engine/src/stirling/api/routes/__init__.pyindex 440ff18f9d..6b76bf7f2d 100644--- a/engine/src/stirling/api/routes/__init__.py+++ b/engine/src/stirling/api/routes/__init__.py@@ -1,6 +1,7 @@from .agent_capabilities import router as agent_capabilities_routerfrom .agent_drafts import router as agent_draft_routerfrom .config import router as config_router+from .docparse import router as docparse_routerfrom .document_classifier import router as document_classifier_routerfrom .documents import router as document_routerfrom .execution import router as execution_router@@ -14,6 +15,7 @@ __all__ = ["agent_capabilities_router","agent_draft_router","config_router",+ "docparse_router","document_classifier_router","document_router","execution_router",diff --git a/engine/src/stirling/api/routes/docparse.py b/engine/src/stirling/api/routes/docparse.pynew file mode 100644index 0000000000..d0b2640799--- /dev/null+++ b/engine/src/stirling/api/routes/docparse.py@@ -0,0 +1,98 @@+"""DocParse ingestion route.++Java converts the PDF to page-attributed Markdown blocks with its layout-aware+converter; the engine packs those into chunks, embeds and indexes them.+"""++from __future__ import annotations++import logging+from typing import Annotated++from fastapi import APIRouter, Depends, HTTPException, status++from stirling.api.dependencies import get_document_service, require_user_id+from stirling.config import AppSettings, load_settings+from stirling.contracts.docparse import DocChunk, IngestRequest, IngestResponse+from stirling.docparse.chunking import pack_blocks, page_texts+from stirling.documents import DocumentService+from stirling.documents.service import CONTENT_TYPE_METADATA_KEY, DOCPARSE_CHUNK_CONTENT_TYPE+from stirling.models import OwnerId, PrincipalId, UserId++logger = logging.getLogger(__name__)++router = APIRouter(prefix="/api/v1/docparse", tags=["docparse"])+++def _settings() -> AppSettings:+ return load_settings()+++def _chunk_metadata(chunk: DocChunk) -> dict[str, str]:+ meta = {CONTENT_TYPE_METADATA_KEY: DOCPARSE_CHUNK_CONTENT_TYPE}+ if chunk.page_start is not None:+ meta["page_start"] = str(chunk.page_start)+ if chunk.page_end is not None:+ meta["page_end"] = str(chunk.page_end)+ if chunk.heading_path:+ meta["heading_path"] = " > ".join(chunk.heading_path)+ return meta++[email protected]("/ingest", response_model=IngestResponse)+async def ingest(+ request: IngestRequest,+ documents: Annotated[DocumentService, Depends(get_document_service)],+ user_id: Annotated[UserId, Depends(require_user_id)],+) -> IngestResponse:+ """Pack the caller's Markdown blocks into chunks, then embed and index them.+ Re-ingesting a documentId replaces its stored content (never duplicates).+ ``index=False`` skips the store; ``includeChunks`` returns the chunks."""+ settings = _settings()+ chunk_size = request.chunk_size if request.chunk_size is not None else settings.rag_chunk_size+ overlap = request.overlap if request.overlap is not None else settings.rag_chunk_overlap++ if not request.blocks:+ # The caller converts the text layer, so an empty payload means the document+ # has none - a scan, not a conversion failure.+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,+ detail="no extractable text: the document has no text layer, so OCR it before ingesting",+ )+ if overlap >= chunk_size:+ # chunk_text derives its stride as chunk_size - overlap; a zero stride raises+ # and a negative one silently drops every over-long sentence.+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,+ detail=f"overlap ({overlap}) must be smaller than chunkSize ({chunk_size})",+ )+ if not request.index and not request.include_chunks:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,+ detail="nothing to do: enable index or includeChunks",+ )++ chunks = pack_blocks(request.blocks, chunk_size, overlap)++ chunks_indexed = 0+ if request.index:+ # Owner/ACL semantics mirror IngestDocumentRequest; omitted values default+ # to the authenticated caller (personal-doc behaviour).+ owner_id = request.owner_id if request.owner_id is not None else OwnerId(user_id)+ read_principals = request.read_principals or [PrincipalId(owner_id)]+ chunks_indexed = await documents.ingest_prepared(+ collection=request.document_id,+ chunks=[(chunk.text, _chunk_metadata(chunk)) for chunk in chunks],+ source=request.source,+ owner_id=owner_id,+ read_principals=read_principals,+ expires_at=request.expires_at,+ pages=page_texts(request.blocks),+ )++ logger.info("docparse: ingested %s: %d chunks indexed", request.document_id, chunks_indexed)+ return IngestResponse(+ document_id=request.document_id,+ chunks_indexed=chunks_indexed,+ chunks=chunks if request.include_chunks else None,+ )diff --git a/engine/src/stirling/contracts/docparse.py b/engine/src/stirling/contracts/docparse.pynew file mode 100644index 0000000000..12b7c60baf--- /dev/null+++ b/engine/src/stirling/contracts/docparse.py@@ -0,0 +1,64 @@+"""Wire contracts for the DocParse ingestion capability.++Java counterpart DTOs live under ``stirling.software.proprietary.model.docparse``+(and ``stirling.software.common.pdf.MarkdownBlock``) and must stay in sync. Java+converts the PDF to page-attributed Markdown blocks; the engine packs those into+chunks, embeds and indexes them.+"""++from __future__ import annotations++from datetime import datetime++from pydantic import Field++from stirling.models import ApiModel, FileId, OwnerId, PrincipalId+++class MarkdownBlock(ApiModel):+ """One rendered Markdown element and the 1-based pages it came from.++ ``page_start`` and ``page_end`` differ only for content the converter stitched+ across a page break. ``heading_path`` is the enclosing heading chain, root first,+ with a heading block including itself.+ """++ markdown: str+ page_start: int = Field(ge=1)+ page_end: int = Field(ge=1)+ heading_path: list[str] = Field(default_factory=list)+++class DocChunk(ApiModel):+ index: int = Field(ge=0)+ text: str+ page_start: int | None = Field(default=None, ge=1)+ page_end: int | None = Field(default=None, ge=1)+ heading_path: list[str] = Field(default_factory=list)+++class IngestRequest(ApiModel):+ """Pack the caller's Markdown blocks into chunks, then optionally embed and index.++ ``owner_id``/``read_principals`` default to the calling user (personal-doc+ semantics); ``chunk_size``/``overlap`` default to the engine's RAG settings.+ ``index=False`` skips the store entirely; ``include_chunks`` returns the chunks+ so the caller can emit a corpus file.+ """++ document_id: FileId = Field(min_length=1)+ source: str = Field(default="docparse", min_length=1)+ owner_id: OwnerId | None = None+ read_principals: list[PrincipalId] | None = Field(default=None, min_length=1)+ expires_at: datetime | None = None+ blocks: list[MarkdownBlock] = Field(default_factory=list)+ chunk_size: int | None = Field(default=None, ge=64, le=32_768)+ overlap: int | None = Field(default=None, ge=0, le=4_096)+ index: bool = True+ include_chunks: bool = False+++class IngestResponse(ApiModel):+ document_id: FileId+ chunks_indexed: int = Field(ge=0)+ chunks: list[DocChunk] | None = Nonediff --git a/engine/src/stirling/docparse/__init__.py b/engine/src/stirling/docparse/__init__.pynew file mode 100644index 0000000000..473b052430--- /dev/null+++ b/engine/src/stirling/docparse/__init__.py@@ -0,0 +1,5 @@+"""DocParse: preparing caller-converted documents for ingestion.++Java's layout-aware PDF-to-Markdown converter supplies the structure; this+package packs those blocks into chunks the document store can index.+"""diff --git a/engine/src/stirling/docparse/chunking.py b/engine/src/stirling/docparse/chunking.pynew file mode 100644index 0000000000..7a2a122728--- /dev/null+++ b/engine/src/stirling/docparse/chunking.py@@ -0,0 +1,128 @@+"""Structure-aware packing of Markdown blocks into chunks.++Java's PDF-to-Markdown converter supplies page-attributed blocks; whole blocks are+packed up to chunk_size so a heading is never separated from the text it introduces.+The character chunker handles the one case blocks cannot: a single block that alone+exceeds chunk_size. Sizes are characters, matching the rest of the engine."""++from __future__ import annotations++import re++from stirling.contracts.docparse import DocChunk, MarkdownBlock+from stirling.contracts.documents import PageText+from stirling.documents.chunker import chunk_text, tail_overlap++_ATX_HEADING = re.compile(r"^#{1,6} \S")+++def _is_heading(markdown: str) -> bool:+ return _ATX_HEADING.match(markdown) is not None+++def _chunk_headings(buffer: list[MarkdownBlock]) -> list[str]:+ """The chain of the chunk's own first heading, or of its first block when it holds none.++ The first block's chain alone would label a chunk whose heading sits mid-chunk with the+ previous section, which is the mistake the breadcrumb exists to avoid.+ """+ for block in buffer:+ if _is_heading(block.markdown):+ return list(block.heading_path)+ return list(buffer[0].heading_path)+++def pack_blocks(blocks: list[MarkdownBlock], chunk_size: int, overlap: int) -> list[DocChunk]:+ """Pack whole blocks up to ``chunk_size``, splitting only a block too big to fit alone.++ ``chunk_size`` bounds the new text a chunk holds; on top of that a chunk carries the+ overlap tail of the one before it and two characters per joiner, which is the same+ approximation ``chunk_text`` makes.+ """+ chunks: list[DocChunk] = []+ buffer: list[MarkdownBlock] = []+ buffer_len = 0+ carry = ""++ def emit() -> None:+ """Turn the buffer into one chunk, then reseed the overlap carry from it."""+ nonlocal buffer, buffer_len, carry+ if not buffer:+ return+ parts = ([carry] if carry else []) + [block.markdown for block in buffer]+ text = "\n\n".join(parts).strip()+ if text:+ chunks.append(+ DocChunk(+ index=len(chunks),+ text=text,+ page_start=min(block.page_start for block in buffer),+ page_end=max(block.page_end for block in buffer),+ heading_path=_chunk_headings(buffer),+ )+ )+ buffer = []+ carry = tail_overlap(chunks[-1].text, overlap) if chunks else ""+ buffer_len = len(carry)++ for block in blocks:+ markdown = block.markdown.strip()+ if not markdown:+ continue+ length = len(markdown)++ if length > chunk_size:+ # Too big to pack whole, so hand it to the character chunker, which applies+ # its own overlap; that is why nothing carries into or across this branch.+ emit()+ buffer, buffer_len, carry = [], 0, ""+ for piece in chunk_text(markdown, chunk_size=chunk_size, overlap=overlap):+ chunks.append(+ DocChunk(+ index=len(chunks),+ text=piece,+ page_start=block.page_start,+ page_end=block.page_end,+ heading_path=list(block.heading_path),+ )+ )+ carry = tail_overlap(chunks[-1].text, overlap) if chunks else ""+ buffer_len = len(carry)+ continue++ if buffer and buffer_len + length > chunk_size:+ # Keep a heading with the text it introduces: a trailing run of heading-only+ # blocks moves to the front of the next chunk instead of ending this one.+ held: list[MarkdownBlock] = []+ while buffer and _is_heading(buffer[-1].markdown):+ held.insert(0, buffer.pop())+ if not buffer:+ buffer, held = held, []+ emit()+ for heading in held:+ buffer.append(heading)+ buffer_len += len(heading.markdown)+ if buffer and buffer_len + length > chunk_size:+ # A long heading run plus this block will not fit either; emit the headings+ # rather than let the migration push the chunk past chunk_size.+ emit()++ buffer.append(block.model_copy(update={"markdown": markdown}))+ buffer_len += length++ emit()+ return chunks+++def page_texts(blocks: list[MarkdownBlock]) -> list[PageText]:+ """The whole-document read representation, one entry per page that has content.++ A block stitched across a page break is attributed to where it started, so its+ text appears once rather than on every page it touches.+ """+ by_page: dict[int, list[str]] = {}+ for block in blocks:+ markdown = block.markdown.strip()+ if markdown:+ by_page.setdefault(block.page_start, []).append(markdown)+ return [PageText(page_number=number, text="\n\n".join(by_page[number])) for number in sorted(by_page)]diff --git a/engine/src/stirling/documents/chunker.py b/engine/src/stirling/documents/chunker.pyindex 689365f6cb..d314370d51 100644--- a/engine/src/stirling/documents/chunker.py+++ b/engine/src/stirling/documents/chunker.py@@ -105,14 +105,20 @@ def _split_long_paragraph(paragraph: str, chunk_size: int, overlap: int) -> listreturn chunks-def _get_overlap(chunks: list[str], overlap: int) -> str:- """Extract the last ~`overlap` characters from the most recent chunk, snapped to a word boundary."""- if not chunks or overlap <= 0:+def tail_overlap(text: str, overlap: int) -> str:+ """Last ~`overlap` characters of `text`, snapped forward past the first space."""+ if not text or overlap <= 0:return ""- last = chunks[-1]- tail = last[-overlap:] if len(last) > overlap else last+ tail = text[-overlap:] if len(text) > overlap else text# Snap to the nearest word boundary to avoid starting mid-wordspace_idx = tail.find(" ")if space_idx > 0:tail = tail[space_idx + 1 :]return tail+++def _get_overlap(chunks: list[str], overlap: int) -> str:+ """Extract the last ~`overlap` characters from the most recent chunk, snapped to a word boundary."""+ if not chunks:+ return ""+ return tail_overlap(chunks[-1], overlap)diff --git a/engine/src/stirling/documents/service.py b/engine/src/stirling/documents/service.pyindex 0415e9d140..a6ab220add 100644--- a/engine/src/stirling/documents/service.py+++ b/engine/src/stirling/documents/service.py@@ -13,6 +13,7 @@ logger = logging.getLogger(__name__)PAGE_NUMBER_METADATA_KEY = "page_number"CONTENT_TYPE_METADATA_KEY = "content_type"PAGE_TEXT_CONTENT_TYPE = "page_text"+DOCPARSE_CHUNK_CONTENT_TYPE = "docparse_chunk"class DocumentService:@@ -109,6 +110,54 @@ class DocumentService:await self._store.add_documents(collection, chunks, embeddings, owner_id)return len(chunks)+ async def ingest_prepared(+ self,+ collection: FileId,+ chunks: list[tuple[str, dict[str, str]]],+ source: str,+ owner_id: OwnerId,+ read_principals: list[PrincipalId],+ expires_at: datetime | None,+ pages: list[PageText] | None = None,+ ) -> int:+ """Replace-ingest pre-chunked content (e.g. docparse structure-aware chunks).++ Same end state as :meth:`ingest` - the ``(collection, owner_id)`` pair holds+ exactly this content - but the ``(text, metadata)`` chunk pairs arrive+ pre-built rather than being chunked here. ``pages`` writes the page+ representation alongside, so a docparse-ingested document is readable whole+ by :meth:`read_pages` and not only findable by search. Returns the number of+ vector chunks indexed.++ Embedding happens before the collection is wiped: the embedder is a remote+ call that can fail or rate-limit part-way, and deleting first would leave the+ document erased from the knowledge base with nothing to replace it.+ """+ if not read_principals:+ raise ValueError("read_principals must not be empty - every doc needs at least one reader")++ documents: list[Document] = []+ for text, metadata in chunks:+ if not text.strip():+ continue+ index = len(documents)+ meta = {**metadata, "source": source, "chunk_index": str(index)}+ documents.append(Document(id=f"{source}:docparse:{index}", text=text, metadata=meta))++ embeddings = await self._embedder.embed_documents([doc.text for doc in documents]) if documents else []++ await self._store.delete_collection(collection, owner_id)+ await self._store.ensure_collection(collection, source, owner_id, expires_at)+ if pages:+ stored_pages = [StoredPage(page_number=p.page_number, text=p.text, char_count=len(p.text)) for p in pages]+ await self._store.add_pages(collection, stored_pages, owner_id)+ await self._store.grant_read(collection, owner_id, read_principals)++ if not documents:+ return 0+ await self._store.add_documents(collection, documents, embeddings, owner_id)+ return len(documents)+async def search(self,query: str,diff --git a/engine/tests/docparse/test_chunking.py b/engine/tests/docparse/test_chunking.pynew file mode 100644index 0000000000..9fcc8f5f20--- /dev/null+++ b/engine/tests/docparse/test_chunking.py@@ -0,0 +1,152 @@+from __future__ import annotations++from stirling.contracts.docparse import MarkdownBlock+from stirling.docparse.chunking import pack_blocks, page_texts+from stirling.documents.chunker import chunk_text+++def block(+ markdown: str,+ page: int = 1,+ page_end: int | None = None,+ headings: list[str] | None = None,+) -> MarkdownBlock:+ return MarkdownBlock(+ markdown=markdown,+ page_start=page,+ page_end=page_end if page_end is not None else page,+ heading_path=headings or [],+ )+++def test_pack_blocks_packs_whole_blocks_up_to_chunk_size() -> None:+ chunks = pack_blocks([block("aaa"), block("bbb"), block("ccc")], chunk_size=10, overlap=0)+ assert [c.text for c in chunks] == ["aaa\n\nbbb\n\nccc"]+ assert chunks[0].index == 0+++def test_pack_blocks_starts_a_new_chunk_when_the_next_block_would_not_fit() -> None:+ chunks = pack_blocks([block("aaaa"), block("bbbb"), block("cccc")], chunk_size=8, overlap=0)+ assert [c.text for c in chunks] == ["aaaa\n\nbbbb", "cccc"]+ assert [c.index for c in chunks] == [0, 1]+++def test_pack_blocks_takes_pages_from_the_min_and_max_of_what_it_packed() -> None:+ chunks = pack_blocks(+ [block("alpha", page=2), block("beta", page=3, page_end=4), block("gamma", page=4)],+ chunk_size=64,+ overlap=0,+ )+ assert len(chunks) == 1+ assert (chunks[0].page_start, chunks[0].page_end) == (2, 4)+++def test_pack_blocks_takes_the_heading_path_of_the_heading_it_holds() -> None:+ chunks = pack_blocks(+ [block("## Risks", headings=["Report", "Risks"]), block("body", headings=["Report", "Risks"])],+ chunk_size=64,+ overlap=0,+ )+ assert chunks[0].heading_path == ["Report", "Risks"]+++def test_pack_blocks_labels_a_chunk_whose_heading_is_not_its_first_block() -> None:+ # Nothing overflows, so the heading sits mid-chunk; the breadcrumb must still find it.+ chunks = pack_blocks(+ [+ block("preamble"),+ block("# Intro", headings=["Intro"]),+ block("body", headings=["Intro"]),+ ],+ chunk_size=512,+ overlap=0,+ )+ assert len(chunks) == 1+ assert chunks[0].heading_path == ["Intro"]+++def test_pack_blocks_keeps_a_migrated_heading_run_inside_chunk_size() -> None:+ # The held headings reseed the next buffer, so they must be re-measured before the block+ # that triggered the migration is appended to them.+ chunks = pack_blocks(+ [+ block("x" * 10),+ block("# Section One", headings=["Section One"]),+ block("## Section Two", headings=["Section One", "Section Two"]),+ block("y" * 20, headings=["Section One", "Section Two"]),+ ],+ chunk_size=40,+ overlap=0,+ )+ assert [c.text for c in chunks] == ["x" * 10, "# Section One\n\n## Section Two", "y" * 20]+ assert all(len(c.text) <= 40 for c in chunks)+++def test_pack_blocks_keeps_a_trailing_heading_with_the_text_it_introduces() -> None:+ chunks = pack_blocks(+ [+ block("para a"),+ block("## Section", headings=["Section"]),+ block("para b", headings=["Section"]),+ ],+ chunk_size=20,+ overlap=0,+ )+ assert [c.text for c in chunks] == ["para a", "## Section\n\npara b"]+ assert [c.heading_path for c in chunks] == [[], ["Section"]]+++def test_pack_blocks_emits_a_heading_only_buffer_rather_than_looping() -> None:+ chunks = pack_blocks([block("# A"), block("## B"), block("body xyz")], chunk_size=8, overlap=0)+ assert [c.text for c in chunks] == ["# A\n\n## B", "body xyz"]+++def test_pack_blocks_carries_overlap_across_a_chunk_boundary() -> None:+ chunks = pack_blocks(+ [block("alpha beta gamma"), block("delta epsilon zeta", page=2)],+ chunk_size=20,+ overlap=8,+ )+ assert [c.text for c in chunks] == ["alpha beta gamma", "gamma\n\ndelta epsilon zeta"]+ # The carry duplicates page 1 text, so it must not drag page 1 into the second chunk.+ assert (chunks[1].page_start, chunks[1].page_end) == (2, 2)+++def test_pack_blocks_falls_back_to_the_character_chunker_for_an_over_long_block() -> None:+ long_block = "Alpha beta gamma delta. " * 10+ chunks = pack_blocks([block(long_block, page=4, page_end=5, headings=["Intro"])], chunk_size=64, overlap=0)+ assert [c.text for c in chunks] == chunk_text(long_block.strip(), chunk_size=64, overlap=0)+ assert len(chunks) > 1+ assert all((c.page_start, c.page_end) == (4, 5) for c in chunks)+ assert all(c.heading_path == ["Intro"] for c in chunks)+ assert [c.index for c in chunks] == list(range(len(chunks)))+++def test_pack_blocks_flushes_the_buffer_before_an_over_long_block() -> None:+ long_block = "Alpha beta gamma delta. " * 10+ chunks = pack_blocks([block("short intro"), block(long_block)], chunk_size=64, overlap=0)+ assert chunks[0].text == "short intro"+ assert len(chunks) == 1 + len(chunk_text(long_block.strip(), chunk_size=64, overlap=0))+++def test_pack_blocks_skips_blank_blocks() -> None:+ chunks = pack_blocks([block(" "), block("real"), block("\n\n")], chunk_size=64, overlap=0)+ assert [c.text for c in chunks] == ["real"]+++def test_pack_blocks_returns_nothing_for_nothing() -> None:+ assert pack_blocks([], chunk_size=64, overlap=0) == []+++def test_page_texts_groups_by_page_and_sorts() -> None:+ pages = page_texts([block("second", page=2), block("first", page=1), block("also first", page=1)])+ assert [(p.page_number, p.text) for p in pages] == [(1, "first\n\nalso first"), (2, "second")]+++def test_page_texts_attributes_a_stitched_block_to_where_it_started() -> None:+ pages = page_texts([block("table halves", page=1, page_end=2), block("page two body", page=2)])+ assert [(p.page_number, p.text) for p in pages] == [(1, "table halves"), (2, "page two body")]+++def test_page_texts_skips_blank_blocks() -> None:+ assert page_texts([block(" ", page=1), block("kept", page=2)]) == page_texts([block("kept", page=2)])diff --git a/engine/tests/docparse/test_ingest.py b/engine/tests/docparse/test_ingest.pynew file mode 100644index 0000000000..e88564a471--- /dev/null+++ b/engine/tests/docparse/test_ingest.py@@ -0,0 +1,269 @@+from __future__ import annotations++from collections.abc import Iterator+from datetime import datetime+from typing import Any++import pytest+from fastapi.testclient import TestClient++from stirling.api import app+from stirling.api.dependencies import get_document_service+from stirling.contracts.documents import PageText+from stirling.documents import DocumentService, SqliteVecStore+from stirling.models import FileId, OwnerId, PrincipalId++HEADERS = {"X-User-Id": "test-user"}+++def block(+ markdown: str,+ page: int = 1,+ page_end: int | None = None,+ headings: list[str] | None = None,+) -> dict[str, Any]:+ return {+ "markdown": markdown,+ "pageStart": page,+ "pageEnd": page_end if page_end is not None else page,+ "headingPath": headings or [],+ }+++class StubDocumentService:+ """Records ingest_prepared calls so the route's passthrough can be asserted."""++ def __init__(self) -> None:+ self.calls: list[dict[str, Any]] = []++ async def ingest_prepared(+ self,+ collection: FileId,+ chunks: list[tuple[str, dict[str, str]]],+ source: str,+ owner_id: OwnerId,+ read_principals: list[PrincipalId],+ expires_at: datetime | None,+ pages: list[PageText] | None = None,+ ) -> int:+ self.calls.append(+ {+ "collection": collection,+ "chunks": chunks,+ "source": source,+ "owner_id": owner_id,+ "read_principals": read_principals,+ "expires_at": expires_at,+ "pages": pages,+ }+ )+ return len(chunks)+++class StubEmbedder:+ """Deterministic embeddings: no network, no provider needed."""++ def __init__(self, dim: int = 8) -> None:+ self._dim = dim++ async def embed_query(self, text: str) -> list[float]:+ h = hash(text) % 1000+ return [(h + i) / 1000.0 for i in range(self._dim)]++ async def embed_documents(self, texts: list[str]) -> list[list[float]]:+ return [await self.embed_query(t) for t in texts]+++def stub_service() -> StubDocumentService:+ return StubDocumentService()+++def client(stub_service: StubDocumentService) -> Iterator[TestClient]:+ app.dependency_overrides[get_document_service] = lambda: stub_service+ try:+ yield TestClient(app)+ finally:+ app.dependency_overrides.pop(get_document_service, None)+++def test_ingest_indexes_chunks_with_metadata(client: TestClient, stub_service: StubDocumentService) -> None:+ response = client.post(+ "/api/v1/docparse/ingest",+ json={+ "documentId": "doc-1",+ "blocks": [+ block("## Findings", headings=["Findings"]),+ block("para one", headings=["Findings"]),+ block("para two", page=2),+ ],+ "chunkSize": 64,+ "overlap": 0,+ },+ headers=HEADERS,+ )+ assert response.status_code == 200+ body = response.json()+ assert body["documentId"] == "doc-1"+ assert body["chunksIndexed"] == 1+ assert body["chunks"] is None++ call = stub_service.calls[0]+ assert call["collection"] == "doc-1"+ assert call["source"] == "docparse"+ text, metadata = call["chunks"][0]+ assert text == "## Findings\n\npara one\n\npara two"+ assert metadata["content_type"] == "docparse_chunk"+ assert metadata["page_start"] == "1"+ assert metadata["page_end"] == "2"+ assert metadata["heading_path"] == "Findings"+++def test_ingest_defaults_owner_and_readers_to_caller(client: TestClient, stub_service: StubDocumentService) -> None:+ client.post(+ "/api/v1/docparse/ingest",+ json={"documentId": "d", "blocks": [block("t")]},+ headers=HEADERS,+ )+ call = stub_service.calls[0]+ assert call["owner_id"] == "test-user"+ assert call["read_principals"] == ["test-user"]+ assert call["expires_at"] is None+++def test_ingest_passes_explicit_owner_acl_and_expiry_through(+ client: TestClient, stub_service: StubDocumentService+) -> None:+ client.post(+ "/api/v1/docparse/ingest",+ json={+ "documentId": "d",+ "source": "handbook.pdf",+ "ownerId": "org:acme",+ "readPrincipals": ["group:eng", "user:bob"],+ "expiresAt": "2030-01-01T00:00:00Z",+ "blocks": [block("t")],+ },+ headers=HEADERS,+ )+ call = stub_service.calls[0]+ assert call["owner_id"] == "org:acme"+ assert call["read_principals"] == ["group:eng", "user:bob"]+ assert call["source"] == "handbook.pdf"+ assert call["expires_at"] is not None+++def test_ingest_chunks_only_skips_the_store(client: TestClient, stub_service: StubDocumentService) -> None:+ response = client.post(+ "/api/v1/docparse/ingest",+ json={+ "documentId": "d",+ "blocks": [block("alpha"), block("beta", page=2)],+ "chunkSize": 64,+ "overlap": 0,+ "index": False,+ "includeChunks": True,+ },+ headers=HEADERS,+ )+ assert response.status_code == 200+ body = response.json()+ assert stub_service.calls == []+ assert body["chunksIndexed"] == 0+ assert [c["text"] for c in body["chunks"]] == ["alpha\n\nbeta"]+ assert body["chunks"][0]["pageStart"] == 1+ assert body["chunks"][0]["pageEnd"] == 2+++def test_ingest_index_off_with_no_export_is_422(client: TestClient) -> None:+ response = client.post(+ "/api/v1/docparse/ingest",+ json={"documentId": "d", "blocks": [block("t")], "index": False},+ headers=HEADERS,+ )+ assert response.status_code == 422+++def test_ingest_without_blocks_is_422(client: TestClient) -> None:+ response = client.post("/api/v1/docparse/ingest", json={"documentId": "d"}, headers=HEADERS)+ assert response.status_code == 422+++def test_ingest_rejects_missing_user_header(client: TestClient) -> None:+ response = client.post("/api/v1/docparse/ingest", json={"documentId": "d", "blocks": [block("t")]})+ assert response.status_code == 401+++def test_ingest_rejects_empty_document_id(client: TestClient) -> None:+ response = client.post(+ "/api/v1/docparse/ingest",+ json={"documentId": "", "blocks": [block("t")]},+ headers=HEADERS,+ )+ assert response.status_code == 422+++async def test_ingest_reingest_replaces_instead_of_duplicating() -> None:+ service = DocumentService(embedder=StubEmbedder(), store=SqliteVecStore.ephemeral(), default_top_k=3) # type: ignore[arg-type]+ app.dependency_overrides[get_document_service] = lambda: service+ try:+ client = TestClient(app)+ payload: dict[str, Any] = {"documentId": "doc-replace", "blocks": [block("first version")]}+ assert client.post("/api/v1/docparse/ingest", json=payload, headers=HEADERS).status_code == 200+ payload["blocks"] = [block("second version")]+ assert client.post("/api/v1/docparse/ingest", json=payload, headers=HEADERS).status_code == 200+ finally:+ app.dependency_overrides.pop(get_document_service, None)++ results = await service.search("version", principals=[PrincipalId("test-user")], collection=FileId("doc-replace"))+ assert [r.document.text for r in results] == ["second version"]+ assert results[0].document.metadata["content_type"] == "docparse_chunk"+ assert results[0].document.metadata["source"] == "docparse"+++def test_ingest_rejects_overlap_at_or_above_chunk_size(client: TestClient) -> None:+ """chunk_text derives its stride as chunk_size - overlap, so an overlap that meets or+ exceeds the chunk size either raises on a zero step or silently drops over-long text."""+ response = client.post(+ "/api/v1/docparse/ingest",+ json={+ "documentId": "doc-1",+ "blocks": [block("para one")],+ "chunkSize": 128,+ "overlap": 128,+ },+ headers=HEADERS,+ )+ assert response.status_code == 422+ assert "overlap" in response.json()["detail"]+++def test_ingest_forwards_pages_so_the_document_is_readable_whole(+ client: TestClient, stub_service: StubDocumentService+) -> None:+ """Chunks alone make a document searchable but not readable: read_pages backs the+ whole-document agents, so the page representation has to be written too."""+ client.post(+ "/api/v1/docparse/ingest",+ json={+ "documentId": "doc-1",+ "blocks": [+ block("page one para"),+ block("a table stitched over the break", page=2, page_end=3),+ block("page three para", page=3),+ ],+ "chunkSize": 128,+ "overlap": 0,+ },+ headers=HEADERS,+ )+ pages = stub_service.calls[0]["pages"]+ assert pages is not None+ # The stitched block belongs to page 2 alone, so page 3 carries only its own text.+ assert [(p.page_number, p.text) for p in pages] == [+ (1, "page one para"),+ (2, "a table stitched over the break"),+ (3, "page three para"),+ ]diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 68cdf0a3bb..65a321e2f7 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -9013,6 +9013,24 @@ undeclared-operation = "Can't check what this step accepts"[portal.pipelines.builder.icon]label = "Change icon"+[portal.pipelines.builder.ingest]+chunkSize = "Chunk size"+chunkSizeHint = "Characters per chunk. Smaller chunks retrieve more precisely; larger ones keep more context together."+editorPdfOnly = "Editor policies return PDFs only. To export chunks or Markdown, choose a saved input source and a file destination."+exportChunks = "Export chunks as JSONL"+exportChunksHint = "One chunk per line with its page span, ready to load into another system."+exportMarkdown = "Export markdown"+exportMarkdownHint = "The document's text as one Markdown file."+includeOriginal = "Include the input PDF"+includeOriginalHint = "Deliver the PDF alongside exported text. This does not change whether the source keeps its original."+index = "Index into the knowledge base"+indexHint = "Embeds the document so it can be searched and asked about. Needs the AI engine."+nothingToDo = "Turn on at least one of indexing or an export, or this step has nothing to do and the run will fail."+overlap = "Overlap"+overlapHint = "Characters repeated between neighbouring chunks, so a sentence split across two is still findable."+overlapTooBig = "Overlap must be smaller than the chunk size ({{chunkSize}})."+unavailable = "AI ingestion needs the AI engine and DocParse turned on, including when the destination database generates embeddings."+[portal.pipelines.builder.routing]addRule = "Add a route"aiDisabled = "AI classification is not enabled. Enable it in Settings, or route on a document property instead."@@ -9284,6 +9302,7 @@ autoRedact = "Redact PII"classifyAndLabel = "Classify"compressPdf = "Compress"flatten = "Flatten"+ingest = "Prepare for knowledge search"ocrPdf = "OCR"pdfa = "Convert to PDF/A"sanitizePdf = "Remove JavaScript"@@ -9507,6 +9526,10 @@ label = "Reduce file size"desc = "Merges form fields and annotations into the page so they can't be edited."label = "Flatten the document"+[portal.policies.wizard.capability.ingest]+desc = "Prepare searchable chunks for the built-in knowledge base, a connected vector database, or a corpus export."+label = "Prepare for knowledge search"+[portal.policies.wizard.capability.ocr]desc = "Runs OCR so scanned pages become selectable, searchable text."label = "Make text searchable"diff --git a/frontend/editor/scripts/generate-tool-api-types.mts b/frontend/editor/scripts/generate-tool-api-types.mtsindex caa85d8bee..b30640b2be 100644--- a/frontend/editor/scripts/generate-tool-api-types.mts+++ b/frontend/editor/scripts/generate-tool-api-types.mts@@ -21,6 +21,7 @@ const ALLOWED_PATH_PREFIXES = ["/api/v1/filter/","/api/v1/integration/","/api/v1/ai/tools/classify-and-label",+ "/api/v1/docparse/ingest",// Admitted on its own rather than the whole form namespace: this is the only /form/ endpoint// that takes a document and returns one, so it is the only one a pipeline can chain."/api/v1/form/form-detection/detect",diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.tsindex 4db168c536..8688d7ef3a 100644--- a/frontend/editor/src/core/types/toolApiTypes.ts+++ b/frontend/editor/src/core/types/toolApiTypes.ts@@ -571,6 +571,36 @@ export interface HTMLToPdfRequest {*/zoom?: number;}+export interface IngestApiRequest {+ /**+ * Target chunk size in characters (64-32768)+ */+ chunkSize?: number;+ /**+ * Stable identifier for the ingested document; re-ingesting the same id replaces its chunks. Defaults to a content hash of the uploaded bytes.+ */+ documentId?: string;+ /**+ * Also return the chunks as a JSONL file (one chunk per line with page span and heading breadcrumb), ready for external embedding or indexing+ */+ exportChunksJsonl?: boolean;+ /**+ * Also return the parsed document as a markdown file, for delivery to external systems (vector DBs, training corpora)+ */+ exportMarkdown?: boolean;+ /**+ * Include the input PDF alongside the requested corpus files+ */+ includeOriginal?: boolean;+ /**+ * Index the document into the built-in knowledge base+ */+ index?: boolean;+ /**+ * Overlap between adjacent chunks in characters (0-4096)+ */+ overlap?: number;+}export interface IntegrationExternalApiCallRequest {bodyMode?: string;bodyTemplate?: string;@@ -1550,6 +1580,7 @@ export type ToolEndpoint =| "/api/v1/convert/text-editor/pdf"| "/api/v1/convert/url/pdf"| "/api/v1/convert/vector/pdf"+ | "/api/v1/docparse/ingest"| "/api/v1/filter/filter-contains-image"| "/api/v1/filter/filter-contains-text"| "/api/v1/filter/filter-file-size"@@ -1658,6 +1689,7 @@ export interface ToolApiParams {"/api/v1/convert/text-editor/pdf": GeneralFile;"/api/v1/convert/url/pdf": UrlToPdfRequest;"/api/v1/convert/vector/pdf": PdfVectorExportRequest;+ "/api/v1/docparse/ingest": IngestApiRequest;"/api/v1/filter/filter-contains-image": PDFWithPageNums;"/api/v1/filter/filter-contains-text": ContainsTextRequest;"/api/v1/filter/filter-file-size": FileSizeRequest;@@ -1767,6 +1799,7 @@ export const TOOL_ENDPOINTS = ["/api/v1/convert/text-editor/pdf","/api/v1/convert/url/pdf","/api/v1/convert/vector/pdf",+ "/api/v1/docparse/ingest","/api/v1/filter/filter-contains-image","/api/v1/filter/filter-contains-text","/api/v1/filter/filter-file-size",diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.tsindex d215f1df23..95aeb2c361 100644--- a/frontend/editor/src/core/types/toolIO.ts+++ b/frontend/editor/src/core/types/toolIO.ts@@ -90,7 +90,7 @@ export const TOOL_FORMAT_EXTENSIONS: Record<ToolFormat, readonly string[]> = {CSV: ["csv"],HTML: ["html", "htm", "xhtml"],XML: ["xml", "xsd", "xsl"],- JSON: ["json"],+ JSON: ["json", "jsonl"],TEXT: ["txt", "text", "md", "markdown"],MARKDOWN: ["md", "markdown"],JAVASCRIPT: ["js", "jsx"],@@ -362,6 +362,38 @@ export const TOOL_IO: ToolIOTable = {produces: "PDF",arity: "SISO",},+ "/api/v1/docparse/ingest": {+ accepts: ["PDF"],+ produces: "PDF",+ arity: "SIMO",+ cases: [+ {+ when: [+ { param: "includeOriginal", matches: ["false"], default: "true" },+ { param: "exportMarkdown", matches: ["false"], default: "false" },+ ],+ produces: "JSON",+ arity: "SIMO",+ },+ {+ when: [+ { param: "includeOriginal", matches: ["false"], default: "true" },+ { param: "exportChunksJsonl", matches: ["false"], default: "false" },+ ],+ produces: "MARKDOWN",+ arity: "SIMO",+ },+ {+ when: [+ { param: "includeOriginal", matches: ["false"], default: "true" },+ { param: "exportMarkdown", matches: ["true"], default: "false" },+ { param: "exportChunksJsonl", matches: ["true"], default: "false" },+ ],+ produces: "ANY",+ arity: "SIMO",+ },+ ],+ },"/api/v1/filter/filter-contains-image": {accepts: ["PDF"],produces: "PDF",diff --git a/frontend/editor/src/core/utils/toolIOCompat.test.ts b/frontend/editor/src/core/utils/toolIOCompat.test.tsindex 23dbf1d92a..91864b561d 100644--- a/frontend/editor/src/core/utils/toolIOCompat.test.ts+++ b/frontend/editor/src/core/utils/toolIOCompat.test.ts@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import {validateToolChain,+ chainOutputFormat,toolAcceptsFile,type ToolChainStep,type ToolDiagnostic,@@ -138,3 +139,34 @@ describe("tool file inputs", () => {},);});++describe("RAG pipeline contract", () => {+ it("recognises OCR followed by a chunks-only RAG export", () => {+ const steps = [+ { operation: "/api/v1/misc/ocr-pdf", parameters: { sidecar: false } },+ {+ operation: "/api/v1/docparse/ingest",+ parameters: {+ includeOriginal: false,+ exportChunksJsonl: true,+ exportMarkdown: false,+ },+ },+ ];+ expect(validateToolChain(steps)).toEqual([]);+ expect(chainOutputFormat(steps)).toBe("JSON");+ });++ it("rejects a PDF operation after a chunks-only export", () => {+ const diagnostics = validateToolChain([+ {+ operation: "/api/v1/docparse/ingest",+ parameters: { includeOriginal: false, exportChunksJsonl: true },+ },+ { operation: "/api/v1/misc/compress-pdf", parameters: {} },+ ]);+ expect(diagnostics).toEqual([+ expect.objectContaining({ stepIndex: 1, severity: "ERROR" }),+ ]);+ });+});diff --git a/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsx b/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsxnew file mode 100644index 0000000000..b7baa0b6f9--- /dev/null+++ b/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsx@@ -0,0 +1,137 @@+import { useTranslation } from "react-i18next";+import { Banner, FormField, Input, ToggleSwitch } from "@app/ui";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import type { IngestStepParams } from "@portal/components/pipelines/docparseStep";++interface IngestStepConfigProps {+ parameters: IngestStepParams;+ editorInput?: boolean;+ onChange: (parameters: IngestStepParams) => void;+}++/** Settings for the ingest step: what it produces and how it chunks. */+export function IngestStepConfig({+ parameters,+ editorInput = false,+ onChange,+}: IngestStepConfigProps) {+ const { t } = useTranslation();+ const { config, loading } = useAppConfig();+ const available = Boolean(config?.aiEngineEnabled);+ const chunkSize = parameters.chunkSize ?? 512;+ const overlap = parameters.overlap ?? 64;+ const index = parameters.index !== false;+ const markdown = parameters.exportMarkdown === true;+ const chunksJsonl = parameters.exportChunksJsonl === true;++ const setNumber = (key: "chunkSize" | "overlap", raw: string) => {+ const value = Number(raw);+ onChange({+ ...parameters,+ [key]: Number.isFinite(value) && raw !== "" ? value : undefined,+ });+ };++ const overlapTooBig = overlap >= chunkSize;+ const includeOriginal = parameters.includeOriginal !== false;+ const doesNothing = (!index || !includeOriginal) && !markdown && !chunksJsonl;++ return (+ <div className="portal-policies__capability-config">+ {!loading && !available && (+ <Banner+ tone="warning"+ description={t("portal.pipelines.builder.ingest.unavailable")}+ />+ )}+ {editorInput && (+ <Banner+ tone="info"+ description={t(+ "portal.pipelines.builder.ingest.editorPdfOnly",+ "Editor policies return PDFs only. To export chunks or Markdown, choose a saved input source and a file destination.",+ )}+ />+ )}+ {(!editorInput || !includeOriginal) && (+ <ToggleSwitch+ size="sm"+ checked={includeOriginal}+ onChange={(checked) =>+ onChange({ ...parameters, includeOriginal: checked })+ }+ label={t("portal.pipelines.builder.ingest.includeOriginal")}+ description={t("portal.pipelines.builder.ingest.includeOriginalHint")}+ />+ )}+ <ToggleSwitch+ size="sm"+ checked={index}+ onChange={(checked) => onChange({ ...parameters, index: checked })}+ label={t("portal.pipelines.builder.ingest.index")}+ description={t("portal.pipelines.builder.ingest.indexHint")}+ />+ {(!editorInput || markdown) && (+ <ToggleSwitch+ size="sm"+ checked={markdown}+ onChange={(checked) =>+ onChange({ ...parameters, exportMarkdown: checked })+ }+ label={t("portal.pipelines.builder.ingest.exportMarkdown")}+ description={t("portal.pipelines.builder.ingest.exportMarkdownHint")}+ />+ )}+ {(!editorInput || chunksJsonl) && (+ <ToggleSwitch+ size="sm"+ checked={chunksJsonl}+ onChange={(checked) =>+ onChange({ ...parameters, exportChunksJsonl: checked })+ }+ label={t("portal.pipelines.builder.ingest.exportChunks")}+ description={t("portal.pipelines.builder.ingest.exportChunksHint")}+ />+ )}+ {doesNothing && (+ <p className="portal-pipelines__step-hint">+ {t("portal.pipelines.builder.ingest.nothingToDo")}+ </p>+ )}+ <FormField+ label={t("portal.pipelines.builder.ingest.chunkSize")}+ helperText={t("portal.pipelines.builder.ingest.chunkSizeHint")}+ >+ <Input+ type="number"+ inputSize="sm"+ min={64}+ max={32768}+ step={64}+ value={parameters.chunkSize ?? ""}+ onChange={(e) => setNumber("chunkSize", e.target.value)}+ />+ </FormField>+ <FormField+ label={t("portal.pipelines.builder.ingest.overlap")}+ helperText={+ overlapTooBig+ ? t("portal.pipelines.builder.ingest.overlapTooBig", {+ chunkSize,+ })+ : t("portal.pipelines.builder.ingest.overlapHint")+ }+ >+ <Input+ type="number"+ inputSize="sm"+ min={0}+ max={4096}+ step={16}+ value={parameters.overlap ?? ""}+ onChange={(e) => setNumber("overlap", e.target.value)}+ />+ </FormField>+ </div>+ );+}diff --git a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsxindex 3d17dbf652..84edd1c8ca 100644--- a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx+++ b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx@@ -15,6 +15,11 @@ import {import { PolicyExternalApiConfig } from "@portal/components/policies/PolicyExternalApiConfig";import { isIntegrationStep } from "@portal/components/pipelines/integrationStep";+import {+ isIngestStep,+ type IngestStepParams,+} from "@portal/components/pipelines/docparseStep";+import { IngestStepConfig } from "@portal/components/pipelines/IngestStepConfig";import type { ExternalApiStepParams } from "@portal/components/policies/stepOperations";import "@portal/components/pipelines/PipelineStepSettings.css";@@ -30,6 +35,7 @@ export type ParamsUpdate =interface PipelineStepSettingsProps {step: WorkingToolStep;+ editorInput?: boolean;registry: Partial<ToolRegistry>;onChange: (update: ParamsUpdate) => void;/** Stored asset id -> file name, for labelling the supporting-file chips on a reopened pipeline. */@@ -82,6 +88,7 @@ function storedFileChips(* supporting files appear as removable chips above the tool's own settings.*/export function PipelineStepSettings({+ editorInput = false,step,registry,onChange,@@ -92,6 +99,18 @@ export function PipelineStepSettings({// above useTranslation would change the hook count between renders and crash.const { t } = useTranslation();+ // Same reasoning as the integration branch below: a DocParse step has no registry entry, so+ // its settings come from its own component rather than a tool's.+ if (isIngestStep(step)) {+ return (+ <IngestStepConfig+ editorInput={editorInput}+ parameters={step.params as unknown as IngestStepParams}+ onChange={(params) => onChange(params as never)}+ />+ );+ }+// An integration step is configured by the operations catalogue, not by a tool's settings UI:// it has no registry entry to look one up from.if (isIntegrationStep(step)) {diff --git a/frontend/editor/src/portal/components/pipelines/docparseStep.test.ts b/frontend/editor/src/portal/components/pipelines/docparseStep.test.tsnew file mode 100644index 0000000000..c86fa4e1f2--- /dev/null+++ b/frontend/editor/src/portal/components/pipelines/docparseStep.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from "vitest";+import {+ newIngestStep,+ ingestStepConfigured,+} from "@portal/components/pipelines/docparseStep";++describe("RAG chunk parameter limits", () => {+ it.each([+ { chunkSize: 63 },+ { chunkSize: 32769 },+ { chunkSize: 100.5 },+ { overlap: -1 },+ { chunkSize: 8192, overlap: 4097 },+ ])("rejects invalid chunk settings %j", (parameters) => {+ const step = newIngestStep();+ expect(+ ingestStepConfigured({+ ...step,+ params: { ...step.params, ...parameters },+ }),+ ).toBe(false);+ });+ it("allows zero overlap", () => {+ const step = newIngestStep();+ expect(+ ingestStepConfigured({+ ...step,+ params: { ...step.params, overlap: 0 },+ }),+ ).toBe(true);+ });+});diff --git a/frontend/editor/src/portal/components/pipelines/docparseStep.ts b/frontend/editor/src/portal/components/pipelines/docparseStep.tsnew file mode 100644index 0000000000..f7858ac4b4--- /dev/null+++ b/frontend/editor/src/portal/components/pipelines/docparseStep.ts@@ -0,0 +1,57 @@+/** The ingest step uses an endpoint step because it has no editor tool-registry entry. */++import type { ErasedToolParams } from "@app/hooks/tools/shared/toolOperationTypes";+import type { WorkingToolStep } from "@app/hooks/tools/shared/toolAutomation";++import type { IngestApiRequest } from "@app/types/toolApiTypes";+import {+ INGEST_ENDPOINT,+ INGEST_DEFAULTS,+ ingestChunkingConfigured,+} from "@app/policies/ingestOperation";+export { INGEST_ENDPOINT } from "@app/policies/ingestOperation";++/** Parameters the ingest endpoint binds, as the builder holds them. */+export type IngestStepParams = IngestApiRequest;++export function isIngestStep(step: WorkingToolStep): boolean {+ return step.toolId === null && step.operation === INGEST_ENDPOINT;+}++/** A new ingest step on the endpoint's own defaults, so it runs without being opened. */+export function newIngestStep(): WorkingToolStep {+ return {+ toolId: null,+ operation: INGEST_ENDPOINT,+ params: { ...INGEST_DEFAULTS } as unknown as ErasedToolParams,+ support: "unknown",+ };+}++/**+ * Whether the step can run. The endpoint rejects a request that would neither index nor export,+ * and an overlap at or above the chunk size, so both are caught here rather than at run time.+ */+export function ingestStepConfigured(+ step: WorkingToolStep,+ editorInput = false,+): boolean {+ if (!isIngestStep(step)) return true;+ const params = step.params as IngestStepParams;+ if (+ editorInput &&+ (params.exportChunksJsonl === true ||+ params.exportMarkdown === true ||+ params.includeOriginal === false)+ )+ return false;+ const doesSomething =+ params.index !== false ||+ params.exportMarkdown === true ||+ params.exportChunksJsonl === true;+ const hasFiles =+ params.includeOriginal !== false ||+ params.exportMarkdown === true ||+ params.exportChunksJsonl === true;+ return doesSomething && hasFiles && ingestChunkingConfigured(params);+}diff --git a/frontend/editor/src/portal/views/PipelineBuilder.tsx b/frontend/editor/src/portal/views/PipelineBuilder.tsxindex 3805da569b..b25561a637 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.tsx@@ -1,5 +1,9 @@import { requiresClassification } from "@app/data/classificationConditions";import { isConditionComplete } from "@app/conditions/validation";+import {+ isIngestStep,+ ingestStepConfigured,+} from "@portal/components/pipelines/docparseStep";import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { useLocation, useNavigate, useParams } from "react-router-dom";import { useTranslation } from "react-i18next";@@ -579,9 +583,14 @@ export function PipelineBuilder() {function updateStepParams(index: number, update: ParamsUpdate) {setSteps((current) =>current.map((step, i) => {- // Integration steps are deliberately toolId-less, so they must be editable too; only a- // genuinely unrecognised step has no editor to send changes from.- if (i !== index || (step.toolId === null && !isIntegrationStep(step)))+ // Integration and DocParse steps are deliberately toolId-less, so they must be editable+ // too; only a genuinely unrecognised step has no editor to send changes from.+ if (+ i !== index ||+ (step.toolId === null &&+ !isIntegrationStep(step) &&+ !isIngestStep(step))+ )return step;// Resolve the update against the CURRENT step params, so a settings UI firing several// single-field changes in one tick (convert's source-format change resets target + options)@@ -617,6 +626,7 @@ export function PipelineBuilder() {if (op) return t(op.labelKey);if (isIntegrationStep(step))return t("portal.pipelines.builder.sendToSystem");+ if (isIngestStep(step)) return t("portal.policies.endpoints.ingest");const entry = step.toolId ? allTools[step.toolId] : undefined;return entry?.name ?? humanizeOperation(step.operation);}@@ -643,6 +653,7 @@ export function PipelineBuilder() {.filter((step) =>!integrationStepConfigured(step) ||+ !ingestStepConfigured(step, isEditorInput) ||stepNeedsConfiguring(step, allTools),).map(stepLabel);@@ -1238,6 +1249,9 @@ export function PipelineBuilder() {function stepDetail(step: WorkingToolStep): string | undefined {if (step.support === "unsupported")return t("portal.pipelines.builder.usesDefaults");+ // Integration and DocParse steps are toolId-less by design and carry their own settings UI,+ // so "unknown" here means "not a registry tool", not "we cannot drive this".+ if (isIntegrationStep(step) || isIngestStep(step)) return undefined;if (step.support === "unknown")return t("portal.pipelines.builder.unknownStep");return undefined;@@ -1400,6 +1414,7 @@ export function PipelineBuilder() {if (selectedStep) {return (<PipelineStepSettings+ editorInput={isEditorInput}step={selectedStep}registry={allTools}onChange={(params) => updateStepParams(chosenSteps[0], params)}diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsxindex 7cb22a3f84..070b80fb96 100644--- a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx@@ -178,6 +178,13 @@ const CAPABILITY_META: Record<descKey: "portal.policies.wizard.capability.watermark.desc",descEn: "Stamps a visible mark (e.g. “Confidential”) across every page.",},+ ingest: {+ labelKey: "portal.policies.wizard.capability.ingest.label",+ labelEn: "Prepare for knowledge search",+ descKey: "portal.policies.wizard.capability.ingest.desc",+ descEn:+ "Prepare searchable chunks for the built-in knowledge base, a connected RAG database, or a corpus export.",+ },ocr: {labelKey: "portal.policies.wizard.capability.ocr.label",labelEn: "Make text searchable",diff --git a/frontend/editor/src/proprietary/policies/ingestOperation.ts b/frontend/editor/src/proprietary/policies/ingestOperation.tsnew file mode 100644index 0000000000..3a2dfbc0d1--- /dev/null+++ b/frontend/editor/src/proprietary/policies/ingestOperation.ts@@ -0,0 +1,62 @@+import type { BidirectionalToolConfig } from "@app/hooks/tools/shared/toolOperationDescriptor";+import type { IngestApiRequest, ToolEndpoint } from "@app/types/toolApiTypes";++export const INGEST_ENDPOINT = "/api/v1/docparse/ingest" satisfies ToolEndpoint;+export const INGEST_DEFAULTS = {+ chunkSize: 512,+ overlap: 64,+ index: true,+ exportMarkdown: false,+ exportChunksJsonl: false,+ includeOriginal: true,+} satisfies IngestApiRequest;++type IngestParameters = Record<keyof typeof INGEST_DEFAULTS, string>;++/** Shared by the guided menus and builder; invalid edits stay visible until corrected. */+export function ingestChunkingConfigured(+ parameters: Pick<IngestApiRequest, "chunkSize" | "overlap">,+): boolean {+ const chunkSize = parameters.chunkSize ?? INGEST_DEFAULTS.chunkSize;+ const overlap = parameters.overlap ?? INGEST_DEFAULTS.overlap;+ return (+ Number.isInteger(chunkSize) &&+ chunkSize >= 64 &&+ chunkSize <= 32768 &&+ Number.isInteger(overlap) &&+ overlap >= 0 &&+ overlap <= 4096 &&+ overlap < chunkSize+ );+}++export const ingestOperationConfig: BidirectionalToolConfig<+ IngestParameters,+ typeof INGEST_ENDPOINT+> = {+ endpoint: INGEST_ENDPOINT,+ defaultParameters: {+ chunkSize: String(INGEST_DEFAULTS.chunkSize),+ overlap: String(INGEST_DEFAULTS.overlap),+ index: "true",+ exportMarkdown: "false",+ exportChunksJsonl: "false",+ includeOriginal: "true",+ },+ toApiParams: (parameters) => ({+ chunkSize: Number(parameters.chunkSize),+ overlap: Number(parameters.overlap),+ index: parameters.index !== "false",+ exportMarkdown: parameters.exportMarkdown === "true",+ exportChunksJsonl: parameters.exportChunksJsonl === "true",+ includeOriginal: parameters.includeOriginal !== "false",+ }),+ fromApiParams: (parameters) => ({+ chunkSize: String(parameters.chunkSize ?? INGEST_DEFAULTS.chunkSize),+ overlap: String(parameters.overlap ?? INGEST_DEFAULTS.overlap),+ index: String(parameters.index ?? true),+ exportMarkdown: String(parameters.exportMarkdown ?? false),+ exportChunksJsonl: String(parameters.exportChunksJsonl ?? false),+ includeOriginal: String(parameters.includeOriginal ?? true),+ }),+};diff --git a/frontend/editor/src/proprietary/policies/operations.test.ts b/frontend/editor/src/proprietary/policies/operations.test.tsindex 0cfe3fa352..b8d207ad10 100644--- a/frontend/editor/src/proprietary/policies/operations.test.ts+++ b/frontend/editor/src/proprietary/policies/operations.test.ts@@ -20,6 +20,7 @@ describe("POLICY_OPERATIONS", () => {"compress","externalApiCall","flatten",+ "ingest","ocr","pdfa","purviewApplyLabel",@@ -157,3 +158,46 @@ describe("compliance steps", () => {expect(back?.params).toEqual({});});});++describe("rag ingest wire round-trip", () => {+ test("sends positive integer sizes and real booleans, and round-trips them", () => {+ const wire = policyStepToWire(+ policyStep("ingest", {+ chunkSize: "1024",+ overlap: "32",+ exportMarkdown: "true",+ }),+ );+ expect(wire.operation).toBe("/api/v1/docparse/ingest");+ expect(wire.parameters).toEqual({+ chunkSize: 1024,+ overlap: 32,+ index: true,+ exportMarkdown: true,+ exportChunksJsonl: false,+ includeOriginal: true,+ });++ const back = policyStepFromWire(wire);+ expect(back?.toolId).toBe("ingest");+ if (back?.toolId === "ingest") {+ expect(back.params.chunkSize).toBe("1024");+ expect(back.params.exportMarkdown).toBe("true");+ expect(back.params.index).toBe("true");+ }+ });++ test("preserves zero overlap through editing and save", () => {+ const wire = policyStepToWire(policyStep("ingest", { overlap: "0" }));+ expect(wire.parameters.overlap).toBe(0);+ const decoded = policyStepFromWire(wire);+ expect(decoded?.params).toMatchObject({ overlap: "0" });+ });++ test("retains an invalid pair so validation can report it without silently changing settings", () => {+ const wire = policyStepToWire(+ policyStep("ingest", { chunkSize: "256", overlap: "512" }),+ );+ expect(wire.parameters).toMatchObject({ chunkSize: 256, overlap: 512 });+ });+});diff --git a/frontend/editor/src/proprietary/policies/operations.ts b/frontend/editor/src/proprietary/policies/operations.tsindex b8d974ff70..57e7446496 100644--- a/frontend/editor/src/proprietary/policies/operations.ts+++ b/frontend/editor/src/proprietary/policies/operations.ts@@ -15,6 +15,10 @@ import { addWatermarkOperationConfig } from "@app/hooks/tools/addWatermark/useAdimport { ocrOperationConfig } from "@app/hooks/tools/ocr/useOCROperation";import { flattenOperationConfig } from "@app/hooks/tools/flatten/useFlattenOperation";import { compressOperationConfig } from "@app/hooks/tools/compress/useCompressOperation";+import {+ INGEST_ENDPOINT,+ ingestOperationConfig,+} from "@app/policies/ingestOperation";import { pdfaOperationConfig } from "@app/policies/pdfaOperation";import type { ToolEndpoint } from "@app/types/toolApiTypes";import type { WirePipelineStep } from "@app/policies/types";@@ -145,9 +149,15 @@ export const POLICY_OPERATIONS = {complianceCheckOperationConfig,),classify: describeAiToolOperation("/api/v1/ai/tools/classify-and-label"),+ ingest: describeToolOperation(INGEST_ENDPOINT, ingestOperationConfig),purviewApplyLabel: describeIntegrationOperation("/api/v1/integration/purview-apply-label",- { connectionId: "", labelId: "", labelName: "", method: "STANDARD" },+ {+ connectionId: "",+ labelId: "",+ labelName: "",+ method: "STANDARD",+ },),purviewReadLabel: describeIntegrationOperation("/api/v1/integration/purview-read-label",diff --git a/frontend/editor/src/proprietary/policies/types.ts b/frontend/editor/src/proprietary/policies/types.tsindex bf54d398a3..8d6e30aae7 100644--- a/frontend/editor/src/proprietary/policies/types.ts+++ b/frontend/editor/src/proprietary/policies/types.ts@@ -78,9 +78,11 @@ export interface WireEditorConfig {runOn: "upload" | "export";}+/** A saved input and its server-side trigger; null runs only on demand. */export interface WirePolicy {id: string;name: string;+ icon?: string;owner?: string;enabled: boolean;/** A policy (blocking on failure) rather than an ordinary pipeline (see `Policy.required`). */@@ -133,6 +135,7 @@ export interface PolicyRunView {export interface PolicyDecodedState {id: string;name: string;+ icon?: string;enabled: boolean;/** A policy (blocking on failure) rather than an ordinary pipeline; first-class, not in options. */required: boolean;