Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Enable routing policy with source stuff (#7221)

Anthony Stirlinge2cee3282fb1
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/classification/ClassificationConditions.java b/app/proprietary/src/main/java/stirling/software/proprietary/classification/ClassificationConditions.java
new file mode 100644
index 0000000000..9f6d13b7eb
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/classification/ClassificationConditions.java
@@ -0,0 +1,20 @@
+package stirling.software.proprietary.classification;
+
+import stirling.software.proprietary.document.conditions.Condition;
+import stirling.software.proprietary.document.conditions.ConditionInput;
+
+/** Identifies conditions that consume a classifier-produced verdict. */
+public final class ClassificationConditions {
+
+ private ClassificationConditions() {}
+
+ /**
+ * Missing or unrelated inputs do not require classification; validation handles invalid ones.
+ */
+ public static boolean requiresClassification(Condition condition) {
+ return condition != null
+ && condition.input() instanceof ConditionInput.DocumentField(var field)
+ && field != null
+ && field.startsWith("classification.");
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/document/DocumentFacts.java b/app/proprietary/src/main/java/stirling/software/proprietary/document/DocumentFacts.java
new file mode 100644
index 0000000000..652f32d166
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/document/DocumentFacts.java
@@ -0,0 +1,207 @@
+package stirling.software.proprietary.document;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Calendar;
+import java.util.List;
+import java.util.Locale;
+
+import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDDocumentInformation;
+import org.springframework.core.io.Resource;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.service.PdfMetadataService;
+import stirling.software.proprietary.integration.purview.PdfSensitivityLabels;
+import stirling.software.proprietary.integration.purview.SensitivityLabel;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ObjectNode;
+
+/**
+ * What Stirling knows about a document from its bytes alone, as one JSON object:
+ *
+ * <pre>
+ * document.filename | .extension | .sizeBytes | .pageCount | .encrypted
+ * .title | .author | .subject | .keywords | .creator | .producer | .created | .modified
+ * classification.* the classifier policy's verdict, when it has run
+ * sensitivityLabel.labelId | .name | .siteId | .method | .protected
+ * </pre>
+ *
+ * <p>Two callers share this shape, which is why it lives apart from either. {@code DocumentContext}
+ * wraps it as the namespace the external-API step's placeholders resolve against, adding the
+ * transfer-only facts a call-out needs - content type, hash, the bytes themselves - and the run it
+ * belongs to. Routing rules match against it, so {@code classification.labels} decides where a
+ * document is delivered.
+ *
+ * <p>Every field is best-effort: a non-PDF or an unparseable PDF simply omits what cannot be known.
+ * Building the facts must never be the reason a step or a delivery fails.
+ */
+@Slf4j
+public final class DocumentFacts {
+
+ private DocumentFacts() {}
+
+ /** The facts for a document already in memory, as a fresh object the caller may add to. */
+ public static ObjectNode of(byte[] content, String filename, ObjectMapper objectMapper) {
+ ObjectNode root = objectMapper.createObjectNode();
+ ObjectNode document = base(root, filename, content == null ? 0 : content.length);
+ if (looksLikePdf(content)) {
+ addPdfFacts(document, root, objectMapper, () -> Loader.loadPDF(content));
+ }
+ return root;
+ }
+
+ /**
+ * The facts for a document the engine is carrying between steps.
+ *
+ * <p>A file-backed resource - what the executor produces between steps - is opened by handle,
+ * so routing a large document does not pull it into memory to read a label off it. Anything
+ * else is read once into a buffer and handled by the in-memory path: a stream-backed resource
+ * can only be consumed once, so sniffing the header and then re-opening it would either fail or
+ * silently read nothing.
+ */
+ public static ObjectNode of(Resource file, ObjectMapper objectMapper) {
+ if (!file.isFile()) {
+ return ofBuffered(file, objectMapper);
+ }
+ ObjectNode root = objectMapper.createObjectNode();
+ ObjectNode document = base(root, file.getFilename(), sizeOf(file));
+ if (looksLikePdfOnDisk(file)) {
+ addPdfFacts(document, root, objectMapper, () -> Loader.loadPDF(file.getFile()));
+ }
+ return root;
+ }
+
+ /** The one-shot path: read the bytes once, then treat it as an in-memory document. */
+ private static ObjectNode ofBuffered(Resource file, ObjectMapper objectMapper) {
+ try {
+ return of(file.getContentAsByteArray(), file.getFilename(), objectMapper);
+ } catch (IOException e) {
+ log.debug("Could not read {} for its facts: {}", file.getFilename(), e.getMessage());
+ ObjectNode root = objectMapper.createObjectNode();
+ base(root, file.getFilename(), 0);
+ return root;
+ }
+ }
+
+ private static ObjectNode base(ObjectNode root, String filename, long sizeBytes) {
+ ObjectNode document = root.putObject("document");
+ document.put("filename", filename);
+ document.put("extension", extensionOf(filename));
+ document.put("sizeBytes", sizeBytes);
+ return document;
+ }
+
+ /** Opens a document the caller's way; anything it throws is swallowed as a missing fact. */
+ private interface PdfSupplier {
+ PDDocument get() throws IOException;
+ }
+
+ /** PDF-only facts. A document we cannot parse still gets the basics above. */
+ private static void addPdfFacts(
+ ObjectNode document, ObjectNode root, ObjectMapper objectMapper, PdfSupplier supplier) {
+ try (PDDocument pdf = supplier.get()) {
+ document.put("pageCount", pdf.getNumberOfPages());
+ document.put("encrypted", pdf.isEncrypted());
+
+ PDDocumentInformation info = pdf.getDocumentInformation();
+ document.put("title", info.getTitle());
+ document.put("author", info.getAuthor());
+ document.put("subject", info.getSubject());
+ document.put("keywords", info.getKeywords());
+ document.put("creator", info.getCreator());
+ document.put("producer", info.getProducer());
+ document.put("created", toIso(info.getCreationDate()));
+ document.put("modified", toIso(info.getModificationDate()));
+
+ addClassification(root, info, objectMapper);
+ addSensitivityLabel(root, pdf);
+ } catch (IOException | RuntimeException e) {
+ // An encrypted or malformed PDF is a normal thing to meet here; the extra facts are a
+ // convenience, not a precondition.
+ log.debug("Could not read PDF facts: {}", e.getMessage());
+ }
+ }
+
+ /** The classifier policy's verdict, so a caller can act on it without re-classifying. */
+ private static void addClassification(
+ ObjectNode root, PDDocumentInformation info, ObjectMapper objectMapper) {
+ String raw = info.getCustomMetadataValue(PdfMetadataService.CLASSIFICATION_KEY);
+ if (raw == null || raw.isBlank()) {
+ return;
+ }
+ try {
+ JsonNode parsed = objectMapper.readTree(raw);
+ root.set("classification", parsed);
+ } catch (RuntimeException e) {
+ // Written by another tool; if it is not JSON, pass it through as text rather than drop
+ // it - the receiving system may still recognise it.
+ root.put("classification", raw);
+ }
+ }
+
+ /** The Purview label already on the document, if any. */
+ private static void addSensitivityLabel(ObjectNode root, PDDocument pdf) {
+ List<SensitivityLabel> labels = PdfSensitivityLabels.readAll(pdf);
+ if (labels.isEmpty()) {
+ return;
+ }
+ SensitivityLabel label = labels.get(0);
+ ObjectNode node = root.putObject("sensitivityLabel");
+ node.put("labelId", label.labelId());
+ node.put("name", label.name());
+ node.put("siteId", label.siteId());
+ node.put("method", label.method() == null ? null : label.method().name());
+ node.put("protected", label.isProtected());
+ }
+
+ /** Cheap check so a non-PDF never pays for a parse attempt. */
+ private static boolean looksLikePdf(byte[] content) {
+ return content != null
+ && content.length > 4
+ && content[0] == '%'
+ && content[1] == 'P'
+ && content[2] == 'D'
+ && content[3] == 'F';
+ }
+
+ /**
+ * The same check on a file, without reading past the header. Safe to re-open afterwards, which
+ * is why this path is only taken for a resource backed by a real file.
+ */
+ private static boolean looksLikePdfOnDisk(Resource file) {
+ byte[] header = new byte[5];
+ try (InputStream in = file.getInputStream()) {
+ return in.readNBytes(header, 0, header.length) == header.length && looksLikePdf(header);
+ } catch (IOException e) {
+ log.debug("Could not read the header of {}: {}", file.getFilename(), e.getMessage());
+ return false;
+ }
+ }
+
+ private static long sizeOf(Resource file) {
+ try {
+ return file.contentLength();
+ } catch (IOException e) {
+ return 0;
+ }
+ }
+
+ private static String toIso(Calendar calendar) {
+ return calendar == null ? null : calendar.toInstant().toString();
+ }
+
+ private static String extensionOf(String filename) {
+ if (filename == null) {
+ return null;
+ }
+ int dot = filename.lastIndexOf('.');
+ return dot < 0 || dot == filename.length() - 1
+ ? null
+ : filename.substring(dot + 1).toLowerCase(Locale.ROOT);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/Condition.java b/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/Condition.java
new file mode 100644
index 0000000000..8af845328d
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/Condition.java
@@ -0,0 +1,24 @@
+package stirling.software.proprietary.document.conditions;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+
+/**
+ * A comparison independent of what its caller does on a match. Each operator owns its operand
+ * types, so numeric comparisons can use numbers without changing string-membership conditions.
+ */
+@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "operator")
+@JsonSubTypes(@JsonSubTypes.Type(value = Condition.MatchesAny.class, name = "matches-any"))
+public sealed interface Condition permits Condition.MatchesAny {
+
+ ConditionInput input();
+
+ /** Matches any scalar or array value, ignoring case and surrounding whitespace. */
+ record MatchesAny(ConditionInput input, List<String> values) implements Condition {
+ public MatchesAny {
+ values = values == null ? List.of() : List.copyOf(values);
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/ConditionEvaluator.java b/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/ConditionEvaluator.java
new file mode 100644
index 0000000000..377051a871
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/ConditionEvaluator.java
@@ -0,0 +1,74 @@
+package stirling.software.proprietary.document.conditions;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.regex.Pattern;
+
+import tools.jackson.databind.JsonNode;
+
+/** Evaluates document conditions without choosing actions or destinations. */
+public final class ConditionEvaluator {
+
+ private ConditionEvaluator() {}
+
+ /**
+ * Missing facts never match. Scalar/array values use case-insensitive, trimmed string matching.
+ * Invalid conditions throw rather than silently returning a non-match.
+ */
+ public static boolean matches(Condition condition, JsonNode documentFacts) {
+ ConditionValidator.validate(condition);
+ JsonNode value =
+ switch (condition.input()) {
+ case ConditionInput.DocumentField(var field) -> nodeAt(documentFacts, field);
+ };
+ return switch (condition) {
+ case Condition.MatchesAny(var input, var values) -> intersects(valuesOf(value), values);
+ };
+ }
+
+ private static boolean intersects(List<String> actual, List<String> wanted) {
+ return wanted.stream().map(ConditionEvaluator::normalise).anyMatch(actual::contains);
+ }
+
+ /**
+ * The resolved values, normalised for comparison. A missing, null, or blank fact has no values,
+ * so no rule claims it.
+ */
+ private static List<String> valuesOf(JsonNode node) {
+ List<String> values = new ArrayList<>();
+ if (node == null || node.isNull() || node.isMissingNode()) {
+ return values;
+ }
+ if (node.isArray()) {
+ node.forEach(element -> addNormalised(values, element.asString()));
+ } else {
+ addNormalised(values, node.asString());
+ }
+ return values;
+ }
+
+ private static void addNormalised(List<String> into, String value) {
+ if (value != null && !value.isBlank()) {
+ into.add(normalise(value));
+ }
+ }
+
+ private static String normalise(String value) {
+ return value == null ? "" : value.trim().toLowerCase(Locale.ROOT);
+ }
+
+ private static JsonNode nodeAt(JsonNode facts, String field) {
+ if (facts == null || field == null || field.isBlank()) {
+ return null;
+ }
+ JsonNode current = facts;
+ for (String segment : field.split(Pattern.quote("."))) {
+ if (current == null || !current.isObject()) {
+ return null;
+ }
+ current = current.get(segment);
+ }
+ return current;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/ConditionInput.java b/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/ConditionInput.java
new file mode 100644
index 0000000000..1ed5d0ac09
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/ConditionInput.java
@@ -0,0 +1,16 @@
+package stirling.software.proprietary.document.conditions;
+
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+
+/**
+ * Identifies where a comparison reads its value. Source variants keep document properties separate
+ * from references requiring execution state, such as a particular tool step's output.
+ */
+@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "source")
+@JsonSubTypes(@JsonSubTypes.Type(value = ConditionInput.DocumentField.class, name = "document"))
+public sealed interface ConditionInput permits ConditionInput.DocumentField {
+
+ /** A dotted path into DocumentFacts, read from the current file at the evaluation point. */
+ record DocumentField(String field) implements ConditionInput {}
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/ConditionValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/ConditionValidator.java
new file mode 100644
index 0000000000..a7ed423b80
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/document/conditions/ConditionValidator.java
@@ -0,0 +1,32 @@
+package stirling.software.proprietary.document.conditions;
+
+/** Validates comparisons without requiring a routing destination or a pipeline. */
+public final class ConditionValidator {
+
+ private ConditionValidator() {}
+
+ /** Rejects incomplete inputs and operands before a condition can be saved or executed. */
+ public static void validate(Condition condition) {
+ if (condition == null) {
+ throw new IllegalArgumentException("a condition is required");
+ }
+ if (condition.input() == null) {
+ throw new IllegalArgumentException("a condition must name an input");
+ }
+ switch (condition.input()) {
+ case ConditionInput.DocumentField(var field) -> {
+ if (field == null || field.isBlank()) {
+ throw new IllegalArgumentException("a document condition must name a field");
+ }
+ }
+ }
+ switch (condition) {
+ case Condition.MatchesAny(var input, var values) -> {
+ if (values.stream().allMatch(String::isBlank)) {
+ throw new IllegalArgumentException(
+ "a matches-any condition has nothing to match against");
+ }
+ }
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/DocumentContext.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/DocumentContext.java
index 044d24c0c5..a5fa31c8d0 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/DocumentContext.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/DocumentContext.java
@@ -1,27 +1,15 @@
package stirling.software.proprietary.integration.api;
-import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Base64;
-import java.util.Calendar;
import java.util.HexFormat;
-import java.util.List;
-import java.util.Locale;
-import org.apache.pdfbox.Loader;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.springframework.web.multipart.MultipartFile;
-import lombok.extern.slf4j.Slf4j;
+import stirling.software.proprietary.document.DocumentFacts;
-import stirling.software.common.service.PdfMetadataService;
-import stirling.software.proprietary.integration.purview.PdfSensitivityLabels;
-import stirling.software.proprietary.integration.purview.SensitivityLabel;
-
-import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.node.ObjectNode;
@@ -47,10 +35,12 @@ import tools.jackson.databind.node.ObjectNode;
* run.policyName | .runId | .timestamp
* </pre>
*
+ * <p>{@link DocumentFacts} supplies everything derivable from the bytes; this adds the three
+ * transfer-only fields a call-out needs and the run it belongs to.
+ *
* <p>Every field is best-effort: a non-PDF, an unparseable PDF, or an ad-hoc run with no policy
* simply omits what it cannot know. Building the context must never be the reason a step fails.
*/
-@Slf4j
final class DocumentContext {
private DocumentContext() {}
@@ -61,23 +51,14 @@ final class DocumentContext {
String policyName,
String runId,
ObjectMapper objectMapper) {
- ObjectNode root = objectMapper.createObjectNode();
- ObjectNode document = root.putObject("document");
-
- String filename = file.getOriginalFilename();
- document.put("filename", filename);
- document.put("extension", extensionOf(filename));
+ ObjectNode root = DocumentFacts.of(content, file.getOriginalFilename(), objectMapper);
+ ObjectNode document = (ObjectNode) root.get("document");
document.put("contentType", file.getContentType());
- document.put("sizeBytes", content.length);
document.put("sha256", sha256(content));
// The bytes themselves, for steps that carry the document inside a JSON body
// (an attachment field, a signing payload) rather than as multipart.
document.put("base64", Base64.getEncoder().encodeToString(content));
- if (looksLikePdf(content)) {
- addPdfFacts(document, root, content, objectMapper);
- }
-
ObjectNode run = root.putObject("run");
run.put("policyName", policyName);
run.put("runId", runId);
@@ -85,73 +66,6 @@ final class DocumentContext {
return root;
}
- /** PDF-only facts. A document we cannot parse still gets the basics above. */
- private static void addPdfFacts(
- ObjectNode document, ObjectNode root, byte[] content, ObjectMapper objectMapper) {
- try (PDDocument pdf = Loader.loadPDF(content)) {
- document.put("pageCount", pdf.getNumberOfPages());
- document.put("encrypted", pdf.isEncrypted());
-
- PDDocumentInformation info = pdf.getDocumentInformation();
- document.put("title", info.getTitle());
- document.put("author", info.getAuthor());
- document.put("subject", info.getSubject());
- document.put("keywords", info.getKeywords());
- document.put("creator", info.getCreator());
- document.put("producer", info.getProducer());
- document.put("created", toIso(info.getCreationDate()));
- document.put("modified", toIso(info.getModificationDate()));
-
- addClassification(root, info, objectMapper);
- addSensitivityLabel(root, pdf);
- } catch (IOException | RuntimeException e) {
- // An encrypted or malformed PDF is a normal thing to send to an external API; the
- // extra facts are a convenience, not a precondition.
- log.debug("Could not read PDF facts for the step context: {}", e.getMessage());
- }
- }
-
- /** The classifier policy's verdict, so a call-out can act on it without re-classifying. */
- private static void addClassification(
- ObjectNode root, PDDocumentInformation info, ObjectMapper objectMapper) {
- String raw = info.getCustomMetadataValue(PdfMetadataService.CLASSIFICATION_KEY);
- if (raw == null || raw.isBlank()) {
- return;
- }
- try {
- JsonNode parsed = objectMapper.readTree(raw);
- root.set("classification", parsed);
- } catch (RuntimeException e) {
- // Written by another tool; if it is not JSON, pass it through as text rather than drop
- // it - the receiving system may still recognise it.
- root.put("classification", raw);
- }
- }
-
- /** The Purview label already on the document, if any. */
- private static void addSensitivityLabel(ObjectNode root, PDDocument pdf) {
- List<SensitivityLabel> labels = PdfSensitivityLabels.readAll(pdf);
- if (labels.isEmpty()) {
- return;
- }
- SensitivityLabel label = labels.get(0);
- ObjectNode node = root.putObject("sensitivityLabel");
- node.put("labelId", label.labelId());
- node.put("name", label.name());
- node.put("siteId", label.siteId());
- node.put("method", label.method() == null ? null : label.method().name());
- node.put("protected", label.isProtected());
- }
-
- /** Cheap check so a non-PDF never pays for a parse attempt. */
- private static boolean looksLikePdf(byte[] content) {
- return content.length > 4
- && content[0] == '%'
- && content[1] == 'P'
- && content[2] == 'D'
- && content[3] == 'F';
- }
-
/**
* A content hash is the field external systems most often key on - dedupe, chain-of-custody,
* "have I already scanned this" - and they cannot compute it without the bytes we are sending.
@@ -163,18 +77,4 @@ final class DocumentContext {
throw new IllegalStateException("SHA-256 is required by the Java platform", e);
}
}
-
- private static String toIso(Calendar calendar) {
- return calendar == null ? null : calendar.toInstant().toString();
- }
-
- private static String extensionOf(String filename) {
- if (filename == null) {
- return null;
- }
- int dot = filename.lastIndexOf('.');
- return dot < 0 || dot == filename.length() - 1
- ? null
- : filename.substring(dot + 1).toLowerCase(Locale.ROOT);
- }
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
index 9d3cdb3506..083327af4a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
@@ -7,6 +7,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.stream.Stream;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
@@ -72,9 +73,11 @@ import stirling.software.proprietary.policy.model.PolicyPermissions;
import stirling.software.proprietary.policy.model.PolicyRun;
import stirling.software.proprietary.policy.model.PolicyRunStatus;
import stirling.software.proprietary.policy.model.PolicyRunView;
+import stirling.software.proprietary.policy.model.RoutingRule;
import stirling.software.proprietary.policy.overview.PoliciesOverviewResponse;
import stirling.software.proprietary.policy.overview.PolicyOverviewService;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
+import stirling.software.proprietary.policy.routing.ClassificationStepPlanner;
import stirling.software.proprietary.policy.source.EditorSource;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.source.SourceAccessGuard;
@@ -284,7 +287,9 @@ public class PolicyController {
+ " assigned; returns the stored policy with its id.")
public ResponseEntity<Policy> savePolicy(@RequestBody Policy policy) {
requirePolicyEditingAllowed();
- Policy owned = withStoredOutputSecrets(resolveOwnership(policy));
+ Policy owned =
+ ClassificationStepPlanner.ensureClassificationFirst(
+ withStoredOutputSecrets(resolveOwnership(policy)));
// Snapshot the previous version before saving so supporting files this edit dropped can
// be cleaned up once nothing references them.
Policy previous =
@@ -355,27 +360,34 @@ public class PolicyController {
"An editor policy delivers back to the editor and can't also have a"
+ " destination");
}
- for (String outputId : policy.outputIds()) {
- Source destination =
- sourceStore
- .get(outputId)
- .filter(sourceAccessGuard::canAccess)
- .orElseThrow(
- () ->
- new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "Unknown or inaccessible output source: "
- + outputId));
- if (EditorSource.TYPE.equals(destination.type())) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "The editor can't be used as an output destination");
- }
- try {
- policyValidator.validateOutput(destination.toOutputSpec());
- } catch (IllegalArgumentException e) {
- throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
- }
+ // A routing rule's destination is checked on exactly the same terms as a plain output: it
+ // must resolve, be accessible, and not be the editor.
+ Stream.concat(
+ policy.outputIds().stream(),
+ policy.routingRules().stream().map(RoutingRule::outputId))
+ .distinct()
+ .forEach(this::requireAccessibleDestination);
+ }
+
+ private void requireAccessibleDestination(String outputId) {
+ Source destination =
+ sourceStore
+ .get(outputId)
+ .filter(sourceAccessGuard::canAccess)
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.BAD_REQUEST,
+ "Unknown or inaccessible output source: "
+ + outputId));
+ if (EditorSource.TYPE.equals(destination.type())) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST, "The editor can't be used as an output destination");
+ }
+ try {
+ policyValidator.validateOutput(destination.toOutputSpec());
+ } catch (IllegalArgumentException e) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
}
@@ -430,7 +442,8 @@ public class PolicyController {
policy.outputIds(),
teamId,
policy.editor(),
- surface);
+ surface,
+ policy.routingRules());
}
/** Output secrets never leave the server: reads return the redaction sentinel instead. */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
index 6a0c038041..bb5a2646fd 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
@@ -3,7 +3,9 @@ package stirling.software.proprietary.policy.engine;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
+import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
@@ -33,6 +35,8 @@ import stirling.software.common.service.ResourceMonitor;
import stirling.software.common.service.TaskManager;
import stirling.software.common.util.ExecutorFactory;
import stirling.software.common.util.JobContext;
+import stirling.software.proprietary.document.DocumentFacts;
+import stirling.software.proprietary.document.conditions.ConditionEvaluator;
import stirling.software.proprietary.failure.DownstreamProblemDetail;
import stirling.software.proprietary.failure.FailureKind;
import stirling.software.proprietary.failure.PolicyFailureRecorder;
@@ -42,6 +46,7 @@ import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.model.PolicyRun;
+import stirling.software.proprietary.policy.model.RoutedDestination;
import stirling.software.proprietary.policy.model.WaitState;
import stirling.software.proprietary.policy.output.OutputDelivery;
import stirling.software.proprietary.policy.output.PolicyOutputResolver;
@@ -49,6 +54,10 @@ import stirling.software.proprietary.policy.output.PolicyOutputSink;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
import stirling.software.proprietary.service.DownstreamEntitlementError;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.json.JsonMapper;
+
/**
* Runs pipelines asynchronously as tracked jobs. {@link #submit} returns a run id immediately; the
* pipeline runs on a virtual thread (so a step blocked on a slow tool does not hold a platform
@@ -89,6 +98,9 @@ public class PolicyEngine {
private final ExecutorService asyncExecutor = ExecutorFactory.newVirtualThreadExecutor();
+ // Builds the per-document facts routing rules match against. Stateless, so a shared instance.
+ private static final ObjectMapper FACTS_MAPPER = JsonMapper.builder().build();
+
/** Stop the service-owned executor when the application context is closed or restarted. */
@PreDestroy
void shutdown() {
@@ -199,7 +211,10 @@ public class PolicyEngine {
resolved = assetResolver.resolve(policy, inputs);
definition =
new PipelineDefinition(
- policy.name(), policy.steps(), outputResolver.resolve(policy));
+ policy.name(),
+ policy.steps(),
+ outputResolver.resolve(policy),
+ outputResolver.resolveRouting(policy));
} catch (RuntimeException e) {
if (sourceId == null) {
throw e;
@@ -389,21 +404,7 @@ public class PolicyEngine {
taskManager.addNote(runId, "Cancelled before delivery; results discarded");
return;
}
- // Deliver the run's files to every destination; no destinations means inline
- // delivery (results stored/returned to the caller), preserving ad-hoc/AI behaviour.
- List<OutputSpec> destinations = run.getDefinition().outputs();
- if (destinations.isEmpty()) {
- destinations = List.of(OutputSpec.inline());
- }
- List<ResultFile> outputs = new ArrayList<>();
- for (OutputSpec destination : destinations) {
- outputs.addAll(
- sinkFor(destination)
- .deliver(
- new OutputDelivery(runId, run.getPolicyId(), inputs),
- result.files(),
- destination));
- }
+ List<ResultFile> outputs = deliver(run, runId, inputs, result.files());
taskManager.setMultipleFileResults(runId, outputs);
taskManager.setComplete(runId);
run.complete(outputs);
@@ -565,6 +566,66 @@ public class PolicyEngine {
};
}
+ /**
+ * Deliver a finished run's files. Without routing rules every file goes to every destination.
+ * With them, each file is matched against the rules in order and delivered to the first
+ * destination that claims it (a file no rule claims falls back to the run's outputs). Files are
+ * grouped by destination so a sink - which sets up a connection per call - is called once each.
+ */
+ private List<ResultFile> deliver(
+ PolicyRun run, String runId, PolicyInputs inputs, List<Resource> files)
+ throws IOException {
+ OutputDelivery delivery = new OutputDelivery(runId, run.getPolicyId(), inputs);
+ List<OutputSpec> fallback = run.getDefinition().outputs();
+ if (fallback.isEmpty()) {
+ // No destinations means inline delivery (results returned to the caller), preserving
+ // ad-hoc/AI behaviour.
+ fallback = List.of(OutputSpec.inline());
+ }
+ List<RoutedDestination> routing = run.getDefinition().routing();
+ if (routing.isEmpty()) {
+ return deliverGrouped(delivery, groupedToAll(files, fallback));
+ }
+ Map<OutputSpec, List<Resource>> byDestination = new LinkedHashMap<>();
+ for (Resource file : files) {
+ JsonNode facts = DocumentFacts.of(file, FACTS_MAPPER);
+ for (OutputSpec target : destinationsFor(routing, fallback, facts)) {
+ byDestination.computeIfAbsent(target, key -> new ArrayList<>()).add(file);
+ }
+ }
+ return deliverGrouped(delivery, byDestination);
+ }
+
+ private static List<OutputSpec> destinationsFor(
+ List<RoutedDestination> routing, List<OutputSpec> fallback, JsonNode facts) {
+ for (RoutedDestination routed : routing) {
+ if (ConditionEvaluator.matches(routed.rule().condition(), facts)) {
+ return List.of(routed.destination());
+ }
+ }
+ return fallback;
+ }
+
+ private static Map<OutputSpec, List<Resource>> groupedToAll(
+ List<Resource> files, List<OutputSpec> destinations) {
+ Map<OutputSpec, List<Resource>> byDestination = new LinkedHashMap<>();
+ for (OutputSpec destination : destinations) {
+ byDestination.put(destination, files);
+ }
+ return byDestination;
+ }
+
+ private List<ResultFile> deliverGrouped(
+ OutputDelivery delivery, Map<OutputSpec, List<Resource>> byDestination)
+ throws IOException {
+ List<ResultFile> outputs = new ArrayList<>();
+ for (Map.Entry<OutputSpec, List<Resource>> entry : byDestination.entrySet()) {
+ outputs.addAll(
+ sinkFor(entry.getKey()).deliver(delivery, entry.getValue(), entry.getKey()));
+ }
+ return outputs;
+ }
+
private PolicyOutputSink sinkFor(OutputSpec spec) {
return outputSinks.stream()
.filter(sink -> sink.supports(spec))
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
index 03b5dd94a9..36f84a06d3 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
@@ -75,10 +75,9 @@ public class PolicyExecutor {
public PolicyExecutionResult execute(
PipelineDefinition definition, PolicyInputs inputs, PolicyProgressListener listener)
throws IOException {
+ // Zero steps is a pure routing policy: inputs pass through unchanged and
+ // are delivered to the policy's output destinations.
List<PipelineStep> steps = definition.steps();
- if (steps.isEmpty()) {
- throw new IllegalArgumentException("Pipeline definition has no steps");
- }
List<PipelineFile> currentFiles = new ArrayList<>();
Map<String, List<Resource>> supportingFiles = inputs.supportingFiles();
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.java
index 1faa016c42..5b302e5987 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
@@ -11,6 +11,7 @@ import lombok.RequiredArgsConstructor;
import stirling.software.common.model.tool.ToolDiagnostic;
import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.service.ToolChainValidator;
+import stirling.software.proprietary.document.conditions.ConditionValidator;
import stirling.software.proprietary.policy.asset.PolicyAssetRefs;
import stirling.software.proprietary.policy.asset.PolicyAssetStore;
import stirling.software.proprietary.policy.input.InputSource;
@@ -19,6 +20,7 @@ import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineInput;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.model.RoutingRule;
import stirling.software.proprietary.policy.model.TriggerConfig;
import stirling.software.proprietary.policy.output.PolicyOutputSink;
import stirling.software.proprietary.policy.source.Source;
@@ -36,6 +38,8 @@ import stirling.software.proprietary.policy.trigger.PolicyTrigger;
@RequiredArgsConstructor
public class PolicyValidator {
+ private static final int MAX_ROUTING_RULES = 100;
+
private final List<PolicyTrigger> triggers;
private final List<InputSource> inputSources;
private final List<PolicyOutputSink> outputSinks;
@@ -73,12 +77,43 @@ public class PolicyValidator {
InputSpec spec = source.toInputSpec();
inputSourceFor(spec).validate(spec);
}
+ validateRoutingRules(policy);
validateSteps(policy.steps());
validateAssetReferences(policy);
validateChain(policy.steps());
validateOutput(policy.output());
}
+ /**
+ * A routing rule must name a field, an operator, a destination that resolves to a writable
+ * source, and something to compare against. A rule failing any of these would never fire,
+ * silently sending its documents to the fallback instead, so it is rejected at save time rather
+ * than left to look like it works.
+ */
+ private void validateRoutingRules(Policy policy) {
+ // A cap, like the one on inputs: rules are evaluated per document per run, so an
+ // unreasonable number is a cost multiplier rather than a configuration anyone wants.
+ if (policy.routingRules().size() > MAX_ROUTING_RULES) {
+ throw new IllegalArgumentException(
+ "a policy supports at most " + MAX_ROUTING_RULES + " routing rules");
+ }
+ for (RoutingRule rule : policy.routingRules()) {
+ ConditionValidator.validate(rule.condition());
+ if (rule.outputId() == null || rule.outputId().isBlank()) {
+ throw new IllegalArgumentException("a routing rule has no destination");
+ }
+ Source destination =
+ sourceStore
+ .get(rule.outputId())
+ .orElseThrow(
+ () ->
+ new IllegalArgumentException(
+ "unknown routing destination: "
+ + rule.outputId()));
+ validateOutput(destination.toOutputSpec());
+ }
+ }
+
/**
* A step binding that names stored assets ({@code asset:<id>}) must resolve in the policy's own
* team, so a saved pipeline can't fail its later (principal-less) runs on a missing file, and a
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PipelineDefinition.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PipelineDefinition.java
index 209756c67f..145d1cf0b2 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PipelineDefinition.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PipelineDefinition.java
@@ -8,11 +8,26 @@ import java.util.List;
* <p>{@code outputs} may be empty for callers that handle result files themselves (e.g. the AI
* workflow, which builds its own response payload) - the engine then falls back to inline delivery.
* A run's files are delivered to every destination in the list.
+ *
+ * <p>{@code routing} is per-document delivery: each entry pairs a rule with its resolved
+ * destination, tried in order, first match wins. When present, a file the rules claim goes to its
+ * matched destination; a file no rule claims falls back to {@code outputs}. Empty means every file
+ * goes to every {@code outputs} destination.
*/
-public record PipelineDefinition(String name, List<PipelineStep> steps, List<OutputSpec> outputs) {
+public record PipelineDefinition(
+ String name,
+ List<PipelineStep> steps,
+ List<OutputSpec> outputs,
+ List<RoutedDestination> routing) {
public PipelineDefinition {
steps = steps == null ? List.of() : steps;
outputs = outputs == null ? List.of() : List.copyOf(outputs);
+ routing = routing == null ? List.of() : List.copyOf(routing);
+ }
+
+ /** Without routing rules: every file goes to every destination. */
+ public PipelineDefinition(String name, List<PipelineStep> steps, List<OutputSpec> outputs) {
+ this(name, steps, outputs, List.of());
}
/** Convenience for the common single-destination (or inline) case. A null output is empty. */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java
index 44f20680cf..bddc5e9c2b 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java
@@ -2,6 +2,7 @@ package stirling.software.proprietary.policy.model;
import java.util.List;
import java.util.Optional;
+import java.util.stream.Stream;
/** A stored automation: ordered tool steps, input bindings, and output destinations. */
public record Policy(
@@ -18,7 +19,8 @@ public record Policy(
Long teamId,
EditorConfig editor,
/** The owning product surface; {@link #SURFACE_POLICY} unless stamped otherwise. */
- String surface) {
+ String surface,
+ List<RoutingRule> routingRules) {
public Policy {
icon = icon == null ? "" : icon;
@@ -28,6 +30,7 @@ public record Policy(
outputIds = outputIds == null ? List.of() : List.copyOf(outputIds);
editor = editor == null ? EditorConfig.disabled() : editor;
surface = surface == null || surface.isBlank() ? SURFACE_POLICY : surface;
+ routingRules = routingRules == null ? List.of() : List.copyOf(routingRules);
}
/** The record belongs to the org policies surface (the default). */
@@ -65,7 +68,8 @@ public record Policy(
outputIds,
teamId,
null,
- SURFACE_POLICY);
+ SURFACE_POLICY,
+ List.of());
}
/**
@@ -97,7 +101,8 @@ public record Policy(
outputIds,
teamId,
editor,
- SURFACE_POLICY);
+ SURFACE_POLICY,
+ List.of());
}
/**
@@ -158,15 +163,39 @@ public record Policy(
/** A copy with the inline output replaced (e.g. resolved for the engine, or migrated). */
public Policy withOutput(OutputSpec resolved) {
return new Policy(
- id, name, owner, enabled, required, icon, inputs, steps, resolved, outputIds,
- teamId, editor, surface);
+ id,
+ name,
+ owner,
+ enabled,
+ required,
+ icon,
+ inputs,
+ steps,
+ resolved,
+ outputIds,
+ teamId,
+ editor,
+ surface,
+ routingRules);
}
/** A copy under a different owner (e.g. moving a seed off a placeholder name). */
public Policy withOwner(String newOwner) {
return new Policy(
- id, name, newOwner, enabled, required, icon, inputs, steps, output, outputIds,
- teamId, editor, surface);
+ id,
+ name,
+ newOwner,
+ enabled,
+ required,
+ icon,
+ inputs,
+ steps,
+ output,
+ outputIds,
+ teamId,
+ editor,
+ surface,
+ routingRules);
}
/** A copy referencing the given saved output destinations. */
@@ -184,7 +213,8 @@ public record Policy(
newOutputIds,
teamId,
editor,
- surface);
+ surface,
+ routingRules);
}
public Policy withEnabled(boolean newEnabled) {
@@ -201,7 +231,37 @@ public record Policy(
outputIds,
teamId,
editor,
- surface);
+ surface,
+ routingRules);
+ }
+
+ public Policy withSteps(List<PipelineStep> newSteps) {
+ return new Policy(
+ id,
+ name,
+ owner,
+ enabled,
+ required,
+ icon,
+ inputs,
+ newSteps,
+ output,
+ outputIds,
+ teamId,
+ editor,
+ surface,
+ routingRules);
+ }
+
+ /**
+ * Every saved destination this policy can deliver to: the {@code outputIds} fallback plus each
+ * routing rule's destination. Used to resolve them all up front and to validate references.
+ */
+ public List<String> allOutputIds() {
+ return Stream.concat(outputIds.stream(), routingRules.stream().map(RoutingRule::outputId))
+ .filter(outputId -> outputId != null && !outputId.isBlank())
+ .distinct()
+ .toList();
}
public Policy withSurface(String newSurface) {
@@ -218,7 +278,8 @@ public record Policy(
outputIds,
teamId,
editor,
- newSurface);
+ newSurface,
+ routingRules);
}
/**
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/RoutedDestination.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/RoutedDestination.java
new file mode 100644
index 0000000000..6a1a37db4c
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/RoutedDestination.java
@@ -0,0 +1,10 @@
+package stirling.software.proprietary.policy.model;
+
+/**
+ * A routing rule with its destination already resolved, the form the engine delivers against.
+ *
+ * <p>Destinations resolve once when a run is submitted, like the run's fallback outputs, rather
+ * than per document: a run should not change where it delivers half way through because a source
+ * was edited underneath it.
+ */
+public record RoutedDestination(RoutingRule rule, OutputSpec destination) {}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/RoutingRule.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/RoutingRule.java
new file mode 100644
index 0000000000..2af5f1f9f5
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/RoutingRule.java
@@ -0,0 +1,42 @@
+package stirling.software.proprietary.policy.model;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import stirling.software.proprietary.document.conditions.Condition;
+import stirling.software.proprietary.document.conditions.ConditionInput;
+
+/**
+ * Delivers a document satisfying {@code condition} to the source referenced by {@code outputId}.
+ *
+ * <p>Rules are evaluated in order and the first match wins, so a policy reads top-to-bottom like
+ * the mail rules it stands in for. A document matching no rule falls back to the policy's {@code
+ * outputIds}, and a policy with neither keeps its inline output.
+ */
+public record RoutingRule(Condition condition, String outputId) {
+
+ /**
+ * Reads both the nested condition and legacy flat rules from stored policies or API callers.
+ * Serialization emits only the nested shape; an explicit condition takes precedence.
+ */
+ @JsonCreator
+ public static RoutingRule fromJson(
+ @JsonProperty("condition") Condition condition,
+ @JsonProperty("outputId") String outputId,
+ @JsonProperty("field") String field,
+ @JsonProperty("operator") String operator,
+ @JsonProperty("values") List<String> values) {
+ if (condition != null) {
+ return new RoutingRule(condition, outputId);
+ }
+ if (!"matches-any".equals(operator)) {
+ throw new IllegalArgumentException(
+ "Unknown or missing condition operator: " + operator);
+ }
+ return new RoutingRule(
+ new Condition.MatchesAny(new ConditionInput.DocumentField(field), values),
+ outputId);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java
index 3b5f737f6c..0524723edb 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java
@@ -8,6 +8,7 @@ import lombok.RequiredArgsConstructor;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.model.RoutedDestination;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.source.SourceStore;
@@ -26,18 +27,25 @@ public class PolicyOutputResolver {
if (outputIds.isEmpty()) {
return List.of(policy.output());
}
- return outputIds.stream()
- .map(
- id ->
- sourceStore
- .get(id)
- .filter(Source::enabled)
- .filter(source -> !"editor".equals(source.type()))
- .orElseThrow(
- () ->
- new IllegalArgumentException(
- "The output destination is missing, disabled, or unavailable"))
- .toOutputSpec())
+ return outputIds.stream().map(this::resolveDestination).toList();
+ }
+
+ /** Resolve each routing rule's destination live; rule order is preserved. */
+ public List<RoutedDestination> resolveRouting(Policy policy) {
+ return policy.routingRules().stream()
+ .map(rule -> new RoutedDestination(rule, resolveDestination(rule.outputId())))
.toList();
}
+
+ private OutputSpec resolveDestination(String id) {
+ return sourceStore
+ .get(id)
+ .filter(Source::enabled)
+ .filter(source -> !"editor".equals(source.type()))
+ .orElseThrow(
+ () ->
+ new IllegalArgumentException(
+ "The output destination is missing, disabled, or unavailable"))
+ .toOutputSpec();
+ }
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/routing/ClassificationStepPlanner.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/routing/ClassificationStepPlanner.java
new file mode 100644
index 0000000000..e14be67823
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/routing/ClassificationStepPlanner.java
@@ -0,0 +1,93 @@
+package stirling.software.proprietary.policy.routing;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import stirling.software.proprietary.classification.ClassificationConditions;
+import stirling.software.proprietary.policy.model.PipelineStep;
+import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.model.RoutingRule;
+
+/**
+ * Guarantees that a policy routing on the classifier's verdict actually has one to route on.
+ *
+ * <p>Routing rules read facts off the document, and the classification facts are only there because
+ * a classify step wrote them. That holds for a document uploaded through the editor, where the
+ * seeded Classification policy runs first - but not for one pulled from a folder, bucket or
+ * webhook, which no classification policy watches. Rather than leave that as an ordering the user
+ * has to know about, a policy that routes on classification gets the classify step prepended to its
+ * own pipeline at save time, so the ordering is a property of the policy rather than of the
+ * deployment.
+ *
+ * <p>The step is added to the saved policy, not slipped in at run time: it shows in the pipeline
+ * the user sees, and a run's history shows it ran.
+ *
+ * <p>It classifies unconditionally, and deliberately does not trust a verdict already on the
+ * document. The classification key is ordinary PDF metadata that whoever supplied the document can
+ * write, and the documents a routing policy reads come from a folder, bucket or webhook - that is,
+ * from outside the team. Honouring an inbound verdict would let the submitter pick their own
+ * destination, so the step overwrites it with a server-produced one.
+ */
+public final class ClassificationStepPlanner {
+
+ public static final String CLASSIFY_ENDPOINT = "/api/v1/ai/tools/classify-and-label";
+
+ /**
+ * Forces a fresh server-side verdict. Without it the tool passes a document through whenever
+ * one is already on it, and that field is metadata the submitter can write, so a routing
+ * decision would be theirs to make.
+ */
+ static final Map<String, Object> RECLASSIFY = Map.of("reclassify", true);
+
+ private ClassificationStepPlanner() {}
+
+ /**
+ * The policy with classification guaranteed to have run before its rules are evaluated. A
+ * policy that routes on nothing classification-related is returned untouched; one that already
+ * classifies somewhere in its pipeline keeps that step where the user put it, with {@link
+ * #RECLASSIFY} forced on it so the verdict the rules read is still a server-produced one.
+ */
+ public static Policy ensureClassificationFirst(Policy policy) {
+ boolean routesOnClassification =
+ policy.routingRules().stream()
+ .map(RoutingRule::condition)
+ .anyMatch(ClassificationConditions::requiresClassification);
+ if (!routesOnClassification) {
+ return policy;
+ }
+ if (classifies(policy.steps())) {
+ return forceReclassification(policy);
+ }
+ List<PipelineStep> steps = new ArrayList<>();
+ steps.add(new PipelineStep(CLASSIFY_ENDPOINT, RECLASSIFY));
+ steps.addAll(policy.steps());
+ return policy.withSteps(steps);
+ }
+
+ private static Policy forceReclassification(Policy policy) {
+ List<PipelineStep> steps = new ArrayList<>();
+ boolean rewritten = false;
+ for (PipelineStep step : policy.steps()) {
+ if (!CLASSIFY_ENDPOINT.equals(step.operation()) || reclassifies(step)) {
+ steps.add(step);
+ continue;
+ }
+ Map<String, Object> parameters = new LinkedHashMap<>(step.parameters());
+ parameters.putAll(RECLASSIFY);
+ steps.add(new PipelineStep(step.operation(), parameters, step.fileParameters()));
+ rewritten = true;
+ }
+ return rewritten ? policy.withSteps(steps) : policy;
+ }
+
+ private static boolean reclassifies(PipelineStep step) {
+ Object value = step.parameters().get("reclassify");
+ return value != null && Boolean.parseBoolean(String.valueOf(value));
+ }
+
+ private static boolean classifies(List<PipelineStep> steps) {
+ return steps.stream().anyMatch(step -> CLASSIFY_ENDPOINT.equals(step.operation()));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java
index 8a034b6179..f22bbd162f 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java
@@ -119,6 +119,7 @@ public class DefaultClassificationPolicySeeder {
teamId,
// Classification runs in the editor on every upload.
EditorConfig.onUpload(),
- Policy.SURFACE_POLICY);
+ Policy.SURFACE_POLICY,
+ List.of());
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceController.java
index 73622738f0..7097d60cbd 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceController.java
@@ -309,15 +309,18 @@ public class SourceController {
/**
* Names of the caller's visible policies that reference the given source - as an input ({@code
- * sourceIds}) or as their output destination ({@code outputId}), so a location in use either
- * way is protected from deletion.
+ * sourceIds}) or as any destination it can deliver to ({@link Policy#allOutputIds()}: the
+ * fallback output and every routing rule's destination), so a location in use any of those ways
+ * is protected from deletion. A routing destination has to be covered here: dropping it would
+ * leave the rule unresolvable at run time, and the documents it claimed would go to the
+ * fallback destination instead.
*/
private List<String> referencingPolicyNames(String sourceId) {
return policyAccessGuard.visibleFrom(policyStore).stream()
.filter(
policy ->
policy.sourceIds().contains(sourceId)
- || policy.outputIds().contains(sourceId))
+ || policy.allOutputIds().contains(sourceId))
.map(Policy::name)
.toList();
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceOverviewService.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceOverviewService.java
index 753c350514..537a0676e5 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceOverviewService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceOverviewService.java
@@ -126,14 +126,15 @@ public class SourceOverviewService {
/**
* Policies referencing each source id, across the caller's visible policies. A source counts
- * whether a policy reads from it ({@code sourceIds}) or writes to it ({@code outputId}); a
- * policy that does both counts once.
+ * whether a policy reads from it ({@code sourceIds}) or writes to it ({@link
+ * Policy#allOutputIds()}, which covers a routing rule's destination as well as the fallback
+ * output); a policy that does both counts once.
*/
private static Map<String, List<Policy>> referencesBySource(List<Policy> policies) {
Map<String, List<Policy>> bySource = new HashMap<>();
for (Policy policy : policies) {
Set<String> referenced = new LinkedHashSet<>(policy.sourceIds());
- referenced.addAll(policy.outputIds());
+ referenced.addAll(policy.allOutputIds());
for (String sourceId : referenced) {
bySource.computeIfAbsent(sourceId, key -> new ArrayList<>()).add(policy);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/InProcessPolicyStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/InProcessPolicyStore.java
index 1d1107aca2..6d7244d00f 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/InProcessPolicyStore.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/InProcessPolicyStore.java
@@ -42,7 +42,8 @@ public class InProcessPolicyStore implements PolicyStore {
policy.outputIds(),
policy.teamId(),
policy.editor(),
- policy.surface());
+ policy.surface(),
+ policy.routingRules());
policies.put(id, stored);
// Existing policy keeps its position; a new one appends to the end of its team's queue.
sortOrders.computeIfAbsent(id, key -> nextSortOrder(stored.teamId()));
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/JpaPolicyStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/JpaPolicyStore.java
index fbf7947115..5d8e931f21 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/JpaPolicyStore.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/JpaPolicyStore.java
@@ -56,7 +56,8 @@ public class JpaPolicyStore implements PolicyStore {
policy.outputIds(),
policy.teamId(),
policy.editor(),
- policy.surface());
+ policy.surface(),
+ policy.routingRules());
PolicyEntity entity = new PolicyEntity();
entity.setId(id);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/document/conditions/ConditionEvaluatorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/document/conditions/ConditionEvaluatorTest.java
new file mode 100644
index 0000000000..7cc0489fd5
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/document/conditions/ConditionEvaluatorTest.java
@@ -0,0 +1,112 @@
+package stirling.software.proprietary.document.conditions;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+/** Tests for {@link ConditionEvaluator}: which rule claims a document, and which does not. */
+class ConditionEvaluatorTest {
+
+ private static final String LABELS = "classification.labels";
+
+ private final JsonMapper mapper = JsonMapper.builder().build();
+
+ private JsonNode facts(String json) {
+ return mapper.readTree(json);
+ }
+
+ private static Condition condition(String field, String... values) {
+ return new Condition.MatchesAny(new ConditionInput.DocumentField(field), List.of(values));
+ }
+
+ @Test
+ void comparesDocumentPropertiesWithoutClassificationOrADestination() {
+ JsonNode document =
+ facts(
+ """
+ {"document": {"extension": "DOCX", "pageCount": 12}}
+ """);
+
+ assertThat(
+ ConditionEvaluator.matches(
+ condition("document.extension", "pdf", " docx "), document))
+ .isTrue();
+ assertThat(ConditionEvaluator.matches(condition("document.pageCount", "12"), document))
+ .isTrue();
+ }
+
+ @Test
+ void missingNullAndBlankValuesDoNotMatch() {
+ for (String json : List.of("{}", "{\"x\":null}", "{\"x\":\" \"}", "{\"x\":[]}")) {
+ assertThat(ConditionEvaluator.matches(condition("x", "invoice"), facts(json)))
+ .isFalse();
+ }
+ }
+
+ @Test
+ void rejectsIncompleteComparisonsInsteadOfTreatingThemAsNonMatches() {
+ assertThatThrownBy(() -> ConditionEvaluator.matches(null, facts("{}")))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ ConditionValidator.validate(
+ new Condition.MatchesAny(null, List.of("invoice"))))
+ .hasMessageContaining("input");
+ assertThatThrownBy(() -> ConditionValidator.validate(condition(" ", "invoice")))
+ .hasMessageContaining("field");
+ assertThatThrownBy(
+ () -> ConditionValidator.validate(condition("classification.labels", " ")))
+ .hasMessageContaining("nothing to match");
+ }
+
+ @Test
+ void matchesWhenTheVerdictCarriesOneOfTheRulesLabels() {
+ JsonNode facts = facts("{\"classification\":{\"labels\":[\"invoice\",\"receipt\"]}}");
+
+ assertThat(ConditionEvaluator.matches(condition(LABELS, "invoice"), facts)).isTrue();
+ assertThat(ConditionEvaluator.matches(condition(LABELS, "contract"), facts)).isFalse();
+ }
+
+ @Test
+ void comparesLabelsIgnoringCaseAndSurroundingSpace() {
+ JsonNode facts = facts("{\"classification\":{\"labels\":[\"purchase-order\"]}}");
+
+ assertThat(ConditionEvaluator.matches(condition(LABELS, " Purchase-Order "), facts))
+ .isTrue();
+ }
+
+ @Test
+ void readsAScalarFactAsASingleValue() {
+ JsonNode facts = facts("{\"classification\":{\"label\":\"invoice\"}}");
+ assertThat(ConditionEvaluator.matches(condition("classification.label", "invoice"), facts))
+ .isTrue();
+ }
+
+ @Test
+ void aDocumentNobodyClassifiedIsClaimedByNoRule() {
+ JsonNode unclassified = facts("{\"document\":{\"filename\":\"a.pdf\"}}");
+
+ assertThat(ConditionEvaluator.matches(condition(LABELS, "invoice"), unclassified))
+ .isFalse();
+ }
+
+ @Test
+ void anEmptyLabelArrayCountsAsNoVerdictRatherThanAnEmptyOne() {
+ JsonNode facts = facts("{\"classification\":{\"labels\":[]}}");
+
+ assertThat(ConditionEvaluator.matches(condition(LABELS, "invoice"), facts)).isFalse();
+ }
+
+ @Test
+ void aFieldWhosePathRunsThroughAMissingObjectSimplyHasNoValue() {
+ JsonNode facts = facts("{\"document\":{\"filename\":\"a.pdf\"}}");
+ assertThat(ConditionEvaluator.matches(condition("sensitivityLabel.name", "Secret"), facts))
+ .isFalse();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
index e99b51e65c..e4b52e5a6c 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
@@ -531,7 +531,8 @@ class PolicyControllerTest {
List.of(),
null,
null,
- Policy.SURFACE_POLICY);
+ Policy.SURFACE_POLICY,
+ List.of());
assertThatThrownBy(() -> controller.savePolicy(withUnknownSource))
.isInstanceOf(ResponseStatusException.class)
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java
new file mode 100644
index 0000000000..6a89e37c01
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java
@@ -0,0 +1,252 @@
+package stirling.software.proprietary.policy.engine;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+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.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.core.io.ByteArrayResource;
+import org.springframework.core.io.Resource;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.model.job.ResultFile;
+import stirling.software.common.service.FileStorage;
+import stirling.software.common.service.InternalApiClient;
+import stirling.software.common.service.JobOwnershipService;
+import stirling.software.common.service.JobQueue;
+import stirling.software.common.service.PdfMetadataService;
+import stirling.software.common.service.ResourceMonitor;
+import stirling.software.common.service.TaskManager;
+import stirling.software.common.service.ToolMetadataService;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.TempFileRegistry;
+import stirling.software.proprietary.document.conditions.Condition;
+import stirling.software.proprietary.document.conditions.ConditionInput;
+import stirling.software.proprietary.failure.PolicyFailureRecorder;
+import stirling.software.proprietary.policy.asset.InProcessPolicyAssetStore;
+import stirling.software.proprietary.policy.asset.PolicyAssetResolver;
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.model.PipelineDefinition;
+import stirling.software.proprietary.policy.model.PolicyInputs;
+import stirling.software.proprietary.policy.model.PolicyRun;
+import stirling.software.proprietary.policy.model.PolicyRunStatus;
+import stirling.software.proprietary.policy.model.RoutedDestination;
+import stirling.software.proprietary.policy.model.RoutingRule;
+import stirling.software.proprietary.policy.output.InlineOutputSink;
+import stirling.software.proprietary.policy.output.OutputDelivery;
+import stirling.software.proprietary.policy.output.PolicyOutputResolver;
+import stirling.software.proprietary.policy.output.PolicyOutputSink;
+import stirling.software.proprietary.policy.progress.PolicyProgressListener;
+import stirling.software.proprietary.policy.source.InProcessSourceStore;
+
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * End-to-end cover for the routing delivery path in {@link PolicyEngine}: a document goes to the
+ * destination its first matching rule names, and one no rule claims goes to the fallback.
+ */
+@ExtendWith(MockitoExtension.class)
+class PolicyEngineRoutingTest {
+
+ @Mock private InternalApiClient internalApiClient;
+ @Mock private ToolMetadataService toolMetadataService;
+ @Mock private TaskManager taskManager;
+ @Mock private FileStorage fileStorage;
+ @Mock private JobOwnershipService jobOwnershipService;
+ @Mock private ResourceMonitor resourceMonitor;
+ @Mock private JobQueue jobQueue;
+ @Mock private PolicyFailureRecorder failureRecorder;
+
+ @TempDir Path tempDir;
+
+ private final RecordingSink sink = new RecordingSink();
+ private PolicyEngine engine;
+
+ @BeforeEach
+ void setUp() {
+ ApplicationProperties props = new ApplicationProperties();
+ props.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
+ props.getSystem().getTempFileManagement().setPrefix("routing-test-");
+ PolicyExecutor executor =
+ new PolicyExecutor(
+ internalApiClient,
+ toolMetadataService,
+ new TempFileManager(new TempFileRegistry(), props),
+ JsonMapper.builder().build());
+ engine =
+ new PolicyEngine(
+ executor,
+ taskManager,
+ new PolicyRunRegistry(props),
+ failureRecorder,
+ fileStorage,
+ jobOwnershipService,
+ List.of(new InlineOutputSink(fileStorage), sink),
+ new PolicyOutputResolver(new InProcessSourceStore()),
+ resourceMonitor,
+ jobQueue,
+ new PolicyAssetResolver(new InProcessPolicyAssetStore()));
+ when(jobOwnershipService.createScopedJobKey(anyString()))
+ .thenAnswer(inv -> inv.getArgument(0));
+ }
+
+ @Test
+ void routesEachDocumentToItsFirstMatchingRuleAndTheRestToTheFallback() throws Exception {
+ Resource invoice = classifiedPdf("invoice.pdf", "invoice", "contract");
+ Resource contract = classifiedPdf("contract.pdf", "contract");
+ Resource unlabelled = classifiedPdf("misc.pdf");
+
+ PipelineDefinition definition =
+ new PipelineDefinition(
+ "routing",
+ List.of(),
+ List.of(new OutputSpec("record", java.util.Map.of("dest", "fallback"))),
+ List.of(routed("invoice", "finance"), routed("contract", "legal")));
+
+ PolicyRun run =
+ engine.submit(
+ definition,
+ PolicyInputs.of(List.of(invoice, contract, unlabelled)),
+ PolicyProgressListener.NOOP)
+ .completion()
+ .get(20, TimeUnit.SECONDS);
+
+ assertThat(run.getStatus()).isEqualTo(PolicyRunStatus.COMPLETED);
+ assertThat(sink.deliveries())
+ .containsExactlyInAnyOrder(
+ "finance:invoice.pdf", "legal:contract.pdf", "fallback:misc.pdf");
+ }
+
+ @Test
+ void noConditionsStillDeliversEveryFileToEveryDestination() throws Exception {
+ Resource invoice = classifiedPdf("invoice.pdf", "invoice");
+ Resource unlabelled = classifiedPdf("misc.pdf");
+ PipelineDefinition definition =
+ new PipelineDefinition(
+ "copy",
+ List.of(),
+ List.of(
+ new OutputSpec("record", java.util.Map.of("dest", "first")),
+ new OutputSpec("record", java.util.Map.of("dest", "second"))));
+
+ PolicyRun run =
+ engine.submit(
+ definition,
+ PolicyInputs.of(List.of(invoice, unlabelled)),
+ PolicyProgressListener.NOOP)
+ .completion()
+ .get(20, TimeUnit.SECONDS);
+
+ assertThat(run.getStatus()).isEqualTo(PolicyRunStatus.COMPLETED);
+ assertThat(sink.deliveries())
+ .containsExactlyInAnyOrder(
+ "first:invoice.pdf",
+ "first:misc.pdf",
+ "second:invoice.pdf",
+ "second:misc.pdf");
+ }
+
+ @Test
+ void aNonPdfOutputCannotBeRoutedAndFallsBack() throws Exception {
+ Resource docx =
+ new ByteArrayResource("PK\u0003\u0004not-a-pdf".getBytes()) {
+ @Override
+ public String getFilename() {
+ return "invoice.docx";
+ }
+ };
+
+ PipelineDefinition definition =
+ new PipelineDefinition(
+ "routing",
+ List.of(),
+ List.of(new OutputSpec("record", java.util.Map.of("dest", "fallback"))),
+ List.of(routed("invoice", "finance")));
+
+ PolicyRun run =
+ engine.submit(
+ definition,
+ PolicyInputs.of(List.of(docx)),
+ PolicyProgressListener.NOOP)
+ .completion()
+ .get(20, TimeUnit.SECONDS);
+
+ assertThat(run.getStatus()).isEqualTo(PolicyRunStatus.COMPLETED);
+ assertThat(sink.deliveries()).containsExactly("fallback:invoice.docx");
+ }
+
+ private static RoutedDestination routed(String label, String dest) {
+ return new RoutedDestination(
+ new RoutingRule(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("classification.labels"),
+ List.of(label)),
+ dest),
+ new OutputSpec("record", java.util.Map.of("dest", dest)));
+ }
+
+ /** A real one-page PDF, optionally carrying the classifier's verdict in its metadata. */
+ private static Resource classifiedPdf(String filename, String... labels) throws IOException {
+ try (PDDocument doc = new PDDocument()) {
+ doc.addPage(new PDPage());
+ if (labels.length > 0) {
+ String json = "{\"labels\":[\"" + String.join("\",\"", labels) + "\"]}";
+ doc.getDocumentInformation()
+ .setCustomMetadataValue(PdfMetadataService.CLASSIFICATION_KEY, json);
+ }
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ doc.save(out);
+ return new ByteArrayResource(out.toByteArray()) {
+ @Override
+ public String getFilename() {
+ return filename;
+ }
+ };
+ }
+ }
+
+ /** Records "{dest}:{filename}" per delivered file. */
+ private static final class RecordingSink implements PolicyOutputSink {
+ private final List<String> deliveries = new ArrayList<>();
+
+ List<String> deliveries() {
+ return deliveries;
+ }
+
+ @Override
+ public String type() {
+ return "record";
+ }
+
+ @Override
+ public boolean supports(OutputSpec spec) {
+ return "record".equals(spec.type());
+ }
+
+ @Override
+ public List<ResultFile> deliver(
+ OutputDelivery delivery, List<Resource> outputs, OutputSpec spec) {
+ String dest = String.valueOf(spec.options().get("dest"));
+ List<ResultFile> results = new ArrayList<>();
+ for (Resource output : outputs) {
+ deliveries.add(dest + ":" + output.getFilename());
+ results.add(new ResultFile(dest, output.getFilename(), "application/pdf", 0L));
+ }
+ return results;
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java
index d31183337f..d87ad44eef 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java
@@ -364,14 +364,18 @@ class PolicyExecutorTest {
}
@Test
- void emptyPipelineIsRejected() {
- assertThrows(
- IllegalArgumentException.class,
- () ->
- executor.execute(
- new PipelineDefinition("empty", List.of(), OutputSpec.inline()),
- PolicyInputs.of(List.of(pdf("in", "in.pdf"))),
- PolicyProgressListener.NOOP));
+ void emptyStepsPassInputsThroughUnchanged() throws Exception {
+ // A pure routing policy has no steps: inputs are delivered to the
+ // destinations untouched, so execute returns them as-is.
+ Resource input = pdf("in", "in.pdf");
+ PolicyExecutionResult result =
+ executor.execute(
+ new PipelineDefinition("empty", List.of(), OutputSpec.inline()),
+ PolicyInputs.of(List.of(input)),
+ PolicyProgressListener.NOOP);
+
+ assertEquals(1, result.files().size());
+ assertEquals("in.pdf", result.files().get(0).getFilename());
}
// --- helpers ---
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.java
index 2928dd3b65..b14c51dca8 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
@@ -23,6 +23,8 @@ import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.model.tool.ToolIOSource;
import stirling.software.common.model.tool.ToolIOSpec;
import stirling.software.common.service.ToolChainValidator;
+import stirling.software.proprietary.document.conditions.Condition;
+import stirling.software.proprietary.document.conditions.ConditionInput;
import stirling.software.proprietary.policy.asset.InProcessPolicyAssetStore;
import stirling.software.proprietary.policy.asset.PolicyAsset;
import stirling.software.proprietary.policy.asset.PolicyAssetRefs;
@@ -33,6 +35,7 @@ import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineInput;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.model.RoutingRule;
import stirling.software.proprietary.policy.model.TriggerConfig;
import stirling.software.proprietary.policy.output.PolicyOutputSink;
import stirling.software.proprietary.policy.source.InProcessSourceStore;
@@ -322,6 +325,89 @@ class PolicyValidatorTest {
assertTrue(ex.getMessage().contains("at most one output"));
}
+ // A routing rule that can never fire is worse than no rule: its documents go to the fallback
+ // destination while the policy still reads as if it routed them, so each way of writing one is
+ // rejected at save time.
+
+ @Test
+ void acceptsARoutingRuleWhoseDestinationResolves() {
+ when(outputSink.supports(any())).thenReturn(true);
+ String destinationId = folderSourceId();
+
+ validator.validate(routingPolicy(rule("classification.labels", "invoice", destinationId)));
+
+ verify(outputSink).validate(sourceStore.get(destinationId).orElseThrow().toOutputSpec());
+ }
+
+ @Test
+ void rejectsARoutingRuleWithNoField() {
+ Policy policy = routingPolicy(rule(" ", "invoice", folderSourceId()));
+
+ IllegalArgumentException ex =
+ assertThrows(IllegalArgumentException.class, () -> validator.validate(policy));
+ assertTrue(ex.getMessage().contains("must name a field"), ex.getMessage());
+ }
+
+ @Test
+ void rejectsARoutingRuleWithNoCondition() {
+ Policy policy = routingPolicy(new RoutingRule(null, "dest"));
+
+ IllegalArgumentException ex =
+ assertThrows(IllegalArgumentException.class, () -> validator.validate(policy));
+ assertTrue(ex.getMessage().contains("a condition is required"), ex.getMessage());
+ }
+
+ @Test
+ void rejectsARoutingRuleWithNothingToMatchAgainst() {
+ Policy policy = routingPolicy(rule("classification.labels", " ", folderSourceId()));
+
+ IllegalArgumentException ex =
+ assertThrows(IllegalArgumentException.class, () -> validator.validate(policy));
+ assertTrue(ex.getMessage().contains("nothing to match against"), ex.getMessage());
+ }
+
+ @Test
+ void rejectsARoutingRuleWithNoDestination() {
+ Policy policy = routingPolicy(rule("classification.labels", "invoice", ""));
+
+ IllegalArgumentException ex =
+ assertThrows(IllegalArgumentException.class, () -> validator.validate(policy));
+ assertTrue(ex.getMessage().contains("no destination"), ex.getMessage());
+ }
+
+ @Test
+ void rejectsARoutingRuleWhoseDestinationIsNotAStoredSource() {
+ Policy policy = routingPolicy(rule("classification.labels", "invoice", "src-deleted"));
+
+ IllegalArgumentException ex =
+ assertThrows(IllegalArgumentException.class, () -> validator.validate(policy));
+ assertTrue(ex.getMessage().contains("unknown routing destination"), ex.getMessage());
+ }
+
+ private static RoutingRule rule(String field, String value, String destinationId) {
+ return new RoutingRule(
+ new Condition.MatchesAny(new ConditionInput.DocumentField(field), List.of(value)),
+ destinationId);
+ }
+
+ private static Policy routingPolicy(RoutingRule... rules) {
+ return new Policy(
+ "p1",
+ "p",
+ "owner",
+ true,
+ false,
+ "",
+ List.of(),
+ List.of(),
+ OutputSpec.inline(),
+ List.of(),
+ null,
+ null,
+ null,
+ List.of(rules));
+ }
+
@Test
void allowsZeroInputsAndZeroOutputs() {
when(outputSink.supports(any())).thenReturn(true);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PortalWirePolicyContractTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PortalWirePolicyContractTest.java
new file mode 100644
index 0000000000..a691a39b3d
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PortalWirePolicyContractTest.java
@@ -0,0 +1,84 @@
+package stirling.software.proprietary.policy.model;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import stirling.software.proprietary.document.conditions.Condition;
+
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * The portal's policy codec (frontend {@code policies/codec.ts}) posts this body to {@code POST
+ * /api/v1/policies}. Both sides pin the same fixture, so a frontend shape change that this record
+ * would silently drop - unknown properties are ignored, which is how {@code sourceIds} + a
+ * top-level {@code trigger} once saved a policy with no source and no trigger at all - fails here
+ * instead of shipping as a no-op.
+ */
+class PortalWirePolicyContractTest {
+
+ private static final String FIXTURE = "/policy/portal-wire-policy.json";
+
+ private final ObjectMapper objectMapper = JsonMapper.builder().build();
+
+ @Test
+ void bindsThePortalBodyToAPolicyWithItsSourceTriggerAndDestination() {
+ Policy policy = objectMapper.readValue(fixture(), Policy.class);
+
+ assertThat(policy.id()).isEqualTo("pol_routing");
+ assertThat(policy.name()).isEqualTo("Routing Policy");
+ assertThat(policy.enabled()).isTrue();
+ // The binding the feature depends on: a real source, pulled by a real trigger.
+ assertThat(policy.sourceIds()).containsExactly("src-dropbox");
+ assertThat(policy.triggerTypes()).containsExactly("schedule");
+ assertThat(policy.inputs().get(0).trigger().options()).containsKey("schedule");
+ assertThat(policy.outputIds()).containsExactly("src-archive");
+ assertThat(policy.routingRules()).hasSize(1);
+ assertThat(policy.routingRules().getFirst().outputId()).isEqualTo("src-finance");
+ assertThat(policy.routingRules().getFirst().condition())
+ .isEqualTo(
+ new Condition.MatchesAny(
+ new stirling.software.proprietary.document.conditions.ConditionInput
+ .DocumentField("classification.labels"),
+ List.of("invoice", "receipt")));
+ assertThat(policy.steps()).hasSize(1);
+ assertThat(policy.steps().get(0).operation()).isEqualTo("/api/v1/misc/compress-pdf");
+ assertThat(policy.steps().get(0).parameters()).containsEntry("optimizeLevel", 5);
+ assertThat(policy.output().type()).isEqualTo("inline");
+ assertThat(policy.output().options()).containsEntry("categoryId", "routing");
+ }
+
+ @Test
+ void carriesScheduleOptionsTheScheduleTriggerCanParse() {
+ Policy policy = objectMapper.readValue(fixture(), Policy.class);
+
+ Object options = policy.inputs().get(0).trigger().options().get("schedule");
+
+ assertThat(objectMapper.convertValue(options, Schedule.class))
+ .isEqualTo(new Schedule.Every(1, Schedule.Unit.HOURS));
+ }
+
+ @Test
+ void serialisesBackToTheSameShapeTheFrontendDecodes() {
+ Policy policy = objectMapper.readValue(fixture(), Policy.class);
+
+ Policy reread =
+ objectMapper.readValue(objectMapper.writeValueAsString(policy), Policy.class);
+
+ assertThat(reread).isEqualTo(policy);
+ }
+
+ private String fixture() {
+ try (InputStream in = getClass().getResourceAsStream(FIXTURE)) {
+ assertThat(in).as("fixture %s", FIXTURE).isNotNull();
+ return new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ } catch (Exception e) {
+ throw new IllegalStateException("cannot read " + FIXTURE, e);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/RoutingRuleTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/RoutingRuleTest.java
new file mode 100644
index 0000000000..4e07e7eb89
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/RoutingRuleTest.java
@@ -0,0 +1,118 @@
+package stirling.software.proprietary.policy.model;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import stirling.software.proprietary.document.conditions.Condition;
+import stirling.software.proprietary.document.conditions.ConditionInput;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+class RoutingRuleTest {
+
+ private final JsonMapper mapper = JsonMapper.builder().build();
+
+ @Test
+ void upgradesLegacyRulesInsideAStoredPolicyAndWritesOnlyNestedConditions() {
+ Policy policy =
+ mapper.readValue(
+ """
+ {
+ "id": "p1", "name": "Route", "enabled": true, "required": false,
+ "routingRules": [
+ {"field": "classification.labels", "operator": "matches-any",
+ "values": [" Invoice ", "receipt"], "outputId": "finance"},
+ {"field": "document.extension", "operator": "matches-any",
+ "values": ["docx"], "outputId": "office"}
+ ],
+ "outputIds": ["archive"]
+ }
+ """,
+ Policy.class);
+
+ assertThat(policy.routingRules())
+ .containsExactly(
+ new RoutingRule(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("classification.labels"),
+ List.of(" Invoice ", "receipt")),
+ "finance"),
+ new RoutingRule(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("document.extension"),
+ List.of("docx")),
+ "office"));
+ assertThat(policy.outputIds()).containsExactly("archive");
+
+ String saved = mapper.writeValueAsString(policy);
+ JsonNode rule = mapper.readTree(saved).path("routingRules").get(0);
+ assertThat(rule.has("field")).isFalse();
+ assertThat(rule.has("operator")).isFalse();
+ assertThat(rule.has("values")).isFalse();
+ assertThat(rule.path("condition").path("operator").asString()).isEqualTo("matches-any");
+ assertThat(rule.path("condition").path("input").path("source").asString())
+ .isEqualTo("document");
+ assertThat(mapper.readValue(saved, Policy.class)).isEqualTo(policy);
+ }
+
+ @Test
+ void explicitConditionTakesPrecedenceOverLegacyFields() {
+ RoutingRule rule =
+ mapper.readValue(
+ """
+ {
+ "condition": {"input": {"source": "document", "field": "document.extension"},
+ "operator": "matches-any", "values": ["pdf"]},
+ "field": "classification.labels", "operator": "matches-any",
+ "values": ["invoice"], "outputId": "archive"
+ }
+ """,
+ RoutingRule.class);
+
+ assertThat(rule.condition())
+ .isEqualTo(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("document.extension"),
+ List.of("pdf")));
+ }
+
+ @Test
+ void rejectsUnknownLegacyOperatorsRatherThanChangingTheirMeaning() {
+ assertThatThrownBy(
+ () ->
+ mapper.readValue(
+ """
+ {"field": "classification.labels", "operator": "not-equal",
+ "values": ["invoice"], "outputId": "archive"}
+ """,
+ RoutingRule.class))
+ .hasMessageContaining("condition operator");
+ }
+
+ @Test
+ void rejectsUnknownConditionOperatorsAndSources() {
+ assertThatThrownBy(
+ () ->
+ mapper.readValue(
+ """
+ {"condition": {"input": {"source": "document", "field": "document.sizeBytes"},
+ "operator": "greater-than", "value": 100}, "outputId": "archive"}
+ """,
+ RoutingRule.class))
+ .hasMessageContaining("greater-than");
+ assertThatThrownBy(
+ () ->
+ mapper.readValue(
+ """
+ {"condition": {"input": {"source": "step", "stepId": "lookup", "output": "code"},
+ "operator": "matches-any", "values": ["REVIEW"]}, "outputId": "archive"}
+ """,
+ RoutingRule.class))
+ .hasMessageContaining("step");
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/overview/PolicyOverviewServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/overview/PolicyOverviewServiceTest.java
index 65d9577325..b0171ed200 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/overview/PolicyOverviewServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/overview/PolicyOverviewServiceTest.java
@@ -159,7 +159,8 @@ class PolicyOverviewServiceTest {
List.of(),
null,
EditorConfig.disabled(),
- null));
+ null,
+ List.of()));
PolicyView view = find(service.overview(), "Mandatory redaction");
assertTrue(view.required());
@@ -182,7 +183,8 @@ class PolicyOverviewServiceTest {
List.of(),
null,
EditorConfig.disabled(),
- null));
+ null,
+ List.of()));
// No explicit icon: a template-derived policy falls back to its categoryId marker.
policyStore.save(
new Policy(
@@ -198,7 +200,8 @@ class PolicyOverviewServiceTest {
List.of(),
null,
EditorConfig.disabled(),
- null));
+ null,
+ List.of()));
assertEquals("shield", find(service.overview(), "Custom with icon").icon());
assertEquals("security", find(service.overview(), "Template derived").icon());
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/routing/ClassificationStepPlannerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/routing/ClassificationStepPlannerTest.java
new file mode 100644
index 0000000000..a6299b032e
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/routing/ClassificationStepPlannerTest.java
@@ -0,0 +1,133 @@
+package stirling.software.proprietary.policy.routing;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+
+import stirling.software.proprietary.document.conditions.Condition;
+import stirling.software.proprietary.document.conditions.ConditionInput;
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.model.PipelineStep;
+import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.model.RoutingRule;
+
+/** Tests for {@link ClassificationStepPlanner}: routing on a verdict guarantees there is one. */
+class ClassificationStepPlannerTest {
+
+ private static final String COMPRESS = "/api/v1/misc/compress-pdf";
+
+ private static Policy policyWith(List<PipelineStep> steps, RoutingRule... rules) {
+ return new Policy(
+ "p1",
+ "p",
+ "owner",
+ true,
+ false,
+ "",
+ List.of(),
+ steps,
+ OutputSpec.inline(),
+ List.of(),
+ null,
+ null,
+ null,
+ List.of(rules));
+ }
+
+ private static RoutingRule classificationRule() {
+ return new RoutingRule(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("classification.labels"),
+ List.of("invoice")),
+ "dest");
+ }
+
+ @Test
+ void prependsClassifyWhenAPolicyRoutesOnTheVerdict() {
+ Policy planned =
+ ClassificationStepPlanner.ensureClassificationFirst(
+ policyWith(
+ List.of(new PipelineStep(COMPRESS, Map.of())),
+ classificationRule()));
+
+ assertThat(planned.steps()).hasSize(2);
+ assertThat(planned.steps().get(0).operation())
+ .isEqualTo(ClassificationStepPlanner.CLASSIFY_ENDPOINT);
+ // The classify tool passes a document through when it already carries a verdict, and that
+ // verdict is attacker-writable metadata, so routing only gets a server-side one with this.
+ assertThat(planned.steps().get(0).parameters()).containsEntry("reclassify", true);
+ assertThat(planned.steps().get(1).operation()).isEqualTo(COMPRESS);
+ }
+
+ @Test
+ void leavesAPolicyThatDoesNotRouteOnClassificationAlone() {
+ RoutingRule bySize =
+ new RoutingRule(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("document.pageCount"),
+ List.of("1")),
+ "dest");
+ Policy original = policyWith(List.of(new PipelineStep(COMPRESS, Map.of())), bySize);
+
+ assertThat(ClassificationStepPlanner.ensureClassificationFirst(original))
+ .isSameAs(original);
+ }
+
+ @Test
+ void leavesAPolicyWithNoRulesAlone() {
+ Policy original = policyWith(List.of(new PipelineStep(COMPRESS, Map.of())));
+
+ assertThat(ClassificationStepPlanner.ensureClassificationFirst(original))
+ .isSameAs(original);
+ }
+
+ @Test
+ void doesNotReorderAPipelineThatAlreadyClassifies() {
+ Policy alreadyClassifies =
+ policyWith(
+ List.of(
+ new PipelineStep(COMPRESS, Map.of()),
+ new PipelineStep(
+ ClassificationStepPlanner.CLASSIFY_ENDPOINT, Map.of())),
+ classificationRule());
+
+ Policy planned = ClassificationStepPlanner.ensureClassificationFirst(alreadyClassifies);
+
+ assertThat(planned.steps().stream().map(PipelineStep::operation))
+ .containsExactly(COMPRESS, ClassificationStepPlanner.CLASSIFY_ENDPOINT);
+ }
+
+ @Test
+ void forcesReclassificationOnAClassifyStepTheUserPlaced() {
+ Policy alreadyClassifies =
+ policyWith(
+ List.of(
+ new PipelineStep(
+ ClassificationStepPlanner.CLASSIFY_ENDPOINT,
+ Map.of("reclassify", false)),
+ new PipelineStep(COMPRESS, Map.of())),
+ classificationRule());
+
+ Policy planned = ClassificationStepPlanner.ensureClassificationFirst(alreadyClassifies);
+
+ assertThat(planned.steps()).hasSize(2);
+ assertThat(planned.steps().get(0).parameters()).containsEntry("reclassify", true);
+ }
+
+ @Test
+ void leavesAClassifyStepThatAlreadyReclassifiesAlone() {
+ Policy alreadyClassifies =
+ policyWith(
+ List.of(
+ new PipelineStep(
+ ClassificationStepPlanner.CLASSIFY_ENDPOINT,
+ Map.of("reclassify", true))),
+ classificationRule());
+
+ assertThat(ClassificationStepPlanner.ensureClassificationFirst(alreadyClassifies))
+ .isSameAs(alreadyClassifies);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/source/SourceControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/source/SourceControllerTest.java
index 20f783f75c..a9730de452 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/source/SourceControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/source/SourceControllerTest.java
@@ -25,6 +25,8 @@ import org.springframework.web.server.ResponseStatusException;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.UserServiceInterface;
import stirling.software.common.util.FileReadinessChecker;
+import stirling.software.proprietary.document.conditions.Condition;
+import stirling.software.proprietary.document.conditions.ConditionInput;
import stirling.software.proprietary.policy.config.PolicyAccessGuard;
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
import stirling.software.proprietary.policy.input.InputSource;
@@ -33,6 +35,7 @@ import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineInput;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.model.RoutingRule;
import stirling.software.proprietary.policy.store.InProcessPolicyStore;
import stirling.software.proprietary.policy.store.PolicyStore;
import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;
@@ -139,6 +142,21 @@ class SourceControllerTest {
assertTrue(sourceStore.get(source.id()).isPresent());
}
+ @Test
+ void deletingARoutingDestinationConflicts() {
+ Source destination = sourceStore.save(folderSource());
+ policyStore.save(policyRoutingTo("Route confidential", destination.id()));
+
+ ResponseStatusException ex =
+ assertThrows(
+ ResponseStatusException.class, () -> controller.delete(destination.id()));
+
+ // Without the guard the rule would go unresolved at run time and its documents would be
+ // delivered to the policy's ordinary fallback destination instead.
+ assertEquals(409, ex.getStatusCode().value());
+ assertTrue(sourceStore.get(destination.id()).isPresent());
+ }
+
@Test
void deletingAnUnreferencedSourceSucceeds() {
Source source = sourceStore.save(folderSource());
@@ -269,6 +287,29 @@ class SourceControllerTest {
null, "Claims intake", "folder", Map.of("directory", "/in"), true, "owner", null);
}
+ private static Policy policyRoutingTo(String name, String destinationId) {
+ return new Policy(
+ null,
+ name,
+ "owner",
+ true,
+ false,
+ "",
+ List.of(),
+ List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
+ OutputSpec.inline(),
+ List.of(),
+ null,
+ null,
+ Policy.SURFACE_POLICY,
+ List.of(
+ new RoutingRule(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("classification.labels"),
+ List.of("confidential")),
+ destinationId)));
+ }
+
private static Policy policyReferencing(String name, String sourceId) {
return new Policy(
null,
diff --git a/app/proprietary/src/test/resources/policy/portal-wire-policy.json b/app/proprietary/src/test/resources/policy/portal-wire-policy.json
new file mode 100644
index 0000000000..921288999e
--- /dev/null
+++ b/app/proprietary/src/test/resources/policy/portal-wire-policy.json
@@ -0,0 +1,51 @@
+{
+ "id": "pol_routing",
+ "name": "Routing Policy",
+ "owner": "",
+ "enabled": true,
+ "required": false,
+ "inputs": [
+ {
+ "sourceId": "src-dropbox",
+ "trigger": {
+ "type": "schedule",
+ "options": {
+ "schedule": { "type": "every", "count": 1, "unit": "HOURS" }
+ }
+ }
+ }
+ ],
+ "steps": [
+ {
+ "operation": "/api/v1/misc/compress-pdf",
+ "parameters": { "optimizeLevel": 5 }
+ }
+ ],
+ "output": {
+ "type": "inline",
+ "options": {
+ "runOn": "upload",
+ "mode": "new_version",
+ "name": "",
+ "position": "suffix",
+ "maxRetries": 3,
+ "retryDelayMinutes": 5,
+ "categoryId": "routing",
+ "sources": ["editor", "src-dropbox"],
+ "scopeTypes": [],
+ "reviewerEmail": "",
+ "fieldValues": {}
+ }
+ },
+ "outputIds": ["src-archive"],
+ "routingRules": [
+ {
+ "condition": {
+ "input": { "source": "document", "field": "classification.labels" },
+ "operator": "matches-any",
+ "values": ["invoice", "receipt"]
+ },
+ "outputId": "src-finance"
+ }
+ ]
+}
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 72a08aa858..6c60b30076 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -8752,6 +8752,8 @@ heading = "To create this pipeline:"
incompatible = "Fix steps that can't run in order: {{tools}}"
managerOnly = "Only an admin or team leader can modify a policy"
name = "Give the pipeline a name"
+routing = "Give every route document types and a destination"
+routingNeedsClassify = "Add a Classify step, or turn off routing by document type"
saveHeading = "To save your changes:"
schedule = "Set how often it runs"
setup = "Finish setting up: {{tools}}"
@@ -8768,6 +8770,17 @@ undeclared-operation = "Can't check what this step accepts"
[portal.pipelines.builder.icon]
label = "Change icon"
+[portal.pipelines.builder.routing]
+addRule = "Add a route"
+fallback = "Everything else goes to"
+heading = "Routes"
+needsClassify = "Add a Classify step to the pipeline first - routes read the document type it works out."
+nodeSummary_one = "1 route, then a fallback"
+nodeSummary_other = "{{count}} routes, then a fallback"
+toggle = "Send document types to different places"
+toggleOff = "Every document goes to the destination below."
+toggleOn = "Documents are routed by the type the Classify step works out."
+
[portal.pipelines.composer]
addTool = "Add a tool"
create = "Create pipeline"
@@ -8999,11 +9012,6 @@ keepFor = "Keep for"
[portal.policies.config.routing]
summary = "Routes documents to the right destination based on type and classification."
-[portal.policies.config.routing.fields]
-destination = "Destination"
-notify = "Notify on route"
-webhookUrl = "Webhook URL"
-
[portal.policies.config.routing.rules]
0 = "Auto-classify"
1 = "Route to folder"
@@ -9320,9 +9328,25 @@ description = "Every uploaded document is classified against the built-in labels
labelsHeading = "Classification labels"
[portal.policies.wizard.errors]
-noTools = "Enable at least one tool in the workflow first."
+noTools = "Enable at least one action."
saveFailed = "Couldn't save the pipeline. Please try again."
+[portal.policies.wizard.routing]
+chooseDestination = "Choose a destination"
+chooseSource = "Choose what to watch"
+description = "Each document is classified first, then delivered to the first rule it matches. Anything matching none goes to the destination below."
+destinationAria = "Destination"
+labelAria = "Document types"
+labelPlaceholder = "Choose document types"
+needsDestination = "Add a destination below first - a rule needs somewhere to send documents to."
+needsSource = "Connect a folder, bucket or webhook for this policy to watch."
+remove = "Remove rule"
+sourceDescription = "Documents arriving here are classified, then sent on by the rules below."
+sourceHeading = "Watch"
+
+[portal.policies.wizard.sources]
+connect = "Connect a source"
+
[portal.policies.wizard.title]
edit = "Edit {{category}} pipeline"
setUp = "Set up {{category}} pipeline"
diff --git a/frontend/editor/src/portal/api/pipelines.ts b/frontend/editor/src/portal/api/pipelines.ts
index e456426585..129814b594 100644
--- a/frontend/editor/src/portal/api/pipelines.ts
+++ b/frontend/editor/src/portal/api/pipelines.ts
@@ -1,4 +1,5 @@
import { apiClient } from "@portal/api/http";
+import type { WireRoutingRule } from "@app/policies/types";
import {
type SupportingFileBindings,
type ToolApiStep,
@@ -79,6 +80,13 @@ export interface Policy {
* output} is used.
*/
outputIds: string[];
+ /**
+ * Per-document delivery: each rule sends the document types it names to its own destination,
+ * tried in order, first match wins. Empty (the default) means every document goes to {@link
+ * outputIds}. A rule reading the classification verdict makes the backend prepend a classify
+ * step, so the verdict exists to route on.
+ */
+ routingRules?: WireRoutingRule[];
/** Whether the editor runs this policy per file, and on which moment. */
editor?: { allowed: boolean; runOn: "upload" | "export" };
teamId?: number | null;
diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.ts
index 2fe40de500..b9e0092080 100644
--- a/frontend/editor/src/portal/api/policies.ts
+++ b/frontend/editor/src/portal/api/policies.ts
@@ -11,7 +11,11 @@
import type { TFunction } from "i18next";
import { apiClient } from "@portal/api/http";
-import { fromWirePolicy, toWirePolicy } from "@app/policies/codec";
+import {
+ fromWirePolicy,
+ policyInputs,
+ toWirePolicy,
+} from "@app/policies/codec";
import { runsToActivity, runsToStats } from "@app/policies/runs";
import {
policyStepFromWire,
@@ -192,7 +196,9 @@ export function parseSimplePolicy(
name: policy.name,
enabled: policy.enabled,
required: policy.required,
- trigger: null,
+ inputs: policy.inputs ?? [],
+ outputIds: policy.outputIds ?? [],
+ routingRules: policy.routingRules ?? [],
steps: policy.steps as WirePipelineStep[],
// The options bag is untyped on the pipeline record; the codec reads it defensively.
output: {
@@ -286,6 +292,10 @@ export function buildWireFromSetup(
required: result.required,
extraOptions: result.extraOptions,
policyKey: entry.category.id,
+ inputs: policyInputs(result.sources, result.trigger ?? null),
+ trigger: result.trigger ?? null,
+ outputIds: result.outputIds ?? stored?.outputIds ?? [],
+ routingRules: result.routingRules ?? stored?.routingRules ?? [],
sources: result.sources,
runsOnEditor: result.runsOnEditor,
scopeTypes: result.scopeTypes,
diff --git a/frontend/editor/src/portal/components/pipelines/DestinationPicker.tsx b/frontend/editor/src/portal/components/pipelines/DestinationPicker.tsx
index 864668b764..1952519091 100644
--- a/frontend/editor/src/portal/components/pipelines/DestinationPicker.tsx
+++ b/frontend/editor/src/portal/components/pipelines/DestinationPicker.tsx
@@ -25,6 +25,8 @@ interface DestinationPickerProps {
onCreateNew: () => void;
/** Edit the chosen destination's own settings (opens the source modal on it). */
onEdit: (sourceId: string) => void;
+ /** Overrides the field label; routing renames this picker to the fallback it becomes. */
+ label?: string;
}
export function DestinationPicker({
@@ -33,6 +35,7 @@ export function DestinationPicker({
onChange,
onCreateNew,
onEdit,
+ label,
}: DestinationPickerProps) {
const { t } = useTranslation();
const chosen = value[0] ?? "";
@@ -43,7 +46,7 @@ export function DestinationPicker({
return (
<>
{hasSources && (
- <FormField label={t("portal.pipelines.composer.output")}>
+ <FormField label={label ?? t("portal.pipelines.composer.output")}>
<div className="portal-builder__input-row">
<div className="portal-builder__input-field">
<Select
diff --git a/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx b/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx
new file mode 100644
index 0000000000..214ba9a223
--- /dev/null
+++ b/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx
@@ -0,0 +1,140 @@
+import { useMemo } from "react";
+import { useNavigate } from "react-router-dom";
+import { useTranslation } from "react-i18next";
+import { Banner, Button, Select } from "@app/ui";
+import type { RoutingSetup } from "@app/components/policies/PolicySetupWizard";
+import type { WireTriggerConfig } from "@app/policies/types";
+import { availableOutputModes } from "@portal/components/pipelines/outputModes";
+import { RoutingRules } from "@portal/components/policies/RoutingRules";
+import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
+import { useSources } from "@portal/queries/sources";
+
+interface PolicyRoutingConfigProps {
+ value: RoutingSetup;
+ onChange: (next: RoutingSetup) => void;
+ onClose: () => void;
+}
+
+/** What pulls a watched source; a folder is watched, a webhook pushes, anything else is swept. */
+function triggerFor(type: string | undefined): WireTriggerConfig | null {
+ if (!type) return null;
+ if (type === "folder") return { type: "folder-watch", options: {} };
+ if (type === "webhook") return { type: "webhook", options: {} };
+ return {
+ type: "schedule",
+ options: { schedule: { every: 1, unit: "HOURS" } },
+ };
+}
+
+export function PolicyRoutingConfig({
+ value,
+ onChange,
+ onClose,
+}: PolicyRoutingConfigProps) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const sourcesAsync = useSources();
+
+ const sources = useMemo(
+ () =>
+ (sourcesAsync.data?.sources ?? []).filter(
+ (src) => src.status !== "disabled" && src.type !== "editor",
+ ),
+ [sourcesAsync.data],
+ );
+ const destinations = useMemo(
+ () =>
+ sources
+ .filter((src) =>
+ (availableOutputModes() as string[]).includes(src.type),
+ )
+ .map((src) => ({ id: src.id, name: src.name })),
+ [sources],
+ );
+
+ function connectSource() {
+ onClose();
+ navigate(`${toPortalPath(VIEW_PATHS.sources)}/new`);
+ }
+
+ return (
+ <div className="portal-policies__wizard-section">
+ <h3 className="portal-policies__wizard-heading">
+ {t("portal.policies.wizard.routing.sourceHeading", "Watch")}
+ </h3>
+ <p className="portal-policies__wizard-desc">
+ {t(
+ "portal.policies.wizard.routing.sourceDescription",
+ "Documents arriving here are classified, then sent on by the rules below.",
+ )}
+ </p>
+ {sources.length === 0 ? (
+ <Banner
+ tone="info"
+ description={t(
+ "portal.policies.wizard.routing.needsSource",
+ "Connect a folder, bucket or webhook for this policy to watch.",
+ )}
+ action={
+ <Button variant="secondary" size="sm" onClick={connectSource}>
+ {t("portal.policies.wizard.sources.connect")}
+ </Button>
+ }
+ />
+ ) : (
+ <Select
+ inputSize="sm"
+ aria-label={t("portal.policies.wizard.routing.sourceHeading")}
+ placeholder={t(
+ "portal.policies.wizard.routing.chooseSource",
+ "Choose what to watch",
+ )}
+ value={value.sourceId || null}
+ invalid={value.sourceId === ""}
+ onChange={(id) =>
+ onChange({
+ ...value,
+ sourceId: id ?? "",
+ trigger: triggerFor(sources.find((s) => s.id === id)?.type),
+ })
+ }
+ options={sources.map((src) => ({ value: src.id, label: src.name }))}
+ comboboxProps={{ withinPortal: true }}
+ />
+ )}
+
+ <h3 className="portal-policies__wizard-heading">
+ {t("portal.pipelines.builder.routing.heading", "Routes")}
+ </h3>
+ <p className="portal-policies__wizard-desc">
+ {t(
+ "portal.policies.wizard.routing.description",
+ "Each document is classified first, then delivered to the first rule it matches. Anything matching none goes to the destination below.",
+ )}
+ </p>
+ <RoutingRules
+ rules={value.routingRules}
+ onChange={(routingRules) => onChange({ ...value, routingRules })}
+ destinations={destinations}
+ onCreateDestination={connectSource}
+ />
+
+ <h3 className="portal-policies__wizard-heading">
+ {t(
+ "portal.pipelines.builder.routing.fallback",
+ "Everything else goes to",
+ )}
+ </h3>
+ <Select
+ inputSize="sm"
+ aria-label={t("portal.pipelines.builder.routing.fallback")}
+ placeholder={t("portal.policies.wizard.routing.chooseDestination")}
+ value={value.outputIds[0] ?? null}
+ invalid={value.outputIds.length !== 1}
+ onChange={(id) => onChange({ ...value, outputIds: id ? [id] : [] })}
+ options={destinations.map((d) => ({ value: d.id, label: d.name }))}
+ comboboxProps={{ withinPortal: true }}
+ />
+ </div>
+ );
+}
diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx
index f65d2c182b..2b82857a8c 100644
--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { t } from "i18next";
import {
fireEvent,
render as baseRender,
@@ -7,9 +8,11 @@ import {
} from "@testing-library/react";
import { PortalTestProviders } from "@portal/test/TestQueryProvider";
import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";
+import { PolicySetupWizard as SharedPolicySetupWizard } from "@app/components/policies/PolicySetupWizard";
import {
POLICY_CATEGORIES,
POLICY_CONFIG,
+ buildWireFromSetup,
type CatalogueEntry,
type DecoratedPolicy,
type PolicySetupResult,
@@ -37,10 +40,19 @@ vi.mock("@portal/api/integrations", () => ({
fetchIntegrations: () => fetchIntegrations(),
}));
+const fetchSources = vi.fn();
+vi.mock("@portal/api/sources", () => ({
+ fetchSources: () => fetchSources(),
+}));
+
+vi.mock("react-router-dom", () => ({ useNavigate: () => vi.fn() }));
+
const SAVE_CHANGES = "portal.policies.wizard.actions.saveChanges";
const ENABLE = "portal.policies.wizard.actions.enablePolicy";
const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;
+const routing = POLICY_CATEGORIES.find((c) => c.id === "routing")!;
+const routingConfig = POLICY_CONFIG.routing;
const securityConfig = POLICY_CONFIG.security;
const compliance = POLICY_CATEGORIES.find((c) => c.id === "compliance")!;
const complianceConfig = POLICY_CONFIG.compliance;
@@ -78,9 +90,16 @@ async function submitWizard(saveLabel: string) {
fireEvent.click(await screen.findByRole("button", { name: saveLabel }));
}
+const routingEntry: CatalogueEntry = {
+ category: routing,
+ config: routingConfig,
+ policy: null,
+};
+
describe("PolicySetupWizard", () => {
beforeEach(() => {
fetchIntegrations.mockResolvedValue([]);
+ fetchSources.mockResolvedValue({ kpis: [], sources: [] });
});
it("round-trips a saved step's backend params on edit", async () => {
@@ -169,6 +188,67 @@ describe("PolicySetupWizard", () => {
expect(redact.listOfText).toBeTruthy();
});
+ it("submits configured routing destinations without editor participation", async () => {
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ render(
+ <SharedPolicySetupWizard
+ entry={routingEntry}
+ onClose={vi.fn()}
+ onSubmit={onSubmit}
+ routingConfig={({ onChange }) => (
+ <button
+ onClick={() =>
+ onChange({
+ sourceId: "inbox",
+ trigger: { type: "folder-watch", options: {} },
+ outputIds: ["archive"],
+ routingRules: [
+ {
+ condition: {
+ input: {
+ source: "document",
+ field: "classification.labels",
+ },
+ operator: "matches-any",
+ values: ["invoice"],
+ },
+ outputId: "finance",
+ },
+ ],
+ })
+ }
+ >
+ Configure routing
+ </button>
+ )}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Configure routing" }));
+ await submitWizard(ENABLE);
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());
+ const result = onSubmit.mock.calls[0][1] as PolicySetupResult;
+ expect(result.steps.map((step) => step.operation)).toEqual([
+ "/api/v1/ai/tools/classify-and-label",
+ ]);
+ const wire = buildWireFromSetup(routingEntry, result, t);
+ expect(wire.editor?.allowed).toBe(false);
+ expect(wire.inputs).toEqual([
+ { sourceId: "inbox", trigger: { type: "folder-watch", options: {} } },
+ ]);
+ expect(wire.outputIds).toEqual(["archive"]);
+ expect(wire.routingRules).toEqual([
+ {
+ condition: {
+ input: { source: "document", field: "classification.labels" },
+ operator: "matches-any",
+ values: ["invoice"],
+ },
+ outputId: "finance",
+ },
+ ]);
+ });
+
it("defaults a new security policy to enforcing on export", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
const entry: CatalogueEntry = {
@@ -190,6 +270,7 @@ describe("PolicySetupWizard", () => {
await waitFor(() => expect(onSubmit).toHaveBeenCalled());
const result = onSubmit.mock.calls[0][1] as PolicySetupResult;
expect(result.runOn).toBe("export");
+ expect(result.runsOnEditor).toBe(true);
});
it("locks the wizard for a non-manager", async () => {
diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx
index 5cab1d870b..808dbdf268 100644
--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx
@@ -10,6 +10,7 @@ import { errorMessage } from "@portal/api/http";
import { useAsync } from "@portal/hooks/useAsync";
import { useMemo } from "react";
import { PolicyPurviewConfig } from "@portal/components/policies/PolicyPurviewConfig";
+import { PolicyRoutingConfig } from "@portal/components/policies/PolicyRoutingConfig";
interface PolicySetupWizardProps {
entry: CatalogueEntry | null;
@@ -42,6 +43,13 @@ export function PolicySetupWizard(props: PolicySetupWizardProps) {
purviewConfig={({ parameters, onChange }) => (
<PolicyPurviewConfig parameters={parameters} onChange={onChange} />
)}
+ routingConfig={({ value, onChange }) => (
+ <PolicyRoutingConfig
+ value={value}
+ onChange={onChange}
+ onClose={props.onClose}
+ />
+ )}
/>
);
}
diff --git a/frontend/editor/src/portal/components/policies/RoutingRules.css b/frontend/editor/src/portal/components/policies/RoutingRules.css
new file mode 100644
index 0000000000..42cfb015f4
--- /dev/null
+++ b/frontend/editor/src/portal/components/policies/RoutingRules.css
@@ -0,0 +1,48 @@
+.portal-routing__optin {
+ padding: 0.75rem 0 0.25rem;
+}
+
+.portal-routing__heading {
+ margin: 0.75rem 0 0;
+ font-size: 0.6875rem;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--c-text-subtle);
+ font-weight: 600;
+}
+
+.portal-routing__desc {
+ margin: 0.25rem 0 0.5rem;
+ font-size: 0.8125rem;
+ line-height: 1.5;
+ color: var(--c-text-subtle);
+}
+
+.portal-routing__rules {
+ display: flex;
+ flex-direction: column;
+}
+
+.portal-routing__rule {
+ padding: 0.75rem 0.875rem;
+}
+
+.portal-routing__rule + .portal-routing__rule {
+ border-top: 1px solid var(--c-border);
+}
+
+/* One rule on one line where there is room, wrapping to stacked fields in the builder's narrow
+ inspector column. Mirrors .portal-builder__input-row, which solves the same problem. */
+.portal-routing__row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+/* The Mantine wrappers are not .sui-input, so each is named rather than relying on one selector. */
+.portal-routing__row .mantine-MultiSelect-root,
+.portal-routing__row .mantine-Select-root {
+ flex: 1 1 11rem;
+ min-width: 9rem;
+}
diff --git a/frontend/editor/src/portal/components/policies/RoutingRules.test.tsx b/frontend/editor/src/portal/components/policies/RoutingRules.test.tsx
new file mode 100644
index 0000000000..99daf4038c
--- /dev/null
+++ b/frontend/editor/src/portal/components/policies/RoutingRules.test.tsx
@@ -0,0 +1,164 @@
+import { classificationCondition } from "@app/data/classificationConditions";
+import { describe, expect, it, vi } from "vitest";
+import {
+ fireEvent,
+ render as baseRender,
+ screen,
+} from "@testing-library/react";
+import { PortalTestProviders } from "@portal/test/TestQueryProvider";
+import {
+ RoutingRules,
+ RoutingSection,
+} from "@portal/components/policies/RoutingRules";
+import type { WireRoutingRule } from "@app/policies/types";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback?: string) => fallback ?? _key,
+ i18n: { changeLanguage: vi.fn() },
+ }),
+}));
+
+const DESTINATIONS = [
+ { id: "src-finance", name: "Finance archive" },
+ { id: "src-legal", name: "Legal review" },
+];
+
+// The builder wraps the routes in the opt-in toggle; the wizard renders them bare.
+function setup(rules: WireRoutingRule[], canClassify = true) {
+ const onChange = vi.fn();
+ baseRender(
+ <RoutingSection
+ rules={rules}
+ onChange={onChange}
+ destinations={DESTINATIONS}
+ canClassify={canClassify}
+ />,
+ { wrapper: PortalTestProviders },
+ );
+ return onChange;
+}
+
+function setupBare(rules: WireRoutingRule[]) {
+ const onChange = vi.fn();
+ baseRender(
+ <RoutingRules
+ rules={rules}
+ onChange={onChange}
+ destinations={DESTINATIONS}
+ />,
+ { wrapper: PortalTestProviders },
+ );
+ return onChange;
+}
+
+const rule = (values: string[], outputId: string): WireRoutingRule => ({
+ condition: classificationCondition(values),
+ outputId,
+});
+
+describe("RoutingRules", () => {
+ it("edits classification values without changing the destination or other routes", () => {
+ const first = rule(["invoice"], "src-finance");
+ const second = rule(["contract"], "src-legal");
+ const onChange = setupBare([first, second]);
+
+ fireEvent.click(
+ screen.getAllByRole("textbox", { name: "Document types" })[0],
+ );
+ fireEvent.click(screen.getByRole("option", { name: "Receipt" }));
+
+ expect(onChange).toHaveBeenCalledWith([
+ rule(["invoice", "receipt"], "src-finance"),
+ second,
+ ]);
+ });
+
+ it("edits a destination without changing its condition", () => {
+ const original = rule(["invoice", "receipt"], "src-finance");
+ const onChange = setupBare([original]);
+
+ fireEvent.click(screen.getByRole("textbox", { name: "Destination" }));
+ fireEvent.click(screen.getByRole("option", { name: "Legal review" }));
+
+ expect(onChange).toHaveBeenCalledWith([
+ { ...original, outputId: "src-legal" },
+ ]);
+ });
+
+ it("renders the routes with no toggle when the surface is routing-only", () => {
+ setupBare([rule(["invoice"], "src-finance")]);
+
+ expect(screen.queryByTestId("routing-toggle")).not.toBeInTheDocument();
+ expect(screen.getByText("Add a route")).toBeInTheDocument();
+ });
+
+ it("offers no rule editor until routing is switched on", () => {
+ setup([]);
+
+ expect(screen.queryByText("Routes")).not.toBeInTheDocument();
+ expect(screen.getByTestId("routing-toggle")).toBeInTheDocument();
+ });
+
+ it("cannot be switched on until the pipeline classifies", () => {
+ const onChange = setup([], false);
+
+ fireEvent.click(screen.getByTestId("routing-toggle"));
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(
+ screen.getByText(
+ "Add a Classify step to the pipeline first - routes read the document type it works out.",
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it("can still be switched off after the classify step is removed", () => {
+ const onChange = setup([rule(["invoice"], "src-finance")], false);
+
+ fireEvent.click(screen.getByTestId("routing-toggle"));
+
+ expect(onChange).toHaveBeenCalledWith([]);
+ });
+
+ it("seeds one blank rule when switched on, since an empty list is 'off'", () => {
+ const onChange = setup([]);
+
+ fireEvent.click(screen.getByTestId("routing-toggle"));
+
+ expect(onChange).toHaveBeenCalledWith([
+ // Blank types, so the invalid state prompts the user; the first destination is a head start.
+ { ...rule([], "src-finance") },
+ ]);
+ });
+
+ it("clears every rule when switched off, so nothing routes behind the user's back", () => {
+ const onChange = setup([rule(["invoice"], "src-finance")]);
+
+ fireEvent.click(screen.getByTestId("routing-toggle"));
+
+ expect(onChange).toHaveBeenCalledWith([]);
+ });
+
+ it("appends a rule without disturbing the ones above it", () => {
+ const onChange = setup([rule(["invoice"], "src-finance")]);
+
+ fireEvent.click(screen.getByText("Add a route"));
+
+ expect(onChange).toHaveBeenCalledWith([
+ rule(["invoice"], "src-finance"),
+ rule([], "src-finance"),
+ ]);
+ });
+
+ it("removes the rule whose remove button was pressed", () => {
+ const onChange = setup([
+ rule(["invoice"], "src-finance"),
+ rule(["contract"], "src-legal"),
+ ]);
+
+ fireEvent.click(screen.getAllByRole("button", { name: "Remove rule" })[0]);
+
+ expect(onChange).toHaveBeenCalledWith([rule(["contract"], "src-legal")]);
+ });
+});
diff --git a/frontend/editor/src/portal/components/policies/RoutingRules.tsx b/frontend/editor/src/portal/components/policies/RoutingRules.tsx
new file mode 100644
index 0000000000..383279e1de
--- /dev/null
+++ b/frontend/editor/src/portal/components/policies/RoutingRules.tsx
@@ -0,0 +1,210 @@
+import { useTranslation } from "react-i18next";
+import AddRoundedIcon from "@mui/icons-material/AddRounded";
+import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
+import {
+ ActionIcon,
+ Banner,
+ Button,
+ Card,
+ Select,
+ ToggleSwitch,
+} from "@app/ui";
+import { ClassificationConditionEditor } from "@app/components/conditions/ClassificationConditionEditor";
+import {
+ classificationCondition,
+ requiresClassification,
+} from "@app/data/classificationConditions";
+import type { WireRoutingRule } from "@app/policies/types";
+import "@portal/components/policies/RoutingRules.css";
+
+export function blankRoutingRule(destinationId = ""): WireRoutingRule {
+ return {
+ condition: classificationCondition(),
+ outputId: destinationId,
+ };
+}
+
+interface DestinationOption {
+ id: string;
+ name: string;
+}
+
+interface RoutingRulesProps {
+ rules: WireRoutingRule[];
+ onChange: (rules: WireRoutingRule[]) => void;
+ /** Sources that can be written to, already filtered by the caller. */
+ destinations: DestinationOption[];
+ /** Open the source builder to create a destination; omitted when offered elsewhere. */
+ onCreateDestination?: () => void;
+}
+
+/**
+ * The routes themselves: which document types go where, tried in order, first match wins. A rule
+ * takes SEVERAL classifications, because "invoices, receipts and credit notes all go to Finance"
+ * is one decision, not three rules that happen to share a destination.
+ */
+export function RoutingRules({
+ rules,
+ onChange,
+ destinations,
+ onCreateDestination,
+}: RoutingRulesProps) {
+ const { t } = useTranslation();
+
+ function update(index: number, patch: Partial<WireRoutingRule>) {
+ onChange(
+ rules.map((rule, i) => (i === index ? { ...rule, ...patch } : rule)),
+ );
+ }
+
+ if (destinations.length === 0) {
+ return onCreateDestination ? (
+ <Button
+ variant="tertiary"
+ size="sm"
+ leftSection={<AddRoundedIcon style={{ fontSize: "1.125rem" }} />}
+ onClick={onCreateDestination}
+ >
+ {t("portal.policies.wizard.sources.connect", "Connect a source")}
+ </Button>
+ ) : (
+ <Banner
+ tone="info"
+ description={t(
+ "portal.policies.wizard.routing.needsDestination",
+ "Add a destination below first - a rule needs somewhere to send documents to.",
+ )}
+ />
+ );
+ }
+
+ return (
+ <>
+ <Card padding="none">
+ <div className="portal-routing__rules">
+ {rules.map((rule, index) => (
+ <div key={index} className="portal-routing__rule">
+ <div className="portal-routing__row">
+ <ClassificationConditionEditor
+ condition={rule.condition}
+ onChange={(condition) => update(index, { condition })}
+ />
+ <Select
+ inputSize="sm"
+ aria-label={t(
+ "portal.policies.wizard.routing.destinationAria",
+ "Destination",
+ )}
+ placeholder={t(
+ "portal.policies.wizard.routing.chooseDestination",
+ "Choose a destination",
+ )}
+ value={rule.outputId || null}
+ invalid={rule.outputId === ""}
+ onChange={(value) => update(index, { outputId: value ?? "" })}
+ options={destinations.map((dest) => ({
+ value: dest.id,
+ label: dest.name,
+ }))}
+ comboboxProps={{ withinPortal: true }}
+ />
+ <ActionIcon
+ variant="tertiary"
+ accent="danger"
+ size="sm"
+ aria-label={t(
+ "portal.policies.wizard.routing.remove",
+ "Remove rule",
+ )}
+ onClick={() => onChange(rules.filter((_, i) => i !== index))}
+ >
+ <CloseRoundedIcon style={{ fontSize: "0.875rem" }} />
+ </ActionIcon>
+ </div>
+ </div>
+ ))}
+ </div>
+ </Card>
+ <Button
+ variant="tertiary"
+ size="sm"
+ leftSection={<AddRoundedIcon style={{ fontSize: "1.125rem" }} />}
+ onClick={() =>
+ onChange([...rules, blankRoutingRule(destinations[0]?.id ?? "")])
+ }
+ >
+ {t("portal.pipelines.builder.routing.addRule", "Add a route")}
+ </Button>
+ </>
+ );
+}
+
+interface RoutingSectionProps extends RoutingRulesProps {
+ /** Whether the pipeline classifies, i.e. whether there is a verdict for a rule to read. */
+ canClassify: boolean;
+}
+
+/**
+ * Routing as an opt-in on an ordinary pipeline: off is the whole of the plain case - one
+ * destination, every document to it - so a pipeline that never meets classification never sees the
+ * routes. It stays switched off until the pipeline has a classify step, because routing reads a
+ * verdict rather than producing one, and leaving that step the user's to place is what lets
+ * classification sit mid-chain instead of being welded to this control.
+ */
+export function RoutingSection({ canClassify, ...rules }: RoutingSectionProps) {
+ const { t } = useTranslation();
+ const enabled = rules.rules.length > 0;
+ const needsClassification = enabled
+ ? rules.rules.some((rule) => requiresClassification(rule.condition))
+ : requiresClassification(classificationCondition());
+ const missingClassification = needsClassification && !canClassify;
+
+ return (
+ <>
+ <div className="portal-routing__optin">
+ <ToggleSwitch
+ size="sm"
+ checked={enabled}
+ // Always switchable off, so a pipeline whose classify step was removed can be put
+ // right from here rather than only by putting the step back.
+ disabled={missingClassification && !enabled}
+ onChange={(next) =>
+ rules.onChange(
+ next ? [blankRoutingRule(rules.destinations[0]?.id ?? "")] : [],
+ )
+ }
+ label={t(
+ "portal.pipelines.builder.routing.toggle",
+ "Send document types to different places",
+ )}
+ description={
+ missingClassification
+ ? t(
+ "portal.pipelines.builder.routing.needsClassify",
+ "Add a Classify step to the pipeline first - routes read the document type it works out.",
+ )
+ : enabled
+ ? t(
+ "portal.pipelines.builder.routing.toggleOn",
+ "Documents are routed by the type the Classify step works out.",
+ )
+ : t(
+ "portal.pipelines.builder.routing.toggleOff",
+ "Every document goes to the destination below.",
+ )
+ }
+ data-testid="routing-toggle"
+ />
+ </div>
+
+ {enabled && (
+ <>
+ <h3 className="portal-routing__heading">
+ {t("portal.pipelines.builder.routing.heading", "Routes")}
+ </h3>
+ <RoutingRules {...rules} />
+ </>
+ )}
+ </>
+ );
+}
diff --git a/frontend/editor/src/portal/mocks/policies.ts b/frontend/editor/src/portal/mocks/policies.ts
index 755c9070af..db0212662f 100644
--- a/frontend/editor/src/portal/mocks/policies.ts
+++ b/frontend/editor/src/portal/mocks/policies.ts
@@ -40,7 +40,7 @@ export function seedPolicies(): WirePolicy[] {
enabled: true,
required: true,
- trigger: null,
+ inputs: [],
steps: SECURITY_STEPS,
output: {
type: "inline",
@@ -64,7 +64,7 @@ export function seedPolicies(): WirePolicy[] {
name: "Classification Policy",
enabled: true,
- trigger: null,
+ inputs: [],
steps: CLASSIFICATION_STEPS,
output: {
type: "inline",
diff --git a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
index 5f3185939a..c1d3c5310d 100644
--- a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
+++ b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
@@ -1,3 +1,4 @@
+import { classificationCondition } from "@app/data/classificationConditions";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
fireEvent,
@@ -265,6 +266,16 @@ vi.mock("@app/contexts/ToolRegistryContext", () => {
return { useToolRegistry: () => catalog };
});
+const routingRule = (values: string[]) => ({
+ condition: classificationCondition(values),
+ outputId: "src-1",
+});
+
+const CLASSIFY_STEP = {
+ operation: "/api/v1/ai/tools/classify-and-label",
+ parameters: {},
+};
+
const POLICY: Policy = {
id: "plc-1",
name: "Existing pipeline",
@@ -845,6 +856,80 @@ describe("PipelineBuilder", () => {
expect(body.outputIds).toEqual([]);
});
+ it("carries a saved pipeline's routes through an unrelated edit", async () => {
+ const routed = routingRule(["invoice"]);
+ fetchPipeline.mockResolvedValue({
+ ...POLICY,
+ inputs: [{ sourceId: "src-in", trigger: null }],
+ // Routing reads the verdict this step writes, so a routing pipeline carries one.
+ steps: [CLASSIFY_STEP],
+ outputIds: ["src-1"],
+ routingRules: [routed],
+ });
+ renderBuilder("/processor/pipelines/plc-1");
+
+ // The name is a heading until the rename affordance is used.
+ fireEvent.click(
+ await screen.findByLabelText("portal.pipelines.builder.rename"),
+ );
+ fireEvent.change(
+ await screen.findByLabelText("portal.pipelines.composer.name"),
+ { target: { value: "Renamed" } },
+ );
+ fireEvent.click(screen.getByText("portal.pipelines.composer.save"));
+
+ await waitFor(() => expect(savePipeline).toHaveBeenCalledTimes(1));
+ // Routing is edited on the destination node; renaming the pipeline must not drop it.
+ expect(savePipeline.mock.calls[0][0].routingRules).toEqual([routed]);
+ });
+
+ it("refuses to save a route with no document types on it", async () => {
+ fetchPipeline.mockResolvedValue({
+ ...POLICY,
+ inputs: [{ sourceId: "src-in", trigger: null }],
+ steps: [CLASSIFY_STEP],
+ outputIds: ["src-1"],
+ // What the toggle seeds: a rule the user has not filled in yet.
+ routingRules: [routingRule([])],
+ });
+ renderBuilder("/processor/pipelines/plc-1");
+
+ fireEvent.click(
+ await screen.findByLabelText("portal.pipelines.builder.rename"),
+ );
+ fireEvent.change(
+ await screen.findByLabelText("portal.pipelines.composer.name"),
+ { target: { value: "Renamed" } },
+ );
+ fireEvent.click(screen.getByText("portal.pipelines.composer.save"));
+
+ // The backend's PolicyValidator would reject this; the builder says so first.
+ await waitFor(() => expect(savePipeline).not.toHaveBeenCalled());
+ });
+
+ it("refuses to save routes whose classify step has been removed", async () => {
+ fetchPipeline.mockResolvedValue({
+ ...POLICY,
+ inputs: [{ sourceId: "src-in", trigger: null }],
+ // Rules outliving the step that feeds them: every document would fall to the fallback.
+ steps: [],
+ outputIds: ["src-1"],
+ routingRules: [routingRule(["invoice"])],
+ });
+ renderBuilder("/processor/pipelines/plc-1");
+
+ fireEvent.click(
+ await screen.findByLabelText("portal.pipelines.builder.rename"),
+ );
+ fireEvent.change(
+ await screen.findByLabelText("portal.pipelines.composer.name"),
+ { target: { value: "Renamed" } },
+ );
+ fireEvent.click(screen.getByText("portal.pipelines.composer.save"));
+
+ await waitFor(() => expect(savePipeline).not.toHaveBeenCalled());
+ });
+
it("runs an existing pipeline and reports success", async () => {
renderBuilder("/processor/pipelines/plc-1");
diff --git a/frontend/editor/src/portal/views/PipelineBuilder.tsx b/frontend/editor/src/portal/views/PipelineBuilder.tsx
index 0d2c9096d7..da049d3e34 100644
--- a/frontend/editor/src/portal/views/PipelineBuilder.tsx
+++ b/frontend/editor/src/portal/views/PipelineBuilder.tsx
@@ -1,3 +1,5 @@
+import { requiresClassification } from "@app/data/classificationConditions";
+import { isConditionComplete } from "@app/conditions/validation";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
@@ -66,6 +68,8 @@ import {
} from "@portal/api/pipelineAssets";
import { clearProcessedHistory } from "@portal/api/policies";
import { DestinationPicker } from "@portal/components/pipelines/DestinationPicker";
+import { RoutingSection } from "@portal/components/policies/RoutingRules";
+import type { WireRoutingRule } from "@app/policies/types";
import { availableOutputModes } from "@portal/components/pipelines/outputModes";
import { type SourceView } from "@portal/api/sources";
import { useSources } from "@portal/queries/sources";
@@ -174,6 +178,16 @@ function buildTriggerFor(input: WorkingInput): TriggerConfig | null {
return { type: input.triggerType, options: {} };
}
+/**
+ * Routing reads the verdict this step writes, so a rule is only offered once the pipeline has one.
+ * Mirrors ClassificationStepPlanner.CLASSIFY_ENDPOINT.
+ */
+const CLASSIFY_OPERATION = "/api/v1/ai/tools/classify-and-label";
+
+function isClassifyStep(step: WorkingToolStep): boolean {
+ return step.operation === CLASSIFY_OPERATION;
+}
+
/** Whether a source can be written to, i.e. offered as a pipeline destination. */
function isWritableSource(source: SourceView): boolean {
return (availableOutputModes() as string[]).includes(source.type);
@@ -277,6 +291,7 @@ export function PipelineBuilder() {
const [testRun, setTestRun] = useState<PolicyRunView | null>(null);
const [testing, setTesting] = useState(false);
const [outputIds, setOutputIds] = useState<string[]>([]);
+ const [routingRules, setRoutingRules] = useState<WireRoutingRule[]>([]);
// A policy (blocking on failure) vs an ordinary pipeline (see Policy.required). Only meaningful for
// an editor-sourced pipeline, so the toggle is shown only then and reset off otherwise (see save).
const [required, setRequired] = useState(false);
@@ -413,6 +428,7 @@ export function PipelineBuilder() {
(policy?.steps ?? []).map((step) => deserializeToolStep(step, allTools)),
);
setOutputIds(seedsEditor ? [] : (policy?.outputIds ?? []));
+ setRoutingRules(seedsEditor ? [] : (policy?.routingRules ?? []));
setSeeded(true);
}, [
isEdit,
@@ -721,6 +737,7 @@ export function PipelineBuilder() {
outputType,
outputOptions,
outputIds: [...outputIds].sort(),
+ routingRules,
});
const baseline = useRef<string | null>(null);
useEffect(() => {
@@ -751,6 +768,17 @@ export function PipelineBuilder() {
const inputValid = sourceChosen && scheduleValid;
// Nor a destination: an editor pipeline's results land back in the workspace the file came from.
const outputValid = isEditorInput || outputIds.length === 1;
+ const classifies = steps.some(isClassifyStep);
+ // Mirrors PolicyValidator.validateRoutingRules: a rule with nothing to match on, or nowhere to
+ // send, would be rejected on save - so it is named here rather than surfaced as a server error.
+ const routingValid = routingRules.every(
+ (rule) => isConditionComplete(rule.condition) && rule.outputId !== "",
+ );
+ // Rules outliving the step that feeds them: the classify step was removed after they were set.
+ // Every document would fall through to the fallback, so this is named rather than left to run.
+ const routingHasVerdict = routingRules.every(
+ (rule) => !requiresClassification(rule.condition) || classifies,
+ );
// The single source of truth for "can this be committed": every reason it can't be, in the order
// they appear down the form, so a disabled Create / Save button can say exactly what is still owed.
@@ -765,6 +793,20 @@ export function PipelineBuilder() {
blockers.push(t("portal.pipelines.builder.blocker.schedule"));
if (!outputValid)
blockers.push(t("portal.pipelines.builder.blocker.destination"));
+ if (!routingValid)
+ blockers.push(
+ t(
+ "portal.pipelines.builder.blocker.routing",
+ "Give every route document types and a destination",
+ ),
+ );
+ if (!routingHasVerdict)
+ blockers.push(
+ t(
+ "portal.pipelines.builder.blocker.routingNeedsClassify",
+ "Add a Classify step, or turn off routing by document type",
+ ),
+ );
if (hasUnconfiguredSteps)
blockers.push(
t("portal.pipelines.builder.blocker.setup", {
@@ -880,6 +922,7 @@ export function PipelineBuilder() {
// An editor pipeline delivers back into the workspace. A stored destination would send the
// run to a folder or bucket instead, leaving the editor's copy untouched.
outputIds: isEditorInput ? [] : outputIds,
+ routingRules: isEditorInput ? [] : routingRules,
};
await savePipeline(policy);
await invalidatePipelines();
@@ -1209,6 +1252,7 @@ export function PipelineBuilder() {
inputs: [{ sourceId: input.sourceId, trigger: buildTriggerFor(input) }],
steps: steps.map((step) => serializeToolStep(step, allTools)),
outputIds,
+ routingRules,
},
null,
2,
@@ -1306,13 +1350,30 @@ export function PipelineBuilder() {
if (selected === "output") {
return (
- <DestinationPicker
- sources={writableSources}
- value={outputIds}
- onChange={setOutputIds}
- onCreateNew={() => createSourceFor("output")}
- onEdit={(sourceId) => setSourceModal({ open: true, sourceId })}
- />
+ <>
+ <RoutingSection
+ rules={routingRules}
+ onChange={setRoutingRules}
+ destinations={writableSources}
+ onCreateDestination={() => createSourceFor("output")}
+ canClassify={classifies}
+ />
+ <DestinationPicker
+ label={
+ routingRules.length > 0
+ ? t(
+ "portal.pipelines.builder.routing.fallback",
+ "Everything else goes to",
+ )
+ : undefined
+ }
+ sources={writableSources}
+ value={outputIds}
+ onChange={setOutputIds}
+ onCreateNew={() => createSourceFor("output")}
+ onEdit={(sourceId) => setSourceModal({ open: true, sourceId })}
+ />
+ </>
);
}
@@ -1444,6 +1505,14 @@ export function PipelineBuilder() {
label:
chosenDestination?.name ??
t("portal.pipelines.builder.chooseDestination"),
+ // With routing on, the destination on the node is only the fallback, so the
+ // node says how many routes come first rather than implying one endpoint.
+ detail:
+ routingRules.length > 0
+ ? t("portal.pipelines.builder.routing.nodeSummary", {
+ count: routingRules.length,
+ })
+ : undefined,
warning: outputValid
? undefined
: t("portal.pipelines.builder.needsDestination"),
diff --git a/frontend/editor/src/proprietary/components/conditions/ClassificationConditionEditor.tsx b/frontend/editor/src/proprietary/components/conditions/ClassificationConditionEditor.tsx
new file mode 100644
index 0000000000..a00d0ad551
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/conditions/ClassificationConditionEditor.tsx
@@ -0,0 +1,50 @@
+import { useTranslation } from "react-i18next";
+import { MultiSelect } from "@app/ui";
+import { LABEL_FAMILIES } from "@app/data/classificationLabels";
+import type { MatchesAnyCondition } from "@app/conditions/types";
+
+interface ClassificationConditionEditorProps {
+ condition: MatchesAnyCondition;
+ onChange: (condition: MatchesAnyCondition) => void;
+}
+
+/** Edits classification values without owning the destination or action taken on a match. */
+export function ClassificationConditionEditor({
+ condition,
+ onChange,
+}: ClassificationConditionEditorProps) {
+ const { t } = useTranslation();
+ const labelData = LABEL_FAMILIES.map((family) => ({
+ group: family.name,
+ items: family.labels.map((label) => ({
+ value: label.id,
+ label: t(`classification.labels.${label.id}`, label.name),
+ })),
+ }));
+
+ return (
+ <MultiSelect
+ inputSize="sm"
+ aria-label={t(
+ "portal.policies.wizard.routing.labelAria",
+ "Document types",
+ )}
+ placeholder={
+ condition.values.length === 0
+ ? t(
+ "portal.policies.wizard.routing.labelPlaceholder",
+ "Choose document types",
+ )
+ : undefined
+ }
+ data={labelData}
+ value={condition.values}
+ onChange={(values) => onChange({ ...condition, values })}
+ invalid={condition.values.length === 0}
+ searchable
+ clearable
+ maxDropdownHeight={280}
+ comboboxProps={{ withinPortal: true }}
+ />
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx
index f445cc9e56..bc99c3e14a 100644
--- a/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx
+++ b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx
@@ -47,13 +47,15 @@ export function FolderProcessingSetup({
const { recordFor } = useProcessingFolders();
const [wizardEntry, setWizardEntry] = useState<CatalogueEntry | null>(null);
- // The same catalogue Processor's gallery assembles, with no saved-policy
- // decoration: a folder setup always starts from the template.
+ // The catalogue Processor's gallery assembles, with no saved-policy decoration: a folder setup
+ // always starts from the template. A category that binds its own source and destinations is left
+ // out - this surface supplies the folder itself and has no destination UI to bind them with.
const entries = useMemo<CatalogueEntry[]>(
() =>
POLICY_CATEGORIES.flatMap((category) => {
const config = POLICY_CONFIG[category.id];
- return config ? [{ category, config, policy: null }] : [];
+ if (!config || category.bindsOwnSource === true) return [];
+ return [{ category, config, policy: null }];
}),
[],
);
diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
index 6662fcfef7..d4617c8142 100644
--- a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
@@ -1,3 +1,4 @@
+import { classificationCondition } from "@app/data/classificationConditions";
import { useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import TuneRoundedIcon from "@mui/icons-material/TuneRounded";
@@ -19,6 +20,7 @@ import {
type PolicyToolStep,
} from "@app/policies/operations";
import { resolveRunOn } from "@app/policies/runOn";
+import type { WireRoutingRule, WireTriggerConfig } from "@app/policies/types";
import { PolicyCategoryBadge } from "@app/components/policies/PolicyCategoryBadge";
import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig";
import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";
@@ -36,6 +38,14 @@ export interface PolicySetupFrame {
canSubmit: boolean;
}
+/** What the routing category binds: where documents come from, where each type goes. */
+export interface RoutingSetup {
+ sourceId: string;
+ trigger: WireTriggerConfig | null;
+ outputIds: string[];
+ routingRules: WireRoutingRule[];
+}
+
interface PolicySetupWizardProps {
/** The category being configured, or null when closed. */
entry: CatalogueEntry | null;
@@ -48,6 +58,14 @@ interface PolicySetupWizardProps {
onCustomise?: (entry: CatalogueEntry, result: PolicySetupResult) => void;
/** Whether a Purview tenant is connected; gates the Purview-backed steps. */
hasPurviewConnection?: boolean;
+ /**
+ * Renders the routing category's source, routes and fallback destination. Portal-only: it reads
+ * the saved Sources. Without it a routing policy shows its steps and nothing to route with.
+ */
+ routingConfig?: (props: {
+ value: RoutingSetup;
+ onChange: (next: RoutingSetup) => void;
+ }) => ReactNode;
/** Renders the Purview step's inline config. Portal-only; without it the step shows bare. */
purviewConfig?: (props: {
parameters: PolicyParams<"purviewApplyLabel">;
@@ -227,6 +245,7 @@ export function PolicySetupWizard({
onCustomise,
hasPurviewConnection,
purviewConfig,
+ routingConfig,
formatError,
enforceControl,
canManagePolicies,
@@ -243,6 +262,7 @@ export function PolicySetupWizard({
onCustomise={onCustomise}
hasPurviewConnection={hasPurviewConnection}
purviewConfig={purviewConfig}
+ routingConfig={routingConfig}
formatError={formatError}
enforceControl={enforceControl}
canManagePolicies={canManagePolicies}
@@ -260,6 +280,7 @@ function PolicySetupWizardBody({
onCustomise,
hasPurviewConnection = false,
purviewConfig,
+ routingConfig,
formatError,
enforceControl = true,
canManagePolicies = true,
@@ -275,6 +296,10 @@ function PolicySetupWizardBody({
parameters: PolicyParams<"purviewApplyLabel">;
onChange: (params: PolicyParams<"purviewApplyLabel">) => void;
}) => ReactNode;
+ routingConfig?: (props: {
+ value: RoutingSetup;
+ onChange: (next: RoutingSetup) => void;
+ }) => ReactNode;
formatError?: (e: unknown) => string;
enforceControl?: boolean;
canManagePolicies?: boolean;
@@ -286,6 +311,20 @@ function PolicySetupWizardBody({
const { category, config, policy } = entry;
const isEdit = policy != null;
const isClassification = category.id === "classification";
+ const isRouting = category.id === "routing";
+ const [routing, setRouting] = useState<RoutingSetup>(() => ({
+ sourceId: policy?.state.sources?.[0] ?? "",
+ trigger: null,
+ outputIds: (policy?.state.outputIds ?? []).slice(0, 1),
+ // One blank route so the form and the saved result agree: an empty list would render a route
+ // the user could fill in and then submit as none.
+ routingRules: policy?.state.routingRules ?? [
+ {
+ condition: classificationCondition(),
+ outputId: "",
+ },
+ ],
+ }));
const [tools, setTools] = useState<ToolState[]>(() => {
const seeded = seedTools(entry);
@@ -364,7 +403,7 @@ function PolicySetupWizardBody({
// Preserve stored options this wizard has no UI for rather than wiping them on save;
// the builder is where those are edited.
extraOptions: policy?.state.extraOptions,
- runsOnEditor: true,
+ runsOnEditor: !isRouting,
fieldValues,
sources: policy?.state.sources ?? [],
scopeTypes,
@@ -376,6 +415,14 @@ function PolicySetupWizardBody({
maxRetries,
retryDelayMinutes,
steps,
+ ...(isRouting
+ ? {
+ sources: routing.sourceId ? [routing.sourceId] : [],
+ trigger: routing.trigger,
+ outputIds: routing.outputIds,
+ routingRules: routing.routingRules,
+ }
+ : {}),
};
}
@@ -431,6 +478,8 @@ function PolicySetupWizardBody({
</div>
)}
+ {isRouting && routingConfig?.({ value: routing, onChange: setRouting })}
+
{!isClassification && (
<div className="portal-policies__wizard-section">
<p className="portal-policies__wizard-desc">
diff --git a/frontend/editor/src/proprietary/conditions/types.ts b/frontend/editor/src/proprietary/conditions/types.ts
new file mode 100644
index 0000000000..17b29d443d
--- /dev/null
+++ b/frontend/editor/src/proprietary/conditions/types.ts
@@ -0,0 +1,12 @@
+/** Source variants distinguish current document facts from values requiring execution state. */
+export type ConditionInput = { source: "document"; field: string };
+
+/** The operator owns its operand types; string membership accepts several candidate values. */
+export interface MatchesAnyCondition {
+ input: ConditionInput;
+ operator: "matches-any";
+ values: string[];
+}
+
+/** Mirrors the backend Condition union, independently of the action taken on a match. */
+export type Condition = MatchesAnyCondition;
diff --git a/frontend/editor/src/proprietary/conditions/validation.test.ts b/frontend/editor/src/proprietary/conditions/validation.test.ts
new file mode 100644
index 0000000000..252a858cdd
--- /dev/null
+++ b/frontend/editor/src/proprietary/conditions/validation.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+import { isConditionComplete } from "@app/conditions/validation";
+import {
+ classificationCondition,
+ requiresClassification,
+} from "@app/data/classificationConditions";
+import type { Condition } from "@app/conditions/types";
+
+describe("document conditions", () => {
+ it("requires classification only for classifier-produced facts", () => {
+ const extension: Condition = {
+ input: { source: "document", field: "document.extension" },
+ operator: "matches-any",
+ values: ["docx"],
+ };
+
+ expect(isConditionComplete(extension)).toBe(true);
+ expect(requiresClassification(extension)).toBe(false);
+ expect(requiresClassification(classificationCondition(["invoice"]))).toBe(
+ true,
+ );
+ });
+
+ it("rejects blank operands and accepts meaningful values with surrounding whitespace", () => {
+ expect(isConditionComplete(classificationCondition())).toBe(false);
+ expect(isConditionComplete(classificationCondition([" "]))).toBe(false);
+ expect(isConditionComplete(classificationCondition([" Invoice "]))).toBe(
+ true,
+ );
+ });
+});
diff --git a/frontend/editor/src/proprietary/conditions/validation.ts b/frontend/editor/src/proprietary/conditions/validation.ts
new file mode 100644
index 0000000000..9c7bcf96e5
--- /dev/null
+++ b/frontend/editor/src/proprietary/conditions/validation.ts
@@ -0,0 +1,9 @@
+import type { Condition } from "@app/conditions/types";
+
+/** Whether the comparison has an input and operands ready to submit to ConditionValidator. */
+export function isConditionComplete(condition: Condition): boolean {
+ return (
+ condition.input.field.trim() !== "" &&
+ condition.values.some((value) => value.trim() !== "")
+ );
+}
diff --git a/frontend/editor/src/proprietary/data/classificationConditions.ts b/frontend/editor/src/proprietary/data/classificationConditions.ts
new file mode 100644
index 0000000000..e2bf26ee03
--- /dev/null
+++ b/frontend/editor/src/proprietary/data/classificationConditions.ts
@@ -0,0 +1,20 @@
+import type { Condition, MatchesAnyCondition } from "@app/conditions/types";
+
+/** Creates the classification comparison offered by the policy wizard and pipeline builder. */
+export function classificationCondition(
+ values: string[] = [],
+): MatchesAnyCondition {
+ return {
+ input: { source: "document", field: "classification.labels" },
+ operator: "matches-any",
+ values,
+ };
+}
+
+/** Classification facts require a classifier-produced verdict; unrelated facts do not. */
+export function requiresClassification(condition: Condition): boolean {
+ return (
+ condition.input.source === "document" &&
+ condition.input.field.startsWith("classification.")
+ );
+}
diff --git a/frontend/editor/src/proprietary/policies/catalog.ts b/frontend/editor/src/proprietary/policies/catalog.ts
index cf9537aa86..563ce614f0 100644
--- a/frontend/editor/src/proprietary/policies/catalog.ts
+++ b/frontend/editor/src/proprietary/policies/catalog.ts
@@ -9,7 +9,11 @@ import {
type UntypedPolicyEndpoint,
} from "@app/policies/operations";
import type { ToolEndpoint } from "@app/types/toolApiTypes";
-import type { WirePipelineStep } from "@app/policies/types";
+import type {
+ WirePipelineStep,
+ WireRoutingRule,
+ WireTriggerConfig,
+} from "@app/policies/types";
export type { WirePipelineStep as PipelineStep } from "@app/policies/types";
@@ -32,6 +36,11 @@ export interface PolicyCategory {
desc: string;
providesClassification?: boolean;
comingSoon?: boolean;
+ /**
+ * The category binds its own source and destinations (routing's Watch and routes). A surface that
+ * supplies the folder itself, and has no destination UI, cannot host one.
+ */
+ bindsOwnSource?: boolean;
requiresAiEngine?: boolean;
}
@@ -44,6 +53,9 @@ export interface PolicyConfigDef {
}
export interface PolicyState {
+ /** The saved destinations and per-document routes; the routing category edits these. */
+ outputIds?: string[];
+ routingRules?: WireRoutingRule[];
configured: boolean;
status: PolicyStatus;
/** A policy rather than an ordinary pipeline (see `Policy.required`). */
@@ -69,6 +81,10 @@ export interface PolicyState {
}
export interface PolicySetupResult {
+ /** Bound by the routing category only; every other category leaves these alone. */
+ trigger?: WireTriggerConfig | null;
+ outputIds?: string[];
+ routingRules?: WireRoutingRule[];
required: boolean;
/** Stored options the wizard doesn't model, carried through so a save preserves them (see codec). */
extraOptions?: Record<string, unknown>;
@@ -172,7 +188,7 @@ export const POLICY_CATEGORIES: PolicyCategory[] = [
label: "portal.policies.categories.routing.label",
tone: "green",
desc: "portal.policies.categories.routing.desc",
- comingSoon: true,
+ bindsOwnSource: true,
},
{
id: "retention",
@@ -276,28 +292,8 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
"portal.policies.config.routing.rules.2",
],
scopeLabel: "portal.policies.config.scopeAll",
- defaultOperations: [policyStep("compress")],
- fields: [
- {
- label: "portal.policies.config.routing.fields.destination",
- key: "destination",
- type: "select",
- value: "documents",
- options: ["documents", "s3Bucket", "sharePoint", "webhook"],
- },
- {
- label: "portal.policies.config.routing.fields.webhookUrl",
- key: "webhookUrl",
- type: "text",
- value: "",
- },
- {
- label: "portal.policies.config.routing.fields.notify",
- key: "notify",
- type: "toggle",
- value: false,
- },
- ],
+ defaultOperations: [policyStep("classify")],
+ fields: [],
},
retention: {
summary: "portal.policies.config.retention.summary",
diff --git a/frontend/editor/src/proprietary/policies/codec.test.ts b/frontend/editor/src/proprietary/policies/codec.test.ts
index 4b1b03b897..7b5f298578 100644
--- a/frontend/editor/src/proprietary/policies/codec.test.ts
+++ b/frontend/editor/src/proprietary/policies/codec.test.ts
@@ -1,6 +1,14 @@
+import { classificationCondition } from "@app/data/classificationConditions";
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
import { describe, it, expect } from "vitest";
-import { toWirePolicy, fromWirePolicy } from "@app/policies/codec";
-import type { PolicyDecodedState } from "@app/policies/types";
+import {
+ toWirePolicy,
+ fromWirePolicy,
+ policyInputs,
+ EDITOR_SOURCE_ID,
+} from "@app/policies/codec";
+import type { PolicyDecodedState, WirePolicy } from "@app/policies/types";
const FULL_STATE: PolicyDecodedState = {
id: "pol_123",
@@ -9,6 +17,7 @@ const FULL_STATE: PolicyDecodedState = {
required: true,
policyKey: "security",
sources: ["editor", "gdrive"],
+ inputs: [{ sourceId: "gdrive", trigger: null }],
runsOnEditor: true,
scopeTypes: ["Contracts", "Invoices"],
reviewerEmail: "[email protected]",
@@ -25,11 +34,16 @@ const FULL_STATE: PolicyDecodedState = {
parameters: { mode: "automatic" },
},
],
+ trigger: null,
+ outputIds: [],
+ routingRules: [],
};
describe("toWirePolicy", () => {
- it("sets trigger to null", () => {
- expect(toWirePolicy(FULL_STATE).trigger).toBeNull();
+ it("emits the bound inputs at the top level", () => {
+ expect(toWirePolicy(FULL_STATE).inputs).toEqual([
+ { sourceId: "gdrive", trigger: null },
+ ]);
});
it("sets output.type to inline", () => {
@@ -81,6 +95,28 @@ describe("toWirePolicy", () => {
});
describe("fromWirePolicy → round-trip", () => {
+ it("round-trips the same nested conditions the backend contract fixture binds", () => {
+ const fixture: WirePolicy = JSON.parse(
+ readFileSync(
+ resolve(
+ __dirname,
+ "../../../../../app/proprietary/src/test/resources/policy/portal-wire-policy.json",
+ ),
+ "utf8",
+ ),
+ );
+ const saved = toWirePolicy(fromWirePolicy(fixture));
+
+ expect(saved.routingRules).toEqual([
+ {
+ condition: classificationCondition(["invoice", "receipt"]),
+ outputId: "src-finance",
+ },
+ ]);
+ expect(saved.routingRules).toEqual(fixture.routingRules);
+ expect(saved.outputIds).toEqual(fixture.outputIds);
+ });
+
it("recovers all fields after encode→decode", () => {
const wire = toWirePolicy(FULL_STATE);
const decoded = fromWirePolicy(wire);
@@ -98,6 +134,21 @@ describe("fromWirePolicy → round-trip", () => {
expect(decoded.maxRetries).toBe(FULL_STATE.maxRetries);
expect(decoded.retryDelayMinutes).toBe(FULL_STATE.retryDelayMinutes);
expect(decoded.steps).toEqual(FULL_STATE.steps);
+ expect(decoded.inputs).toEqual(FULL_STATE.inputs);
+ expect(decoded.outputIds).toEqual(FULL_STATE.outputIds);
+ expect(decoded.routingRules).toEqual(FULL_STATE.routingRules);
+ });
+
+ it("round-trips routing rules", () => {
+ const rules = [
+ {
+ condition: classificationCondition(["invoice", "receipt"]),
+ outputId: "src-finance",
+ },
+ ];
+ const wire = toWirePolicy({ ...FULL_STATE, routingRules: rules });
+ expect(wire.routingRules).toEqual(rules);
+ expect(fromWirePolicy(wire).routingRules).toEqual(rules);
});
// The moment has two possible homes now (the `editor` block, and the legacy
@@ -176,12 +227,16 @@ describe("fromWirePolicy → round-trip", () => {
id: "x",
name: "X",
enabled: false,
- trigger: null,
+ inputs: [],
steps: [],
output: { type: "inline", options: {} },
});
expect(decoded.policyKey).toBe("");
expect(decoded.sources).toEqual([]);
+ expect(decoded.inputs).toEqual([]);
+ expect(decoded.outputIds).toEqual([]);
+ expect(decoded.routingRules).toEqual([]);
+ expect(decoded.trigger).toBeNull();
expect(decoded.runsOnEditor).toBe(false);
expect(decoded.runOn).toBe("upload");
expect(decoded.outputMode).toBe("new_version");
@@ -194,7 +249,7 @@ describe("fromWirePolicy → round-trip", () => {
id: "legacy",
name: "Security Policy",
enabled: true,
- trigger: null,
+ inputs: [],
steps: [],
output: { type: "inline", options: { categoryId: "security" } },
});
@@ -226,3 +281,60 @@ describe("fromWirePolicy → round-trip", () => {
).toEqual({ name: "x" });
});
});
+
+describe("policyInputs → binding a source selection", () => {
+ const trigger = {
+ type: "schedule",
+ options: { schedule: { type: "every", count: 1, unit: "HOURS" } },
+ };
+
+ it("drops the virtual editor source and never binds it", () => {
+ expect(policyInputs([EDITOR_SOURCE_ID, "src-dropbox"], trigger)).toEqual([
+ { sourceId: "src-dropbox", trigger },
+ ]);
+ });
+
+ it("pairs every real source with the given trigger", () => {
+ expect(policyInputs(["src-dropbox"], null)).toEqual([
+ { sourceId: "src-dropbox", trigger: null },
+ ]);
+ });
+
+ it("returns no inputs for an editor-only selection", () => {
+ expect(policyInputs([EDITOR_SOURCE_ID], trigger)).toEqual([]);
+ });
+});
+
+describe("fromWirePolicy → routing bindings", () => {
+ it("unions the options-bag sources with the bound inputs", () => {
+ // A record saved before inputs were emitted (sources only in the bag) plus
+ // a bound input still decodes to the complete selection, no duplicates.
+ const decoded = fromWirePolicy({
+ id: "pol_routing",
+ name: "Routing",
+ enabled: true,
+ inputs: [{ sourceId: "src-dropbox", trigger: null }],
+ steps: [],
+ output: {
+ type: "inline",
+ options: { categoryId: "routing", sources: ["editor", "src-dropbox"] },
+ },
+ outputIds: ["src-archive"],
+ });
+ expect(decoded.sources).toEqual(["editor", "src-dropbox"]);
+ expect(decoded.outputIds).toEqual(["src-archive"]);
+ });
+
+ it("surfaces the bound input's trigger as the read-view trigger", () => {
+ const trigger = { type: "webhook", options: {} };
+ const decoded = fromWirePolicy({
+ id: "pol_routing",
+ name: "Routing",
+ enabled: true,
+ inputs: [{ sourceId: "src-hook", trigger }],
+ steps: [],
+ output: { type: "inline", options: { categoryId: "routing" } },
+ });
+ expect(decoded.trigger).toEqual(trigger);
+ });
+});
diff --git a/frontend/editor/src/proprietary/policies/codec.ts b/frontend/editor/src/proprietary/policies/codec.ts
index 6c4d923e03..5ae9ea2082 100644
--- a/frontend/editor/src/proprietary/policies/codec.ts
+++ b/frontend/editor/src/proprietary/policies/codec.ts
@@ -1,16 +1,23 @@
/**
* Bidirectional codec between the portal's frontend `PolicyDecodedState` and
* the backend `WirePolicy`. All policy-level metadata rides in
- * `output.options`; `trigger` is always null (the editor fires runs on
- * upload/export via `/run`). Mirrors the editor's `buildBackendPolicy` /
- * `fromBackendPolicy` from `policyPipeline.ts`, minus the editor-only
- * `automation` blob and toolRegistry coupling.
+ * `output.options`; the virtual editor source lives only there, while real
+ * backend sources become `inputs` entries (source + trigger) so the backend's
+ * `Policy.inputs` binds them and triggers/sweeps see them. Mirrors the editor's
+ * `buildBackendPolicy` / `fromBackendPolicy` from `policyPipeline.ts`, minus
+ * the editor-only `automation` blob and toolRegistry coupling.
+ *
+ * `sources` and `inputs` are deliberately separate: `sources` is the display
+ * selection the options bag has always carried unchecked, `inputs` is the
+ * binding the backend validates and caps. The codec round-trips each as it
+ * found it; only `policyInputs` turns a selection into a binding.
*/
import { resolveRunOn } from "@app/policies/runOn";
import type {
PolicyDecodedState,
WireOutputOptions,
+ WirePipelineInput,
WirePolicy,
} from "@app/policies/types";
@@ -19,6 +26,25 @@ const DEFAULTS = {
retryDelayMinutes: 5,
} as const;
+/** The virtual editor source: display metadata only, never a wire sourceId. */
+export const EDITOR_SOURCE_ID = "editor";
+
+/**
+ * Bind a source selection as wire inputs: the virtual editor is dropped, and
+ * every real source is paired with the trigger that pulls it. Only a deliberate
+ * edit binds sources, so this is the wizard's call to make - never a re-derive
+ * from a decoded record, whose selection may name more sources than the backend
+ * binds (see `PolicyDecodedState.inputs`).
+ */
+export function policyInputs(
+ sources: string[],
+ trigger: WirePipelineInput["trigger"],
+): WirePipelineInput[] {
+ return sources
+ .filter((id) => id !== EDITOR_SOURCE_ID)
+ .map((sourceId) => ({ sourceId, trigger }));
+}
+
// The options-bag keys this codec models. Anything else in a stored bag is unknown to the frontend
// and preserved via PolicyDecodedState.extraOptions. Keep in sync with WireOutputOptions.
const MODELLED_OPTION_KEYS: ReadonlySet<string> = new Set([
@@ -55,11 +81,13 @@ export function toWirePolicy(state: PolicyDecodedState): WirePolicy {
owner: "",
enabled: state.enabled,
required: state.required,
- trigger: null,
+ inputs: state.inputs,
steps: state.steps,
// Unmodelled keys go under the typed ones, which always win, so preserving them can't corrupt a
// known field.
output: { type: "inline", options: { ...state.extraOptions, ...options } },
+ outputIds: state.outputIds,
+ routingRules: state.routingRules,
// Omitting this makes the backend stamp EditorConfig.disabled(), so a pause or a
// wizard save would quietly take the policy off the editor.
editor: { allowed: state.runsOnEditor, runOn: state.runOn },
@@ -79,13 +107,23 @@ export function fromWirePolicy(policy: WirePolicy): PolicyDecodedState {
? "auto-number"
: "prefix";
const policyKey = str(raw.categoryId);
+ // Selection = display metadata ∪ bound inputs, so policies saved before
+ // inputs were emitted (sources only in options) still round-trip complete.
+ const optionSources = Array.isArray(raw.sources)
+ ? (raw.sources as string[])
+ : [];
+ const inputs = policy.inputs ?? [];
+ const sources = [
+ ...new Set([...optionSources, ...inputs.map((i) => i.sourceId)]),
+ ];
return {
id: policy.id,
name: policy.name,
enabled: policy.enabled,
required: policy.required ?? false,
policyKey,
- sources: Array.isArray(raw.sources) ? raw.sources : [],
+ sources,
+ inputs,
runsOnEditor: policy.editor?.allowed === true,
scopeTypes: Array.isArray(raw.scopeTypes) ? raw.scopeTypes : [],
reviewerEmail: str(raw.reviewerEmail),
@@ -108,5 +146,8 @@ export function fromWirePolicy(policy: WirePolicy): PolicyDecodedState {
),
),
steps: Array.isArray(policy.steps) ? policy.steps : [],
+ trigger: inputs.find((i) => i.trigger)?.trigger ?? null,
+ outputIds: policy.outputIds ?? [],
+ routingRules: policy.routingRules ?? [],
};
}
diff --git a/frontend/editor/src/proprietary/policies/types.ts b/frontend/editor/src/proprietary/policies/types.ts
index fc80ebcfd5..bf54d398a3 100644
--- a/frontend/editor/src/proprietary/policies/types.ts
+++ b/frontend/editor/src/proprietary/policies/types.ts
@@ -4,11 +4,13 @@
*
* The backend stores all portal-level metadata (categoryId, sources, scope,
* reviewer, fieldValues, runOn, output settings) inside `output.options` — the
- * same "options bag" the editor uses. `trigger` is always null for
- * portal/editor-authored policies; the editor fires runs on upload/export via
- * `/run`, so there is no server-side trigger.
+ * same "options bag" the editor uses. Real backend sources ride in `inputs`,
+ * each paired with the trigger that pulls it; an editor-only policy has no
+ * inputs and fires on upload/export via `/run`.
*/
+import type { Condition } from "@app/conditions/types";
+
// ── Wire types (match Policy.java / PipelineStep.java / PolicyRunView.java) ──
export interface WirePipelineStep {
@@ -41,6 +43,31 @@ export interface WireOutputSpec {
options: Partial<WireOutputOptions>;
}
+/** When a policy fires automatically. `type` keys a backend trigger bean. */
+export interface WireTriggerConfig {
+ type: string;
+ options: Record<string, unknown>;
+}
+
+/**
+ * One input: a persisted source paired with the trigger that pulls it. Mirrors
+ * `PipelineInput.java`; a null trigger makes the input manual-only.
+ */
+export interface WirePipelineInput {
+ sourceId: string;
+ trigger: WireTriggerConfig | null;
+}
+
+/**
+ * One routing rule: when `condition` matches, the document is delivered
+ * to `outputId` instead of the policy's fallback destinations. Mirrors `RoutingRule.java`; rules
+ * are tried in order, first match wins.
+ */
+export interface WireRoutingRule {
+ condition: Condition;
+ outputId: string;
+}
+
/**
* Mirrors `EditorConfig.java`. Absent only on records that never went through the
* backend (hand-built fixtures); a stored policy always carries it, derived from
@@ -58,9 +85,14 @@ export interface WirePolicy {
enabled: boolean;
/** A policy (blocking on failure) rather than an ordinary pipeline (see `Policy.required`). */
required?: boolean;
- trigger: null;
+ /** Sources pulled from (never the virtual editor); the backend allows at most one. */
+ inputs: WirePipelineInput[];
steps: WirePipelineStep[];
output: WireOutputSpec;
+ /** Saved sources used as write targets; empty means the inline output. */
+ outputIds?: string[];
+ /** Per-document destinations: first matching rule wins, else the outputIds fallback. */
+ routingRules?: WireRoutingRule[];
editor?: WireEditorConfig;
teamId?: string;
}
@@ -105,7 +137,10 @@ export interface PolicyDecodedState {
/** A policy (blocking on failure) rather than an ordinary pipeline; first-class, not in options. */
required: boolean;
policyKey: string;
+ /** Display selection, editor included; may exceed what the backend binds. */
sources: string[];
+ /** The bound inputs exactly as stored; only a wizard save rebinds these. */
+ inputs: WirePipelineInput[];
/**
* Whether the editor runs this policy per file. Its own field, not derived from
* `sources`: the seeded Classification policy is editor-run with empty sources,
@@ -127,6 +162,12 @@ export interface PolicyDecodedState {
*/
extraOptions?: Record<string, unknown>;
steps: WirePipelineStep[];
+ /** Read view of the bound input's trigger; encoding takes it from `inputs`. */
+ trigger: WireTriggerConfig | null;
+ /** Saved sources the output is also delivered to (write targets). */
+ outputIds: string[];
+ /** Per-document routing rules; empty for a plain deliver-to-all policy. */
+ routingRules: WireRoutingRule[];
}
// ── Display types (returned by runs.ts derivations) ───────────────────────────