#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add non-AI routing and gate classification on AI (#7996)
Anthony Stirling5171b1852854
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/routing/RoutingOnRealDocumentsTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/routing/RoutingOnRealDocumentsTest.javanew file mode 100644index 0000000000..74a40296d2--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/routing/RoutingOnRealDocumentsTest.java@@ -0,0 +1,202 @@+package stirling.software.proprietary.policy.routing;++import static org.assertj.core.api.Assertions.assertThat;++import java.io.IOException;+import java.io.InputStream;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.ArrayList;+import java.util.List;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDDocumentInformation;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.PDPageContentStream;+import org.apache.pdfbox.pdmodel.font.PDType1Font;+import org.apache.pdfbox.pdmodel.font.Standard14Fonts;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.springframework.core.io.FileSystemResource;+import org.springframework.core.io.Resource;++import stirling.software.common.service.PdfMetadataService;+import stirling.software.proprietary.document.DocumentFacts;+import stirling.software.proprietary.document.conditions.Condition;+import stirling.software.proprietary.document.conditions.ConditionEvaluator;+import stirling.software.proprietary.document.conditions.ConditionInput;+import stirling.software.proprietary.policy.model.RoutingRule;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.json.JsonMapper;++/**+ * Routes real files, not hand-written fact JSON: each document is written to disk, read back+ * through {@link DocumentFacts}, and matched with {@link ConditionEvaluator} in the order and+ * first-match-wins shape {@code PolicyEngine.destinationsFor} uses at dispatch.+ */+class RoutingOnRealDocumentsTest {++ private static final String FALLBACK = "archive";++ private final JsonMapper mapper = JsonMapper.builder().build();++ /** The dispatch decision, mirroring PolicyEngine: first rule that claims the file wins. */+ private String destinationFor(List<RoutingRule> rules, Resource file) {+ JsonNode facts = DocumentFacts.of(file, mapper);+ for (RoutingRule rule : rules) {+ if (ConditionEvaluator.matches(rule.condition(), facts)) {+ return rule.outputId();+ }+ }+ return FALLBACK;+ }++ private static RoutingRule rule(String field, String outputId, String... values) {+ return new RoutingRule(+ new Condition.MatchesAny(new ConditionInput.DocumentField(field), List.of(values)),+ outputId);+ }++ /** A real PDF with one page of text and, optionally, Info-dictionary title/author. */+ private static Resource pdf(Path dir, String name, String title, String author, String body)+ throws IOException {+ Path target = dir.resolve(name);+ try (PDDocument doc = new PDDocument()) {+ PDPage page = new PDPage();+ doc.addPage(page);+ try (PDPageContentStream content = new PDPageContentStream(doc, page)) {+ content.beginText();+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);+ content.newLineAtOffset(72, 700);+ content.showText(body);+ content.endText();+ }+ PDDocumentInformation info = doc.getDocumentInformation();+ if (title != null) info.setTitle(title);+ if (author != null) info.setAuthor(author);+ doc.save(target.toFile());+ }+ return new FileSystemResource(target);+ }++ private static Resource file(Path dir, String name, byte[] bytes) throws IOException {+ Path target = dir.resolve(name);+ Files.write(target, bytes);+ return new FileSystemResource(target);+ }++ @Test+ void routesRealFilesOnEveryNonAiDocumentProperty(@TempDir Path dir) throws IOException {+ List<RoutingRule> rules =+ List.of(+ rule("document.filename", "scans", "scan-001.pdf"),+ rule("document.title", "finance", "Q3 Invoice"),+ rule("document.author", "legal", "Legal Team"),+ rule("document.extension", "images", "png", "jpg"));++ Resource byFilename = pdf(dir, "scan-001.pdf", "Untitled", "Nobody", "scanned page");+ Resource byTitle = pdf(dir, "anything.pdf", "Q3 Invoice", "Nobody", "invoice body");+ Resource byAuthor = pdf(dir, "other.pdf", "Contract", "Legal Team", "contract body");+ Resource byExtension = file(dir, "logo.png", new byte[] {(byte) 0x89, 'P', 'N', 'G'});+ Resource unmatched = pdf(dir, "misc.pdf", "Something Else", "Someone", "misc body");++ assertThat(destinationFor(rules, byFilename)).isEqualTo("scans");+ assertThat(destinationFor(rules, byTitle)).isEqualTo("finance");+ assertThat(destinationFor(rules, byAuthor)).isEqualTo("legal");+ assertThat(destinationFor(rules, byExtension)).isEqualTo("images");+ assertThat(destinationFor(rules, unmatched)).isEqualTo(FALLBACK);+ }++ @Test+ void matchingIsCaseAndWhitespaceInsensitiveOnRealMetadata(@TempDir Path dir)+ throws IOException {+ List<RoutingRule> rules = List.of(rule("document.title", "finance", " q3 INVOICE "));+ assertThat(destinationFor(rules, pdf(dir, "a.pdf", "Q3 Invoice", null, "x")))+ .isEqualTo("finance");+ }++ @Test+ void earlierRuleWinsWhenARealFileSatisfiesBoth(@TempDir Path dir) throws IOException {+ Resource both = pdf(dir, "invoice.pdf", "Q3 Invoice", null, "x");+ assertThat(+ destinationFor(+ List.of(+ rule("document.extension", "images", "pdf"),+ rule("document.title", "finance", "Q3 Invoice")),+ both))+ .isEqualTo("images");+ assertThat(+ destinationFor(+ List.of(+ rule("document.title", "finance", "Q3 Invoice"),+ rule("document.extension", "images", "pdf")),+ both))+ .isEqualTo("finance");+ }++ @Test+ void noRulesMeansEveryRealFileTakesTheSingleDestination(@TempDir Path dir) throws IOException {+ List<RoutingRule> none = List.of();+ assertThat(destinationFor(none, pdf(dir, "a.pdf", "Q3 Invoice", "Legal Team", "x")))+ .isEqualTo(FALLBACK);+ assertThat(+ destinationFor(+ none, file(dir, "b.png", new byte[] {(byte) 0x89, 'P', 'N', 'G'})))+ .isEqualTo(FALLBACK);+ }++ /**+ * The AI half: {@code routing/classify.labels.json} is a recorded verdict the engine's+ * DocumentClassifierAgent produced for an invoice against the built-in label vocabulary, and+ * routing reads it back off the PDF exactly as dispatch does. A missing verdict fails rather+ * than quietly passing.+ */+ @Test+ void routesOnAClassificationVerdictWrittenByARealModel(@TempDir Path dir) throws IOException {+ String verdict = realVerdict();+ List<String> labels = labelsOf(verdict);+ assertThat(labels).as("the recorded model verdict carries a label").isNotEmpty();++ Path target = dir.resolve("classified.pdf");+ try (PDDocument doc = new PDDocument()) {+ doc.addPage(new PDPage());+ doc.getDocumentInformation()+ .setCustomMetadataValue(PdfMetadataService.CLASSIFICATION_KEY, verdict);+ doc.save(target.toFile());+ }+ Resource classified = new FileSystemResource(target);++ JsonNode facts = DocumentFacts.of(classified, mapper);+ assertThat(facts.path("classification").path("labels").isArray()).isTrue();++ List<RoutingRule> rules =+ List.of(+ rule("classification.labels", "finance", labels.get(0)),+ rule("document.extension", "images", "png"));+ assertThat(destinationFor(rules, classified)).isEqualTo("finance");++ List<RoutingRule> otherLabelOnly =+ List.of(rule("classification.labels", "finance", "a-label-the-model-did-not-pick"));+ assertThat(destinationFor(otherLabelOnly, classified)).isEqualTo(FALLBACK);+ }++ /**+ * Read from the classpath so Gradle treats the verdict as a test input and re-runs on change.+ */+ private static String realVerdict() throws IOException {+ try (InputStream in =+ RoutingOnRealDocumentsTest.class.getResourceAsStream(+ "/routing/classify.labels.json")) {+ assertThat(in).as("routing/classify.labels.json is on the test classpath").isNotNull();+ return new String(in.readAllBytes(), StandardCharsets.UTF_8).trim();+ }+ }++ private List<String> labelsOf(String verdict) {+ List<String> labels = new ArrayList<>();+ mapper.readTree(verdict).path("labels").forEach(node -> labels.add(node.asString()));+ return labels;+ }+}diff --git a/app/proprietary/src/test/resources/routing/classify.labels.json b/app/proprietary/src/test/resources/routing/classify.labels.jsonnew file mode 100644index 0000000000..2dbcdc08c0--- /dev/null+++ b/app/proprietary/src/test/resources/routing/classify.labels.json@@ -0,0 +1 @@+{"labels": ["invoice"]}\ No newline at end of filediff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 28e32a21a1..02d1113775 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -8859,6 +8859,7 @@ usesDefaults = "Runs with default settings"viewDefinition = "View definition"[portal.pipelines.builder.blocker]+aiClassification = "Enable AI classification in Settings, or remove the Classify step"destination = "Choose a destination"heading = "To create this pipeline:"incompatible = "Fix steps that can't run in order: {{tools}}"@@ -8884,14 +8885,27 @@ label = "Change icon"[portal.pipelines.builder.routing]addRule = "Add a route"+aiDisabled = "AI classification is not enabled. Enable it in Settings, or route on a document property instead."+aiToolDisabled = "Unavailable until AI classification is enabled in Settings"+aiUnavailable = "Document-type routing is disabled because AI classification is unavailable. Route on a document property instead."+extensionPlaceholder = "pdf, docx, png"fallback = "Everything else goes to"heading = "Routes"-needsClassify = "Add a Classify step to the pipeline first - routes read the document type it works out."+matchAuthor = "PDF author"+matchBy = "Match by"+matchDocumentType = "Document type (AI classification)"+matchDocumentTypeDisabled = "Document type (AI unavailable)"+matchExtension = "File extension"+matchFilename = "Exact filename"+matchTitle = "PDF title"+matchValues = "Values to match"+needsClassify = "Add a Classify step to use document-type routing, or match on a document property instead."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."+toggleOn = "Documents are routed by the first document condition they match."+valuePlaceholder = "Enter exact values, separated by commas"[portal.pipelines.composer]addTool = "Add a tool"diff --git a/frontend/editor/src/core/hooks/useAiClassificationEnabled.ts b/frontend/editor/src/core/hooks/useAiClassificationEnabled.tsnew file mode 100644index 0000000000..1f95b02611--- /dev/null+++ b/frontend/editor/src/core/hooks/useAiClassificationEnabled.ts@@ -0,0 +1,7 @@+import { useAppConfig } from "@app/contexts/AppConfigContext";++/** Whether server-side document classification can run on this deployment. */+export function useAiClassificationEnabled(): boolean {+ const { config } = useAppConfig();+ return Boolean(config?.aiEngineEnabled && config.aiFeatures?.classify);+}diff --git a/frontend/editor/src/core/types/appConfig.ts b/frontend/editor/src/core/types/appConfig.tsindex c493b646d5..79cf18d66e 100644--- a/frontend/editor/src/core/types/appConfig.ts+++ b/frontend/editor/src/core/types/appConfig.ts@@ -71,6 +71,14 @@ export interface AppConfig {timestampCustomTsaUrls?: string[];timestampTsaPresets?: { label: string; url: string }[];aiEngineEnabled?: boolean;+ aiFeatures?: {+ chat?: boolean;+ documentQuestions?: boolean;+ createPdf?: boolean;+ mathAuditor?: boolean;+ pdfComment?: boolean;+ classify?: boolean;+ };}export type AppConfigBootstrapMode = "blocking" | "non-blocking";diff --git a/frontend/editor/src/desktop/hooks/useAiClassificationEnabled.ts b/frontend/editor/src/desktop/hooks/useAiClassificationEnabled.tsnew file mode 100644index 0000000000..5a39025e46--- /dev/null+++ b/frontend/editor/src/desktop/hooks/useAiClassificationEnabled.ts@@ -0,0 +1,7 @@+import { useSaasAppConfig } from "@app/hooks/useSaasAppConfig";++/** Desktop classification runs on the connected SaaS deployment. */+export function useAiClassificationEnabled(): boolean {+ const config = useSaasAppConfig();+ return Boolean(config?.aiEngineEnabled && config.aiFeatures?.classify);+}diff --git a/frontend/editor/src/portal/api/policies.test.ts b/frontend/editor/src/portal/api/policies.test.tsindex 3ea4f6ce0e..1d280b3849 100644--- a/frontend/editor/src/portal/api/policies.test.ts+++ b/frontend/editor/src/portal/api/policies.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import {buildWireFromSetup,+ assemblePolicies,parseSimplePolicy,type PolicySetupResult,} from "@portal/api/policies";@@ -111,6 +112,47 @@ describe("parseSimplePolicy", () => {});});+describe("assemblePolicies", () => {+ it("keeps routing bindings in decorated state when a saved policy is reopened", () => {+ const routingRule = {+ condition: {+ input: { source: "document" as const, field: "document.extension" },+ operator: "matches-any" as const,+ values: ["pdf"],+ },+ outputId: "finance",+ };+ const response = assemblePolicies(+ [+ {+ id: "route-1",+ name: "Route documents",+ enabled: true,+ inputs: [+ {+ sourceId: "inbox",+ trigger: { type: "folder-watch", options: {} },+ },+ ],+ steps: [],+ output: { type: "inline", options: { categoryId: "routing" } },+ outputIds: ["archive"],+ routingRules: [routingRule],+ editor: { allowed: false, runOn: "upload" },+ },+ ],+ [],+ );++ const state = response.catalogue.find(+ (entry) => entry.category.id === "routing",+ )?.policy?.state;+ expect(state?.trigger).toEqual({ type: "folder-watch", options: {} });+ expect(state?.outputIds).toEqual(["archive"]);+ expect(state?.routingRules).toEqual([routingRule]);+ });+});+describe("buildWireFromSetup", () => {it("preserves the stored icon and name so a wizard save doesn't reset them", () => {const policy: Policy = {diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.tsindex b9e0092080..de4b0be427 100644--- a/frontend/editor/src/portal/api/policies.ts+++ b/frontend/editor/src/portal/api/policies.ts@@ -66,6 +66,9 @@ function decoratePolicy(required: decoded.required,extraOptions: decoded.extraOptions,sources: decoded.sources,+ trigger: decoded.trigger,+ outputIds: decoded.outputIds,+ routingRules: decoded.routingRules,runsOnEditor: decoded.runsOnEditor,scopeTypes: decoded.scopeTypes,reviewerEmail: decoded.reviewerEmail,diff --git a/frontend/editor/src/portal/components/pipelines/ToolPicker.tsx b/frontend/editor/src/portal/components/pipelines/ToolPicker.tsxindex 03bd941475..0fad8dd158 100644--- a/frontend/editor/src/portal/components/pipelines/ToolPicker.tsx+++ b/frontend/editor/src/portal/components/pipelines/ToolPicker.tsx@@ -34,6 +34,8 @@ interface ToolPickerProps {* problem once the step is added.*/precedingOutput?: ToolFormat;+ /** Keeps an unavailable tool visible and explains why it cannot be added. */+ unavailableReason?: (tool: ExecutableTool) => string | undefined;}/**@@ -47,6 +49,7 @@ export function ToolPicker({operations = [],onPickOperation,precedingOutput,+ unavailableReason,}: ToolPickerProps) {const { t } = useTranslation();const [query, setQuery] = useState("");@@ -122,6 +125,7 @@ export function ToolPicker({const incompatible = Boolean(precedingOutput && !acceptsPreceding(tool),);+ const unavailable = unavailableReason?.(tool);return (<Buttonkey={tool.toolId}@@ -134,6 +138,7 @@ export function ToolPicker({].filter(Boolean).join(" ")}+ disabled={Boolean(unavailable)}onClick={() => onPick(tool)}leftSection={<span@@ -155,6 +160,11 @@ export function ToolPicker({})}</span>)}+ {unavailable && (+ <span className="portal-pipelines__picker-note">+ {unavailable}+ </span>+ )}</span></Button>);diff --git a/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.test.ts b/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.test.tsnew file mode 100644index 0000000000..0954fab13f--- /dev/null+++ b/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vitest";+import { triggerFor } from "@portal/components/policies/PolicyRoutingConfig";++describe("triggerFor", () => {+ it("uses the schedule contract accepted by the backend", () => {+ expect(triggerFor("s3")).toEqual({+ type: "schedule",+ options: {+ schedule: { type: "every", count: 1, unit: "HOURS" },+ },+ });+ });++ it("keeps folder and webhook triggers event-driven", () => {+ expect(triggerFor("folder")).toEqual({+ type: "folder-watch",+ options: {},+ });+ expect(triggerFor("webhook")).toEqual({ type: "webhook", options: {} });+ });+});diff --git a/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx b/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsxindex 214ba9a223..9361a7974a 100644--- a/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx+++ b/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx@@ -8,6 +8,7 @@ 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";+import { useAiEngineEnabled } from "@portal/hooks/useAiEngineEnabled";interface PolicyRoutingConfigProps {value: RoutingSetup;@@ -16,13 +17,13 @@ interface PolicyRoutingConfigProps {}/** What pulls a watched source; a folder is watched, a webhook pushes, anything else is swept. */-function triggerFor(type: string | undefined): WireTriggerConfig | null {+export 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" } },+ options: { schedule: { type: "every", count: 1, unit: "HOURS" } },};}@@ -34,6 +35,7 @@ export function PolicyRoutingConfig({const { t } = useTranslation();const navigate = useNavigate();const sourcesAsync = useSources();+ const { classificationEnabled, loading: aiLoading } = useAiEngineEnabled();const sources = useMemo(() =>@@ -117,6 +119,15 @@ export function PolicyRoutingConfig({onChange={(routingRules) => onChange({ ...value, routingRules })}destinations={destinations}onCreateDestination={connectSource}+ classificationAvailable={aiLoading || classificationEnabled}+ classificationUnavailableReason={+ aiLoading+ ? undefined+ : t(+ "portal.pipelines.builder.routing.aiDisabled",+ "AI classification is not enabled. Enable it in Settings, or route on a document property instead.",+ )+ }/><h3 className="portal-policies__wizard-heading">diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsxindex 2b82857a8c..bd027d5ef5 100644--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx@@ -47,6 +47,11 @@ vi.mock("@portal/api/sources", () => ({vi.mock("react-router-dom", () => ({ useNavigate: () => vi.fn() }));+const aiClassificationEnabled = { value: true };+vi.mock("@app/hooks/useAiClassificationEnabled", () => ({+ useAiClassificationEnabled: () => aiClassificationEnabled.value,+}));+const SAVE_CHANGES = "portal.policies.wizard.actions.saveChanges";const ENABLE = "portal.policies.wizard.actions.enablePolicy";@@ -98,6 +103,7 @@ const routingEntry: CatalogueEntry = {describe("PolicySetupWizard", () => {beforeEach(() => {+ aiClassificationEnabled.value = true;fetchIntegrations.mockResolvedValue([]);fetchSources.mockResolvedValue({ kpis: [], sources: [] });});@@ -249,6 +255,65 @@ describe("PolicySetupWizard", () => {]);});+ it("allows deterministic routing without AI or a classify step", async () => {+ aiClassificationEnabled.value = false;+ 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: "document.extension",+ },+ operator: "matches-any",+ values: ["pdf"],+ },+ outputId: "finance",+ },+ ],+ })+ }+ >+ Configure deterministic routing+ </button>+ )}+ />,+ );++ fireEvent.click(+ screen.getByRole("button", { name: "Configure deterministic routing" }),+ );+ await submitWizard(ENABLE);++ await waitFor(() => expect(onSubmit).toHaveBeenCalled());+ const result = onSubmit.mock.calls[0][1] as PolicySetupResult;+ expect(result.steps).toEqual([]);+ // The deterministic condition reaches the wire unchanged - the backend's+ // ConditionEvaluator reads any document.* field off DocumentFacts.+ expect(buildWireFromSetup(routingEntry, result, t).routingRules).toEqual([+ {+ condition: {+ input: { source: "document", field: "document.extension" },+ operator: "matches-any",+ values: ["pdf"],+ },+ outputId: "finance",+ },+ ]);+ });+it("defaults a new security policy to enforcing on export", async () => {const onSubmit = vi.fn().mockResolvedValue(undefined);const entry: CatalogueEntry = {diff --git a/frontend/editor/src/portal/components/policies/RoutingRules.css b/frontend/editor/src/portal/components/policies/RoutingRules.cssindex 42cfb015f4..20c18a63bc 100644--- a/frontend/editor/src/portal/components/policies/RoutingRules.css+++ b/frontend/editor/src/portal/components/policies/RoutingRules.css@@ -40,8 +40,16 @@gap: 0.5rem;}+.portal-routing__condition {+ display: flex;+ flex: 2 1 22rem;+ flex-wrap: wrap;+ 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-InputWrapper-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.tsxindex 99daf4038c..89f775d13a 100644--- a/frontend/editor/src/portal/components/policies/RoutingRules.test.tsx+++ b/frontend/editor/src/portal/components/policies/RoutingRules.test.tsx@@ -25,7 +25,11 @@ const DESTINATIONS = [];// The builder wraps the routes in the opt-in toggle; the wizard renders them bare.-function setup(rules: WireRoutingRule[], canClassify = true) {+function setup(+ rules: WireRoutingRule[],+ canClassify = true,+ aiClassificationEnabled = true,+) {const onChange = vi.fn();baseRender(<RoutingSection@@ -33,6 +37,7 @@ function setup(rules: WireRoutingRule[], canClassify = true) {onChange={onChange}destinations={DESTINATIONS}canClassify={canClassify}+ aiClassificationEnabled={aiClassificationEnabled}/>,{ wrapper: PortalTestProviders },);@@ -100,17 +105,67 @@ describe("RoutingRules", () => {expect(screen.getByTestId("routing-toggle")).toBeInTheDocument();});- it("cannot be switched on until the pipeline classifies", () => {+ it("starts with a no-AI condition when the pipeline does not classify", () => {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();+ expect(onChange).toHaveBeenCalledWith([+ {+ condition: {+ input: { source: "document", field: "document.extension" },+ operator: "matches-any",+ values: [],+ },+ outputId: "src-finance",+ },+ ]);+ });++ it("switches match type and emits the document-field condition the backend evaluates", () => {+ const onChange = setupBare([rule(["invoice"], "src-finance")]);++ fireEvent.click(screen.getByRole("textbox", { name: "Match by" }));+ fireEvent.click(screen.getByText("PDF title"));++ expect(onChange).toHaveBeenCalledWith([+ {+ condition: {+ input: { source: "document", field: "document.title" },+ operator: "matches-any",+ values: [],+ },+ outputId: "src-finance",+ },+ ]);+ });++ it("splits typed values on commas, trimmed, for a document-field route", () => {+ const onChange = setupBare([+ {+ condition: {+ input: { source: "document", field: "document.extension" },+ operator: "matches-any",+ values: [],+ },+ outputId: "src-finance",+ },+ ]);++ fireEvent.change(screen.getByRole("textbox", { name: "Values to match" }), {+ target: { value: "pdf, DOCX , png" },+ });++ expect(onChange).toHaveBeenCalledWith([+ {+ condition: {+ input: { source: "document", field: "document.extension" },+ operator: "matches-any",+ values: ["pdf", "DOCX", "png"],+ },+ outputId: "src-finance",+ },+ ]);});it("can still be switched off after the classify step is removed", () => {@@ -121,6 +176,22 @@ describe("RoutingRules", () => {expect(onChange).toHaveBeenCalledWith([]);});+ it("explains why a saved classification route is disabled when AI is off", () => {+ setup([rule(["invoice"], "src-finance")], true, false);++ expect(+ screen.getByText(+ "AI classification is not enabled. Enable it in Settings, or route on a document property instead.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("textbox", { name: "Document types" }),+ ).toBeDisabled();+ expect(screen.getByRole("textbox", { name: "Match by" })).toHaveValue(+ "Document type (AI unavailable)",+ );+ });+it("seeds one blank rule when switched on, since an empty list is 'off'", () => {const onChange = setup([]);diff --git a/frontend/editor/src/portal/components/policies/RoutingRules.tsx b/frontend/editor/src/portal/components/policies/RoutingRules.tsxindex 383279e1de..755930bc28 100644--- a/frontend/editor/src/portal/components/policies/RoutingRules.tsx+++ b/frontend/editor/src/portal/components/policies/RoutingRules.tsx@@ -9,17 +9,23 @@ import {Select,ToggleSwitch,} from "@app/ui";-import { ClassificationConditionEditor } from "@app/components/conditions/ClassificationConditionEditor";+import { RoutingConditionEditor } from "@app/components/conditions/RoutingConditionEditor";import {classificationCondition,+ documentFieldCondition,requiresClassification,} from "@app/data/classificationConditions";import type { WireRoutingRule } from "@app/policies/types";import "@portal/components/policies/RoutingRules.css";-export function blankRoutingRule(destinationId = ""): WireRoutingRule {+export function blankRoutingRule(+ destinationId = "",+ classificationAvailable = true,+): WireRoutingRule {return {- condition: classificationCondition(),+ condition: classificationAvailable+ ? classificationCondition()+ : documentFieldCondition("document.extension"),outputId: destinationId,};}@@ -36,6 +42,9 @@ interface RoutingRulesProps {destinations: DestinationOption[];/** Open the source builder to create a destination; omitted when offered elsewhere. */onCreateDestination?: () => void;+ /** Classification requires both an available AI service and, in the full builder, its step. */+ classificationAvailable?: boolean;+ classificationUnavailableReason?: string;}/**@@ -48,6 +57,8 @@ export function RoutingRules({onChange,destinations,onCreateDestination,+ classificationAvailable = true,+ classificationUnavailableReason,}: RoutingRulesProps) {const { t } = useTranslation();@@ -80,14 +91,28 @@ export function RoutingRules({return (<>+ {rules.some((rule) => requiresClassification(rule.condition)) &&+ !classificationAvailable && (+ <Banner+ tone="warning"+ description={+ classificationUnavailableReason ??+ t(+ "portal.pipelines.builder.routing.aiUnavailable",+ "Document-type routing is disabled because AI classification is unavailable. Route on a document property instead.",+ )+ }+ />+ )}<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+ <RoutingConditionEditorcondition={rule.condition}onChange={(condition) => update(index, { condition })}+ classificationAvailable={classificationAvailable}/><SelectinputSize="sm"@@ -130,7 +155,13 @@ export function RoutingRules({size="sm"leftSection={<AddRoundedIcon style={{ fontSize: "1.125rem" }} />}onClick={() =>- onChange([...rules, blankRoutingRule(destinations[0]?.id ?? "")])+ onChange([+ ...rules,+ blankRoutingRule(+ destinations[0]?.id ?? "",+ classificationAvailable,+ ),+ ])}>{t("portal.pipelines.builder.routing.addRule", "Add a route")}@@ -142,6 +173,7 @@ export function RoutingRules({interface RoutingSectionProps extends RoutingRulesProps {/** Whether the pipeline classifies, i.e. whether there is a verdict for a rule to read. */canClassify: boolean;+ aiClassificationEnabled?: boolean;}/**@@ -151,13 +183,25 @@ interface RoutingSectionProps extends RoutingRulesProps {* 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) {+export function RoutingSection({+ canClassify,+ aiClassificationEnabled = true,+ ...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;+ const classificationAvailable = canClassify && aiClassificationEnabled;+ const unavailableReason = !aiClassificationEnabled+ ? t(+ "portal.pipelines.builder.routing.aiDisabled",+ "AI classification is not enabled. Enable it in Settings, or route on a document property instead.",+ )+ : !canClassify+ ? t(+ "portal.pipelines.builder.routing.needsClassify",+ "Add a Classify step to use document-type routing, or match on a document property instead.",+ )+ : undefined;return (<>@@ -165,12 +209,16 @@ export function RoutingSection({ canClassify, ...rules }: RoutingSectionProps) {<ToggleSwitchsize="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 ?? "")] : [],+ next+ ? [+ blankRoutingRule(+ rules.destinations[0]?.id ?? "",+ classificationAvailable,+ ),+ ]+ : [],)}label={t(@@ -178,20 +226,15 @@ export function RoutingSection({ canClassify, ...rules }: RoutingSectionProps) {"Send document types to different places",)}description={- missingClassification+ enabled? t(- "portal.pipelines.builder.routing.needsClassify",- "Add a Classify step to the pipeline first - routes read the document type it works out.",+ "portal.pipelines.builder.routing.toggleOn",+ "Documents are routed by the first document condition they match.",+ )+ : t(+ "portal.pipelines.builder.routing.toggleOff",+ "Every document goes to the destination below.",)- : 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"/>@@ -202,7 +245,11 @@ export function RoutingSection({ canClassify, ...rules }: RoutingSectionProps) {<h3 className="portal-routing__heading">{t("portal.pipelines.builder.routing.heading", "Routes")}</h3>- <RoutingRules {...rules} />+ <RoutingRules+ {...rules}+ classificationAvailable={classificationAvailable}+ classificationUnavailableReason={unavailableReason}+ /></>)}</>diff --git a/frontend/editor/src/portal/hooks/useAiEngineEnabled.ts b/frontend/editor/src/portal/hooks/useAiEngineEnabled.tsindex ea6d14a0c1..1f7329d77b 100644--- a/frontend/editor/src/portal/hooks/useAiEngineEnabled.ts+++ b/frontend/editor/src/portal/hooks/useAiEngineEnabled.ts@@ -1,28 +1,18 @@-// AI-engine flag from the backend's public app-config. Gates Classification-// setup: the card always shows but can't be enabled until the engine is on.-// `loading` lets callers hold the decision rather than flash a locked card.--import { useQuery } from "@tanstack/react-query";-import { apiClient } from "@portal/api/http";-import { qk } from "@portal/queries/keys";--interface AppConfigShape {- aiEngineEnabled?: boolean;-}+import { useAppConfig } from "@app/contexts/AppConfigContext";export interface AiEngineState {enabled: boolean;+ classificationEnabled: boolean;loading: boolean;}export function useAiEngineEnabled(): AiEngineState {- const query = useQuery({- queryKey: qk.appConfig(),- queryFn: () =>- apiClient.local.json<AppConfigShape>("/api/v1/config/app-config"),- });+ const { config, loading } = useAppConfig();return {- enabled: Boolean(query.data?.aiEngineEnabled),- loading: query.isPending,+ enabled: Boolean(config?.aiEngineEnabled),+ classificationEnabled: Boolean(+ config?.aiEngineEnabled && config.aiFeatures?.classify,+ ),+ loading,};}diff --git a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx b/frontend/editor/src/portal/views/PipelineBuilder.test.tsxindex c1d3c5310d..16d48edd5f 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx@@ -29,6 +29,14 @@ vi.mock("react-i18next", () => ({}),}));+vi.mock("@portal/hooks/useAiEngineEnabled", () => ({+ useAiEngineEnabled: () => ({+ enabled: true,+ classificationEnabled: true,+ loading: false,+ }),+}));+const fetchPipeline = vi.fn();const fetchTriggers = vi.fn();const savePipeline = vi.fn();diff --git a/frontend/editor/src/portal/views/PipelineBuilder.tsx b/frontend/editor/src/portal/views/PipelineBuilder.tsxindex da049d3e34..3805da569b 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.tsx@@ -77,6 +77,7 @@ import { useCanManagePolicies } from "@portal/queries/policyPermissions";import { SourceModal } from "@portal/components/sources/SourceModal";import { EDITOR_SOURCE_TYPE } from "@portal/components/sources/sourceTypes";import { useAsync } from "@portal/hooks/useAsync";+import { useAiEngineEnabled } from "@portal/hooks/useAiEngineEnabled";import { useQueryClient } from "@tanstack/react-query";import { qk } from "@portal/queries/keys";import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";@@ -188,6 +189,13 @@ function isClassifyStep(step: WorkingToolStep): boolean {return step.operation === CLASSIFY_OPERATION;}+function isClassifyTool(tool: ExecutableTool): boolean {+ return (+ tool.endpoint === CLASSIFY_OPERATION ||+ tool.endpoints?.includes(CLASSIFY_OPERATION) === true+ );+}+/** 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);@@ -220,6 +228,10 @@ export function PipelineBuilder() {// runs in the background so run/pause/delete act on the last-saved version.const handoff = location.state as { draft?: Policy } | null;const seedDraft = handoff?.draft ?? null;+ const {+ classificationEnabled: aiClassificationEnabled,+ loading: aiAvailabilityLoading,+ } = useAiEngineEnabled();const { allTools } = useToolRegistry();const executableTools = useMemo(() => getExecutableTools(allTools),@@ -807,6 +819,13 @@ export function PipelineBuilder() {"Add a Classify step, or turn off routing by document type",),);+ if (classifies && !aiAvailabilityLoading && !aiClassificationEnabled)+ blockers.push(+ t(+ "portal.pipelines.builder.blocker.aiClassification",+ "Enable AI classification in Settings, or remove the Classify step",+ ),+ );if (hasUnconfiguredSteps)blockers.push(t("portal.pipelines.builder.blocker.setup", {@@ -1164,7 +1183,7 @@ export function PipelineBuilder() {}}- if (isEdit && !seeded) {+ if (aiAvailabilityLoading || (isEdit && !seeded)) {return (<div className="portal-builder__loading"><Spinner />@@ -1357,6 +1376,7 @@ export function PipelineBuilder() {destinations={writableSources}onCreateDestination={() => createSourceFor("output")}canClassify={classifies}+ aiClassificationEnabled={aiClassificationEnabled}/><DestinationPickerlabel={@@ -1582,6 +1602,14 @@ export function PipelineBuilder() {operations={STEP_OPERATIONS}onPickOperation={addOperationStep}precedingOutput={precedingOutput}+ unavailableReason={(tool) =>+ isClassifyTool(tool) && !aiClassificationEnabled+ ? t(+ "portal.pipelines.builder.routing.aiToolDisabled",+ "Unavailable until AI classification is enabled in Settings",+ )+ : undefined+ }onClose={() => setPickerAt(null)}/></Modal>diff --git a/frontend/editor/src/proprietary/components/conditions/ClassificationConditionEditor.tsx b/frontend/editor/src/proprietary/components/conditions/ClassificationConditionEditor.tsxindex a00d0ad551..5561a04f53 100644--- a/frontend/editor/src/proprietary/components/conditions/ClassificationConditionEditor.tsx+++ b/frontend/editor/src/proprietary/components/conditions/ClassificationConditionEditor.tsx@@ -6,12 +6,14 @@ import type { MatchesAnyCondition } from "@app/conditions/types";interface ClassificationConditionEditorProps {condition: MatchesAnyCondition;onChange: (condition: MatchesAnyCondition) => void;+ disabled?: boolean;}/** Edits classification values without owning the destination or action taken on a match. */export function ClassificationConditionEditor({condition,onChange,+ disabled = false,}: ClassificationConditionEditorProps) {const { t } = useTranslation();const labelData = LABEL_FAMILIES.map((family) => ({@@ -41,6 +43,7 @@ export function ClassificationConditionEditor({value={condition.values}onChange={(values) => onChange({ ...condition, values })}invalid={condition.values.length === 0}+ disabled={disabled}searchableclearablemaxDropdownHeight={280}diff --git a/frontend/editor/src/proprietary/components/conditions/RoutingConditionEditor.tsx b/frontend/editor/src/proprietary/components/conditions/RoutingConditionEditor.tsxnew file mode 100644index 0000000000..f0c59b1089--- /dev/null+++ b/frontend/editor/src/proprietary/components/conditions/RoutingConditionEditor.tsx@@ -0,0 +1,129 @@+import { useTranslation } from "react-i18next";+import { Input, Select } from "@app/ui";+import { ClassificationConditionEditor } from "@app/components/conditions/ClassificationConditionEditor";+import {+ classificationCondition,+ documentFieldCondition,+ requiresClassification,+} from "@app/data/classificationConditions";+import type { MatchesAnyCondition } from "@app/conditions/types";++interface RoutingConditionEditorProps {+ condition: MatchesAnyCondition;+ onChange: (condition: MatchesAnyCondition) => void;+ classificationAvailable: boolean;+}++const DOCUMENT_FIELDS = [+ "classification.labels",+ "document.extension",+ "document.filename",+ "document.title",+ "document.author",+] as const;++/** Edits either an AI classification match or a deterministic document-fact match. */+export function RoutingConditionEditor({+ condition,+ onChange,+ classificationAvailable,+}: RoutingConditionEditorProps) {+ const { t } = useTranslation();+ const field = condition.input.field;+ const classification = requiresClassification(condition);+ const options = [+ {+ value: DOCUMENT_FIELDS[0],+ label: classificationAvailable+ ? t(+ "portal.pipelines.builder.routing.matchDocumentType",+ "Document type (AI classification)",+ )+ : t(+ "portal.pipelines.builder.routing.matchDocumentTypeDisabled",+ "Document type (AI unavailable)",+ ),+ disabled: !classificationAvailable,+ },+ {+ value: DOCUMENT_FIELDS[1],+ label: t(+ "portal.pipelines.builder.routing.matchExtension",+ "File extension",+ ),+ },+ {+ value: DOCUMENT_FIELDS[2],+ label: t(+ "portal.pipelines.builder.routing.matchFilename",+ "Exact filename",+ ),+ },+ {+ value: DOCUMENT_FIELDS[3],+ label: t("portal.pipelines.builder.routing.matchTitle", "PDF title"),+ },+ {+ value: DOCUMENT_FIELDS[4],+ label: t("portal.pipelines.builder.routing.matchAuthor", "PDF author"),+ },+ ];++ function changeField(next: string | null) {+ if (!next) return;+ onChange(+ next === "classification.labels"+ ? classificationCondition()+ : documentFieldCondition(next),+ );+ }++ return (+ <div className="portal-routing__condition">+ <Select+ inputSize="sm"+ aria-label={t("portal.pipelines.builder.routing.matchBy", "Match by")}+ value={field}+ onChange={changeField}+ options={options}+ comboboxProps={{ withinPortal: true }}+ />+ {classification ? (+ <ClassificationConditionEditor+ condition={condition}+ onChange={onChange}+ disabled={!classificationAvailable}+ />+ ) : (+ <Input+ inputSize="sm"+ aria-label={t(+ "portal.pipelines.builder.routing.matchValues",+ "Values to match",+ )}+ placeholder={+ field === "document.extension"+ ? t(+ "portal.pipelines.builder.routing.extensionPlaceholder",+ "pdf, docx, png",+ )+ : t(+ "portal.pipelines.builder.routing.valuePlaceholder",+ "Enter exact values, separated by commas",+ )+ }+ value={condition.values.join(", ")}+ invalid={condition.values.every((value) => value.trim() === "")}+ onChange={(event) =>+ onChange({+ ...condition,+ values: event.target.value+ .split(",")+ .map((value) => value.trim()),+ })+ }+ />+ )}+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsxindex d4617c8142..0f706189c7 100644--- a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx@@ -1,4 +1,8 @@-import { classificationCondition } from "@app/data/classificationConditions";+import {+ classificationCondition,+ documentFieldCondition,+ requiresClassification,+} from "@app/data/classificationConditions";import { useMemo, useState, type ReactNode } from "react";import { useTranslation } from "react-i18next";import TuneRoundedIcon from "@mui/icons-material/TuneRounded";@@ -26,6 +30,8 @@ import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig"import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";import { PolicyPdfaConfig } from "@app/components/policies/PolicyPdfaConfig";import { ClassificationLabelsSection } from "@app/components/policies/ClassificationLabelsSection";+import { useAiClassificationEnabled } from "@app/hooks/useAiClassificationEnabled";+import { isConditionComplete } from "@app/conditions/validation";import "@app/components/policies/PolicySetupWizard.css";/** What a host frame needs to wrap the form: the middle content plus submit state. */@@ -307,6 +313,7 @@ function PolicySetupWizardBody({children?: (frame: PolicySetupFrame) => ReactNode;}) {const { t } = useTranslation();+ const aiClassificationEnabled = useAiClassificationEnabled();const { category, config, policy } = entry;const isEdit = policy != null;@@ -314,13 +321,15 @@ function PolicySetupWizardBody({const isRouting = category.id === "routing";const [routing, setRouting] = useState<RoutingSetup>(() => ({sourceId: policy?.state.sources?.[0] ?? "",- trigger: null,+ trigger: policy?.state.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(),+ condition: aiClassificationEnabled+ ? classificationCondition()+ : documentFieldCondition("document.extension"),outputId: "",},],@@ -395,9 +404,16 @@ function PolicySetupWizardBody({/** The wizard's current state as a submit result: shared by Save and Customise. */function collectResult(): PolicySetupResult {- const steps: PipelineStep[] = enabledTools.map((tl) =>- policyStepToWire(tl),+ const routingNeedsClassification = routing.routingRules.some((rule) =>+ requiresClassification(rule.condition),);+ const steps: PipelineStep[] = isRouting+ ? routingNeedsClassification+ ? tools+ .filter((tool) => tool.toolId === "classify")+ .map((tool) => policyStepToWire(tool))+ : []+ : enabledTools.map((tool) => policyStepToWire(tool));return {required,// Preserve stored options this wizard has no UI for rather than wiping them on save;@@ -433,7 +449,7 @@ function PolicySetupWizardBody({async function submit() {if (submitting) return;- if (enabledTools.length === 0) {+ if (!isRouting && enabledTools.length === 0) {setError(t("portal.policies.wizard.errors.noTools"));return;}@@ -449,7 +465,18 @@ function PolicySetupWizardBody({}}- const canSubmit = enabledTools.length > 0;+ const routingNeedsClassification = routing.routingRules.some((rule) =>+ requiresClassification(rule.condition),+ );+ const routingComplete =+ routing.sourceId !== "" &&+ routing.outputIds.length === 1 &&+ routing.routingRules.length > 0 &&+ routing.routingRules.every(+ (rule) => isConditionComplete(rule.condition) && rule.outputId !== "",+ ) &&+ (!routingNeedsClassification || aiClassificationEnabled);+ const canSubmit = isRouting ? routingComplete : enabledTools.length > 0;const content = (<>{error && (@@ -480,7 +507,7 @@ function PolicySetupWizardBody({{isRouting && routingConfig?.({ value: routing, onChange: setRouting })}- {!isClassification && (+ {!isClassification && !isRouting && (<div className="portal-policies__wizard-section"><p className="portal-policies__wizard-desc">{t(diff --git a/frontend/editor/src/proprietary/data/classificationConditions.ts b/frontend/editor/src/proprietary/data/classificationConditions.tsindex e2bf26ee03..18e1bc4936 100644--- a/frontend/editor/src/proprietary/data/classificationConditions.ts+++ b/frontend/editor/src/proprietary/data/classificationConditions.ts@@ -11,6 +11,18 @@ export function classificationCondition(};}+/** Creates a deterministic comparison against facts read directly from the document. */+export function documentFieldCondition(+ field: string,+ values: string[] = [],+): MatchesAnyCondition {+ return {+ input: { source: "document", field },+ operator: "matches-any",+ values,+ };+}+/** Classification facts require a classifier-produced verdict; unrelated facts do not. */export function requiresClassification(condition: Condition): boolean {return (diff --git a/frontend/editor/src/proprietary/policies/catalog.ts b/frontend/editor/src/proprietary/policies/catalog.tsindex 563ce614f0..dcfc77f5e9 100644--- a/frontend/editor/src/proprietary/policies/catalog.ts+++ b/frontend/editor/src/proprietary/policies/catalog.ts@@ -56,6 +56,7 @@ export interface PolicyState {/** The saved destinations and per-document routes; the routing category edits these. */outputIds?: string[];routingRules?: WireRoutingRule[];+ trigger?: WireTriggerConfig | null;configured: boolean;status: PolicyStatus;/** A policy rather than an ordinary pipeline (see `Policy.required`). */