Skip to content

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

Record policy-run failures as durable, actionable events (Review Flow PR 1) (#7269)

EthanHealy01c9293864428c
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/AcknowledgeAction.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/AcknowledgeAction.java
new file mode 100644
index 0000000000..7f8741b3d3
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/AcknowledgeAction.java
@@ -0,0 +1,39 @@
+package stirling.software.proprietary.failure;
+
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+
+/**
+ * "Seen, and I own it." Moves {@code NEW} to {@code ACKNOWLEDGED} so the row stops counting as
+ * unread while staying in the open list. Touches only the status, not the document, ledger or run.
+ *
+ * <p>Re-acknowledging is a no-op that keeps the original actor and timestamp, so the first person
+ * to pick it up stays credited.
+ */
+@Component
+@RequiredArgsConstructor
+public class AcknowledgeAction implements FailureAction {
+
+ private final FileRunEventStore store;
+
+ @Override
+ public FailureActionId id() {
+ return FailureActionId.ACKNOWLEDGE;
+ }
+
+ @Override
+ public FileRunEvent execute(FileRunEvent event, Map<String, String> inputs, String actor) {
+ // Guarded on NEW so a racing acknowledger cannot re-stamp the row, and so re-acknowledging
+ // returns the first actor's row rather than taking their credit.
+ return store.applyStatusOnce(
+ event.id(),
+ event.teamId(),
+ FileRunEventStatus.ACKNOWLEDGED,
+ actor,
+ List.of(FileRunEventStatus.NEW));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/DismissAction.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/DismissAction.java
new file mode 100644
index 0000000000..3ea22df414
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/DismissAction.java
@@ -0,0 +1,32 @@
+package stirling.software.proprietary.failure;
+
+import java.util.Map;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+
+/**
+ * "No remediation will happen; close it." Terminal. Named Dismiss rather than Reject because it
+ * closes the incident, not the document: nothing is deleted or delivered, the ledger row is left
+ * alone, and a different file failing the same way still opens its own incident.
+ *
+ * <p>Recurrences of this exact failure fold onto the dismissed row, which is what makes "stop
+ * showing me this" hold for a source that re-lists the same failing file each sweep.
+ */
+@Component
+@RequiredArgsConstructor
+public class DismissAction implements FailureAction {
+
+ private final FileRunEventStore store;
+
+ @Override
+ public FailureActionId id() {
+ return FailureActionId.DISMISS;
+ }
+
+ @Override
+ public FileRunEvent execute(FileRunEvent event, Map<String, String> inputs, String actor) {
+ return store.applyStatus(event.id(), event.teamId(), FileRunEventStatus.DISMISSED, actor);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureAction.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureAction.java
new file mode 100644
index 0000000000..98c8ae328c
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureAction.java
@@ -0,0 +1,23 @@
+package stirling.software.proprietary.failure;
+
+import java.util.Map;
+
+/**
+ * The behaviour behind one {@link FailureActionId}. Implementations are Spring beans injected as a
+ * {@code List} and resolved by id, the pattern already used for {@code InputSource}, {@code
+ * PolicyOutputSink} and {@code PolicyTrigger}.
+ *
+ * <p>Keeping behaviour out of the registry keeps that pure data, so a new kind ships by declaring
+ * an action id that already has a handler.
+ */
+public interface FailureAction {
+
+ FailureActionId id();
+
+ /**
+ * Apply the action and return the updated event. {@code inputs} carries whatever the action
+ * declared it needs, which is nothing for the two that exist today. Implementations leave the
+ * document, ledger, run and output destinations alone unless that is the action's purpose.
+ */
+ FileRunEvent execute(FileRunEvent event, Map<String, String> inputs, String actor);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionException.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionException.java
new file mode 100644
index 0000000000..1c899ab529
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionException.java
@@ -0,0 +1,49 @@
+package stirling.software.proprietary.failure;
+
+import lombok.Getter;
+
+/**
+ * Why an action could not be dispatched. Carries a {@link Reason} rather than an HTTP status, so
+ * the service stays web-agnostic and the controller owns the mapping.
+ */
+@Getter
+public class FailureActionException extends RuntimeException {
+
+ public enum Reason {
+ /**
+ * No such event, it belongs to another team, or the caller's team did not resolve. One
+ * reason for all three, so the response does not vary with which it was. Unrelated to
+ * {@link FailureKind#UNKNOWN}, which is an unclassified failure rather than a refused
+ * action.
+ */
+ EVENT_NOT_FOUND,
+
+ /** The action id is not in the vocabulary at all, or has no registered handler. */
+ ACTION_NOT_RECOGNISED,
+
+ /**
+ * The action exists but this kind does not declare it, so an incoherent pairing (releasing
+ * a document whose destination is what failed) cannot be dispatched even by hand.
+ *
+ * <p>Unreachable today: both kinds declare both actions, so no request can trip this guard
+ * until a kind ships with a restricted action set. Declared now because the guard must
+ * exist before that kind does, not after.
+ */
+ ACTION_NOT_DECLARED,
+
+ /** The event is already closed, so no further transition is possible. */
+ ALREADY_CLOSED
+ }
+
+ private final Reason reason;
+
+ public FailureActionException(Reason reason, String message) {
+ this(reason, message, null);
+ }
+
+ /** For a refusal that follows from a lower-level failure, so its stack is not dropped. */
+ public FailureActionException(Reason reason, String message, Throwable cause) {
+ super(message, cause);
+ this.reason = reason;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java
new file mode 100644
index 0000000000..dbfcff7fb4
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java
@@ -0,0 +1,11 @@
+package stirling.software.proprietary.failure;
+
+/**
+ * The actions a {@link FailureKind} may declare. Both are incident dispositions: they change how
+ * the event is shown and touch nothing else, which is what makes them valid for every kind
+ * including {@link FailureKind#UNKNOWN}, and why there is no {@code APPROVE} yet.
+ */
+public enum FailureActionId {
+ ACKNOWLEDGE,
+ DISMISS
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionRegistry.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionRegistry.java
new file mode 100644
index 0000000000..3928e91845
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionRegistry.java
@@ -0,0 +1,68 @@
+package stirling.software.proprietary.failure;
+
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import org.springframework.stereotype.Service;
+
+import jakarta.annotation.PostConstruct;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Resolves a {@link FailureActionId} to the bean that implements it. The startup check is the
+ * point: because kinds declare action ids as data, one could name an action nobody implements,
+ * which would otherwise show up as a button that 400s rather than as a failed boot.
+ */
+@Slf4j
+@Service
+public class FailureActionRegistry {
+
+ private final Map<FailureActionId, FailureAction> byId = new EnumMap<>(FailureActionId.class);
+
+ public FailureActionRegistry(List<FailureAction> actions) {
+ for (FailureAction action : actions) {
+ FailureAction clash = byId.put(action.id(), action);
+ if (clash != null) {
+ throw new IllegalStateException(
+ "Two handlers registered for action "
+ + action.id()
+ + ": "
+ + clash.getClass().getName()
+ + " and "
+ + action.getClass().getName());
+ }
+ }
+ }
+
+ /**
+ * Fail fast if any kind declares an action with no handler, naming every gap rather than the
+ * first, so one boot tells you everything that is missing.
+ */
+ @PostConstruct
+ void verifyEveryDeclaredActionHasAHandler() {
+ List<String> gaps =
+ Arrays.stream(FailureKind.values())
+ .flatMap(
+ kind ->
+ kind.getActions().stream()
+ .filter(action -> !byId.containsKey(action))
+ .map(action -> kind.getId() + " -> " + action))
+ .toList();
+ if (!gaps.isEmpty()) {
+ throw new IllegalStateException(
+ "Failure kinds declare actions with no registered handler: " + gaps);
+ }
+ log.debug(
+ "Failure action registry initialised with {} handler(s) for {} kind(s)",
+ byId.size(),
+ FailureKind.values().length);
+ }
+
+ public Optional<FailureAction> find(FailureActionId id) {
+ return Optional.ofNullable(byId.get(id));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureClassifier.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureClassifier.java
new file mode 100644
index 0000000000..e3350225a5
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureClassifier.java
@@ -0,0 +1,109 @@
+package stirling.software.proprietary.failure;
+
+import java.util.List;
+
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestClientResponseException;
+
+import jakarta.annotation.PostConstruct;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.util.ExceptionUtils;
+
+import tools.jackson.core.JacksonException;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+
+/**
+ * Maps a thrown failure onto a {@link FailureKind}. A tool's 4xx arrives as a {@link
+ * RestClientResponseException} whose body is the Problem Details document carrying {@code
+ * errorCode}, so this matches on codes rather than exception messages.
+ *
+ * <p>Anything unrecognised becomes {@link FailureKind#UNKNOWN}, so every failed run still gets a
+ * record.
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class FailureClassifier {
+
+ /** Set by {@code GlobalExceptionHandler#createProblemDetailResponse}. */
+ private static final String ERROR_CODE_PROPERTY = "errorCode";
+
+ /**
+ * Depth bound on the cause chain. The JDK forbids self-causation but not a longer cycle (A
+ * caused by B caused by A), which an unbounded walk would spin on. Real chains are a handful
+ * deep.
+ */
+ private static final int MAX_CAUSE_DEPTH = 16;
+
+ private final ObjectMapper objectMapper;
+
+ /**
+ * Refuse to start on an ambiguous registry: two kinds claiming one code would make {@link
+ * #classify} depend on declaration order. Checked here because this is what resolves codes to
+ * kinds, and at boot so the message names the codes rather than arriving as a class-init error.
+ */
+ @PostConstruct
+ void verifyNoErrorCodeIsClaimedTwice() {
+ List<String> duplicates = FailureKind.duplicateErrorCodes();
+ if (!duplicates.isEmpty()) {
+ throw new IllegalStateException(
+ "Error codes claimed by more than one failure kind: " + duplicates);
+ }
+ }
+
+ /** Never null, never throws. A classifier that can fail would lose the failure it describes. */
+ public FailureKind classify(Throwable throwable) {
+ Throwable current = throwable;
+ for (int depth = 0; current != null && depth < MAX_CAUSE_DEPTH; depth++) {
+ FailureKind resolved = classifyOne(current);
+ if (resolved != FailureKind.UNKNOWN) {
+ return resolved;
+ }
+ Throwable cause = current.getCause();
+ current = cause == current ? null : cause;
+ }
+ return FailureKind.UNKNOWN;
+ }
+
+ private FailureKind classifyOne(Throwable throwable) {
+ // A tool step's 4xx/5xx: the Problem Details body names the error code.
+ if (throwable instanceof RestClientResponseException responseException) {
+ String code = errorCodeFromBody(responseException);
+ if (code != null) {
+ return FailureKind.byErrorCode(code).orElse(FailureKind.UNKNOWN);
+ }
+ }
+ // Thrown in-process (not over loopback): the exception carries its own code.
+ if (throwable instanceof ExceptionUtils.ErrorCodeProvider provider) {
+ return FailureKind.byErrorCode(provider.getErrorCode()).orElse(FailureKind.UNKNOWN);
+ }
+ return FailureKind.UNKNOWN;
+ }
+
+ /**
+ * Pull {@code errorCode} from a Problem Details body, or null when the body is absent, not
+ * JSON, or has no such property (an entitlement sentinel has {@code error} instead).
+ */
+ private String errorCodeFromBody(RestClientResponseException exception) {
+ String body = exception.getResponseBodyAsString();
+ if (body == null || body.isBlank()) {
+ return null;
+ }
+ try {
+ JsonNode root = objectMapper.readTree(body);
+ JsonNode code = root.get(ERROR_CODE_PROPERTY);
+ if (code == null || !code.isTextual()) {
+ return null;
+ }
+ String text = code.asString();
+ return text.isBlank() ? null : text;
+ } catch (JacksonException e) {
+ log.debug("Downstream error body was not JSON; classifying as UNKNOWN");
+ return null;
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
new file mode 100644
index 0000000000..d46f2d85e1
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
@@ -0,0 +1,236 @@
+package stirling.software.proprietary.failure;
+
+import static stirling.software.proprietary.failure.FailureActionId.ACKNOWLEDGE;
+import static stirling.software.proprietary.failure.FailureActionId.DISMISS;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Stream;
+
+import lombok.AccessLevel;
+import lombok.Getter;
+
+/**
+ * The registry of failure kinds, described as data: a stable id, i18n keys and an English fallback
+ * like {@code ExceptionUtils.ErrorCode}, plus the facets a review surface needs.
+ *
+ * <p>Actions are declared here but implemented in {@link FailureAction} beans resolved by id, so a
+ * new kind ships as a registry entry plus copy. Two members today: {@link #UNKNOWN} gives every
+ * failed run a record, and kinds get promoted out of it as production shows what occurs.
+ */
+@Getter
+public enum FailureKind {
+ INPUT_PASSWORD_PROTECTED(
+ FailureStage.INPUT,
+ FailureSeverity.ERROR,
+ FailureRemedy.NEEDS_USER_INPUT,
+ FailureScope.FILE,
+ errorCodes("E004"),
+ fallback("This document is password-protected, so the pipeline could not read it."),
+ offer(ACKNOWLEDGE),
+ offer(DISMISS, "dismissSkipFile")),
+
+ UNKNOWN(
+ FailureStage.INTERNAL,
+ FailureSeverity.ERROR,
+ FailureRemedy.PERMANENT,
+ FailureScope.RUN,
+ noErrorCodes(),
+ fallback("This run failed for a reason Stirling does not yet recognise."),
+ offer(ACKNOWLEDGE),
+ offer(DISMISS));
+
+ private static final String KEY_PREFIX = "portal.failures.kind.";
+ private static final String ACTION_KEY_PREFIX = "portal.failures.action.";
+
+ /**
+ * Every claimed {@code ErrorCode}, to the kind claiming it. Indexed once rather than scanned
+ * per lookup, so a duplicate cannot be resolved by declaration order without anyone noticing. A
+ * duplicate is refused at boot; see {@link #duplicateErrorCodes()}.
+ */
+ private static final Map<String, FailureKind> BY_ERROR_CODE = indexErrorCodes();
+
+ private final FailureStage stage;
+ private final FailureSeverity severity;
+ private final FailureRemedy remedy;
+ private final FailureScope scope;
+
+ /** English fallback, used when the client has no translation for {@link #getTitleKey()}. */
+ private final String defaultTitle;
+
+ /** Codes from {@code ExceptionUtils.ErrorCode} that map onto this kind; may be empty. */
+ private final List<String> errorCodes;
+
+ /**
+ * What the review surface may offer, in display order. Never empty. No generated accessor,
+ * because {@link Offer} is private; read via {@link #getActions()} or {@link #labelKeyFor}.
+ */
+ @Getter(AccessLevel.NONE)
+ private final List<Offer> offers;
+
+ FailureKind(
+ FailureStage stage,
+ FailureSeverity severity,
+ FailureRemedy remedy,
+ FailureScope scope,
+ List<String> errorCodes,
+ String defaultTitle,
+ Offer... offers) {
+ this.stage = stage;
+ this.severity = severity;
+ this.remedy = remedy;
+ this.scope = scope;
+ this.errorCodes = List.copyOf(errorCodes);
+ this.defaultTitle = defaultTitle;
+ this.offers = List.of(offers);
+ }
+
+ /**
+ * One action this kind offers, with the key to label it by. One ordered list rather than ids
+ * plus a parallel map of overrides, which could disagree with each other.
+ *
+ * @param labelKeySuffix key under {@code portal.failures.action.}, or null for the generic
+ * label
+ */
+ private record Offer(FailureActionId id, String labelKeySuffix) {}
+
+ /** An action labelled by this kind's own wording, where the generic label reads badly. */
+ private static Offer offer(FailureActionId id, String labelKeySuffix) {
+ return new Offer(id, labelKeySuffix);
+ }
+
+ /** An action labelled by the shared wording for that action. */
+ private static Offer offer(FailureActionId id) {
+ return new Offer(id, null);
+ }
+
+ /**
+ * The {@code ErrorCode}s this kind claims. Java has no named arguments, so these factories
+ * exist to label the two constructor arguments whose types do not already name themselves.
+ */
+ private static List<String> errorCodes(String... codes) {
+ return List.of(codes);
+ }
+
+ /** Claims no {@code ErrorCode}: reached only through the classifier's fallback. */
+ private static List<String> noErrorCodes() {
+ return List.of();
+ }
+
+ /** The English text shown when the client has no translation for this kind. */
+ private static String fallback(String englishTitle) {
+ return englishTitle;
+ }
+
+ /** Stable wire id. Never renamed once shipped: persisted rows reference it. */
+ public String getId() {
+ return name();
+ }
+
+ public String getTitleKey() {
+ return KEY_PREFIX + lowerCamelId() + ".title";
+ }
+
+ public String getDescriptionKey() {
+ return KEY_PREFIX + lowerCamelId() + ".description";
+ }
+
+ /** The actions this kind offers, in display order. */
+ public List<FailureActionId> getActions() {
+ return offers.stream().map(Offer::id).toList();
+ }
+
+ /** Whether this kind offers {@code action}. The dispatch guard: see {@code FailureActionId}. */
+ public boolean declares(FailureActionId action) {
+ return offers.stream().anyMatch(offer -> offer.id() == action);
+ }
+
+ /** The label key for {@code action}: this kind's own wording, else the generic one. */
+ public String labelKeyFor(FailureActionId action) {
+ return offers.stream()
+ .filter(offer -> offer.id() == action && offer.labelKeySuffix() != null)
+ .map(offer -> ACTION_KEY_PREFIX + offer.labelKeySuffix())
+ .findFirst()
+ .orElseGet(() -> genericLabelKey(action));
+ }
+
+ /** The label key used when a kind supplies no wording of its own. */
+ static String genericLabelKey(FailureActionId action) {
+ return ACTION_KEY_PREFIX + toLowerCamel(action.name());
+ }
+
+ /**
+ * Lookup by wire id. Empty rather than throwing: ids arrive from persisted rows and clients.
+ */
+ public static Optional<FailureKind> byId(String id) {
+ if (id == null || id.isBlank()) {
+ return Optional.empty();
+ }
+ return Arrays.stream(values()).filter(kind -> kind.name().equals(id)).findFirst();
+ }
+
+ private static Map<String, FailureKind> indexErrorCodes() {
+ Map<String, FailureKind> index = new HashMap<>();
+ for (FailureKind kind : values()) {
+ for (String code : kind.errorCodes) {
+ index.putIfAbsent(code, kind);
+ }
+ }
+ return Map.copyOf(index);
+ }
+
+ /**
+ * Codes claimed by more than one kind, which would make classification depend on declaration
+ * order. Empty in a well-formed registry.
+ *
+ * <p>Reported for a caller to act on rather than thrown from class init, where it would arrive
+ * as an {@code ExceptionInInitializerError} blamed on whatever touched the enum first, then as
+ * {@code NoClassDefFoundError} everywhere after. {@link FailureClassifier} refuses to start.
+ */
+ static List<String> duplicateErrorCodes() {
+ return duplicatesIn(Arrays.stream(values()).flatMap(kind -> kind.errorCodes.stream()));
+ }
+
+ /**
+ * The codes appearing more than once, first-seen order. Split out from the registry because the
+ * registry is a closed enum: this is the only seam at which the detection itself can be shown
+ * to find anything.
+ */
+ static List<String> duplicatesIn(Stream<String> codes) {
+ Set<String> seen = new HashSet<>();
+ return codes.filter(code -> !seen.add(code)).distinct().toList();
+ }
+
+ /** The kind claiming {@code errorCode}, if any. Empty for a code no kind has adopted yet. */
+ public static Optional<FailureKind> byErrorCode(String errorCode) {
+ if (errorCode == null || errorCode.isBlank()) {
+ return Optional.empty();
+ }
+ return Optional.ofNullable(BY_ERROR_CODE.get(errorCode));
+ }
+
+ private String lowerCamelId() {
+ return toLowerCamel(name());
+ }
+
+ /**
+ * {@code INPUT_PASSWORD_PROTECTED} to {@code inputPasswordProtected}, for i18n key building.
+ */
+ private static String toLowerCamel(String screamingSnake) {
+ String[] parts = screamingSnake.toLowerCase(Locale.ROOT).split("_");
+ StringBuilder out = new StringBuilder(parts[0]);
+ for (int i = 1; i < parts.length; i++) {
+ if (parts[i].isEmpty()) {
+ continue;
+ }
+ out.append(Character.toUpperCase(parts[i].charAt(0))).append(parts[i].substring(1));
+ }
+ return out.toString();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKindView.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKindView.java
new file mode 100644
index 0000000000..b3e2145ba3
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKindView.java
@@ -0,0 +1,43 @@
+package stirling.software.proprietary.failure;
+
+import java.util.List;
+
+/**
+ * Wire shape of one registry entry, served so a client can describe kinds it was not built with.
+ * Also a feature probe: a build without the proprietary module has no such route, so a 404 means
+ * there is no failure tracking here.
+ */
+public record FailureKindView(
+ String id,
+ FailureStage stage,
+ FailureSeverity severity,
+ FailureRemedy remedy,
+ FailureScope scope,
+ List<String> errorCodes,
+ String titleKey,
+ String descriptionKey,
+ String defaultTitle,
+ List<ActionDeclaration> actions) {
+
+ public static FailureKindView of(FailureKind kind) {
+ return new FailureKindView(
+ kind.getId(),
+ kind.getStage(),
+ kind.getSeverity(),
+ kind.getRemedy(),
+ kind.getScope(),
+ kind.getErrorCodes(),
+ kind.getTitleKey(),
+ kind.getDescriptionKey(),
+ kind.getDefaultTitle(),
+ kind.getActions().stream()
+ .map(
+ action ->
+ new ActionDeclaration(
+ action.name(), kind.labelKeyFor(action)))
+ .toList());
+ }
+
+ /** An action this kind offers, with the label key to render it by. */
+ public record ActionDeclaration(String id, String labelKey) {}
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureOrigin.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureOrigin.java
new file mode 100644
index 0000000000..78194b610e
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureOrigin.java
@@ -0,0 +1,23 @@
+package stirling.software.proprietary.failure;
+
+/**
+ * What kind of run failed, not where it was started from. A policy is a policy whether a schedule
+ * fired it or someone clicked Run in the editor, so the two questions are answered separately:
+ * {@code actor} names the person for an attended run and {@code sourceId} names the folder, bucket
+ * or webhook for an unattended one.
+ */
+public enum FailureOrigin {
+
+ /** One tool called directly, with no policy around it. Today that means the editor. */
+ TOOL,
+
+ /** The policy engine ran it, however the run was triggered. */
+ POLICY,
+
+ /**
+ * The watched-folder pipeline that predates policies. Declared ahead of its producer: nothing
+ * writes this yet, because that pipeline records no failures at all. Instrumenting it is its
+ * own piece of work.
+ */
+ PIPELINE
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureRemedy.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureRemedy.java
new file mode 100644
index 0000000000..966c727065
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureRemedy.java
@@ -0,0 +1,14 @@
+package stirling.software.proprietary.failure;
+
+/**
+ * What intervention would clear this failure. Advisory metadata for the review surface; nothing
+ * branches on it server-side yet.
+ */
+public enum FailureRemedy {
+ TRANSIENT,
+ NEEDS_USER_INPUT,
+ NEEDS_FILE_FIX,
+ NEEDS_CONFIG_FIX,
+ NEEDS_SERVER_FIX,
+ PERMANENT
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureScope.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureScope.java
new file mode 100644
index 0000000000..a6b882ce5d
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureScope.java
@@ -0,0 +1,13 @@
+package stirling.software.proprietary.failure;
+
+/**
+ * What the failure is about, which is what the dedup key groups repeats by: one file, run, policy,
+ * source, or the whole server.
+ */
+public enum FailureScope {
+ FILE,
+ RUN,
+ POLICY,
+ SOURCE,
+ SERVER
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureSeverity.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureSeverity.java
new file mode 100644
index 0000000000..f5d097a13d
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureSeverity.java
@@ -0,0 +1,8 @@
+package stirling.software.proprietary.failure;
+
+/** How loudly a failure kind should be surfaced. */
+public enum FailureSeverity {
+ ERROR,
+ WARNING,
+ INFO
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureStage.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureStage.java
new file mode 100644
index 0000000000..f1aca8f9ed
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureStage.java
@@ -0,0 +1,17 @@
+package stirling.software.proprietary.failure;
+
+/**
+ * Where in a run's life the failure happened: reading the document ({@code INPUT}), a tool step or
+ * the engine ({@code INTERNAL}), delivery ({@code OUTPUT}), a gate refusing it ({@code BLOCKED}),
+ * or never admitted ({@code NEVER_RAN}).
+ *
+ * <p>All five declared up front so a later kind needs no enum change, which would strand the value
+ * already snapshotted on existing rows.
+ */
+public enum FailureStage {
+ INPUT,
+ INTERNAL,
+ OUTPUT,
+ BLOCKED,
+ NEVER_RAN
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEvent.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEvent.java
new file mode 100644
index 0000000000..cb6b3a452f
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEvent.java
@@ -0,0 +1,59 @@
+package stirling.software.proprietary.failure;
+
+import java.time.Instant;
+
+/**
+ * Read model for one recorded incident: the entity's fields with the registry kind already
+ * resolved.
+ *
+ * <p>The facets are the row's own snapshots and can differ from {@code kind}'s current facets on an
+ * old row, which is the point of snapshotting, so read them here rather than from {@code kind}.
+ */
+public record FileRunEvent(
+ String id,
+ Long teamId,
+ String actor,
+ FailureKind kind,
+ FailureStage stage,
+ FailureSeverity severity,
+ FailureScope scope,
+ FailureOrigin origin,
+ String policyId,
+ String runId,
+ String fileId,
+ String detail,
+ String dedupKey,
+ int occurrences,
+ FileRunEventStatus status,
+ String statusActor,
+ Instant statusAt,
+ Instant createdAt,
+ Instant lastSeenAt) {
+
+ /**
+ * Project an entity. An unrecognised {@code kindId} (written by a newer build, or since
+ * removed) falls back to {@link FailureKind#UNKNOWN}, so the row stays readable and actionable.
+ */
+ public static FileRunEvent of(FileRunEventEntity entity) {
+ return new FileRunEvent(
+ entity.getId(),
+ entity.getTeamId(),
+ entity.getActor(),
+ FailureKind.byId(entity.getKindId()).orElse(FailureKind.UNKNOWN),
+ entity.getStage(),
+ entity.getSeverity(),
+ entity.getScope(),
+ entity.getOrigin(),
+ entity.getPolicyId(),
+ entity.getRunId(),
+ entity.getFileId(),
+ entity.getDetail(),
+ entity.getDedupKey(),
+ entity.getOccurrences(),
+ entity.getStatus(),
+ entity.getStatusActor(),
+ entity.getStatusAt(),
+ entity.getCreatedAt(),
+ entity.getLastSeenAt());
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventController.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventController.java
new file mode 100644
index 0000000000..49aab9aff6
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventController.java
@@ -0,0 +1,146 @@
+package stirling.software.proprietary.failure;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.server.ResponseStatusException;
+
+import io.swagger.v3.oas.annotations.Hidden;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
+
+/**
+ * Read and triage recorded failures for the caller's team. Note the absence of a team parameter:
+ * the team comes from the authenticated principal, never the request.
+ *
+ * <p>Reviewing failures is a leader-level capability, gated the same way policy editing is: see
+ * {@link #requireFailureReviewAllowed()}.
+ */
+@Slf4j
+@RestController
+@RequestMapping("/api/v1/file-run-events")
+@Hidden
+@RequiredArgsConstructor
+@Tag(name = "File run events", description = "Recorded policy and pipeline failures")
+public class FileRunEventController {
+
+ /** Cap on one page, so a client cannot ask for the whole table. */
+ private static final int MAX_LIMIT = 200;
+
+ private static final int DEFAULT_LIMIT = 50;
+
+ private final FileRunEventService service;
+ private final PolicyManagementAuthority policyManagementAuthority;
+ private final ApplicationProperties applicationProperties;
+
+ @GetMapping
+ @Operation(
+ summary = "List recorded failures",
+ description =
+ "Failures recorded for the caller's team, newest first. Each row carries its"
+ + " available actions already resolved.")
+ public FileRunEventsResponse list(
+ // Spring's converter 400s on a value outside the enum, so no hand-rolled parse.
+ @RequestParam(required = false) FileRunEventStatus status,
+ @RequestParam(required = false) String kindId,
+ @RequestParam(required = false) Integer limit) {
+ requireFailureReviewAllowed();
+ int cappedLimit = Math.min(limit == null ? DEFAULT_LIMIT : Math.max(1, limit), MAX_LIMIT);
+
+ List<FileRunEventView> events =
+ // The kind filter is part of the query, before the limit is applied: filtering an
+ // already-limited page could return nothing while matching rows exist.
+ service.list(status, kindId, cappedLimit).stream()
+ .map(event -> FileRunEventView.of(event, service.availableActions(event)))
+ .toList();
+ return new FileRunEventsResponse(events);
+ }
+
+ @PostMapping("/{eventId}/actions/{actionId}")
+ @Operation(
+ summary = "Apply an action to a recorded failure",
+ description =
+ "Rejected with 400 if the failure's kind does not declare the action, so an"
+ + " action that makes no sense for a given failure cannot be applied.")
+ public FileRunEventView act(
+ @PathVariable String eventId,
+ @PathVariable String actionId,
+ @RequestBody(required = false) ActionRequest request) {
+ requireFailureReviewAllowed();
+ Map<String, String> inputs = request == null ? Map.of() : request.safeInputs();
+ try {
+ FileRunEvent updated = service.dispatch(eventId, actionId, inputs);
+ return FileRunEventView.of(updated, service.availableActions(updated));
+ } catch (FailureActionException e) {
+ throw new ResponseStatusException(statusFor(e.getReason()), e.getMessage(), e);
+ }
+ }
+
+ @GetMapping("/kinds")
+ @Operation(
+ summary = "List known failure kinds",
+ description =
+ "The failure registry. Lets a client describe kinds it was not built with, and"
+ + " doubles as the probe for whether failure tracking exists at all.")
+ public List<FailureKindView> kinds() {
+ requireFailureReviewAllowed();
+ return Arrays.stream(FailureKind.values()).map(FailureKindView::of).toList();
+ }
+
+ /**
+ * Triage is for a team leader (SaaS) or admin (self-hosted), mirroring {@code
+ * PolicyController.requirePolicyEditingAllowed()} rather than inventing a second notion of who
+ * manages a team's automation: a member can trigger runs, a leader reviews them.
+ *
+ * <p>Login disabled means a single-user deployment with no roles to tell apart, the same
+ * carve-out the policy endpoints make. Team scoping is separate, and lives in the service.
+ */
+ private void requireFailureReviewAllowed() {
+ if (!applicationProperties.getSecurity().isEnableLogin()) {
+ return;
+ }
+ if (!policyManagementAuthority.canEditPolicies()) {
+ throw new ResponseStatusException(
+ HttpStatus.FORBIDDEN,
+ "Recorded failures may only be reviewed by a team leader");
+ }
+ }
+
+ /**
+ * A closed row is a conflict rather than a bad request: the request was well-formed and would
+ * have been valid a moment earlier.
+ */
+ private static HttpStatus statusFor(FailureActionException.Reason reason) {
+ return switch (reason) {
+ case EVENT_NOT_FOUND -> HttpStatus.NOT_FOUND;
+ case ACTION_NOT_RECOGNISED, ACTION_NOT_DECLARED -> HttpStatus.BAD_REQUEST;
+ case ALREADY_CLOSED -> HttpStatus.CONFLICT;
+ };
+ }
+
+ /** Wrapped rather than a bare array so pagination can be added without breaking clients. */
+ public record FileRunEventsResponse(List<FileRunEventView> events) {}
+
+ /** Inputs an action declared it needs. Empty for both actions that exist today. */
+ public record ActionRequest(Map<String, String> inputs) {
+
+ Map<String, String> safeInputs() {
+ return inputs == null ? Map.of() : inputs;
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventEntity.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventEntity.java
new file mode 100644
index 0000000000..9659941fc9
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventEntity.java
@@ -0,0 +1,116 @@
+package stirling.software.proprietary.failure;
+
+import java.io.Serializable;
+import java.time.Instant;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EnumType;
+import jakarta.persistence.Enumerated;
+import jakarta.persistence.Id;
+import jakarta.persistence.Index;
+import jakarta.persistence.Table;
+import jakarta.persistence.UniqueConstraint;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+/**
+ * One recorded failure incident. {@code actor} and {@code teamId} are plain values rather than
+ * foreign keys, matching {@link stirling.software.proprietary.policy.source.SourceEntity}, and the
+ * facets are snapshots at write time so re-classifying a kind never rewrites an old row.
+ *
+ * <p>Holds no document name or content: {@code fileId} is opaque, and {@code detail} is stripped of
+ * names by {@link RecordFailure}.
+ */
+@Entity
+@Table(
+ name = "file_run_events",
+ indexes = {
+ // the review surface: this team's rows, newest first, optionally filtered by status
+ @Index(name = "idx_file_run_events_team", columnList = "team_id, status, last_seen_at")
+ },
+ // One row per incident, enforced by the database rather than only by the store's read-then-
+ // insert: two runs failing identically at the same moment would otherwise both find no row
+ // and both insert, leaving a twin that reappears after the first is dismissed. Doubles as
+ // the
+ // rollup's lookup index. Note SQL treats NULLs as distinct, so this does not constrain the
+ // unteamed rows a login-disabled deployment writes.
+ uniqueConstraints =
+ @UniqueConstraint(
+ name = "uk_file_run_events_dedup",
+ columnNames = {"team_id", "dedup_key"}))
+@NoArgsConstructor
+@Getter
+@Setter
+public class FileRunEventEntity implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name = "id")
+ private String id;
+
+ @Column(name = "team_id")
+ private Long teamId;
+
+ /** The user whose work produced the failure. Null when login is disabled. */
+ @Column(name = "actor")
+ private String actor;
+
+ @Column(name = "kind_id", nullable = false)
+ private String kindId;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "stage", nullable = false)
+ private FailureStage stage;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "severity", nullable = false)
+ private FailureSeverity severity;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "scope", nullable = false)
+ private FailureScope scope;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "origin", nullable = false)
+ private FailureOrigin origin;
+
+ @Column(name = "policy_id")
+ private String policyId;
+
+ @Column(name = "run_id")
+ private String runId;
+
+ @Column(name = "file_id")
+ private String fileId;
+
+ @Column(name = "detail", columnDefinition = "text")
+ private String detail;
+
+ @Column(name = "dedup_key", length = 64, nullable = false)
+ private String dedupKey;
+
+ /** How many times this same failure has been seen. Starts at 1; the rollup increments it. */
+ @Column(name = "occurrences", nullable = false)
+ private int occurrences;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "status", nullable = false)
+ private FileRunEventStatus status;
+
+ /** Who last changed {@link #status}. Null while the row is untouched. */
+ @Column(name = "status_actor")
+ private String statusActor;
+
+ @Column(name = "status_at")
+ private Instant statusAt;
+
+ @Column(name = "created_at", nullable = false)
+ private Instant createdAt;
+
+ @Column(name = "last_seen_at", nullable = false)
+ private Instant lastSeenAt;
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventRepository.java
new file mode 100644
index 0000000000..6da6a9b004
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventRepository.java
@@ -0,0 +1,104 @@
+package stirling.software.proprietary.failure;
+
+import java.time.Instant;
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+@Repository
+public interface FileRunEventRepository extends JpaRepository<FileRunEventEntity, String> {
+
+ /**
+ * This team's events, newest first, scoped in the query rather than loaded and filtered. A
+ * {@code null} teamId matches the rows with no team (login disabled), mirroring {@link
+ * stirling.software.proprietary.policy.source.SourceRepository#findByTeam}, since a plain
+ * {@code = null} would return nothing.
+ */
+ @Query(
+ "select e from FileRunEventEntity e where ((:teamId is null and e.teamId is null) or"
+ + " e.teamId = :teamId) and (:kindId is null or e.kindId = :kindId)"
+ + " order by e.lastSeenAt desc")
+ List<FileRunEventEntity> findByTeam(
+ @Param("teamId") Long teamId, @Param("kindId") String kindId, Pageable pageable);
+
+ /** As {@link #findByTeam} but restricted to one status, for the review surface's filters. */
+ @Query(
+ "select e from FileRunEventEntity e where ((:teamId is null and e.teamId is null) or"
+ + " e.teamId = :teamId) and e.status = :status"
+ + " and (:kindId is null or e.kindId = :kindId) order by e.lastSeenAt desc")
+ List<FileRunEventEntity> findByTeamAndStatus(
+ @Param("teamId") Long teamId,
+ @Param("status") FileRunEventStatus status,
+ @Param("kindId") String kindId,
+ Pageable pageable);
+
+ /**
+ * Fold a repeat into an incident in one statement, against the row's <em>current</em> values. A
+ * read-modify-save here would be a merge of a possibly stale snapshot: concurrent folds would
+ * lose counts, and an in-flight fold could overwrite a reviewer's dismiss. Same idiom as {@code
+ * SourceDocCountRepository#increment} and friends.
+ */
+ @Modifying(clearAutomatically = true)
+ @Transactional
+ @Query(
+ "update FileRunEventEntity e set e.occurrences = e.occurrences + 1,"
+ + " e.lastSeenAt = :now, e.detail = coalesce(:detail, e.detail)"
+ + " where e.id = :id")
+ int fold(@Param("id") String id, @Param("now") Instant now, @Param("detail") String detail);
+
+ /**
+ * Reopen a resolved incident whose failure has recurred. Guarded on the current status so only
+ * {@code RESOLVED} flips; a concurrent dismiss is never overwritten back to {@code NEW}.
+ */
+ @Modifying(clearAutomatically = true)
+ @Transactional
+ @Query(
+ "update FileRunEventEntity e set"
+ + " e.status = stirling.software.proprietary.failure.FileRunEventStatus.NEW,"
+ + " e.statusActor = null, e.statusAt = null where e.id = :id and e.status ="
+ + " stirling.software.proprietary.failure.FileRunEventStatus.RESOLVED")
+ int reopenIfResolved(@Param("id") String id);
+
+ /**
+ * Apply a status transition only if the row is still in one of {@code allowedFrom}. The guard
+ * runs in the database, so two racing closes cannot both succeed: the loser updates zero rows.
+ */
+ @Modifying(clearAutomatically = true)
+ @Transactional
+ @Query(
+ "update FileRunEventEntity e set e.status = :target, e.statusActor = :actor,"
+ + " e.statusAt = :now where e.id = :id and ((:teamId is null and e.teamId is"
+ + " null) or e.teamId = :teamId) and e.status in :allowedFrom")
+ int applyStatusIf(
+ @Param("id") String id,
+ @Param("teamId") Long teamId,
+ @Param("target") FileRunEventStatus target,
+ @Param("actor") String actor,
+ @Param("now") Instant now,
+ @Param("allowedFrom") Collection<FileRunEventStatus> allowedFrom);
+
+ /**
+ * The most recent row for this exact failure, so the rollup can increment an existing incident
+ * instead of opening a new one. Team-scoped, so the same failure in two teams stays two rows.
+ */
+ @Query(
+ "select e from FileRunEventEntity e where ((:teamId is null and e.teamId is null) or"
+ + " e.teamId = :teamId) and e.dedupKey = :dedupKey order by e.lastSeenAt desc")
+ List<FileRunEventEntity> findByTeamAndDedupKey(
+ @Param("teamId") Long teamId, @Param("dedupKey") String dedupKey, Pageable pageable);
+
+ /** One row by id, but only if it belongs to {@code teamId}. */
+ @Query(
+ "select e from FileRunEventEntity e where e.id = :id and ((:teamId is null and e.teamId"
+ + " is null) or e.teamId = :teamId)")
+ Optional<FileRunEventEntity> findByIdAndTeam(
+ @Param("id") String id, @Param("teamId") Long teamId);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventService.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventService.java
new file mode 100644
index 0000000000..94b9c00a2c
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventService.java
@@ -0,0 +1,159 @@
+package stirling.software.proprietary.failure;
+
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.UserServiceInterface;
+import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
+
+/**
+ * Reads and acts on incidents for the calling user's team.
+ *
+ * <p>Team scoping mirrors {@code PolicyAccessGuard}: everyone sees only their own team's rows, the
+ * team always comes from the authenticated principal, and scoping applies only when login is
+ * enabled so single-user deployments keep working. When the team cannot be resolved the caller
+ * reads nothing; see {@link #scope()}.
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class FileRunEventService {
+
+ private final FileRunEventStore store;
+ private final FailureActionRegistry actionRegistry;
+ private final PolicyManagementAuthority policyManagementAuthority;
+ private final UserServiceInterface userService;
+ private final ApplicationProperties applicationProperties;
+
+ /** The calling user's events, newest first. Empty when their team cannot be resolved. */
+ public List<FileRunEvent> list(FileRunEventStatus status, String kindId, int limit) {
+ TeamScope scope = scope();
+ if (!scope.permitted()) {
+ return List.of();
+ }
+ return store.list(scope.teamId(), status, kindId, limit);
+ }
+
+ /**
+ * Dispatch an action against one event.
+ *
+ * @throws FailureActionException if the event is not the caller's, the action is unknown, the
+ * event's kind does not declare the action, or the event is already closed
+ */
+ public FileRunEvent dispatch(String eventId, String actionId, Map<String, String> inputs) {
+ TeamScope scope = scope();
+ if (!scope.permitted()) {
+ // Reported as "no such event", the same as an id from another team, so the response
+ // does
+ // not depend on whether the id happens to exist.
+ throw new FailureActionException(
+ FailureActionException.Reason.EVENT_NOT_FOUND, "No such event: " + eventId);
+ }
+ FileRunEvent event =
+ store.find(eventId, scope.teamId())
+ .orElseThrow(
+ () ->
+ new FailureActionException(
+ FailureActionException.Reason.EVENT_NOT_FOUND,
+ "No such event: " + eventId));
+
+ FailureActionId resolvedId = parseActionId(actionId);
+
+ // A kind that does not offer an action cannot have it applied, so an action that makes no
+ // sense for a failure is unreachable rather than merely unrendered.
+ if (!event.kind().declares(resolvedId)) {
+ throw new FailureActionException(
+ FailureActionException.Reason.ACTION_NOT_DECLARED,
+ "Kind " + event.kind().getId() + " does not offer action " + resolvedId);
+ }
+ if (event.status().terminal()) {
+ throw new FailureActionException(
+ FailureActionException.Reason.ALREADY_CLOSED,
+ "Event " + eventId + " is already " + event.status());
+ }
+
+ FailureAction action =
+ actionRegistry
+ .find(resolvedId)
+ .orElseThrow(
+ () ->
+ new FailureActionException(
+ FailureActionException.Reason.ACTION_NOT_RECOGNISED,
+ "No handler for action " + resolvedId));
+
+ return action.execute(event, inputs == null ? Map.of() : inputs, currentActor());
+ }
+
+ /**
+ * Which of an event's declared actions are usable right now. Decided per row, so the client
+ * never renders a button that would be refused.
+ */
+ public List<AvailableAction> availableActions(FileRunEvent event) {
+ boolean closed = event.status().terminal();
+ return event.kind().getActions().stream()
+ .map(
+ action ->
+ new AvailableAction(
+ action,
+ event.kind().labelKeyFor(action),
+ !closed,
+ closed ? "portal.failures.disabled.closed" : null))
+ .toList();
+ }
+
+ private FailureActionId parseActionId(String actionId) {
+ for (FailureActionId candidate : FailureActionId.values()) {
+ if (candidate.name().equals(actionId)) {
+ return candidate;
+ }
+ }
+ throw new FailureActionException(
+ FailureActionException.Reason.ACTION_NOT_RECOGNISED, "Unknown action: " + actionId);
+ }
+
+ /**
+ * Which rows the caller may touch, since a null team id means two different things. Login
+ * disabled is the self-hosted setup with no users or teams, where unteamed rows are everyone's,
+ * as {@code PolicyAccessGuard} also treats them. Login enabled with no resolvable team reads
+ * nothing, because unteamed rows there are shared by every team's ad-hoc runs.
+ */
+ private TeamScope scope() {
+ if (!enforced()) {
+ return TeamScope.of(null);
+ }
+ Long teamId = policyManagementAuthority.currentUserTeamId();
+ return teamId == null ? TeamScope.denied() : TeamScope.of(teamId);
+ }
+
+ /**
+ * The caller's readable team, or a refusal. {@code teamId} is only meaningful when permitted.
+ */
+ private record TeamScope(boolean permitted, Long teamId) {
+
+ static TeamScope of(Long teamId) {
+ return new TeamScope(true, teamId);
+ }
+
+ static TeamScope denied() {
+ return new TeamScope(false, null);
+ }
+ }
+
+ private String currentActor() {
+ return enforced() ? userService.getCurrentUsername() : null;
+ }
+
+ private boolean enforced() {
+ return applicationProperties.getSecurity().isEnableLogin();
+ }
+
+ /** One action as offered for a specific event, with its resolved availability. */
+ public record AvailableAction(
+ FailureActionId id, String labelKey, boolean enabled, String disabledReasonKey) {}
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventStatus.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventStatus.java
new file mode 100644
index 0000000000..cae0529334
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventStatus.java
@@ -0,0 +1,34 @@
+package stirling.software.proprietary.failure;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Disposition of one recorded failure. {@code RESOLVED} is declared but not set yet (it becomes
+ * system-set later); the rollup already defines what a repeat means for it, which is to reopen.
+ */
+public enum FileRunEventStatus {
+ NEW(false),
+ ACKNOWLEDGED(false),
+ DISMISSED(true),
+ RESOLVED(true);
+
+ /** The statuses a review queue shows by default: everything still needing a decision. */
+ private static final List<FileRunEventStatus> OPEN =
+ Arrays.stream(values()).filter(status -> !status.terminal).toList();
+
+ /** Whether no further transition is possible: the row is closed. */
+ private final boolean terminal;
+
+ FileRunEventStatus(boolean terminal) {
+ this.terminal = terminal;
+ }
+
+ public boolean terminal() {
+ return terminal;
+ }
+
+ public static List<FileRunEventStatus> open() {
+ return OPEN;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventStore.java
new file mode 100644
index 0000000000..e1fc7cc453
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventStore.java
@@ -0,0 +1,201 @@
+package stirling.software.proprietary.failure;
+
+import java.time.Instant;
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Durable store for recorded incidents. Who may act lives in {@link FileRunEventService}.
+ *
+ * <p>{@link #record} folds a repeat into the existing incident rather than inserting again, keyed
+ * on {@code (teamId, dedupKey)}. That matters for a stateless {@code snapshot} source, which
+ * re-lists every file on each sweep: the same broken file is one incident, not one per sweep.
+ * Distinct files keep distinct rows, so a reviewer can still act on any one of them.
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class FileRunEventStore {
+
+ /** Only ever need the newest match; the index is ordered so this is a single-row read. */
+ private static final Pageable NEWEST = PageRequest.of(0, 1);
+
+ private final FileRunEventRepository repository;
+
+ /**
+ * Record a failure, folding it into an existing incident when one matches.
+ *
+ * <p>Deliberately not {@code @Transactional}: each repository call runs in its own transaction,
+ * so losing the insert race below leaves no rolled-back transaction to recover from.
+ */
+ public FileRunEvent record(RecordFailure command) {
+ String dedupKey = command.dedupKey();
+ Instant now = Instant.now();
+
+ Optional<FileRunEvent> folded =
+ findByDedupKey(command.teamId(), dedupKey)
+ .flatMap(row -> absorb(row.getId(), command, now));
+ if (folded.isPresent()) {
+ return folded.get();
+ }
+
+ try {
+ return FileRunEvent.of(insert(command, dedupKey, now));
+ } catch (DataIntegrityViolationException e) {
+ // The unique constraint fired, so a concurrent writer inserted this incident between
+ // our read and our insert. Their row is the incident; fold into it instead of failing.
+ return findByDedupKey(command.teamId(), dedupKey)
+ .flatMap(row -> absorb(row.getId(), command, now))
+ .orElseThrow(() -> e);
+ }
+ }
+
+ private Optional<FileRunEventEntity> findByDedupKey(Long teamId, String dedupKey) {
+ return repository.findByTeamAndDedupKey(teamId, dedupKey, NEWEST).stream().findFirst();
+ }
+
+ /**
+ * Fold a repeat into an existing incident. {@code DISMISSED} stays dismissed, so a reviewer's
+ * "stop showing me this" holds; {@code RESOLVED} reopens, so a recurrence is visible again.
+ *
+ * <p>Both steps are single guarded UPDATE statements against the row's current values, never a
+ * save of the entity we read: that would merge a possibly stale snapshot over concurrent
+ * writes, losing counts and reverting a dismiss that landed in between.
+ *
+ * <p>Empty when the row went away between the caller's read and the fold, so the caller inserts
+ * instead. Reporting that as an error would lose the incident for a log line.
+ */
+ private Optional<FileRunEvent> absorb(String id, RecordFailure command, Instant now) {
+ if (repository.fold(id, now, command.detail()) == 0) {
+ return Optional.empty();
+ }
+ repository.reopenIfResolved(id);
+ return repository.findById(id).map(FileRunEvent::of);
+ }
+
+ private FileRunEventEntity insert(RecordFailure command, String dedupKey, Instant now) {
+ FailureKind kind = command.kind();
+ FileRunEventEntity entity = new FileRunEventEntity();
+ entity.setId(UUID.randomUUID().toString());
+ entity.setTeamId(command.teamId());
+ entity.setActor(command.actor());
+ entity.setKindId(kind.getId());
+ // Snapshot the facets so a later registry edit does not rewrite what this row meant.
+ entity.setStage(kind.getStage());
+ entity.setSeverity(kind.getSeverity());
+ entity.setScope(kind.getScope());
+ entity.setOrigin(command.origin());
+ entity.setPolicyId(command.policyId());
+ entity.setRunId(command.runId());
+ entity.setFileId(command.fileId());
+ entity.setDetail(command.detail());
+ entity.setDedupKey(dedupKey);
+ entity.setOccurrences(1);
+ entity.setStatus(FileRunEventStatus.NEW);
+ entity.setCreatedAt(now);
+ entity.setLastSeenAt(now);
+ // Flushed so a duplicate-key violation surfaces here, inside record()'s catch. A plain
+ // save() defers the INSERT to commit time once a caller is transactional, and the
+ // violation would escape the catch as a 500.
+ return repository.saveAndFlush(entity);
+ }
+
+ /**
+ * A page of incidents, newest first, optionally narrowed to one status and one kind. The kind
+ * filter lives in the query, before the limit: filtering a already-limited page could return
+ * nothing while matching rows exist.
+ */
+ @Transactional(readOnly = true)
+ public List<FileRunEvent> list(
+ Long teamId, FileRunEventStatus status, String kindId, int limit) {
+ Pageable page = PageRequest.of(0, Math.max(1, limit));
+ List<FileRunEventEntity> rows =
+ status == null
+ ? repository.findByTeam(teamId, kindId, page)
+ : repository.findByTeamAndStatus(teamId, status, kindId, page);
+ return rows.stream().map(FileRunEvent::of).toList();
+ }
+
+ @Transactional(readOnly = true)
+ public Optional<FileRunEvent> find(String id, Long teamId) {
+ return repository.findByIdAndTeam(id, teamId).map(FileRunEvent::of);
+ }
+
+ /**
+ * Transition an open row, refusing a closed one. The service checks {@code terminal()} before
+ * dispatching, but that check and this write are separate requests under concurrency; the
+ * guarded UPDATE is what makes two racing closes resolve to one winner.
+ *
+ * @throws FailureActionException {@code ALREADY_CLOSED} when the row exists but is terminal,
+ * {@code EVENT_NOT_FOUND} when it does not exist for this team
+ */
+ @Transactional
+ public FileRunEvent applyStatus(
+ String id, Long teamId, FileRunEventStatus target, String actor) {
+ return applyStatus(id, teamId, target, actor, FileRunEventStatus.open())
+ .orElseThrow(() -> refusalFor(id, teamId));
+ }
+
+ /**
+ * As {@link #applyStatus(String, Long, FileRunEventStatus, String)} but with the caller naming
+ * which current statuses may transition. Empty when the row exists outside {@code allowedFrom}.
+ *
+ * <p>The UPDATE runs first and nothing is read beforehand: a pre-read only to classify the
+ * refusal would be one more thing to race with, and would report a row deleted in between as
+ * closed rather than missing.
+ */
+ @Transactional
+ public Optional<FileRunEvent> applyStatus(
+ String id,
+ Long teamId,
+ FileRunEventStatus target,
+ String actor,
+ Collection<FileRunEventStatus> allowedFrom) {
+ if (repository.applyStatusIf(id, teamId, target, actor, Instant.now(), allowedFrom) == 0) {
+ return Optional.empty();
+ }
+ return repository.findByIdAndTeam(id, teamId).map(FileRunEvent::of);
+ }
+
+ /**
+ * Transition, or accept that someone else already reached {@code target}. The loser of a race
+ * reads the winner's row back rather than re-stamping it, so the first actor keeps the credit.
+ */
+ @Transactional
+ public FileRunEvent applyStatusOnce(
+ String id,
+ Long teamId,
+ FileRunEventStatus target,
+ String actor,
+ Collection<FileRunEventStatus> allowedFrom) {
+ return applyStatus(id, teamId, target, actor, allowedFrom)
+ .or(() -> find(id, teamId).filter(current -> current.status() == target))
+ .orElseThrow(() -> refusalFor(id, teamId));
+ }
+
+ /**
+ * Why the guarded UPDATE refused, worked out only once it has. Missing and closed are told
+ * apart after the fact rather than before, so the answer describes the row the UPDATE saw.
+ */
+ private FailureActionException refusalFor(String id, Long teamId) {
+ return repository.findByIdAndTeam(id, teamId).isPresent()
+ ? new FailureActionException(
+ FailureActionException.Reason.ALREADY_CLOSED,
+ "Event " + id + " is already closed")
+ // The same reason the service raises for an id it never found, so losing a delete
+ // race answers 404 like every other "no such event" rather than 400.
+ : new FailureActionException(
+ FailureActionException.Reason.EVENT_NOT_FOUND, "No such event: " + id);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventView.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventView.java
new file mode 100644
index 0000000000..cbaab4684d
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventView.java
@@ -0,0 +1,73 @@
+package stirling.software.proprietary.failure;
+
+import java.util.List;
+
+/**
+ * Wire shape of one incident. Carries i18n keys plus {@code defaultTitle} rather than rendered
+ * copy, so the server can ship a new kind without a client release, and {@code actions} arrive
+ * already resolved so the client needs no rules. No document name: {@code fileId} is an opaque
+ * reference.
+ */
+public record FileRunEventView(
+ String id,
+ String kindId,
+ FailureStage stage,
+ FailureSeverity severity,
+ FailureScope scope,
+ FailureOrigin origin,
+ FailureRemedy remedy,
+ String titleKey,
+ String descriptionKey,
+ String defaultTitle,
+ String detail,
+ String policyId,
+ String runId,
+ String fileId,
+ String actor,
+ int occurrences,
+ FileRunEventStatus status,
+ String statusActor,
+ List<ActionView> actions,
+ long createdAt,
+ long lastSeenAt) {
+
+ public static FileRunEventView of(
+ FileRunEvent event, List<FileRunEventService.AvailableAction> actions) {
+ FailureKind kind = event.kind();
+ return new FileRunEventView(
+ event.id(),
+ kind.getId(),
+ event.stage(),
+ event.severity(),
+ event.scope(),
+ event.origin(),
+ kind.getRemedy(),
+ kind.getTitleKey(),
+ kind.getDescriptionKey(),
+ kind.getDefaultTitle(),
+ event.detail(),
+ event.policyId(),
+ event.runId(),
+ event.fileId(),
+ event.actor(),
+ event.occurrences(),
+ event.status(),
+ event.statusActor(),
+ actions.stream().map(ActionView::of).toList(),
+ event.createdAt() == null ? 0L : event.createdAt().toEpochMilli(),
+ event.lastSeenAt() == null ? 0L : event.lastSeenAt().toEpochMilli());
+ }
+
+ /** One button, as offered for this specific row. */
+ public record ActionView(
+ String id, String labelKey, boolean enabled, String disabledReasonKey) {
+
+ static ActionView of(FileRunEventService.AvailableAction action) {
+ return new ActionView(
+ action.id().name(),
+ action.labelKey(),
+ action.enabled(),
+ action.disabledReasonKey());
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/PolicyFailureRecorder.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/PolicyFailureRecorder.java
new file mode 100644
index 0000000000..7d4516939a
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/PolicyFailureRecorder.java
@@ -0,0 +1,79 @@
+package stirling.software.proprietary.failure;
+
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.proprietary.policy.store.PolicyStore;
+
+/**
+ * The seam the policy engine calls when a run fails: classify, then record. Best-effort throughout,
+ * so failing to write a row cannot change the failure the caller already observed.
+ *
+ * <p>The team comes from the originating policy rather than the calling thread, which carries only
+ * an audit principal. An ad-hoc run has no stored policy, so its rows land unteamed.
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class PolicyFailureRecorder {
+
+ private final FailureClassifier classifier;
+ private final FileRunEventStore store;
+ private final PolicyStore policyStore;
+
+ /**
+ * Record a failed run, classifying {@code cause}. {@code detail} is the message the run itself
+ * reported, kept verbatim so an {@link FailureKind#UNKNOWN} row is still diagnosable.
+ */
+ public void recordRunFailure(
+ String runId,
+ String policyId,
+ String actor,
+ String fileIdentity,
+ String detail,
+ Throwable cause) {
+ record(classifier.classify(cause), runId, policyId, actor, fileIdentity, detail);
+ }
+
+ /**
+ * Record a failure whose kind is already decided, for paths with no exception to classify (a
+ * run rejected at admission). Named distinctly rather than overloading {@link
+ * #recordRunFailure}, whose argument list is otherwise near-identical, so a null cause cannot
+ * pick the wrong one.
+ */
+ public void recordRunFailureAs(
+ FailureKind kind, String runId, String policyId, String actor, String detail) {
+ record(kind, runId, policyId, actor, null, detail);
+ }
+
+ private void record(
+ FailureKind kind,
+ String runId,
+ String policyId,
+ String actor,
+ String fileIdentity,
+ String detail) {
+ try {
+ store.record(
+ RecordFailure.forRun(
+ kind, teamFor(policyId), actor, policyId, runId, fileIdentity, detail));
+ } catch (RuntimeException e) {
+ // Deliberately swallowed: see the class comment.
+ log.warn("Could not record failure event for run {} (kind {})", runId, kind.getId(), e);
+ }
+ }
+
+ private Long teamFor(String policyId) {
+ if (policyId == null || policyId.isBlank()) {
+ return null;
+ }
+ try {
+ return policyStore.get(policyId).map(policy -> policy.teamId()).orElse(null);
+ } catch (RuntimeException e) {
+ log.debug("Could not resolve team for policy {}: {}", policyId, e.getMessage());
+ return null;
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/RecordFailure.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/RecordFailure.java
new file mode 100644
index 0000000000..1f45d52e17
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/RecordFailure.java
@@ -0,0 +1,117 @@
+package stirling.software.proprietary.failure;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+
+/**
+ * Everything needed to record one failure. Every reference field is nullable, because a failure can
+ * happen before a file or policy is known and with no user at all (a trigger-fired run on a
+ * login-disabled deployment). Only {@code kind} and {@code origin} are required.
+ */
+public record RecordFailure(
+ FailureKind kind,
+ FailureOrigin origin,
+ Long teamId,
+ String actor,
+ String policyId,
+ String runId,
+ String sourceId,
+ String fileId,
+ String detail) {
+
+ /** Upper bound on a stored message, so one enormous stack trace cannot fill the column. */
+ private static final int MAX_DETAIL_LENGTH = 2_000;
+
+ public RecordFailure {
+ if (kind == null) {
+ throw new IllegalArgumentException("kind is required");
+ }
+ if (origin == null) {
+ throw new IllegalArgumentException("origin is required");
+ }
+ // Capped here rather than at each call site, since this record is the only way a row is
+ // written, and an unclassified failure carries a raw message of unbounded length. Stored
+ // verbatim otherwise: it is the user's own error about their own file, and hiding parts of
+ // it makes the row harder to act on without making it meaningfully safer.
+ detail = truncate(detail);
+ }
+
+ /** A processor-side failure with no file or source context, e.g. a run that failed outright. */
+ public static RecordFailure forRun(
+ FailureKind kind,
+ Long teamId,
+ String actor,
+ String policyId,
+ String runId,
+ String fileId,
+ String detail) {
+ return new RecordFailure(
+ kind, FailureOrigin.POLICY, teamId, actor, policyId, runId, null, fileId, detail);
+ }
+
+ /**
+ * What this failure is about, per the row's scope. Two failures sharing a kind and a scope
+ * reference are the same incident; see {@link #dedupKey()}.
+ */
+ public String scopeRef() {
+ return switch (kind.getScope()) {
+ case FILE -> nullToEmpty(policyId) + "|" + fileOrRun();
+ case RUN -> nullToEmpty(runId);
+ case POLICY -> nullToEmpty(policyId);
+ case SOURCE -> nullToEmpty(sourceId);
+ // One server-wide condition is one incident regardless of which run tripped over it.
+ case SERVER -> "";
+ };
+ }
+
+ /**
+ * The file this failure is about, or the run when the producer could not name one. Without the
+ * fallback, every file failing the same way under one policy shares a scope reference, and the
+ * second onwards folds into the first as though one document had failed repeatedly.
+ *
+ * <p>Prefixed so a file id and a run id cannot collide.
+ */
+ private String fileOrRun() {
+ return isBlank(fileId) ? "run:" + nullToEmpty(runId) : "file:" + fileId;
+ }
+
+ /**
+ * Decides whether this failure repeats an existing incident: SHA-256 of {@code
+ * kindId|scope|scopeRef}. Hashed so a long scope reference (an S3 key) fits a fixed-width
+ * index, and deterministic so two nodes converge on one incident. Every input is an enum name
+ * or an id.
+ */
+ public String dedupKey() {
+ String raw = kind.getId() + "|" + kind.getScope().name() + "|" + scopeRef();
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ return HexFormat.of().formatHex(digest.digest(raw.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException e) {
+ // SHA-256 is mandated by the JDK; unreachable outside a broken runtime.
+ throw new IllegalStateException("SHA-256 unavailable", e);
+ }
+ }
+
+ private static String truncate(String detail) {
+ if (detail == null || detail.length() <= MAX_DETAIL_LENGTH) {
+ return detail;
+ }
+ // Leave room for the ellipsis so the cap is the cap, and step back once more rather than
+ // cutting between the halves of a surrogate pair, which would store invalid UTF-16.
+ int end = MAX_DETAIL_LENGTH - 1;
+ if (Character.isHighSurrogate(detail.charAt(end - 1))) {
+ end--;
+ }
+ return detail.substring(0, end) + "…";
+ }
+
+ private static boolean isBlank(String value) {
+ return value == null || value.isBlank();
+ }
+
+ private static String nullToEmpty(String value) {
+ return value == null ? "" : value;
+ }
+}
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 1f31d153a6..33ac70d510 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
@@ -32,6 +32,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.failure.FailureKind;
+import stirling.software.proprietary.failure.PolicyFailureRecorder;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.Policy;
@@ -72,6 +74,8 @@ public class PolicyEngine {
private final PolicyExecutor stepExecutor;
private final TaskManager taskManager;
private final PolicyRunRegistry registry;
+ // Durable record of why a run failed. Best-effort by contract: see PolicyFailureRecorder.
+ private final PolicyFailureRecorder failureRecorder;
private final FileStorage fileStorage;
private final JobOwnershipService jobOwnershipService;
private final List<PolicyOutputSink> outputSinks;
@@ -123,12 +127,26 @@ public class PolicyEngine {
// async
// worker.
String principal = currentActingPrincipal();
- return submitForPrincipal(principal, principal, policyId, definition, inputs, listener);
+ return submitForPrincipal(
+ principal, principal, policyId, definition, inputs, null, listener);
}
/** Run a stored policy on demand. {@code enabled} gates triggers, not explicit runs. */
public PolicyRunHandle runPolicy(
Policy policy, PolicyInputs inputs, PolicyProgressListener listener) {
+ return runPolicy(policy, inputs, null, listener);
+ }
+
+ /**
+ * As {@link #runPolicy(Policy, PolicyInputs, PolicyProgressListener)}, with the source's opaque
+ * reference to the document being run. Carried so a failure can say which document it was
+ * about, and so the same document failing again folds into one incident.
+ */
+ public PolicyRunHandle runPolicy(
+ Policy policy,
+ PolicyInputs inputs,
+ String fileIdentity,
+ PolicyProgressListener listener) {
// Bill the policy owner: trigger-fired runs have no security context, and the async worker
// doesn't inherit the caller's, so the owner (stamped at policy creation) is the reliable
// billing identity — and for org-wide policies the org/owner is meant to pay. But own the
@@ -145,7 +163,7 @@ public class PolicyEngine {
new PipelineDefinition(
policy.name(), policy.steps(), outputResolver.resolve(policy));
return submitForPrincipal(
- policy.owner(), fileOwner, policy.id(), definition, inputs, listener);
+ policy.owner(), fileOwner, policy.id(), definition, inputs, fileIdentity, listener);
}
private PolicyRunHandle submitForPrincipal(
@@ -154,6 +172,7 @@ public class PolicyEngine {
String policyId,
PipelineDefinition definition,
PolicyInputs inputs,
+ String fileIdentity,
PolicyProgressListener listener) {
// Scope the run id to the current user (this request thread) so the file-download
// ownership check passes. No-op when security is off.
@@ -163,7 +182,7 @@ public class PolicyEngine {
if (policyId != null) {
taskManager.putMetadata(runId, "policyId", policyId);
}
- PolicyRun run = new PolicyRun(runId, policyId, definition);
+ PolicyRun run = new PolicyRun(runId, policyId, definition, fileIdentity);
registry.register(run);
CompletableFuture<PolicyRun> completion = new CompletableFuture<>();
PolicyProgressListener tracking = trackingListener(runId, run, listener);
@@ -271,6 +290,7 @@ public class PolicyEngine {
e.getMessage());
run.fail(message);
taskManager.setError(runId, message);
+ recordFailure(run, message, e);
} catch (RestClientResponseException e) {
// A downstream tool call returned an error status. When it's a structured
// entitlement
@@ -294,17 +314,20 @@ public class PolicyEngine {
run.failWithCode(
message, code, DownstreamEntitlementError.extractSubscribed(e));
taskManager.setError(runId, message);
+ recordFailure(run, message, e);
} else {
String message = "Policy run failed: " + e.getMessage();
log.error("Policy run {} failed (downstream HTTP error)", runId, e);
run.fail(message);
taskManager.setError(runId, message);
+ recordFailure(run, message, e);
}
} catch (Exception e) {
String message = "Policy run failed: " + e.getMessage();
log.error("Policy run {} failed", runId, e);
run.fail(message);
taskManager.setError(runId, message);
+ recordFailure(run, message, e);
} finally {
// Always resolve so stream/await callers unblock.
completion.complete(run);
@@ -322,11 +345,29 @@ public class PolicyEngine {
// Transient admission rejection, not a processing failure (see QUEUE_FULL_CODE).
run.failWithCode(message, QUEUE_FULL_CODE, null);
taskManager.setError(run.getRunId(), message);
+ // No exception to classify here: nothing was thrown by a tool, the run simply was not
+ // admitted. Record it explicitly so a run lost to load pressure is still accounted for.
+ failureRecorder.recordRunFailureAs(
+ FailureKind.UNKNOWN, run.getRunId(), run.getPolicyId(), null, message);
completion.complete(run);
}
return null;
}
+ /**
+ * Record why a run failed. Called after the run's own state transition and task-manager update,
+ * so a recording problem cannot change the outcome the caller observes.
+ */
+ private void recordFailure(PolicyRun run, String message, Throwable cause) {
+ failureRecorder.recordRunFailure(
+ run.getRunId(),
+ run.getPolicyId(),
+ MDC.get(AUDIT_PRINCIPAL_MDC_KEY),
+ run.getFileIdentity(),
+ message,
+ cause);
+ }
+
private WaitState suspend(PolicyInputRequiredException e) {
List<String> fileIds = new ArrayList<>();
for (Resource resource : e.getPendingFiles()) {
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 d6202b520e..06ac1c8d7c 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
@@ -281,18 +281,33 @@ public class PolicyExecutor {
}
for (Resource file : files) {
if (!matchesType(file, accepted)) {
+ // Reports the extension rather than the filename, since this message becomes the
+ // run's error and is persisted on the failure record.
throw new IOException(
"Step "
+ operation
+ " accepts "
+ accepted
- + " but received '"
- + file.getFilename()
- + "'");
+ + " but received a '"
+ + extensionOf(file)
+ + "' file");
}
}
}
+ /** The file's extension, or {@code unknown} when it has no usable name. */
+ private static String extensionOf(Resource file) {
+ String filename = file.getFilename();
+ if (filename == null) {
+ return "unknown";
+ }
+ int dot = filename.lastIndexOf('.');
+ if (dot < 0 || dot == filename.length() - 1) {
+ return "unknown";
+ }
+ return filename.substring(dot + 1).toLowerCase(Locale.ROOT);
+ }
+
private static boolean matchesType(Resource file, List<String> acceptedExtensions) {
String filename = file.getFilename();
if (filename == null) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java
index 837e3bd0ae..04dda0871e 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java
@@ -79,7 +79,7 @@ public class PolicyRunner {
// Generator pipeline: one run with no input. Still fall through to the cleanup
// below so rows recorded for its folder outputs are pruned like anything else,
// instead of accumulating until the policy is deleted.
- runIds.add(startRun(policy, PolicyInputs.of(List.of()), unused -> {}));
+ runIds.add(startRun(policy, PolicyInputs.of(List.of()), null, unused -> {}));
}
for (PipelineInput input : inputs) {
String sourceId = input.sourceId();
@@ -167,17 +167,18 @@ public class PolicyRunner {
List<String> runIds = new ArrayList<>();
long docsFed = 0;
for (ResolvedInput unit : work) {
- runIds.add(startRun(policy, unit.inputs(), unit.onComplete()));
+ runIds.add(startRun(policy, unit.inputs(), unit.fileIdentity(), unit.onComplete()));
docsFed += unit.inputs().primary().size();
}
docCounter.record(sourceId, docsFed);
return runIds;
}
- private String startRun(Policy policy, PolicyInputs inputs, Consumer<Boolean> onComplete) {
+ private String startRun(
+ Policy policy, PolicyInputs inputs, String fileIdentity, Consumer<Boolean> onComplete) {
log.info("Running policy {} ({})", policy.id(), policy.name());
PolicyRunHandle handle =
- policyEngine.runPolicy(policy, inputs, PolicyProgressListener.NOOP);
+ policyEngine.runPolicy(policy, inputs, fileIdentity, PolicyProgressListener.NOOP);
handle.completion()
.whenComplete((run, throwable) -> onComplete.accept(succeeded(run, throwable)));
return handle.runId();
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java
index 4f02d13c82..1e07185ab5 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java
@@ -118,8 +118,9 @@ public class FolderInputSource implements InputSource {
continue;
}
work.add(
- new ResolvedInput(
+ ResolvedInput.forFile(
PolicyInputs.of(List.of(fileResource(file))),
+ identity,
success ->
completeConsumed(
ctx, identity, file, gate, contentHash, success)));
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/ResolvedInput.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/ResolvedInput.java
index b5d7de94f8..1b10ff3a06 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/ResolvedInput.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/ResolvedInput.java
@@ -2,21 +2,40 @@ package stirling.software.proprietary.policy.input;
import java.util.function.Consumer;
+import stirling.software.proprietary.policy.ledger.IdentityHasher;
import stirling.software.proprietary.policy.model.PolicyInputs;
/**
* One unit of work from an {@link InputSource}: the files to run plus a completion callback invoked
* with the run's success (e.g. a folder source routes the input to done/error). A source may return
* several of these, one per file.
+ *
+ * @param fileIdentity stable opaque reference to the document, or null when the source has none.
+ * Always hashed, never the source's own identity: a folder identity is a path, and a path is a
+ * filename. See {@link #forFile}.
*/
-public record ResolvedInput(PolicyInputs inputs, Consumer<Boolean> onComplete) {
+public record ResolvedInput(
+ PolicyInputs inputs, String fileIdentity, Consumer<Boolean> onComplete) {
public ResolvedInput {
onComplete = onComplete == null ? success -> {} : onComplete;
}
- /** No completion side effect. */
+ /**
+ * One document, referenced by the hash of the source's identity for it. Stable across sweeps,
+ * which is what lets the same broken file fold into one incident instead of opening a fresh one
+ * every time the source re-lists it.
+ */
+ public static ResolvedInput forFile(
+ PolicyInputs inputs, String identity, Consumer<Boolean> onComplete) {
+ return new ResolvedInput(
+ inputs,
+ identity == null ? null : IdentityHasher.identityHash(identity),
+ onComplete);
+ }
+
+ /** No document reference and no completion side effect. */
public static ResolvedInput of(PolicyInputs inputs) {
- return new ResolvedInput(inputs, success -> {});
+ return new ResolvedInput(inputs, null, success -> {});
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java
index 34576b47b9..326ccef147 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java
@@ -119,8 +119,9 @@ public class S3InputSource implements InputSource {
continue;
}
work.add(
- new ResolvedInput(
+ ResolvedInput.forFile(
PolicyInputs.of(List.of(objectResource(client, config, object))),
+ identity,
success ->
completeConsumed(
ctx,
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/WebhookInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/WebhookInputSource.java
index 49cb3c70c4..ff79b5be20 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/WebhookInputSource.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/WebhookInputSource.java
@@ -100,8 +100,9 @@ public class WebhookInputSource implements InputSource {
continue;
}
work.add(
- new ResolvedInput(
+ ResolvedInput.forFile(
PolicyInputs.of(List.of(fileResource(file))),
+ identity,
success -> completeConsumed(ctx, identity, file, gate, success)));
}
return work;
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java
index bba84813ce..24a97f6c2a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java
@@ -22,6 +22,13 @@ public class PolicyRun {
private final String policyId;
private final PipelineDefinition definition;
+
+ /**
+ * The source's opaque reference to the document this run is about; null for an ad-hoc run or a
+ * source that names no document. Hashed upstream, so never a path or a filename.
+ */
+ private final String fileIdentity;
+
private final Instant createdAt = Instant.now();
private volatile PolicyRunStatus status = PolicyRunStatus.PENDING;
@@ -49,10 +56,12 @@ public class PolicyRun {
private volatile List<ResultFile> outputs = List.of();
private volatile Instant updatedAt = Instant.now();
- public PolicyRun(String runId, String policyId, PipelineDefinition definition) {
+ public PolicyRun(
+ String runId, String policyId, PipelineDefinition definition, String fileIdentity) {
this.runId = runId;
this.policyId = policyId;
this.definition = definition;
+ this.fileIdentity = fileIdentity;
}
public int stepCount() {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java
index 0b6ff0aa45..0fdf8d116f 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java
@@ -103,8 +103,9 @@ public class NetworkInputSource implements InputSource {
continue;
}
work.add(
- new ResolvedInput(
+ ResolvedInput.forFile(
PolicyInputs.of(List.of(resource(config, file))),
+ identity,
success ->
completeConsumed(ctx, config, file, identity, gate, success)));
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java
index a5bb305e06..3bc3807e1e 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java
@@ -38,7 +38,8 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
"stirling.software.proprietary.policy.ledger",
"stirling.software.proprietary.accountlink",
"stirling.software.proprietary.access.repository",
- "stirling.software.proprietary.integration.repository"
+ "stirling.software.proprietary.integration.repository",
+ "stirling.software.proprietary.failure"
})
@EntityScan({
"stirling.software.proprietary.security.model",
@@ -51,7 +52,8 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
"stirling.software.proprietary.policy.ledger",
"stirling.software.proprietary.accountlink",
"stirling.software.proprietary.access.model",
- "stirling.software.proprietary.integration.model"
+ "stirling.software.proprietary.integration.model",
+ "stirling.software.proprietary.failure"
})
public class DatabaseConfig {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureClassifierTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureClassifierTest.java
new file mode 100644
index 0000000000..951b11c056
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureClassifierTest.java
@@ -0,0 +1,216 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.client.HttpClientErrorException;
+
+import jakarta.annotation.PostConstruct;
+
+import stirling.software.common.service.InternalApiTimeoutException;
+import stirling.software.common.util.ExceptionUtils;
+
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Tests for {@link FailureClassifier}. The fixtures matter as much as the assertions: a tool's 400
+ * arrives as a {@link org.springframework.web.client.RestClientResponseException} carrying the
+ * Problem Details body, so these build that exact shape rather than a convenient stand-in.
+ */
+class FailureClassifierTest {
+
+ private final FailureClassifier classifier =
+ new FailureClassifier(JsonMapper.builder().build());
+
+ /** The Problem Details body {@code GlobalExceptionHandler} produces for a coded exception. */
+ private static HttpClientErrorException problemDetail(HttpStatus status, String errorCode) {
+ String body =
+ """
+ {"type":"/errors/pdf-password","title":"PDF password required",\
+ "status":%d,"detail":"The PDF Document is passworded",\
+ "errorCode":"%s","timestamp":"2026-01-01T00:00:00Z"}"""
+ .formatted(status.value(), errorCode);
+ return HttpClientErrorException.create(
+ status,
+ status.getReasonPhrase(),
+ new HttpHeaders(),
+ body.getBytes(StandardCharsets.UTF_8),
+ StandardCharsets.UTF_8);
+ }
+
+ private static HttpClientErrorException rawBody(String body) {
+ return HttpClientErrorException.create(
+ HttpStatus.BAD_REQUEST,
+ "Bad Request",
+ new HttpHeaders(),
+ body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8),
+ StandardCharsets.UTF_8);
+ }
+
+ @Nested
+ @DisplayName("a downstream tool error")
+ class DownstreamErrors {
+
+ @Test
+ void withAClaimedErrorCodeClassifiesToThatKind() {
+ assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, "E004")))
+ .isEqualTo(FailureKind.INPUT_PASSWORD_PROTECTED);
+ }
+
+ @Test
+ void withAnUnclaimedErrorCodeFallsBackToUnknown() {
+ // E001 (corrupted PDF) is a real code that no kind has adopted yet. It must land in
+ // UNKNOWN rather than being force-fitted to the nearest kind.
+ assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, "E001")))
+ .isEqualTo(FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void withANonJsonBodyFallsBackToUnknownWithoutThrowing() {
+ assertThat(classifier.classify(rawBody("Internal Server Error")))
+ .isEqualTo(FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void withAnEmptyBodyFallsBackToUnknown() {
+ assertThat(classifier.classify(rawBody(""))).isEqualTo(FailureKind.UNKNOWN);
+ assertThat(classifier.classify(rawBody(null))).isEqualTo(FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void withJsonButNoErrorCodePropertyFallsBackToUnknown() {
+ assertThat(classifier.classify(rawBody("{\"detail\":\"nope\"}")))
+ .isEqualTo(FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void entitlementSentinelIsNotMistakenForACodedFailure() {
+ // An entitlement 402 carries `error`, not `errorCode`. It must not be misclassified,
+ // and specifically must not be attributed to a file problem.
+ FailureKind kind =
+ classifier.classify(
+ rawBody("{\"error\":\"PAYG_LIMIT_REACHED\",\"subscribed\":false}"));
+ assertThat(kind).isEqualTo(FailureKind.UNKNOWN);
+ assertThat(kind).isNotEqualTo(FailureKind.INPUT_PASSWORD_PROTECTED);
+ }
+ }
+
+ @Nested
+ @DisplayName("an exception thrown in process")
+ class InProcess {
+
+ @Test
+ void carryingItsOwnErrorCodeIsClassifiedByThatCode() {
+ // Not every path goes over loopback; a coded exception thrown directly must work too.
+ ExceptionUtils.PdfPasswordException e =
+ ExceptionUtils.createPdfPasswordException(new IOException("password"));
+ assertThat(classifier.classify(e)).isEqualTo(FailureKind.INPUT_PASSWORD_PROTECTED);
+ }
+
+ @Test
+ void isClassifiedWhenWrappedInsideAnotherException() {
+ // The engine wraps and rethrows, so the code is often not on the outermost throwable.
+ Throwable wrapped =
+ new IllegalStateException(
+ "step failed",
+ ExceptionUtils.createPdfPasswordException(new IOException("pw")));
+ assertThat(classifier.classify(wrapped))
+ .isEqualTo(FailureKind.INPUT_PASSWORD_PROTECTED);
+ }
+ }
+
+ @Nested
+ @DisplayName("anything unrecognised")
+ class Fallback {
+
+ @Test
+ void toolTimeoutIsUnknownUntilAKindClaimsIt() {
+ // Deliberate: a timeout has its own catch site in the engine but no kind yet. This
+ // proves the fallback holds even where specific handling already exists.
+ InternalApiTimeoutException e =
+ new InternalApiTimeoutException(
+ "/api/v1/misc/ocr-pdf", Duration.ofSeconds(30), new IOException("t"));
+ assertThat(classifier.classify(e)).isEqualTo(FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void bareRuntimeExceptionIsUnknown() {
+ assertThat(classifier.classify(new RuntimeException("boom")))
+ .isEqualTo(FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void nullMessageDoesNotBreakClassification() {
+ assertThat(classifier.classify(new RuntimeException((String) null)))
+ .isEqualTo(FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void nullThrowableIsUnknown() {
+ assertThat(classifier.classify(null)).isEqualTo(FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void cyclicCauseChainTerminates() {
+ // The JDK blocks self-causation but not a two-node cycle, and an unbounded walk would
+ // spin on it forever, taking the run's error handling down with it.
+ RuntimeException outer = new RuntimeException("outer");
+ RuntimeException inner = new RuntimeException("inner", outer);
+ outer.initCause(inner);
+
+ assertThat(classifier.classify(outer)).isEqualTo(FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void aCodeBuriedBeyondTheDepthBoundIsNotFound() {
+ // Documents the trade: the bound is what guarantees termination, so a pathologically
+ // deep chain classifies as UNKNOWN rather than hanging. UNKNOWN is always recoverable.
+ Throwable deepest =
+ ExceptionUtils.createPdfPasswordException(new IOException("password"));
+ Throwable chain = deepest;
+ for (int i = 0; i < 20; i++) {
+ chain = new IllegalStateException("wrap " + i, chain);
+ }
+ assertThat(classifier.classify(chain)).isEqualTo(FailureKind.UNKNOWN);
+ }
+ }
+
+ @Nested
+ @DisplayName("the boot guard on an ambiguous registry")
+ class BootGuard {
+
+ @Test
+ void isWiredToRunAtStartupRatherThanOnlyBeingCallable() throws Exception {
+ // The check moved out of FailureKind's class initialiser to get a readable message.
+ // That only buys anything if Spring actually invokes it.
+ assertThat(
+ FailureClassifier.class
+ .getDeclaredMethod("verifyNoErrorCodeIsClaimedTwice")
+ .isAnnotationPresent(PostConstruct.class))
+ .isTrue();
+ }
+
+ @Test
+ void acceptsTheRealRegistry() {
+ assertThatCode(classifier::verifyNoErrorCodeIsClaimedTwice).doesNotThrowAnyException();
+ }
+
+ @Test
+ void wouldRejectADuplicate() {
+ // FailureKind is a closed enum, so the guard cannot be handed a bad registry. What can
+ // be shown is that the detection it depends on finds a duplicate when there is one.
+ assertThat(FailureKind.duplicatesIn(Stream.of("E004", "E001", "E004")))
+ .containsExactly("E004");
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java
new file mode 100644
index 0000000000..1a1b1a1599
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java
@@ -0,0 +1,263 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import stirling.software.common.util.ExceptionUtils;
+
+/**
+ * Tests for {@link FailureKind}. Mostly invariants over the whole enum rather than assertions about
+ * individual members, so a kind added later cannot be malformed in a way that only shows up as a
+ * button that fails at runtime.
+ */
+class FailureKindTest {
+
+ @Nested
+ @DisplayName("every kind is well formed")
+ class Invariants {
+
+ @ParameterizedTest
+ @EnumSource(FailureKind.class)
+ void hasAllFacetsAndAtLeastOneAction(FailureKind kind) {
+ assertThat(kind.getStage()).isNotNull();
+ assertThat(kind.getSeverity()).isNotNull();
+ assertThat(kind.getRemedy()).isNotNull();
+ assertThat(kind.getScope()).isNotNull();
+ assertThat(kind.getActions())
+ .as("a kind with no actions cannot be triaged at all")
+ .isNotEmpty();
+ }
+
+ @ParameterizedTest
+ @EnumSource(FailureKind.class)
+ void hasCopyKeysAndAnEnglishFallback(FailureKind kind) {
+ assertThat(kind.getTitleKey()).isNotBlank();
+ assertThat(kind.getDescriptionKey()).isNotBlank();
+ // The fallback is what lets a client render a kind it was never built with.
+ assertThat(kind.getDefaultTitle()).isNotBlank();
+ }
+
+ @ParameterizedTest
+ @EnumSource(FailureKind.class)
+ void idIsScreamingSnakeCase(FailureKind kind) {
+ assertThat(kind.getId()).matches("^[A-Z][A-Z0-9_]*$");
+ }
+
+ @Test
+ void idsAreUnique() {
+ Set<String> ids = new HashSet<>();
+ for (FailureKind kind : FailureKind.values()) {
+ assertThat(ids.add(kind.getId())).as("duplicate id %s", kind.getId()).isTrue();
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(FailureKind.class)
+ void everyDeclaredErrorCodeIsARealErrorCode(FailureKind kind) {
+ Set<String> known =
+ Arrays.stream(ExceptionUtils.ErrorCode.values())
+ .map(ExceptionUtils.ErrorCode::getCode)
+ .collect(Collectors.toSet());
+ assertThat(known).containsAll(kind.getErrorCodes());
+ }
+
+ @ParameterizedTest
+ @EnumSource(FailureKind.class)
+ void everyDeclaredActionResolvesToALabelKey(FailureKind kind) {
+ // Offers are one ordered list, so a label with no matching action is unrepresentable;
+ // all that is left to assert is that each action gets a key.
+ for (FailureActionId action : kind.getActions()) {
+ assertThat(kind.labelKeyFor(action)).startsWith("portal.failures.action.");
+ }
+ }
+
+ @Test
+ void noTwoKindsClaimTheSameErrorCode() {
+ // Computed independently of duplicateErrorCodes(), then checked against it: the boot
+ // guard reads that method, so a version of it that always returned empty would leave
+ // the guard decorative and every other test still passing.
+ assertThat(FailureKind.duplicateErrorCodes()).isEmpty();
+
+ Set<String> claimed = new HashSet<>();
+ Stream.of(FailureKind.values())
+ .flatMap(kind -> kind.getErrorCodes().stream())
+ .forEach(
+ code ->
+ assertThat(claimed.add(code))
+ .as("error code %s claimed twice", code)
+ .isTrue());
+ }
+ }
+
+ @Nested
+ @DisplayName("every derived key resolves to English copy")
+ class Copy {
+
+ /**
+ * The enum builds its i18n keys from the constant name, so renaming a kind or shipping a
+ * new one sends keys the client has no copy for, and the UI renders the raw key. Nothing
+ * else checks that: the portal reads these keys at runtime, and the unused-translation
+ * audit only looks the other way, for copy no source file mentions.
+ */
+ private static final Set<String> KEYS = englishKeys();
+
+ @ParameterizedTest
+ @EnumSource(FailureKind.class)
+ void titleAndDescriptionAreTranslated(FailureKind kind) {
+ assertThat(KEYS).contains(kind.getTitleKey(), kind.getDescriptionKey());
+ }
+
+ @ParameterizedTest
+ @EnumSource(FailureKind.class)
+ void everyOfferedActionIsLabelled(FailureKind kind) {
+ for (FailureActionId action : kind.getActions()) {
+ assertThat(KEYS)
+ .as("%s offers %s, but nothing labels it", kind.getId(), action)
+ .contains(kind.labelKeyFor(action));
+ }
+ }
+
+ /**
+ * Every dotted key in the English file, as {@code [section]} plus the name before {@code
+ * =}.
+ */
+ private static Set<String> englishKeys() {
+ Set<String> keys = new HashSet<>();
+ String section = "";
+ for (String raw : readTranslations()) {
+ String line = raw.strip();
+ if (line.isEmpty() || line.startsWith("#")) {
+ continue;
+ }
+ if (line.startsWith("[") && line.endsWith("]")) {
+ section = line.substring(1, line.length() - 1).strip() + ".";
+ continue;
+ }
+ int equals = line.indexOf('=');
+ if (equals > 0) {
+ keys.add(section + line.substring(0, equals).strip());
+ }
+ }
+ return keys;
+ }
+
+ private static List<String> readTranslations() {
+ // Located by walking up, so the test does not depend on the directory Gradle runs it
+ // in.
+ Path relative = Path.of("frontend/editor/public/locales/en-US/translation.toml");
+ for (Path dir = Path.of("").toAbsolutePath(); dir != null; dir = dir.getParent()) {
+ Path candidate = dir.resolve(relative);
+ if (Files.isRegularFile(candidate)) {
+ try {
+ return Files.readAllLines(candidate, StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+ }
+ throw new IllegalStateException(
+ "No " + relative + " above " + Path.of("").toAbsolutePath());
+ }
+ }
+
+ @Nested
+ @DisplayName("UNKNOWN is the catch-all")
+ class Unknown {
+
+ @Test
+ void existsAndCanBeTriaged() {
+ assertThat(FailureKind.UNKNOWN.getActions())
+ .containsExactlyInAnyOrder(
+ FailureActionId.ACKNOWLEDGE, FailureActionId.DISMISS);
+ }
+
+ @Test
+ void claimsNoErrorCodeSoItNeverWinsALookup() {
+ assertThat(FailureKind.UNKNOWN.getErrorCodes()).isEmpty();
+ }
+ }
+
+ @Nested
+ @DisplayName("lookup")
+ class Lookup {
+
+ @Test
+ void byIdRoundTripsEveryKind() {
+ for (FailureKind kind : FailureKind.values()) {
+ assertThat(FailureKind.byId(kind.getId())).contains(kind);
+ }
+ }
+
+ @Test
+ void byIdIsEmptyForAnUnknownId() {
+ // Ids arrive from persisted rows and from clients, so this must not throw.
+ assertThat(FailureKind.byId("NO_SUCH_KIND")).isEmpty();
+ assertThat(FailureKind.byId(null)).isEmpty();
+ assertThat(FailureKind.byId(" ")).isEmpty();
+ }
+
+ @Test
+ void byErrorCodeResolvesTheClaimingKind() {
+ assertThat(FailureKind.byErrorCode("E004"))
+ .contains(FailureKind.INPUT_PASSWORD_PROTECTED);
+ }
+
+ @Test
+ void byErrorCodeIsEmptyForACodeNoKindHasAdoptedYet() {
+ // E001 is PDF_CORRUPTED: a real error code, deliberately not yet a kind.
+ assertThat(FailureKind.byErrorCode("E001")).isEmpty();
+ assertThat(FailureKind.byErrorCode(null)).isEmpty();
+ }
+ }
+
+ @Nested
+ @DisplayName("action declaration and labels")
+ class Actions {
+
+ @Test
+ void declaresOnlyWhatItLists() {
+ assertThat(FailureKind.UNKNOWN.declares(FailureActionId.ACKNOWLEDGE)).isTrue();
+ assertThat(FailureKind.UNKNOWN.declares(FailureActionId.DISMISS)).isTrue();
+ }
+
+ @Test
+ void overriddenLabelWinsOverTheGenericOne() {
+ String label =
+ FailureKind.INPUT_PASSWORD_PROTECTED.labelKeyFor(FailureActionId.DISMISS);
+ assertThat(label).isEqualTo("portal.failures.action.dismissSkipFile");
+ assertThat(label).isNotEqualTo(FailureKind.genericLabelKey(FailureActionId.DISMISS));
+ }
+
+ @Test
+ void genericLabelIsUsedWhenAKindDeclaresNoOverride() {
+ assertThat(FailureKind.UNKNOWN.labelKeyFor(FailureActionId.DISMISS))
+ .isEqualTo(FailureKind.genericLabelKey(FailureActionId.DISMISS))
+ .isEqualTo("portal.failures.action.dismiss");
+ }
+
+ @Test
+ void copyKeysAreDerivedFromTheIdInLowerCamel() {
+ assertThat(FailureKind.INPUT_PASSWORD_PROTECTED.getTitleKey())
+ .isEqualTo("portal.failures.kind.inputPasswordProtected.title");
+ assertThat(FailureKind.INPUT_PASSWORD_PROTECTED.getDescriptionKey())
+ .isEqualTo("portal.failures.kind.inputPasswordProtected.description");
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventControllerTest.java
new file mode 100644
index 0000000000..a4b830d0f8
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventControllerTest.java
@@ -0,0 +1,403 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.lenient;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.UserServiceInterface;
+import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
+
+/**
+ * Tests for {@link FileRunEventController}: the wire shape, the status mapping for each refusal
+ * reason, and that the team is taken from the principal rather than the request.
+ */
+@ExtendWith(MockitoExtension.class)
+class FileRunEventControllerTest {
+
+ private static final Long TEAM = 4L;
+
+ @Mock private PolicyManagementAuthority authority;
+ @Mock private UserServiceInterface userService;
+
+ private FileRunEventStore store;
+ private FileRunEventController controller;
+
+ @BeforeEach
+ void setUp() {
+ ApplicationProperties props = new ApplicationProperties();
+ props.getSecurity().setEnableLogin(true);
+ store = new FileRunEventStore(new InMemoryFileRunEventRepository());
+ FailureActionRegistry registry =
+ new FailureActionRegistry(
+ List.of(new AcknowledgeAction(store), new DismissAction(store)));
+ controller =
+ new FileRunEventController(
+ new FileRunEventService(store, registry, authority, userService, props),
+ authority,
+ props);
+
+ lenient().when(authority.canEditPolicies()).thenReturn(true);
+ lenient().when(authority.currentUserTeamId()).thenReturn(TEAM);
+ lenient().when(userService.getCurrentUsername()).thenReturn("[email protected]");
+ }
+
+ private FileRunEvent given(FailureKind kind, Long teamId, String fileId) {
+ return store.record(
+ new RecordFailure(
+ kind,
+ FailureOrigin.POLICY,
+ teamId,
+ "policy-1",
+ "run-1",
+ null,
+ fileId,
+ "the raw failure message"));
+ }
+
+ @Nested
+ @DisplayName("listing")
+ class Listing {
+
+ @Test
+ void returnsOnlyTheCallersTeamsRows() {
+ given(FailureKind.UNKNOWN, TEAM, "mine");
+ given(FailureKind.UNKNOWN, 99L, "theirs");
+
+ assertThat(controller.list(null, null, null).events())
+ .extracting(FileRunEventView::fileId)
+ .containsExactly("mine");
+ }
+
+ @Test
+ void carriesTheCopyKeysAndTheEnglishFallback() {
+ given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
+
+ FileRunEventView view = controller.list(null, null, null).events().getFirst();
+
+ assertThat(view.titleKey())
+ .isEqualTo("portal.failures.kind.inputPasswordProtected.title");
+ assertThat(view.descriptionKey())
+ .isEqualTo("portal.failures.kind.inputPasswordProtected.description");
+ assertThat(view.defaultTitle()).isNotBlank();
+ assertThat(view.detail()).isEqualTo("the raw failure message");
+ }
+
+ @Test
+ void carriesActionsAlreadyResolvedForTheRow() {
+ given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
+
+ List<FileRunEventView.ActionView> actions =
+ controller.list(null, null, null).events().getFirst().actions();
+
+ assertThat(actions)
+ .extracting(FileRunEventView.ActionView::id)
+ .containsExactlyInAnyOrder("ACKNOWLEDGE", "DISMISS");
+ assertThat(actions).allMatch(FileRunEventView.ActionView::enabled);
+ }
+
+ @Test
+ void showsAClosedRowsActionsDisabledWithAReasonRatherThanHidingThem() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+ controller.act(event.id(), "DISMISS", null);
+
+ List<FileRunEventView.ActionView> actions =
+ controller
+ .list(FileRunEventStatus.DISMISSED, null, null)
+ .events()
+ .getFirst()
+ .actions();
+
+ assertThat(actions).noneMatch(FileRunEventView.ActionView::enabled);
+ assertThat(actions)
+ .allMatch(a -> "portal.failures.disabled.closed".equals(a.disabledReasonKey()));
+ }
+
+ @Test
+ void filtersByStatusAndByKind() {
+ FileRunEvent open = given(FailureKind.UNKNOWN, TEAM, "open");
+ given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "locked");
+ controller.act(open.id(), "ACKNOWLEDGE", null);
+
+ assertThat(controller.list(FileRunEventStatus.ACKNOWLEDGED, null, null).events())
+ .hasSize(1);
+ assertThat(controller.list(null, "INPUT_PASSWORD_PROTECTED", null).events())
+ .extracting(FileRunEventView::fileId)
+ .containsExactly("locked");
+ assertThat(controller.list(null, "NO_SUCH_KIND", null).events()).isEmpty();
+ }
+
+ @Test
+ void capsTheRequestedLimitSoAClientCannotAskForTheWholeTable() {
+ // Distinct files, so five genuinely distinct rows exist. The earlier version of this
+ // test used a RUN-scoped kind with one hardcoded run id, so all five folded into one
+ // row and the assertion measured the rollup rather than the cap.
+ for (int i = 0; i < 5; i++) {
+ given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f" + i);
+ }
+
+ // Over-large and non-positive limits are both coerced rather than rejected.
+ assertThat(controller.list(null, null, 100_000).events()).hasSize(5);
+ assertThat(controller.list(null, null, 2).events()).hasSize(2);
+ assertThat(controller.list(null, null, 0).events()).hasSize(1);
+ }
+
+ @Test
+ void kindFilterAppliesBeforeTheLimitNotAfter() {
+ // A post-limit filter would take the newest N rows and then discard non-matches,
+ // returning nothing while matching rows exist. The filter lives in the query.
+ given(FailureKind.UNKNOWN, TEAM, "old-unknown");
+ for (int i = 0; i < 3; i++) {
+ given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "newer-" + i);
+ }
+
+ assertThat(controller.list(null, "UNKNOWN", 1).events())
+ .extracting(FileRunEventView::fileId)
+ .containsExactly("old-unknown");
+ }
+ }
+
+ @Nested
+ @DisplayName("acting")
+ class Acting {
+
+ @Test
+ void appliesADeclaredActionAndReturnsTheUpdatedRow() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+
+ FileRunEventView updated = controller.act(event.id(), "ACKNOWLEDGE", null);
+
+ assertThat(updated.status()).isEqualTo(FileRunEventStatus.ACKNOWLEDGED);
+ assertThat(updated.statusActor()).isEqualTo("[email protected]");
+ }
+
+ @Test
+ void acceptsAnAbsentBodyBecauseTheseActionsNeedNoInput() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+
+ assertThat(controller.act(event.id(), "DISMISS", null).status())
+ .isEqualTo(FileRunEventStatus.DISMISSED);
+ }
+
+ @Test
+ void anUnknownActionIsABadRequest() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+
+ assertThat(statusOf(() -> controller.act(event.id(), "APPROVE", null)))
+ .isEqualTo(HttpStatus.BAD_REQUEST);
+ }
+
+ @Test
+ void anotherTeamsRowIsNotFoundRatherThanForbidden() {
+ // 404 rather than 403, so the response does not confirm the row exists.
+ FileRunEvent theirs = given(FailureKind.UNKNOWN, 99L, "f1");
+
+ assertThat(statusOf(() -> controller.act(theirs.id(), "ACKNOWLEDGE", null)))
+ .isEqualTo(HttpStatus.NOT_FOUND);
+ }
+
+ @Test
+ void anAlreadyClosedRowIsAConflict() {
+ // The request was well formed and would have been valid a moment earlier.
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+ controller.act(event.id(), "DISMISS", null);
+
+ assertThat(statusOf(() -> controller.act(event.id(), "ACKNOWLEDGE", null)))
+ .isEqualTo(HttpStatus.CONFLICT);
+ }
+
+ private HttpStatus statusOf(Runnable call) {
+ try {
+ call.run();
+ } catch (ResponseStatusException e) {
+ return HttpStatus.valueOf(e.getStatusCode().value());
+ }
+ throw new AssertionError("expected the call to be refused");
+ }
+ }
+
+ @Nested
+ @DisplayName("the kinds catalogue")
+ class Kinds {
+
+ @Test
+ void servesEveryRegisteredKindWithItsFacetsAndDeclaredActions() {
+ List<FailureKindView> kinds = controller.kinds();
+
+ assertThat(kinds).hasSameSizeAs(FailureKind.values());
+ assertThat(kinds).extracting(FailureKindView::id).contains("UNKNOWN");
+ assertThat(kinds).allMatch(k -> k.stage() != null && !k.actions().isEmpty());
+ }
+
+ @Test
+ void carriesTheLabelKeyForEachDeclaredAction() {
+ FailureKindView locked =
+ controller.kinds().stream()
+ .filter(k -> "INPUT_PASSWORD_PROTECTED".equals(k.id()))
+ .findFirst()
+ .orElseThrow();
+
+ assertThat(locked.actions())
+ .extracting(FailureKindView.ActionDeclaration::labelKey)
+ .contains("portal.failures.action.dismissSkipFile");
+ }
+
+ @Test
+ void reportsTheErrorCodesEachKindClaims() {
+ FailureKindView locked =
+ controller.kinds().stream()
+ .filter(k -> "INPUT_PASSWORD_PROTECTED".equals(k.id()))
+ .findFirst()
+ .orElseThrow();
+
+ assertThat(locked.errorCodes()).containsExactly("E004");
+ }
+ }
+
+ @Nested
+ @DisplayName("only a team leader may review failures")
+ class Authorization {
+
+ @Test
+ void aMemberCannotListThem() {
+ when(authority.canEditPolicies()).thenReturn(false);
+
+ assertThatThrownBy(() -> controller.list(null, null, null))
+ .isInstanceOf(ResponseStatusException.class)
+ .satisfies(
+ e ->
+ assertThat(((ResponseStatusException) e).getStatusCode())
+ .isEqualTo(HttpStatus.FORBIDDEN));
+ }
+
+ @Test
+ void aMemberCannotDispatchAnAction() {
+ // The read being refused is not enough on its own: an id learned any other way must
+ // not let a member close another user's failure.
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f-1");
+ when(authority.canEditPolicies()).thenReturn(false);
+
+ assertThatThrownBy(() -> controller.act(event.id(), "DISMISS", null))
+ .isInstanceOf(ResponseStatusException.class)
+ .satisfies(
+ e ->
+ assertThat(((ResponseStatusException) e).getStatusCode())
+ .isEqualTo(HttpStatus.FORBIDDEN));
+ }
+
+ @Test
+ void theRegistryIsAlsoLeaderOnly() {
+ when(authority.canEditPolicies()).thenReturn(false);
+
+ assertThatThrownBy(() -> controller.kinds())
+ .isInstanceOf(ResponseStatusException.class);
+ }
+
+ @Test
+ void loginDisabledTrustsTheLocalOperator() {
+ // A single-user deployment has no roles to distinguish, so the role gate must not lock
+ // the only user out of their own failures.
+ ApplicationProperties unsecured = new ApplicationProperties();
+ unsecured.getSecurity().setEnableLogin(false);
+ FileRunEventController noLogin =
+ new FileRunEventController(
+ new FileRunEventService(
+ store,
+ new FailureActionRegistry(
+ List.of(
+ new AcknowledgeAction(store),
+ new DismissAction(store))),
+ authority,
+ userService,
+ unsecured),
+ authority,
+ unsecured);
+
+ assertThatCode(() -> noLogin.list(null, null, null)).doesNotThrowAnyException();
+ // Not merely permitted: the role is never consulted at all, which is what makes the
+ // carve-out independent of however the authority answers with no users configured.
+ verify(authority, never()).canEditPolicies();
+ }
+ }
+
+ @Nested
+ @DisplayName("team scoping cannot be influenced by the caller")
+ class Scoping {
+
+ @Test
+ void thereIsNoWayToAskForAnotherTeam() {
+ // Stated as a test because the absence of the parameter is the property. Adding a
+ // teamId parameter to list() breaks this at compile time.
+ given(FailureKind.UNKNOWN, 99L, "theirs");
+
+ FileRunEventController.FileRunEventsResponse response =
+ controller.list(null, null, null);
+
+ assertThat(response.events()).isEmpty();
+ assertThat(
+ Arrays.stream(FileRunEventController.class.getDeclaredMethods())
+ .filter(m -> "list".equals(m.getName()))
+ .flatMap(m -> Arrays.stream(m.getParameterTypes()))
+ .toList())
+ .doesNotContain(Long.class);
+ }
+
+ @Test
+ void loginDisabledReadsTheUnteamedRows() {
+ ApplicationProperties unsecured = new ApplicationProperties();
+ unsecured.getSecurity().setEnableLogin(false);
+ FileRunEventController noLogin =
+ new FileRunEventController(
+ new FileRunEventService(
+ store,
+ new FailureActionRegistry(
+ List.of(
+ new AcknowledgeAction(store),
+ new DismissAction(store))),
+ authority,
+ userService,
+ unsecured),
+ authority,
+ unsecured);
+ given(FailureKind.UNKNOWN, null, "unteamed");
+ given(FailureKind.UNKNOWN, TEAM, "teamed");
+
+ assertThat(noLogin.list(null, null, null).events())
+ .extracting(FileRunEventView::fileId)
+ .containsExactly("unteamed");
+ }
+ }
+
+ @Nested
+ @DisplayName("action request body")
+ class RequestBody {
+
+ @Test
+ void nullInputsAreTreatedAsEmpty() {
+ assertThat(new FileRunEventController.ActionRequest(null).safeInputs()).isEmpty();
+ assertThat(
+ new FileRunEventController.ActionRequest(Map.of("password", "x"))
+ .safeInputs())
+ .containsEntry("password", "x");
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventHttpIntegrationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventHttpIntegrationTest.java
new file mode 100644
index 0000000000..3537c9e06c
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventHttpIntegrationTest.java
@@ -0,0 +1,379 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.util.List;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration;
+import org.springframework.boot.security.autoconfigure.UserDetailsServiceAutoConfiguration;
+import org.springframework.boot.security.autoconfigure.actuate.web.servlet.ManagementWebSecurityAutoConfiguration;
+import org.springframework.boot.security.autoconfigure.web.servlet.SecurityFilterAutoConfiguration;
+import org.springframework.boot.security.autoconfigure.web.servlet.ServletWebSecurityAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.server.LocalServerPort;
+import org.springframework.context.annotation.Bean;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.UserServiceInterface;
+import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * End-to-end test of the read path and action dispatch over real HTTP, against live Jetty on a
+ * random port.
+ *
+ * <p>The other tests here call controller methods directly, which skips response serialisation,
+ * body binding, query coercion and status mapping. A double-encoded request body already slipped
+ * through that gap once, so these use a real {@link HttpClient} against a real socket.
+ */
+@SpringBootTest(
+ classes = FileRunEventHttpIntegrationTest.TestApp.class,
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class FileRunEventHttpIntegrationTest {
+
+ private static final Long TEAM = 42L;
+ private static final String ACTOR = "[email protected]";
+
+ @LocalServerPort private int port;
+
+ private final HttpClient http = HttpClient.newHttpClient();
+ private final JsonMapper mapper = JsonMapper.builder().build();
+
+ /** Shared so a test can seed a row and then read it back over the wire. */
+ private static InMemoryFileRunEventRepository repository;
+
+ @BeforeEach
+ void resetRows() {
+ repository.rows.clear();
+ }
+
+ private String seed(FailureKind kind, Long teamId, String fileId, String detail) {
+ FileRunEventStore store = new FileRunEventStore(repository);
+ return store.record(
+ new RecordFailure(
+ kind,
+ FailureOrigin.POLICY,
+ teamId,
+ "policy-1",
+ "run-1",
+ null,
+ fileId,
+ detail))
+ .id();
+ }
+
+ private HttpResponse<String> get(String path) throws Exception {
+ return http.send(
+ HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)).GET().build(),
+ HttpResponse.BodyHandlers.ofString());
+ }
+
+ private HttpResponse<String> post(String path, String jsonBody) throws Exception {
+ HttpRequest.Builder builder =
+ HttpRequest.newBuilder(URI.create("http://localhost:" + port + path))
+ .header("Content-Type", "application/json");
+ builder =
+ jsonBody == null
+ ? builder.POST(HttpRequest.BodyPublishers.noBody())
+ : builder.POST(HttpRequest.BodyPublishers.ofString(jsonBody));
+ return http.send(builder.build(), HttpResponse.BodyHandlers.ofString());
+ }
+
+ @Nested
+ @DisplayName("the read path")
+ class ReadPath {
+
+ @Test
+ void serialisesAnEventWithItsFacetsCopyKeysAndResolvedActions() throws Exception {
+ seed(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "acme-msa", "locked tight");
+
+ HttpResponse<String> response = get("/api/v1/file-run-events");
+
+ assertThat(response.statusCode()).isEqualTo(200);
+ JsonNode row = mapper.readTree(response.body()).get("events").get(0);
+
+ assertThat(row.get("kindId").asString()).isEqualTo("INPUT_PASSWORD_PROTECTED");
+ assertThat(row.get("stage").asString()).isEqualTo("INPUT");
+ assertThat(row.get("severity").asString()).isEqualTo("ERROR");
+ assertThat(row.get("scope").asString()).isEqualTo("FILE");
+ assertThat(row.get("origin").asString()).isEqualTo("POLICY");
+ assertThat(row.get("remedy").asString()).isEqualTo("NEEDS_USER_INPUT");
+ assertThat(row.get("titleKey").asString())
+ .isEqualTo("portal.failures.kind.inputPasswordProtected.title");
+ assertThat(row.get("defaultTitle").asString()).isNotBlank();
+ assertThat(row.get("detail").asString()).isEqualTo("locked tight");
+ assertThat(row.get("status").asString()).isEqualTo("NEW");
+ assertThat(row.get("occurrences").asInt()).isEqualTo(1);
+ // Epoch millis, not an ISO string: the client renders relative times from a number.
+ assertThat(row.get("lastSeenAt").isNumber()).isTrue();
+
+ JsonNode actions = row.get("actions");
+ assertThat(actions).hasSize(2);
+ assertThat(actions.get(0).get("id").asString()).isEqualTo("ACKNOWLEDGE");
+ assertThat(actions.get(0).get("labelKey").asString())
+ .isEqualTo("portal.failures.action.acknowledge");
+ assertThat(actions.get(0).get("enabled").asBoolean()).isTrue();
+ assertThat(actions.get(0).get("disabledReasonKey").isNull()).isTrue();
+ }
+
+ @Test
+ void doesNotReturnAnotherTeamsRows() throws Exception {
+ seed(FailureKind.UNKNOWN, 999L, "theirs", "not yours");
+
+ JsonNode events = mapper.readTree(get("/api/v1/file-run-events").body()).get("events");
+
+ assertThat(events).isEmpty();
+ }
+
+ @Test
+ void ignoresAClientSuppliedTeamId() throws Exception {
+ // The team comes from the principal, so a teamId query param is ignored rather than
+ // honoured.
+ seed(FailureKind.UNKNOWN, 999L, "theirs", "not yours");
+
+ JsonNode events =
+ mapper.readTree(get("/api/v1/file-run-events?teamId=999").body()).get("events");
+
+ assertThat(events).isEmpty();
+ }
+
+ @Test
+ void coercesQueryParametersAndFiltersOnThem() throws Exception {
+ String open = seed(FailureKind.UNKNOWN, TEAM, "open", "a");
+ seed(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "locked", "b");
+ post("/api/v1/file-run-events/" + open + "/actions/ACKNOWLEDGE", "{\"inputs\":{}}");
+
+ JsonNode acknowledged =
+ mapper.readTree(get("/api/v1/file-run-events?status=ACKNOWLEDGED").body())
+ .get("events");
+ assertThat(acknowledged).hasSize(1);
+
+ JsonNode byKind =
+ mapper.readTree(
+ get("/api/v1/file-run-events?kindId=INPUT_PASSWORD_PROTECTED")
+ .body())
+ .get("events");
+ assertThat(byKind).hasSize(1);
+ assertThat(byKind.get(0).get("fileId").asString()).isEqualTo("locked");
+
+ // `limit` binds as an Integer, so a non-numeric value is a bad request, not a 500.
+ assertThat(get("/api/v1/file-run-events?limit=abc").statusCode()).isEqualTo(400);
+ }
+
+ @Test
+ void rejectsAnUnknownStatusFilter() throws Exception {
+ assertThat(get("/api/v1/file-run-events?status=BANANA").statusCode()).isEqualTo(400);
+ }
+
+ @Test
+ void servesTheKindsCatalogue() throws Exception {
+ HttpResponse<String> response = get("/api/v1/file-run-events/kinds");
+
+ assertThat(response.statusCode()).isEqualTo(200);
+ JsonNode kinds = mapper.readTree(response.body());
+ assertThat(kinds).hasSize(FailureKind.values().length);
+ assertThat(kinds.get(0).get("actions").isArray()).isTrue();
+ }
+ }
+
+ @Nested
+ @DisplayName("action dispatch")
+ class Dispatch {
+
+ @Test
+ void bindsTheRequestBodyAndReturnsTheUpdatedRow() throws Exception {
+ // The regression guard: an object body, sent as real JSON over the wire, binding into
+ // ActionRequest. A double-encoded string would fail here.
+ String id = seed(FailureKind.UNKNOWN, TEAM, "f1", "boom");
+
+ HttpResponse<String> response =
+ post(
+ "/api/v1/file-run-events/" + id + "/actions/ACKNOWLEDGE",
+ "{\"inputs\":{}}");
+
+ assertThat(response.statusCode()).isEqualTo(200);
+ JsonNode row = mapper.readTree(response.body());
+ assertThat(row.get("status").asString()).isEqualTo("ACKNOWLEDGED");
+ assertThat(row.get("statusActor").asString()).isEqualTo(ACTOR);
+ }
+
+ @Test
+ void acceptsAPopulatedInputsMap() throws Exception {
+ // Nothing consumes inputs yet, but the shape must bind so the first action that needs
+ // one (a password) does not discover a broken contract.
+ String id = seed(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1", "locked");
+
+ HttpResponse<String> response =
+ post(
+ "/api/v1/file-run-events/" + id + "/actions/ACKNOWLEDGE",
+ "{\"inputs\":{\"password\":\"hunter2\"}}");
+
+ assertThat(response.statusCode()).isEqualTo(200);
+ }
+
+ @Test
+ void acceptsAnAbsentBody() throws Exception {
+ String id = seed(FailureKind.UNKNOWN, TEAM, "f1", "boom");
+
+ assertThat(
+ post("/api/v1/file-run-events/" + id + "/actions/DISMISS", null)
+ .statusCode())
+ .isEqualTo(200);
+ }
+
+ @Test
+ void mapsAnUnknownActionToBadRequest() throws Exception {
+ String id = seed(FailureKind.UNKNOWN, TEAM, "f1", "boom");
+
+ assertThat(
+ post(
+ "/api/v1/file-run-events/" + id + "/actions/APPROVE",
+ "{\"inputs\":{}}")
+ .statusCode())
+ .isEqualTo(400);
+ }
+
+ @Test
+ void mapsAnotherTeamsRowToNotFound() throws Exception {
+ String id = seed(FailureKind.UNKNOWN, 999L, "theirs", "boom");
+
+ assertThat(
+ post(
+ "/api/v1/file-run-events/"
+ + id
+ + "/actions/ACKNOWLEDGE",
+ "{\"inputs\":{}}")
+ .statusCode())
+ .isEqualTo(404);
+ }
+
+ @Test
+ void mapsAnAlreadyClosedRowToConflict() throws Exception {
+ String id = seed(FailureKind.UNKNOWN, TEAM, "f1", "boom");
+ post("/api/v1/file-run-events/" + id + "/actions/DISMISS", "{\"inputs\":{}}");
+
+ assertThat(
+ post(
+ "/api/v1/file-run-events/"
+ + id
+ + "/actions/ACKNOWLEDGE",
+ "{\"inputs\":{}}")
+ .statusCode())
+ .isEqualTo(409);
+ }
+
+ @Test
+ void aDismissedRowComesBackWithItsActionsDisabled() throws Exception {
+ String id = seed(FailureKind.UNKNOWN, TEAM, "f1", "boom");
+
+ JsonNode row =
+ mapper.readTree(
+ post("/api/v1/file-run-events/" + id + "/actions/DISMISS", null)
+ .body());
+
+ assertThat(row.get("status").asString()).isEqualTo("DISMISSED");
+ for (JsonNode action : row.get("actions")) {
+ assertThat(action.get("enabled").asBoolean()).isFalse();
+ assertThat(action.get("disabledReasonKey").asString())
+ .isEqualTo("portal.failures.disabled.closed");
+ }
+ }
+ }
+
+ /**
+ * Spring Security is excluded rather than configured to permit everything: the auto-configured
+ * chain would answer 401 before the handler runs, and this test is about routing, body binding,
+ * serialisation and status mapping. Authorisation and team scoping have their own tests.
+ */
+ @SpringBootConfiguration
+ @EnableAutoConfiguration(
+ exclude = {
+ SecurityAutoConfiguration.class,
+ ServletWebSecurityAutoConfiguration.class,
+ ManagementWebSecurityAutoConfiguration.class,
+ SecurityFilterAutoConfiguration.class,
+ UserDetailsServiceAutoConfiguration.class
+ })
+ static class TestApp {
+
+ /**
+ * Backed by the shared in-memory repository, since this test is about the HTTP layer and
+ * persistence has its own tests.
+ */
+ @Bean
+ FileRunEventStore fileRunEventStore() {
+ repository = new InMemoryFileRunEventRepository();
+ return new FileRunEventStore(repository);
+ }
+
+ @Bean
+ FailureActionRegistry failureActionRegistry(List<FailureAction> actions) {
+ return new FailureActionRegistry(actions);
+ }
+
+ @Bean
+ AcknowledgeAction acknowledgeAction(FileRunEventStore store) {
+ return new AcknowledgeAction(store);
+ }
+
+ @Bean
+ DismissAction dismissAction(FileRunEventStore store) {
+ return new DismissAction(store);
+ }
+
+ @Bean
+ ApplicationProperties applicationProperties() {
+ ApplicationProperties props = new ApplicationProperties();
+ props.getSecurity().setEnableLogin(true);
+ props.getAutomaticallyGenerated().setAppVersion("test");
+ return props;
+ }
+
+ @Bean
+ PolicyManagementAuthority policyManagementAuthority() {
+ PolicyManagementAuthority authority =
+ org.mockito.Mockito.mock(PolicyManagementAuthority.class);
+ org.mockito.Mockito.when(authority.currentUserTeamId()).thenReturn(TEAM);
+ org.mockito.Mockito.when(authority.canEditPolicies()).thenReturn(true);
+ return authority;
+ }
+
+ @Bean
+ UserServiceInterface userService() {
+ UserServiceInterface users = org.mockito.Mockito.mock(UserServiceInterface.class);
+ org.mockito.Mockito.when(users.getCurrentUsername()).thenReturn(ACTOR);
+ return users;
+ }
+
+ @Bean
+ FileRunEventService fileRunEventService(
+ FileRunEventStore store,
+ FailureActionRegistry registry,
+ PolicyManagementAuthority authority,
+ UserServiceInterface users,
+ ApplicationProperties props) {
+ return new FileRunEventService(store, registry, authority, users, props);
+ }
+
+ @Bean
+ FileRunEventController fileRunEventController(
+ FileRunEventService service,
+ PolicyManagementAuthority authority,
+ ApplicationProperties props) {
+ return new FileRunEventController(service, authority, props);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventServiceTest.java
new file mode 100644
index 0000000000..cd75c181c5
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventServiceTest.java
@@ -0,0 +1,393 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.lenient;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Field;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.UserServiceInterface;
+import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
+
+/**
+ * Tests for {@link FileRunEventService}: team scoping, the declaration guard, transition legality,
+ * and that triaging an incident leaves the document alone.
+ */
+@ExtendWith(MockitoExtension.class)
+class FileRunEventServiceTest {
+
+ private static final Long TEAM = 3L;
+ private static final String ACTOR = "[email protected]";
+
+ @Mock private PolicyManagementAuthority authority;
+ @Mock private UserServiceInterface userService;
+
+ private FileRunEventStore store;
+ private FileRunEventService service;
+
+ @BeforeEach
+ void setUp() {
+ ApplicationProperties props = new ApplicationProperties();
+ props.getSecurity().setEnableLogin(true);
+
+ store = new FileRunEventStore(new InMemoryFileRunEventRepository());
+ FailureActionRegistry registry =
+ new FailureActionRegistry(
+ List.of(new AcknowledgeAction(store), new DismissAction(store)));
+ registry.verifyEveryDeclaredActionHasAHandler();
+
+ service = new FileRunEventService(store, registry, authority, userService, props);
+
+ lenient().when(authority.currentUserTeamId()).thenReturn(TEAM);
+ lenient().when(userService.getCurrentUsername()).thenReturn(ACTOR);
+ }
+
+ private FileRunEvent given(FailureKind kind, Long teamId, String fileId) {
+ return store.record(
+ new RecordFailure(
+ kind,
+ FailureOrigin.POLICY,
+ teamId,
+ "policy-1",
+ "run-1",
+ null,
+ fileId,
+ "detail"));
+ }
+
+ @Nested
+ @DisplayName("acknowledge")
+ class Acknowledge {
+
+ @Test
+ void movesANewEventToAcknowledgedAndStampsTheActor() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+
+ FileRunEvent updated = service.dispatch(event.id(), "ACKNOWLEDGE", Map.of());
+
+ assertThat(updated.status()).isEqualTo(FileRunEventStatus.ACKNOWLEDGED);
+ assertThat(updated.statusActor()).isEqualTo(ACTOR);
+ assertThat(updated.statusAt()).isNotNull();
+ }
+
+ @Test
+ void isANoOpWhenAlreadyAcknowledgedSoOwnershipIsNotStolen() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+ FileRunEvent first = service.dispatch(event.id(), "ACKNOWLEDGE", Map.of());
+ Instant originalAt = first.statusAt();
+
+ when(userService.getCurrentUsername()).thenReturn("[email protected]");
+ FileRunEvent second = service.dispatch(event.id(), "ACKNOWLEDGE", Map.of());
+
+ assertThat(second.status()).isEqualTo(FileRunEventStatus.ACKNOWLEDGED);
+ assertThat(second.statusActor()).isEqualTo(ACTOR);
+ assertThat(second.statusAt()).isEqualTo(originalAt);
+ }
+ }
+
+ @Nested
+ @DisplayName("dismiss")
+ class Dismiss {
+
+ @Test
+ void closesANewEvent() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+
+ assertThat(service.dispatch(event.id(), "DISMISS", Map.of()).status())
+ .isEqualTo(FileRunEventStatus.DISMISSED);
+ }
+
+ @Test
+ void closesAnAcknowledgedEvent() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+ service.dispatch(event.id(), "ACKNOWLEDGE", Map.of());
+
+ assertThat(service.dispatch(event.id(), "DISMISS", Map.of()).status())
+ .isEqualTo(FileRunEventStatus.DISMISSED);
+ }
+ }
+
+ @Nested
+ @DisplayName("triage never touches the document")
+ class NeverTouchesTheDocument {
+
+ /**
+ * What makes both actions valid for every kind, UNKNOWN included: they are incident
+ * dispositions, not document ones. Asserted structurally — an action whose only dependency
+ * is the event store <em>cannot</em> reach the ledger, file storage, or an output sink. A
+ * mocked-collaborator version of this test passed vacuously, because nothing ever handed
+ * the mocks to the actions.
+ */
+ @Test
+ void actionsDependOnNothingButTheEventStore() {
+ for (FailureAction action :
+ List.of(new AcknowledgeAction(store), new DismissAction(store))) {
+ String name = action.getClass().getSimpleName();
+ List<Class<?>> dependencies =
+ Arrays.stream(action.getClass().getDeclaredFields())
+ // Coverage instrumentation adds its own field; only ours count.
+ .filter(field -> !field.isSynthetic())
+ .map(Field::getType)
+ .toList();
+
+ // Asserted first, so an action that lost its fields fails here rather than
+ // satisfying the check below by holding nothing at all.
+ assertThat(dependencies).as("%s declares no dependencies", name).isNotEmpty();
+ assertThat(dependencies)
+ .as(
+ "%s: an incident disposition reaches the event store and nothing"
+ + " else. Adding to this is how one starts touching"
+ + " documents.",
+ name)
+ .containsOnly(FileRunEventStore.class);
+ }
+ }
+
+ @Test
+ void dismissLeavesTheFileReferenceIntactRatherThanClearingIt() {
+ // Nothing is deleted, so the row must still say which file it was about.
+ FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
+
+ FileRunEvent dismissed = service.dispatch(event.id(), "DISMISS", Map.of());
+
+ assertThat(dismissed.fileId()).isEqualTo("f1");
+ }
+ }
+
+ @Nested
+ @DisplayName("guards")
+ class Guards {
+
+ @Test
+ void anotherTeamsEventIsNotFound() {
+ FileRunEvent theirs = given(FailureKind.UNKNOWN, 99L, "f1");
+
+ assertThatThrownBy(() -> service.dispatch(theirs.id(), "ACKNOWLEDGE", Map.of()))
+ .isInstanceOf(FailureActionException.class)
+ .extracting(e -> ((FailureActionException) e).getReason())
+ .isEqualTo(FailureActionException.Reason.EVENT_NOT_FOUND);
+ }
+
+ @Test
+ void anUnknownEventIdIsNotFound() {
+ assertThatThrownBy(() -> service.dispatch("nope", "ACKNOWLEDGE", Map.of()))
+ .isInstanceOf(FailureActionException.class)
+ .extracting(e -> ((FailureActionException) e).getReason())
+ .isEqualTo(FailureActionException.Reason.EVENT_NOT_FOUND);
+ }
+
+ @Test
+ void anUnknownActionIdIsRejected() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+
+ assertThatThrownBy(() -> service.dispatch(event.id(), "APPROVE", Map.of()))
+ .isInstanceOf(FailureActionException.class)
+ .extracting(e -> ((FailureActionException) e).getReason())
+ .isEqualTo(FailureActionException.Reason.ACTION_NOT_RECOGNISED);
+ }
+
+ @Test
+ void aDeclaredActionWithNoRegisteredHandlerIsRejectedWithoutAnyStateChange() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+ ApplicationProperties props = new ApplicationProperties();
+ props.getSecurity().setEnableLogin(true);
+ FileRunEventService missingHandler =
+ new FileRunEventService(
+ store,
+ new FailureActionRegistry(List.of(new AcknowledgeAction(store))),
+ authority,
+ userService,
+ props);
+
+ assertThatThrownBy(() -> missingHandler.dispatch(event.id(), "DISMISS", Map.of()))
+ .isInstanceOf(FailureActionException.class)
+ .extracting(e -> ((FailureActionException) e).getReason())
+ .isEqualTo(FailureActionException.Reason.ACTION_NOT_RECOGNISED);
+
+ assertThat(store.find(event.id(), TEAM).orElseThrow().status())
+ .isEqualTo(FileRunEventStatus.NEW);
+ }
+
+ @Test
+ void aClosedEventCannotBeActedOnAgain() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+ service.dispatch(event.id(), "DISMISS", Map.of());
+
+ assertThatThrownBy(() -> service.dispatch(event.id(), "ACKNOWLEDGE", Map.of()))
+ .isInstanceOf(FailureActionException.class)
+ .extracting(e -> ((FailureActionException) e).getReason())
+ .isEqualTo(FailureActionException.Reason.ALREADY_CLOSED);
+
+ assertThatThrownBy(() -> service.dispatch(event.id(), "DISMISS", Map.of()))
+ .isInstanceOf(FailureActionException.class)
+ .extracting(e -> ((FailureActionException) e).getReason())
+ .isEqualTo(FailureActionException.Reason.ALREADY_CLOSED);
+ }
+ }
+
+ @Nested
+ @DisplayName("available actions are resolved per row")
+ class Availability {
+
+ @Test
+ void openRowOffersEveryDeclaredActionEnabled() {
+ FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
+
+ List<FileRunEventService.AvailableAction> actions = service.availableActions(event);
+
+ assertThat(actions).hasSize(2);
+ assertThat(actions).allMatch(FileRunEventService.AvailableAction::enabled);
+ assertThat(actions).allMatch(action -> action.disabledReasonKey() == null);
+ }
+
+ @Test
+ void closedRowOffersThemDisabledWithAReasonRatherThanHidingThem() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+ FileRunEvent dismissed = service.dispatch(event.id(), "DISMISS", Map.of());
+
+ List<FileRunEventService.AvailableAction> actions = service.availableActions(dismissed);
+
+ assertThat(actions).isNotEmpty();
+ assertThat(actions).noneMatch(FileRunEventService.AvailableAction::enabled);
+ assertThat(actions)
+ .allMatch(
+ action ->
+ "portal.failures.disabled.closed"
+ .equals(action.disabledReasonKey()));
+ }
+
+ @Test
+ void carriesTheKindsOverriddenLabelWhereItHasOne() {
+ FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
+
+ assertThat(service.availableActions(event))
+ .extracting(FileRunEventService.AvailableAction::labelKey)
+ .contains("portal.failures.action.dismissSkipFile");
+ }
+
+ @Test
+ void fallsBackToTheGenericLabelWhereTheKindDeclaresNoOverride() {
+ FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
+
+ assertThat(service.availableActions(event))
+ .extracting(FileRunEventService.AvailableAction::labelKey)
+ .containsExactlyInAnyOrder(
+ "portal.failures.action.acknowledge", "portal.failures.action.dismiss");
+ }
+ }
+
+ @Nested
+ @DisplayName("team scoping")
+ class Scoping {
+
+ @Test
+ void listReturnsOnlyTheCallersTeam() {
+ given(FailureKind.UNKNOWN, TEAM, "mine");
+ given(FailureKind.UNKNOWN, 99L, "theirs");
+
+ assertThat(service.list(null, null, 50))
+ .extracting(FileRunEvent::fileId)
+ .containsExactly("mine");
+ }
+
+ @Test
+ void aCallerWhoseTeamCannotBeResolvedReadsNothing() {
+ // A run with no stored policy is recorded unteamed, and those rows are shared by every
+ // team, so a caller whose team does not resolve reads nothing instead.
+ given(FailureKind.UNKNOWN, null, "someone-elses-adhoc-run");
+ given(FailureKind.UNKNOWN, TEAM, "mine");
+ when(authority.currentUserTeamId()).thenReturn(null);
+
+ assertThat(service.list(null, null, 50)).isEmpty();
+ }
+
+ @Test
+ void aCallerWhoseTeamCannotBeResolvedCannotActOnAnUnteamedRow() {
+ FileRunEvent unteamed = given(FailureKind.UNKNOWN, null, "someone-elses-adhoc-run");
+ when(authority.currentUserTeamId()).thenReturn(null);
+
+ assertThatThrownBy(() -> service.dispatch(unteamed.id(), "ACKNOWLEDGE", Map.of()))
+ .isInstanceOf(FailureActionException.class)
+ .extracting(e -> ((FailureActionException) e).getReason())
+ // Not a distinct "no team" reason: that would confirm the id exists.
+ .isEqualTo(FailureActionException.Reason.EVENT_NOT_FOUND);
+
+ assertThat(store.find(unteamed.id(), null).orElseThrow().status())
+ .isEqualTo(FileRunEventStatus.NEW);
+ }
+
+ @Test
+ void loginDisabledFallsBackToTheUnteamedRowsWithoutConsultingTheAuthority() {
+ ApplicationProperties props = new ApplicationProperties();
+ props.getSecurity().setEnableLogin(false);
+ FailureActionRegistry registry =
+ new FailureActionRegistry(
+ List.of(new AcknowledgeAction(store), new DismissAction(store)));
+ FileRunEventService unsecured =
+ new FileRunEventService(store, registry, authority, userService, props);
+
+ given(FailureKind.UNKNOWN, null, "unteamed");
+ given(FailureKind.UNKNOWN, TEAM, "teamed");
+
+ assertThat(unsecured.list(null, null, 50))
+ .extracting(FileRunEvent::fileId)
+ .containsExactly("unteamed");
+ }
+ }
+
+ @Nested
+ @DisplayName("the action registry")
+ class Registry {
+
+ @Test
+ void refusesToStartWhenAKindDeclaresAnActionWithNoHandler() {
+ // A missing handler would otherwise surface as a button that 400s in production.
+ FailureActionRegistry incomplete =
+ new FailureActionRegistry(List.of(new AcknowledgeAction(store)));
+
+ assertThatThrownBy(incomplete::verifyEveryDeclaredActionHasAHandler)
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("DISMISS");
+ }
+
+ @Test
+ void refusesTwoHandlersForTheSameAction() {
+ assertThatThrownBy(
+ () ->
+ new FailureActionRegistry(
+ List.of(
+ new AcknowledgeAction(store),
+ new AcknowledgeAction(store))))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("ACKNOWLEDGE");
+ }
+
+ @Test
+ void acceptsACompleteSetOfHandlers() {
+ FailureActionRegistry complete =
+ new FailureActionRegistry(
+ List.of(new AcknowledgeAction(store), new DismissAction(store)));
+
+ complete.verifyEveryDeclaredActionHasAHandler();
+
+ for (FailureActionId id : FailureActionId.values()) {
+ assertThat(complete.find(id)).isPresent();
+ }
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventStoreDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventStoreDbTest.java
new file mode 100644
index 0000000000..46d2be8a0d
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventStoreDbTest.java
@@ -0,0 +1,303 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Proxy;
+import java.time.Instant;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * {@link FileRunEventStore} against the real JPQL on a real (H2) database. Every other test in this
+ * package substitutes {@link InMemoryFileRunEventRepository}, whose Java filters would keep passing
+ * if the queries themselves regressed — the team-isolation clause could be deleted from the JPQL
+ * and no in-memory test would notice.
+ *
+ * <p>{@code NOT_SUPPORTED} suspends {@code @DataJpaTest}'s per-test transaction, so every store
+ * call commits in its own transaction as at runtime. That is what makes the stale-snapshot test
+ * meaningful: inside one shared persistence context, both reads would hand back the same managed
+ * instance and the bug could not show.
+ */
+@DataJpaTest
+@Transactional(propagation = Propagation.NOT_SUPPORTED)
+class FileRunEventStoreDbTest {
+
+ private static final Long TEAM = 7L;
+ private static final Long OTHER_TEAM = 9L;
+
+ @Autowired private FileRunEventRepository repository;
+
+ private FileRunEventStore store;
+
+ @BeforeEach
+ void setUp() {
+ store = new FileRunEventStore(repository);
+ }
+
+ @AfterEach
+ void wipe() {
+ repository.deleteAllInBatch();
+ }
+
+ private RecordFailure failure(FailureKind kind, Long teamId, String fileId) {
+ return new RecordFailure(
+ kind,
+ FailureOrigin.POLICY,
+ teamId,
+ "policy-1",
+ "run-1",
+ null,
+ fileId,
+ "detail");
+ }
+
+ @Test
+ @DisplayName("team isolation is enforced by the query, including the unteamed rows")
+ void teamIsolationIsEnforcedBySql() {
+ store.record(failure(FailureKind.UNKNOWN, TEAM, "ours"));
+ store.record(failure(FailureKind.UNKNOWN, OTHER_TEAM, "theirs"));
+ store.record(failure(FailureKind.UNKNOWN, null, "unteamed"));
+
+ assertThat(store.list(TEAM, null, null, 10))
+ .extracting(FileRunEvent::fileId)
+ .containsExactly("ours");
+ // A plain `e.teamId = :teamId` would return nothing here: SQL equality against NULL is
+ // never true, which is what the explicit null branch in the JPQL exists for.
+ assertThat(store.list(null, null, null, 10))
+ .extracting(FileRunEvent::fileId)
+ .containsExactly("unteamed");
+ }
+
+ @Test
+ @DisplayName("a fold lands on the row's current state, not the caller's snapshot")
+ void foldTargetsTheCurrentRowNotACallersSnapshot() {
+ // The lost-update shape: record reads the row, a reviewer dismisses it, then the fold
+ // applies. A save() of the stale snapshot would merge status = NEW back over the dismiss.
+ FileRunEvent event = store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f"));
+ store.applyStatus(event.id(), TEAM, FileRunEventStatus.DISMISSED, "[email protected]");
+
+ FileRunEvent folded =
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f"));
+
+ assertThat(folded.status()).isEqualTo(FileRunEventStatus.DISMISSED);
+ assertThat(folded.statusActor()).isEqualTo("[email protected]");
+ assertThat(folded.occurrences()).isEqualTo(2);
+ }
+
+ @Test
+ @DisplayName("a dismiss landing mid-fold is not reverted by the folder's stale snapshot")
+ void aDismissLandingMidFoldIsNotReverted() {
+ // The reviewer's repro, made deterministic: the fold's read happens, then a dismiss lands,
+ // then the fold applies. The old save()-based absorb merged the pre-dismiss snapshot back
+ // over the row, reverting status to NEW and erasing the reviewer's action.
+ FileRunEvent event = store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f"));
+ AtomicBoolean interleaved = new AtomicBoolean();
+ FileRunEventRepository interleaving =
+ (FileRunEventRepository)
+ Proxy.newProxyInstance(
+ getClass().getClassLoader(),
+ new Class<?>[] {FileRunEventRepository.class},
+ (proxy, method, args) -> {
+ Object result;
+ try {
+ result = method.invoke(repository, args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ }
+ if ("findByTeamAndDedupKey".equals(method.getName())
+ && interleaved.compareAndSet(false, true)) {
+ store.applyStatus(
+ event.id(),
+ TEAM,
+ FileRunEventStatus.DISMISSED,
+ }
+ return result;
+ });
+
+ FileRunEvent folded =
+ new FileRunEventStore(interleaving)
+ .record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f"));
+
+ assertThat(folded.status()).isEqualTo(FileRunEventStatus.DISMISSED);
+ assertThat(folded.statusActor()).isEqualTo("[email protected]");
+ assertThat(folded.occurrences()).isEqualTo(2);
+ }
+
+ @Test
+ @DisplayName("a row deleted between the dedup read and the fold is re-inserted, not lost")
+ void aVanishedRowIsReinsertedRatherThanLost() {
+ // Retention or a manual purge can delete the row a fold was about to land on. The fold
+ // then matches nothing, and treating that as an error would drop the incident entirely:
+ // the recorder swallows what record() throws, leaving the failure as only a log line.
+ FileRunEvent first = store.record(failure(FailureKind.UNKNOWN, TEAM, "f"));
+ AtomicBoolean deleted = new AtomicBoolean();
+ FileRunEventRepository vanishing =
+ (FileRunEventRepository)
+ Proxy.newProxyInstance(
+ getClass().getClassLoader(),
+ new Class<?>[] {FileRunEventRepository.class},
+ (proxy, method, args) -> {
+ if ("fold".equals(method.getName())
+ && deleted.compareAndSet(false, true)) {
+ repository.deleteById(first.id());
+ }
+ try {
+ return method.invoke(repository, args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ }
+ });
+
+ FileRunEvent replacement =
+ new FileRunEventStore(vanishing).record(failure(FailureKind.UNKNOWN, TEAM, "f"));
+
+ assertThat(replacement.id()).isNotEqualTo(first.id());
+ assertThat(replacement.occurrences()).isEqualTo(1);
+ assertThat(store.list(TEAM, null, null, 10)).hasSize(1);
+ }
+
+ @Test
+ @DisplayName("the same broken file folds across runs, and distinct files do not")
+ void repeatsFoldOnTheDocumentNotTheRun() {
+ // The point of the rollup. Each sweep starts a new run, so keying on the run id alone
+ // meant a file that failed every sweep opened a new incident every sweep, and several
+ // files failing in one run collapsed into one. Both are wrong; the document is the key.
+ RecordFailure firstSweep = locked("run-1", "file-hash-a");
+ RecordFailure secondSweep = locked("run-2", "file-hash-a");
+ RecordFailure otherFile = locked("run-1", "file-hash-b");
+
+ store.record(firstSweep);
+ store.record(otherFile);
+ FileRunEvent folded = store.record(secondSweep);
+
+ assertThat(folded.occurrences()).isEqualTo(2);
+ assertThat(store.list(TEAM, null, null, 10))
+ .as("one incident per document, however many runs it failed in")
+ .extracting(FileRunEvent::fileId)
+ .containsExactlyInAnyOrder("file-hash-a", "file-hash-b");
+ }
+
+ private RecordFailure locked(String runId, String fileId) {
+ return RecordFailure.forRun(
+ FailureKind.INPUT_PASSWORD_PROTECTED,
+ TEAM,
+ null,
+ "policy-1",
+ runId,
+ fileId,
+ "locked");
+ }
+
+ @Test
+ @DisplayName("the kind filter applies before the limit, not after")
+ void kindFilterAppliesBeforeTheLimit() {
+ store.record(failure(FailureKind.UNKNOWN, TEAM, "old-unknown"));
+ for (int i = 0; i < 3; i++) {
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "newer-" + i));
+ }
+
+ assertThat(store.list(TEAM, null, "UNKNOWN", 1))
+ .extracting(FileRunEvent::fileId)
+ .containsExactly("old-unknown");
+ }
+
+ @Test
+ @DisplayName("two racing closes resolve to one winner")
+ void twoClosesResolveToOneWinner() {
+ FileRunEvent event = store.record(failure(FailureKind.UNKNOWN, TEAM, "f"));
+ store.applyStatus(event.id(), TEAM, FileRunEventStatus.DISMISSED, "[email protected]");
+
+ // The second close passed the service's terminal() pre-check in its own request; the
+ // guarded UPDATE is what refuses it here.
+ assertThatThrownBy(
+ () ->
+ store.applyStatus(
+ event.id(),
+ TEAM,
+ FileRunEventStatus.DISMISSED,
+ .isInstanceOf(FailureActionException.class)
+ .extracting(e -> ((FailureActionException) e).getReason())
+ .isEqualTo(FailureActionException.Reason.ALREADY_CLOSED);
+
+ assertThat(store.find(event.id(), TEAM).orElseThrow().statusActor())
+ .isEqualTo("[email protected]");
+ }
+
+ @Test
+ @DisplayName("losing a delete race reports the row missing, not closed")
+ void aDeletedRowIsReportedMissingRatherThanClosed() {
+ // Both refusals come from the same guarded UPDATE returning zero rows, so the store has to
+ // tell them apart afterwards. Getting it wrong answers 400 for a row that is simply gone,
+ // where every other "no such event" answers 404.
+ FileRunEvent event = store.record(failure(FailureKind.UNKNOWN, TEAM, "f"));
+ repository.deleteById(event.id());
+
+ assertThatThrownBy(
+ () ->
+ store.applyStatus(
+ event.id(),
+ TEAM,
+ FileRunEventStatus.DISMISSED,
+ .isInstanceOf(FailureActionException.class)
+ .extracting(e -> ((FailureActionException) e).getReason())
+ .isEqualTo(FailureActionException.Reason.EVENT_NOT_FOUND);
+ }
+
+ @Test
+ @DisplayName("a reopened incident only flips from RESOLVED, never from DISMISSED")
+ void reopenFlipsOnlyResolved() {
+ FileRunEvent resolved = store.record(failure(FailureKind.UNKNOWN, TEAM, "resolved-file"));
+ store.applyStatus(resolved.id(), TEAM, FileRunEventStatus.RESOLVED, "system");
+
+ FileRunEvent reopened = store.record(failure(FailureKind.UNKNOWN, TEAM, "resolved-file"));
+
+ assertThat(reopened.status()).isEqualTo(FileRunEventStatus.NEW);
+ assertThat(reopened.statusActor()).isNull();
+ }
+
+ @Test
+ @DisplayName("the unique constraint exists in the DDL, not only in the entity annotation")
+ void duplicateIncidentInsertTripsTheUniqueConstraint() {
+ store.record(failure(FailureKind.UNKNOWN, TEAM, "f"));
+ String dedupKey = failure(FailureKind.UNKNOWN, TEAM, "f").dedupKey();
+
+ FileRunEventEntity duplicate = new FileRunEventEntity();
+ duplicate.setId(UUID.randomUUID().toString());
+ duplicate.setTeamId(TEAM);
+ duplicate.setKindId(FailureKind.UNKNOWN.getId());
+ duplicate.setStage(FailureStage.INTERNAL);
+ duplicate.setSeverity(FailureSeverity.ERROR);
+ duplicate.setScope(FailureScope.RUN);
+ duplicate.setOrigin(FailureOrigin.POLICY);
+ duplicate.setDedupKey(dedupKey);
+ duplicate.setOccurrences(1);
+ duplicate.setStatus(FileRunEventStatus.NEW);
+ duplicate.setCreatedAt(Instant.now());
+ duplicate.setLastSeenAt(Instant.now());
+
+ assertThatThrownBy(() -> repository.saveAndFlush(duplicate))
+ .isInstanceOf(DataIntegrityViolationException.class);
+ }
+
+ @SpringBootConfiguration
+ @AutoConfigurationPackage
+ static class TestApp {}
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventStoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventStoreTest.java
new file mode 100644
index 0000000000..2adbc7d2b2
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventStoreTest.java
@@ -0,0 +1,351 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests for {@link FileRunEventStore}, driven through a hand-written in-memory repository so the
+ * rollup rules are tested directly and fast. The rollup is the load-bearing part: without it,
+ * Dismiss means nothing for a source that re-lists the same failing file on every sweep.
+ */
+class FileRunEventStoreTest {
+
+ private static final Long TEAM = 7L;
+ private static final Long OTHER_TEAM = 9L;
+
+ private InMemoryFileRunEventRepository repository;
+ private FileRunEventStore store;
+
+ @BeforeEach
+ void setUp() {
+ repository = new InMemoryFileRunEventRepository();
+ store = new FileRunEventStore(repository);
+ }
+
+ private RecordFailure failure(FailureKind kind, Long teamId, String fileId, String detail) {
+ return new RecordFailure(
+ kind,
+ FailureOrigin.POLICY,
+ teamId,
+ "policy-1",
+ "run-1",
+ null,
+ fileId,
+ detail);
+ }
+
+ @Nested
+ @DisplayName("recording a new failure")
+ class Insert {
+
+ @Test
+ void persistsEveryFieldAndSnapshotsTheRegistryFacets() {
+ FileRunEvent event =
+ store.record(
+ failure(
+ FailureKind.INPUT_PASSWORD_PROTECTED,
+ TEAM,
+ "file-1",
+ "locked"));
+
+ assertThat(event.id()).isNotBlank();
+ assertThat(event.teamId()).isEqualTo(TEAM);
+ assertThat(event.actor()).isEqualTo("[email protected]");
+ assertThat(event.kind()).isEqualTo(FailureKind.INPUT_PASSWORD_PROTECTED);
+ assertThat(event.policyId()).isEqualTo("policy-1");
+ assertThat(event.runId()).isEqualTo("run-1");
+ assertThat(event.fileId()).isEqualTo("file-1");
+ assertThat(event.origin()).isEqualTo(FailureOrigin.POLICY);
+ assertThat(event.status()).isEqualTo(FileRunEventStatus.NEW);
+ assertThat(event.occurrences()).isEqualTo(1);
+ assertThat(event.createdAt()).isNotNull();
+ assertThat(event.lastSeenAt()).isNotNull();
+
+ // Snapshotted, not derived: re-classifying a kind later must not rewrite this row.
+ assertThat(event.stage()).isEqualTo(FailureStage.INPUT);
+ assertThat(event.severity()).isEqualTo(FailureSeverity.ERROR);
+ assertThat(event.scope()).isEqualTo(FailureScope.FILE);
+ }
+
+ @Test
+ void keepsTheRawDetailVerbatimForAnUnknownKind() {
+ // For UNKNOWN this string is the only diagnostic there is, so it has to reach the row
+ // unaltered. Redaction itself has its own tests.
+ String raw = "Policy run failed: java.lang.IllegalStateException: pool exhausted";
+ FileRunEvent event = store.record(failure(FailureKind.UNKNOWN, TEAM, null, raw));
+
+ assertThat(event.detail()).isEqualTo(raw);
+ }
+ }
+
+ @Nested
+ @DisplayName("the rollup")
+ class Rollup {
+
+ @Test
+ void foldsARepeatIntoTheOpenIncidentInsteadOfInsertingAgain() {
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "file-1", "first"));
+ FileRunEvent second =
+ store.record(
+ failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "file-1", "again"));
+
+ assertThat(second.occurrences()).isEqualTo(2);
+ assertThat(repository.rows).hasSize(1);
+ }
+
+ @Test
+ void refreshesTheDetailSoTheNewestDiagnosticIsTheOneOnShow() {
+ store.record(failure(FailureKind.UNKNOWN, TEAM, "file-1", "old message"));
+ FileRunEvent second =
+ store.record(failure(FailureKind.UNKNOWN, TEAM, "file-1", "new message"));
+
+ assertThat(second.detail()).isEqualTo("new message");
+ }
+
+ @Test
+ void treatsADifferentFileAsItsOwnIncident() {
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "file-1", "a"));
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "file-2", "b"));
+
+ assertThat(repository.rows).hasSize(2);
+ }
+
+ @Test
+ void treatsADifferentKindAsItsOwnIncident() {
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "file-1", "a"));
+ store.record(failure(FailureKind.UNKNOWN, TEAM, "file-1", "b"));
+
+ assertThat(repository.rows).hasSize(2);
+ }
+
+ @Test
+ void neverFoldsAcrossTeams() {
+ // Two tenants hitting the same problem are two incidents, each owned by its own team.
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "file-1", "a"));
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, OTHER_TEAM, "file-1", "b"));
+
+ assertThat(repository.rows).hasSize(2);
+ }
+
+ @Test
+ void absorbsARepeatOntoADismissedRowWithoutReopeningIt() {
+ // A snapshot-mode source re-lists every file each sweep, so without absorption a
+ // dismissed failure would reappear as a new row every time.
+ FileRunEvent first =
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f", "a"));
+ store.applyStatus(
+ first.id(), TEAM, FileRunEventStatus.DISMISSED, "[email protected]");
+
+ FileRunEvent repeat =
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f", "b"));
+
+ assertThat(repository.rows).hasSize(1);
+ assertThat(repeat.status()).isEqualTo(FileRunEventStatus.DISMISSED);
+ assertThat(repeat.occurrences()).isEqualTo(2);
+ assertThat(repeat.statusActor()).isEqualTo("[email protected]");
+ }
+
+ @Test
+ void reopensAResolvedRowBecauseTheProblemHasComeBack() {
+ // The counterweight to absorption, so a recurrence still surfaces.
+ FileRunEvent first =
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f", "a"));
+ store.applyStatus(first.id(), TEAM, FileRunEventStatus.RESOLVED, "system");
+
+ FileRunEvent repeat =
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f", "b"));
+
+ assertThat(repository.rows).hasSize(1);
+ assertThat(repeat.status()).isEqualTo(FileRunEventStatus.NEW);
+ assertThat(repeat.occurrences()).isEqualTo(2);
+ // The previous closer no longer owns a reopened incident.
+ assertThat(repeat.statusActor()).isNull();
+ assertThat(repeat.statusAt()).isNull();
+ }
+
+ @Test
+ void keepsAnAcknowledgedRowAcknowledgedOnRepeat() {
+ FileRunEvent first =
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f", "a"));
+ store.applyStatus(first.id(), TEAM, FileRunEventStatus.ACKNOWLEDGED, "owner");
+
+ FileRunEvent repeat =
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f", "b"));
+
+ assertThat(repeat.status()).isEqualTo(FileRunEventStatus.ACKNOWLEDGED);
+ assertThat(repeat.statusActor()).isEqualTo("owner");
+ }
+
+ @Test
+ void aSweepWhereEveryFileFailsProducesARowPerFile() {
+ // Each resolved input gets its own run, so a 400-file sweep is 400 incidents rather
+ // than one with a counter of 400. Grouping for display is a read-time concern.
+ for (int i = 0; i < 50; i++) {
+ store.record(
+ new RecordFailure(
+ FailureKind.UNKNOWN,
+ FailureOrigin.POLICY,
+ TEAM,
+ "policy-1",
+ "run-" + i,
+ null,
+ "file-" + i,
+ "OCR unavailable"));
+ }
+
+ assertThat(repository.rows).hasSize(50);
+ assertThat(repository.rows.values()).allMatch(row -> row.getOccurrences() == 1);
+ }
+
+ @Test
+ void treatsEachFileAsItsOwnIncidentEvenWhenNoFileIdWasCaptured() {
+ // The producer path cannot always name a file, and a FILE-scoped kind then falls back
+ // to
+ // the run. Without that, every locked file under one policy would fold into one row.
+ store.record(withoutFileId("run-a"));
+ store.record(withoutFileId("run-b"));
+
+ assertThat(repository.rows).hasSize(2);
+ assertThat(repository.rows.values()).allMatch(row -> row.getOccurrences() == 1);
+ }
+
+ @Test
+ void aRetryOfTheSameRunStillFoldsWhenNoFileIdWasCaptured() {
+ // The flip side: the fallback must not turn a genuine repeat into a second row.
+ store.record(withoutFileId("run-a"));
+ store.record(withoutFileId("run-a"));
+
+ assertThat(repository.rows).hasSize(1);
+ assertThat(repository.rows.values().iterator().next().getOccurrences()).isEqualTo(2);
+ }
+
+ @Test
+ void foldsIntoTheWinnersRowWhenAConcurrentWriterInsertedFirst() {
+ // Two runs failing identically at once: both read, find nothing, and try to insert. The
+ // loser's insert trips the unique constraint and has to fold rather than fail.
+ RecordFailure command = failure(FailureKind.UNKNOWN, TEAM, "file-1", "OCR unavailable");
+ FileRunEventEntity winner = rowFor(command);
+ repository.beforeNextSave = () -> repository.rows.put(winner.getId(), winner);
+
+ FileRunEvent result = store.record(command);
+
+ assertThat(repository.rows).hasSize(1);
+ assertThat(result.id()).isEqualTo(winner.getId());
+ assertThat(result.occurrences()).isEqualTo(2);
+ }
+
+ /** A row as the winning writer would have inserted it, for the race above. */
+ private FileRunEventEntity rowFor(RecordFailure command) {
+ FileRunEventEntity entity = new FileRunEventEntity();
+ entity.setId("winner");
+ entity.setTeamId(command.teamId());
+ entity.setKindId(command.kind().getId());
+ entity.setStage(command.kind().getStage());
+ entity.setSeverity(command.kind().getSeverity());
+ entity.setScope(command.kind().getScope());
+ entity.setOrigin(command.origin());
+ entity.setDedupKey(command.dedupKey());
+ entity.setOccurrences(1);
+ entity.setStatus(FileRunEventStatus.NEW);
+ entity.setCreatedAt(java.time.Instant.now());
+ entity.setLastSeenAt(java.time.Instant.now());
+ return entity;
+ }
+
+ private RecordFailure withoutFileId(String runId) {
+ return new RecordFailure(
+ FailureKind.INPUT_PASSWORD_PROTECTED,
+ FailureOrigin.POLICY,
+ TEAM,
+ "policy-1",
+ runId,
+ null,
+ null,
+ "The PDF Document is passworded");
+ }
+ }
+
+ @Nested
+ @DisplayName("reading")
+ class Reading {
+
+ @Test
+ void neverReturnsAnotherTeamsRows() {
+ store.record(failure(FailureKind.UNKNOWN, TEAM, "mine", "a"));
+ store.record(failure(FailureKind.UNKNOWN, OTHER_TEAM, "theirs", "b"));
+
+ assertThat(store.list(TEAM, null, null, 50))
+ .extracting(FileRunEvent::fileId)
+ .containsExactly("mine");
+ }
+
+ @Test
+ void treatsANullTeamAsTheUnteamedRows() {
+ // Login-disabled deployments have no team; a plain `= null` comparison would return
+ // nothing, which is why the query special-cases it.
+ store.record(failure(FailureKind.UNKNOWN, null, "unteamed", "a"));
+ store.record(failure(FailureKind.UNKNOWN, TEAM, "teamed", "b"));
+
+ assertThat(store.list(null, null, null, 50))
+ .extracting(FileRunEvent::fileId)
+ .containsExactly("unteamed");
+ }
+
+ @Test
+ void filtersByStatus() {
+ FileRunEvent open = store.record(failure(FailureKind.UNKNOWN, TEAM, "open", "a"));
+ store.record(failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "closed", "b"));
+ store.applyStatus(open.id(), TEAM, FileRunEventStatus.ACKNOWLEDGED, "me");
+
+ assertThat(store.list(TEAM, FileRunEventStatus.ACKNOWLEDGED, null, 50))
+ .extracting(FileRunEvent::fileId)
+ .containsExactly("open");
+ }
+
+ @Test
+ void findScopesByTeamSoAnIdFromAnotherTeamIsInvisible() {
+ FileRunEvent theirs = store.record(failure(FailureKind.UNKNOWN, OTHER_TEAM, "x", "a"));
+
+ assertThat(store.find(theirs.id(), TEAM)).isEmpty();
+ assertThat(store.find(theirs.id(), OTHER_TEAM)).isPresent();
+ }
+ }
+
+ @Nested
+ @DisplayName("dedup keys")
+ class Keys {
+
+ @Test
+ void areDeterministicForTheSameFailure() {
+ RecordFailure command = failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f", "a");
+
+ assertThat(command.dedupKey()).isEqualTo(command.dedupKey());
+ }
+
+ @Test
+ void differByKindAndByScopeReference() {
+ RecordFailure a = failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1", "x");
+ RecordFailure b = failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f2", "x");
+ RecordFailure c = failure(FailureKind.UNKNOWN, TEAM, "f1", "x");
+
+ assertThat(a.dedupKey()).isNotEqualTo(b.dedupKey());
+ assertThat(a.dedupKey()).isNotEqualTo(c.dedupKey());
+ }
+
+ @Test
+ void areFixedWidthSoAnyLengthOfScopeReferenceFitsTheIndex() {
+ String longKey = "s3://bucket/" + "nested/".repeat(500) + "file.pdf";
+ RecordFailure command =
+ failure(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, longKey, "x");
+
+ assertThat(command.dedupKey()).hasSize(64);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/InMemoryFileRunEventRepository.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/InMemoryFileRunEventRepository.java
new file mode 100644
index 0000000000..ed8b6f29cd
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/InMemoryFileRunEventRepository.java
@@ -0,0 +1,316 @@
+package stirling.software.proprietary.failure;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Function;
+
+import org.springframework.data.domain.Pageable;
+
+/**
+ * Minimal stand-in for the JPA repository: enough to exercise the store's branching without a
+ * database. Ordering mirrors the real queries (newest first) since the rollup relies on it, and
+ * {@link #save} enforces the {@code (team_id, dedup_key)} unique constraint the real table
+ * declares.
+ */
+class InMemoryFileRunEventRepository implements FileRunEventRepository {
+
+ final Map<String, FileRunEventEntity> rows = new HashMap<>();
+
+ /**
+ * Runs once at the start of the next {@link #save}, so a test can interleave a competing writer
+ * between the store's read and its insert.
+ */
+ Runnable beforeNextSave;
+
+ private static boolean sameTeam(FileRunEventEntity entity, Long teamId) {
+ return teamId == null ? entity.getTeamId() == null : teamId.equals(entity.getTeamId());
+ }
+
+ private List<FileRunEventEntity> newestFirst(List<FileRunEventEntity> matches) {
+ List<FileRunEventEntity> sorted = new ArrayList<>(matches);
+ sorted.sort(
+ (a, b) -> {
+ int byTime = b.getLastSeenAt().compareTo(a.getLastSeenAt());
+ // Stable tiebreak: identical timestamps are common in fast tests.
+ return byTime != 0 ? byTime : a.getId().compareTo(b.getId());
+ });
+ return sorted;
+ }
+
+ /** The real queries page in SQL, so the fake must page too or limit tests test nothing. */
+ private static List<FileRunEventEntity> page(List<FileRunEventEntity> rows, Pageable pageable) {
+ return pageable == null || pageable.isUnpaged() || rows.size() <= pageable.getPageSize()
+ ? rows
+ : rows.subList(0, pageable.getPageSize());
+ }
+
+ private static boolean sameKind(FileRunEventEntity entity, String kindId) {
+ return kindId == null || kindId.equals(entity.getKindId());
+ }
+
+ @Override
+ public List<FileRunEventEntity> findByTeam(Long teamId, String kindId, Pageable pageable) {
+ return page(
+ newestFirst(
+ rows.values().stream()
+ .filter(e -> sameTeam(e, teamId) && sameKind(e, kindId))
+ .toList()),
+ pageable);
+ }
+
+ @Override
+ public List<FileRunEventEntity> findByTeamAndStatus(
+ Long teamId, FileRunEventStatus status, String kindId, Pageable pageable) {
+ return page(
+ newestFirst(
+ rows.values().stream()
+ .filter(
+ e ->
+ sameTeam(e, teamId)
+ && e.getStatus() == status
+ && sameKind(e, kindId))
+ .toList()),
+ pageable);
+ }
+
+ @Override
+ public int fold(String id, Instant now, String detail) {
+ FileRunEventEntity entity = rows.get(id);
+ if (entity == null) {
+ return 0;
+ }
+ entity.setOccurrences(entity.getOccurrences() + 1);
+ entity.setLastSeenAt(now);
+ if (detail != null) {
+ entity.setDetail(detail);
+ }
+ return 1;
+ }
+
+ @Override
+ public int reopenIfResolved(String id) {
+ FileRunEventEntity entity = rows.get(id);
+ if (entity == null || entity.getStatus() != FileRunEventStatus.RESOLVED) {
+ return 0;
+ }
+ entity.setStatus(FileRunEventStatus.NEW);
+ entity.setStatusActor(null);
+ entity.setStatusAt(null);
+ return 1;
+ }
+
+ @Override
+ public int applyStatusIf(
+ String id,
+ Long teamId,
+ FileRunEventStatus target,
+ String actor,
+ Instant now,
+ Collection<FileRunEventStatus> allowedFrom) {
+ FileRunEventEntity entity = rows.get(id);
+ if (entity == null
+ || !sameTeam(entity, teamId)
+ || !allowedFrom.contains(entity.getStatus())) {
+ return 0;
+ }
+ entity.setStatus(target);
+ entity.setStatusActor(actor);
+ entity.setStatusAt(now);
+ return 1;
+ }
+
+ @Override
+ public List<FileRunEventEntity> findByTeamAndDedupKey(
+ Long teamId, String dedupKey, Pageable pageable) {
+ return newestFirst(
+ rows.values().stream()
+ .filter(e -> sameTeam(e, teamId) && dedupKey.equals(e.getDedupKey()))
+ .toList());
+ }
+
+ @Override
+ public Optional<FileRunEventEntity> findByIdAndTeam(String id, Long teamId) {
+ return Optional.ofNullable(rows.get(id)).filter(e -> sameTeam(e, teamId));
+ }
+
+ @Override
+ public <S extends FileRunEventEntity> S save(S entity) {
+ if (beforeNextSave != null) {
+ Runnable hook = beforeNextSave;
+ beforeNextSave = null;
+ hook.run();
+ }
+ boolean isInsert = !rows.containsKey(entity.getId());
+ if (isInsert && clashesOnDedupKey(entity)) {
+ throw new org.springframework.dao.DataIntegrityViolationException(
+ "uk_file_run_events_dedup violated for " + entity.getDedupKey());
+ }
+ rows.put(entity.getId(), entity);
+ return entity;
+ }
+
+ /** Mirrors the unique constraint. SQL treats NULL teams as distinct, and so does this. */
+ private boolean clashesOnDedupKey(FileRunEventEntity candidate) {
+ if (candidate.getTeamId() == null) {
+ return false;
+ }
+ return rows.values().stream()
+ .anyMatch(
+ row ->
+ candidate.getTeamId().equals(row.getTeamId())
+ && candidate.getDedupKey().equals(row.getDedupKey()));
+ }
+
+ // ── unused JpaRepository surface ────────────────────────────────────────
+ @Override
+ public void flush() {}
+
+ @Override
+ public <S extends FileRunEventEntity> S saveAndFlush(S entity) {
+ return save(entity);
+ }
+
+ @Override
+ public <S extends FileRunEventEntity> List<S> saveAllAndFlush(Iterable<S> entities) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void deleteAllInBatch(Iterable<FileRunEventEntity> entities) {}
+
+ @Override
+ public void deleteAllByIdInBatch(Iterable<String> ids) {}
+
+ @Override
+ public void deleteAllInBatch() {}
+
+ @Override
+ public FileRunEventEntity getOne(String id) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public FileRunEventEntity getById(String id) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public FileRunEventEntity getReferenceById(String id) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public <S extends FileRunEventEntity> List<S> findAll(
+ org.springframework.data.domain.Example<S> example) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public <S extends FileRunEventEntity> List<S> findAll(
+ org.springframework.data.domain.Example<S> example,
+ org.springframework.data.domain.Sort sort) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public <S extends FileRunEventEntity> List<S> saveAll(Iterable<S> entities) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public List<FileRunEventEntity> findAll() {
+ return List.copyOf(rows.values());
+ }
+
+ @Override
+ public List<FileRunEventEntity> findAllById(Iterable<String> ids) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Optional<FileRunEventEntity> findById(String id) {
+ return Optional.ofNullable(rows.get(id));
+ }
+
+ @Override
+ public boolean existsById(String id) {
+ return rows.containsKey(id);
+ }
+
+ @Override
+ public long count() {
+ return rows.size();
+ }
+
+ @Override
+ public void deleteById(String id) {
+ rows.remove(id);
+ }
+
+ @Override
+ public void delete(FileRunEventEntity entity) {
+ rows.remove(entity.getId());
+ }
+
+ @Override
+ public void deleteAllById(Iterable<? extends String> ids) {}
+
+ @Override
+ public void deleteAll(Iterable<? extends FileRunEventEntity> entities) {}
+
+ @Override
+ public void deleteAll() {
+ rows.clear();
+ }
+
+ @Override
+ public List<FileRunEventEntity> findAll(org.springframework.data.domain.Sort sort) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public org.springframework.data.domain.Page<FileRunEventEntity> findAll(Pageable pageable) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public <S extends FileRunEventEntity> Optional<S> findOne(
+ org.springframework.data.domain.Example<S> example) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public <S extends FileRunEventEntity> org.springframework.data.domain.Page<S> findAll(
+ org.springframework.data.domain.Example<S> example, Pageable pageable) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public <S extends FileRunEventEntity> long count(
+ org.springframework.data.domain.Example<S> example) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public <S extends FileRunEventEntity> boolean exists(
+ org.springframework.data.domain.Example<S> example) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public <S extends FileRunEventEntity, R> R findBy(
+ org.springframework.data.domain.Example<S> example,
+ Function<
+ org.springframework.data.repository.query.FluentQuery
+ .FetchableFluentQuery<
+ S>,
+ R>
+ queryFunction) {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureRecorderTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureRecorderTest.java
new file mode 100644
index 0000000000..841fdec684
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureRecorderTest.java
@@ -0,0 +1,311 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.lenient;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Optional;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.client.HttpClientErrorException;
+
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.store.PolicyStore;
+
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Tests for {@link PolicyFailureRecorder}. Two behaviours beyond "it writes a row": the team comes
+ * from the originating policy, and a store problem is swallowed rather than replacing the failure
+ * being recorded.
+ */
+@ExtendWith(MockitoExtension.class)
+class PolicyFailureRecorderTest {
+
+ private static final Long TEAM = 11L;
+
+ @Mock private PolicyStore policyStore;
+
+ private InMemoryFileRunEventRepository repository;
+ private FileRunEventStore store;
+ private PolicyFailureRecorder recorder;
+
+ @BeforeEach
+ void setUp() {
+ repository = new InMemoryFileRunEventRepository();
+ store = new FileRunEventStore(repository);
+ recorder =
+ new PolicyFailureRecorder(
+ new FailureClassifier(JsonMapper.builder().build()), store, policyStore);
+ }
+
+ private static Policy policy(String id, Long teamId) {
+ return new Policy(
+ id,
+ "Contract redaction",
+ true,
+ List.of(),
+ List.of(),
+ OutputSpec.inline(),
+ List.of(),
+ teamId);
+ }
+
+ private static HttpClientErrorException passwordFailure() {
+ String body = "{\"type\":\"/errors/pdf-password\",\"errorCode\":\"E004\"}";
+ return HttpClientErrorException.create(
+ HttpStatus.BAD_REQUEST,
+ "Bad Request",
+ new HttpHeaders(),
+ body.getBytes(StandardCharsets.UTF_8),
+ StandardCharsets.UTF_8);
+ }
+
+ @Nested
+ @DisplayName("classifying and recording")
+ class Recording {
+
+ @Test
+ void classifiesTheCauseAndStoresTheRunsOwnMessage() {
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ recorder.recordRunFailure(
+ "run-1",
+ "policy-1",
+ null,
+ "Policy run failed: locked",
+ passwordFailure());
+
+ FileRunEvent event = store.list(TEAM, null, null, 10).getFirst();
+ assertThat(event.kind()).isEqualTo(FailureKind.INPUT_PASSWORD_PROTECTED);
+ assertThat(event.runId()).isEqualTo("run-1");
+ assertThat(event.policyId()).isEqualTo("policy-1");
+ assertThat(event.actor()).isEqualTo("[email protected]");
+ assertThat(event.origin()).isEqualTo(FailureOrigin.POLICY);
+ // The run's message, not the exception's: that is what the operator saw. Stored
+ // verbatim, including for a kind we recognise, so the row says what actually happened.
+ assertThat(event.detail()).isEqualTo("Policy run failed: locked");
+ }
+
+ @Test
+ void keepsTheMessageForAFailureItCouldNotClassify() {
+ // The opposite case, and the reason the message is stored at all: with no kind to
+ // describe it, this text is the only thing telling a reviewer what went wrong.
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ recorder.recordRunFailure(
+ "run-1",
+ "policy-1",
+ null,
+ "Policy run failed: something we do not recognise",
+ new RuntimeException("boom"));
+
+ FileRunEvent event = store.list(TEAM, null, null, 10).getFirst();
+ assertThat(event.kind()).isEqualTo(FailureKind.UNKNOWN);
+ assertThat(event.detail()).contains("something we do not recognise");
+ }
+
+ @Test
+ void recordsAnUnclassifiableFailureAsUnknownRatherThanDroppingIt() {
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ recorder.recordRunFailure(
+ "run-2",
+ "policy-1",
+ null,
+ null,
+ "Policy run failed: java.lang.NullPointerException",
+ new RuntimeException("npe"));
+
+ FileRunEvent event = store.list(TEAM, null, null, 10).getFirst();
+ assertThat(event.kind()).isEqualTo(FailureKind.UNKNOWN);
+ assertThat(event.detail()).contains("NullPointerException");
+ }
+
+ @Test
+ void acceptsAPreDecidedKindForPathsWithNothingToClassify() {
+ // A run rejected at admission threw nothing; the outcome is still known.
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ recorder.recordRunFailureAs(
+ FailureKind.UNKNOWN, "run-3", "policy-1", null, "could not be queued");
+
+ assertThat(store.list(TEAM, null, null, 10)).hasSize(1);
+ }
+
+ @Test
+ void twoFilesFailingTheSameWayUnderOnePolicyAreTwoIncidents() {
+ // The producer records per run and cannot name a file, so a FILE-scoped kind has only
+ // the
+ // run to tell two documents apart. Tested here rather than against a hand-built
+ // RecordFailure, because that is what let three locked files collapse into one row.
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ recorder.recordRunFailure(
+ "run-1", "policy-1", "[email protected]", null, "locked", passwordFailure());
+ recorder.recordRunFailure(
+ "run-2", "policy-1", "[email protected]", null, "locked", passwordFailure());
+
+ List<FileRunEvent> events = store.list(TEAM, null, null, 10);
+ assertThat(events).hasSize(2);
+ assertThat(events).allMatch(event -> event.occurrences() == 1);
+ assertThat(events)
+ .extracting(FileRunEvent::runId)
+ .containsExactlyInAnyOrder("run-1", "run-2");
+ }
+
+ @Test
+ void thatSameRunFailingTwiceStaysOneIncident() {
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ recorder.recordRunFailure(
+ "run-1", "policy-1", "[email protected]", null, "locked", passwordFailure());
+ recorder.recordRunFailure(
+ "run-1", "policy-1", "[email protected]", null, "locked", passwordFailure());
+
+ assertThat(store.list(TEAM, null, null, 10))
+ .singleElement()
+ .extracting(FileRunEvent::occurrences)
+ .isEqualTo(2);
+ }
+ }
+
+ @Nested
+ @DisplayName("team resolution")
+ class TeamResolution {
+
+ @Test
+ void takesTheTeamFromTheOriginatingPolicy() {
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ recorder.recordRunFailure(
+ "run-1", "policy-1", null, null, "boom", new RuntimeException());
+
+ assertThat(store.list(TEAM, null, null, 10)).hasSize(1);
+ }
+
+ @Test
+ void leavesAnAdHocRunUnteamedRatherThanGuessing() {
+ // No stored policy means no team to attribute it to. Recorded unteamed rather than
+ // attributed to whichever team happened to be nearby.
+ recorder.recordRunFailure("run-1", null, null, null, "boom", new RuntimeException());
+
+ assertThat(store.list(null, null, null, 10)).hasSize(1);
+ assertThat(store.list(TEAM, null, null, 10)).isEmpty();
+ }
+
+ @Test
+ void survivesAPolicyLookupFailure() {
+ when(policyStore.get(anyString())).thenThrow(new RuntimeException("db down"));
+
+ assertThatCode(
+ () ->
+ recorder.recordRunFailure(
+ "run-1",
+ "policy-1",
+ null,
+ null,
+ "boom",
+ new RuntimeException()))
+ .doesNotThrowAnyException();
+ // Still recorded, just unteamed: a lookup problem must not lose the incident.
+ assertThat(store.list(null, null, null, 10)).hasSize(1);
+ }
+ }
+
+ @Nested
+ @DisplayName("recording is best effort")
+ class BestEffort {
+
+ @Test
+ void aStoreFailureIsSwallowedSoItCannotReplaceTheRealFailure() {
+ // If this threw, the engine's catch block would report a store error instead of the
+ // password problem that actually stopped the run.
+ FileRunEventStore broken = mock(FileRunEventStore.class);
+ when(broken.record(any())).thenThrow(new RuntimeException("event store unavailable"));
+ lenient()
+ .when(policyStore.get("policy-1"))
+ .thenReturn(Optional.of(policy("policy-1", TEAM)));
+ PolicyFailureRecorder fragile =
+ new PolicyFailureRecorder(
+ new FailureClassifier(JsonMapper.builder().build()),
+ broken,
+ policyStore);
+
+ assertThatCode(
+ () ->
+ fragile.recordRunFailure(
+ "run-1",
+ "policy-1",
+ null,
+ null,
+ "Policy run failed: locked",
+ passwordFailure()))
+ .doesNotThrowAnyException();
+ }
+
+ @Test
+ void aNullCauseDoesNotBreakRecording() {
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ assertThatCode(
+ () ->
+ recorder.recordRunFailure(
+ "run-1", "policy-1", null, null, "no cause", null))
+ .doesNotThrowAnyException();
+ assertThat(store.list(TEAM, null, null, 10).getFirst().kind())
+ .isEqualTo(FailureKind.UNKNOWN);
+ }
+ }
+
+ @Nested
+ @DisplayName("repeats")
+ class Repeats {
+
+ @Test
+ void twoIdenticalRunFailuresFoldIntoOneIncident() {
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ recorder.recordRunFailure(
+ "run-1", "policy-1", null, null, "boom", new IOException("x"));
+ recorder.recordRunFailure(
+ "run-1", "policy-1", null, null, "boom", new IOException("x"));
+
+ List<FileRunEvent> events = store.list(TEAM, null, null, 10);
+ assertThat(events).hasSize(1);
+ assertThat(events.getFirst().occurrences()).isEqualTo(2);
+ }
+
+ @Test
+ void twoDifferentRunsAreSeparateIncidents() {
+ // UNKNOWN is RUN-scoped, so the run id is what distinguishes them.
+ when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
+
+ recorder.recordRunFailure(
+ "run-1", "policy-1", null, null, "boom", new IOException("x"));
+ recorder.recordRunFailure(
+ "run-2", "policy-1", null, null, "boom", new IOException("x"));
+
+ assertThat(store.list(TEAM, null, null, 10)).hasSize(2);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/RecordFailurePrivacyTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/RecordFailurePrivacyTest.java
new file mode 100644
index 0000000000..ef9648571f
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/RecordFailurePrivacyTest.java
@@ -0,0 +1,110 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.RecordComponent;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+
+/**
+ * The privacy contract: a recorded failure carries no document identity of its own. There is no
+ * name column and the dedup key is built only from opaque ids, so nothing here derives from what a
+ * document is called.
+ *
+ * <p>The message itself is stored verbatim. It is the user's own error about their own file, and
+ * scrubbing it made rows harder to act on without making them meaningfully safer.
+ */
+@DisplayName("a recorded failure carries no document identity of its own")
+class RecordFailurePrivacyTest {
+
+ private static RecordFailure withDetail(String detail) {
+ return RecordFailure.forRun(
+ FailureKind.UNKNOWN, 1L, "[email protected]", "policy-1", "run-1", null, detail);
+ }
+
+ @Test
+ void toleratesAnAbsentMessage() {
+ assertThat(withDetail(null).detail()).isNull();
+ }
+
+ @Test
+ void hasNoFileNameFieldAtAll() {
+ // Structural, not behavioural: if a fileName component is ever added back, this fails.
+ assertThat(List.of(RecordFailure.class.getRecordComponents()))
+ .extracting(RecordComponent::getName)
+ .doesNotContain("fileName");
+ assertThat(List.of(FileRunEventEntity.class.getDeclaredFields()))
+ .extracting(Field::getName)
+ .doesNotContain("fileName");
+ assertThat(List.of(FileRunEventView.class.getRecordComponents()))
+ .extracting(RecordComponent::getName)
+ .doesNotContain("fileName");
+ }
+
+ @Test
+ void dedupKeyIsBuiltOnlyFromOpaqueIdentifiers() {
+ // Two files under the same policy hash differently (so they stay separate incidents), but
+ // the inputs are ids, so the hash is not reversible to a document name.
+ RecordFailure a =
+ new RecordFailure(
+ FailureKind.INPUT_PASSWORD_PROTECTED,
+ FailureOrigin.POLICY,
+ 1L,
+ null,
+ "policy-1",
+ "run-1",
+ null,
+ "file-aaa",
+ "x");
+ RecordFailure b =
+ new RecordFailure(
+ FailureKind.INPUT_PASSWORD_PROTECTED,
+ FailureOrigin.POLICY,
+ 1L,
+ null,
+ "policy-1",
+ "run-1",
+ null,
+ "file-bbb",
+ "x");
+
+ assertThat(a.dedupKey()).isNotEqualTo(b.dedupKey());
+ assertThat(a.dedupKey()).hasSize(64).isEqualTo(a.dedupKey());
+ assertThat(a.scopeRef()).doesNotContain(".pdf");
+ }
+
+ @Nested
+ @DisplayName("the detail cap")
+ class DetailCap {
+
+ @Test
+ void capsAnOversizedMessageAtTheLimitIncludingTheEllipsis() {
+ String stored = withDetail("x".repeat(5_000)).detail();
+
+ assertThat(stored).hasSize(2_000).endsWith("…");
+ }
+
+ @Test
+ void leavesAMessageAtTheLimitAlone() {
+ String atLimit = "x".repeat(2_000);
+
+ assertThat(withDetail(atLimit).detail()).isEqualTo(atLimit);
+ }
+
+ @Test
+ void neverCutsBetweenTheHalvesOfASurrogatePair() {
+ // A string of astral-plane characters: every char is half of a surrogate pair, so a
+ // blind substring at the cap has a 50% chance of storing invalid UTF-16.
+ String stored = withDetail("\uD835\uDC9C".repeat(3_000)).detail();
+
+ assertThat(new String(stored.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8))
+ .as("a round-trip through UTF-8 mangles an unpaired surrogate")
+ .isEqualTo(stored);
+ }
+ }
+}
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 56e5b2d9cd..6cafde14c8 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
@@ -213,7 +213,7 @@ class PolicyControllerTest {
}
private static PolicyRunHandle handle(String runId) {
- PolicyRun run = new PolicyRun(runId, null, definitionWithStep());
+ PolicyRun run = new PolicyRun(runId, null, definitionWithStep(), null);
return new PolicyRunHandle(runId, CompletableFuture.completedFuture(run));
}
@@ -314,7 +314,7 @@ class PolicyControllerTest {
@Test
@DisplayName("returns the run view when present")
void found() {
- PolicyRun run = new PolicyRun("run-3", null, definitionWithStep());
+ PolicyRun run = new PolicyRun("run-3", null, definitionWithStep(), null);
when(runRegistry.get("run-3")).thenReturn(run);
ResponseEntity<PolicyRunView> response = controller.status("run-3");
@@ -343,9 +343,9 @@ class PolicyControllerTest {
@Test
@DisplayName("excludes ad-hoc runs and runs owned by others")
void filtersRuns() {
- PolicyRun adHoc = new PolicyRun("adhoc", null, definitionWithStep());
- PolicyRun ownedStored = new PolicyRun("owned", "policy-A", definitionWithStep());
- PolicyRun otherStored = new PolicyRun("other", "policy-B", definitionWithStep());
+ PolicyRun adHoc = new PolicyRun("adhoc", null, definitionWithStep(), null);
+ PolicyRun ownedStored = new PolicyRun("owned", "policy-A", definitionWithStep(), null);
+ PolicyRun otherStored = new PolicyRun("other", "policy-B", definitionWithStep(), null);
when(runRegistry.all()).thenReturn(List.of(adHoc, ownedStored, otherStored));
// ownedByCurrentUser: strip then re-apply scope reproduces the key only for the owned
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java
index 560c80d7cd..479dccd3ca 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java
@@ -3,6 +3,7 @@ package stirling.software.proprietary.policy.engine;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
@@ -10,9 +11,11 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException;
@@ -22,6 +25,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
@@ -50,6 +54,7 @@ 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.failure.PolicyFailureRecorder;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.PipelineStep;
@@ -85,6 +90,7 @@ class PolicyEngineTest {
@Mock private JobOwnershipService jobOwnershipService;
@Mock private ResourceMonitor resourceMonitor;
@Mock private JobQueue jobQueue;
+ @Mock private PolicyFailureRecorder failureRecorder;
@TempDir Path tempDir;
@@ -112,6 +118,7 @@ class PolicyEngineTest {
executor,
taskManager,
registry,
+ failureRecorder,
fileStorage,
jobOwnershipService,
List.of(sink, recordingSink),
@@ -212,6 +219,52 @@ class PolicyEngineTest {
assertEquals(PolicyRunStatus.FAILED, run.getStatus());
verify(taskManager).setError(eq(runId), anyString());
verify(taskManager, never()).setComplete(runId);
+ // A failed run is recorded durably, so an admin can see it after the in-memory run expires.
+ verify(failureRecorder)
+ .recordRunFailure(
+ eq(runId), any(), any(), any(), anyString(), any(Throwable.class));
+ }
+
+ @Test
+ void recordingAFailureNeverChangesTheRunsOutcome() throws Exception {
+ // Recording is best-effort: losing the incident row is bad, but turning a classified
+ // failure
+ // into a different, confusing failure is worse.
+ when(toolMetadataService.isMultiInput(ROTATE)).thenReturn(false);
+ when(internalApiClient.post(eq(ROTATE), any())).thenThrow(new RuntimeException("boom"));
+ doThrow(new RuntimeException("event store unavailable"))
+ .when(failureRecorder)
+ .recordRunFailure(
+ anyString(), any(), any(), any(), anyString(), any(Throwable.class));
+
+ PolicyRunHandle handle =
+ engine.submit(
+ definition(new PipelineStep(ROTATE, Map.of())),
+ PolicyInputs.of(List.of(pdf("input", "input.pdf"))),
+ PolicyProgressListener.NOOP);
+ PolicyRun run = handle.completion().get(10, TimeUnit.SECONDS);
+
+ assertEquals(PolicyRunStatus.FAILED, run.getStatus());
+ // The original failure message survives, rather than being replaced by the store's.
+ assertTrue(run.getError().contains("boom"));
+ }
+
+ @Test
+ void successfulRunRecordsNoFailureEvent() throws Exception {
+ when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
+ when(toolMetadataService.shouldUnpackZipResponse(anyString())).thenReturn(false);
+ stubEndpoint(ROTATE, pdf("rotated", "rotated.pdf"));
+ when(fileStorage.storeInputStream(any(InputStream.class), anyString()))
+ .thenReturn(new StoredFile("file-1", 7L));
+
+ engine.submit(
+ definition(new PipelineStep(ROTATE, Map.of())),
+ PolicyInputs.of(List.of(pdf("input", "input.pdf"))),
+ PolicyProgressListener.NOOP)
+ .completion()
+ .get(10, TimeUnit.SECONDS);
+
+ verifyNoInteractions(failureRecorder);
}
@Test
@@ -407,6 +460,43 @@ class PolicyEngineTest {
assertFalse(engine.cancel("does-not-exist"));
}
+ @Test
+ void cancellingARunRecordsNoFailureEvent() throws Exception {
+ // A cancellation is an intended outcome, not an incident. Recording one would put a row in
+ // front of an admin describing something a user deliberately did.
+ //
+ // The cancel happens while the tool call is in flight, held on a latch: an earlier version
+ // of this test awaited completion first, and cancel() on a finished run is a documented
+ // no-op, so it asserted nothing.
+ when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
+ when(toolMetadataService.shouldUnpackZipResponse(anyString())).thenReturn(false);
+ CountDownLatch toolEntered = new CountDownLatch(1);
+ CountDownLatch releaseTool = new CountDownLatch(1);
+ when(internalApiClient.post(eq(ROTATE), any()))
+ .thenAnswer(
+ invocation -> {
+ toolEntered.countDown();
+ assertTrue(
+ releaseTool.await(10, TimeUnit.SECONDS),
+ "test never released the tool call");
+ return ResponseEntity.ok(pdf("rotated", "rotated.pdf"));
+ });
+ when(fileStorage.storeInputStream(any(InputStream.class), anyString()))
+ .thenReturn(new StoredFile("file-1", 7L));
+
+ PolicyRunHandle handle =
+ engine.submit(
+ definition(new PipelineStep(ROTATE, Map.of())),
+ PolicyInputs.of(List.of(pdf("input", "input.pdf"))),
+ PolicyProgressListener.NOOP);
+ assertTrue(toolEntered.await(10, TimeUnit.SECONDS), "run never reached the tool call");
+ assertTrue(engine.cancel(handle.runId()), "cancel was a no-op, so this asserts nothing");
+ releaseTool.countDown();
+ handle.completion().get(10, TimeUnit.SECONDS);
+
+ verifyNoInteractions(failureRecorder);
+ }
+
// --- helpers ---
private static PipelineDefinition definition(PipelineStep... steps) {
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 4d9ea1deb7..6e2ab66df7 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
@@ -1,6 +1,7 @@
package stirling.software.proprietary.policy.engine;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -299,7 +300,11 @@ class PolicyExecutorTest {
definition(new PipelineStep(compress, Map.of())),
PolicyInputs.of(List.of(pdf("img", "image.png"))),
PolicyProgressListener.NOOP));
- assertTrue(ex.getMessage().contains("image.png"));
+ // Names the rejected extension, never the document. This message becomes the run's error
+ // and
+ // is persisted on the failure record, which holds no document name.
+ assertTrue(ex.getMessage().contains("png"));
+ assertFalse(ex.getMessage().contains("image.png"));
// Type check happens before any dispatch.
verify(internalApiClient, never()).post(anyString(), any());
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java
index 0d1361c5d9..784baa207c 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java
@@ -96,7 +96,8 @@ class PolicyRunRegistryTest {
private PolicyRun register(String runId) {
PolicyRun run =
- new PolicyRun(runId, null, new PipelineDefinition(runId, List.of(), List.of()));
+ new PolicyRun(
+ runId, null, new PipelineDefinition(runId, List.of(), List.of()), null);
registry.register(run);
return run;
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java
index 51959a2525..ba66cb8b2d 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java
@@ -78,13 +78,13 @@ class PolicyRunnerTest {
@Test
void runsOnceWithNoFilesWhenThePolicyHasNoSources() {
Policy policy = policy(List.of());
- when(policyEngine.runPolicy(eq(policy), any(), any()))
+ when(policyEngine.runPolicy(eq(policy), any(), any(), any()))
.thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));
runner.run(policy);
ArgumentCaptor<PolicyInputs> inputs = ArgumentCaptor.forClass(PolicyInputs.class);
- verify(policyEngine).runPolicy(eq(policy), inputs.capture(), any());
+ verify(policyEngine).runPolicy(eq(policy), inputs.capture(), any(), any());
assertTrue(inputs.getValue().primary().isEmpty());
// Ledger hygiene still runs: rows recorded for a generator policy's folder outputs
// are pruned by its own sweeps rather than accumulating until the policy is deleted.
@@ -137,12 +137,12 @@ class PolicyRunnerTest {
List.of(
ResolvedInput.of(PolicyInputs.of(List.of())),
ResolvedInput.of(PolicyInputs.of(List.of()))));
- when(policyEngine.runPolicy(any(), any(), any()))
+ when(policyEngine.runPolicy(any(), any(), any(), any()))
.thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));
runner.run(policy);
- verify(policyEngine, times(2)).runPolicy(eq(policy), any(), any());
+ verify(policyEngine, times(2)).runPolicy(eq(policy), any(), any(), any());
}
@Test
@@ -150,11 +150,11 @@ class PolicyRunnerTest {
InputSpec spec = InputSpec.folder("/in");
Policy policy = policy(List.of(spec));
AtomicBoolean outcome = new AtomicBoolean(false);
- ResolvedInput unit = new ResolvedInput(PolicyInputs.of(List.of()), outcome::set);
+ ResolvedInput unit = new ResolvedInput(PolicyInputs.of(List.of()), null, outcome::set);
when(folderSource.supports(spec)).thenReturn(true);
when(folderSource.resolve(eq(spec), any())).thenReturn(List.of(unit));
CompletableFuture<PolicyRun> completion = new CompletableFuture<>();
- when(policyEngine.runPolicy(any(), any(), any()))
+ when(policyEngine.runPolicy(any(), any(), any(), any()))
.thenReturn(new PolicyRunHandle("r", completion));
runner.run(policy);
@@ -171,11 +171,11 @@ class PolicyRunnerTest {
InputSpec spec = InputSpec.folder("/in");
Policy policy = policy(List.of(spec));
AtomicBoolean outcome = new AtomicBoolean(true);
- ResolvedInput unit = new ResolvedInput(PolicyInputs.of(List.of()), outcome::set);
+ ResolvedInput unit = new ResolvedInput(PolicyInputs.of(List.of()), null, outcome::set);
when(folderSource.supports(spec)).thenReturn(true);
when(folderSource.resolve(eq(spec), any())).thenReturn(List.of(unit));
CompletableFuture<PolicyRun> completion = new CompletableFuture<>();
- when(policyEngine.runPolicy(any(), any(), any()))
+ when(policyEngine.runPolicy(any(), any(), any(), any()))
.thenReturn(new PolicyRunHandle("r", completion));
runner.run(policy);
@@ -224,12 +224,12 @@ class PolicyRunnerTest {
when(folderSource.supports(spec)).thenReturn(true);
when(folderSource.resolve(eq(spec), any()))
.thenReturn(List.of(ResolvedInput.of(PolicyInputs.of(List.of()))));
- when(policyEngine.runPolicy(any(), any(), any()))
+ when(policyEngine.runPolicy(any(), any(), any(), any()))
.thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));
runner.run(policy, SweepKind.LIGHT);
- verify(policyEngine).runPolicy(eq(policy), any(), any());
+ verify(policyEngine).runPolicy(eq(policy), any(), any(), any());
verify(processedLedger, never()).markSeen(any(), any());
verify(processedLedger, never()).deleteUnseen(any(), anyLong());
}
@@ -244,12 +244,12 @@ class PolicyRunnerTest {
when(folderSource.resolve(eq(broken), any())).thenThrow(new IOException("mount gone"));
when(folderSource.resolve(eq(healthy), any()))
.thenReturn(List.of(ResolvedInput.of(PolicyInputs.of(List.of()))));
- when(policyEngine.runPolicy(any(), any(), any()))
+ when(policyEngine.runPolicy(any(), any(), any(), any()))
.thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));
runner.run(policy);
- verify(policyEngine).runPolicy(eq(policy), any(), any()); // healthy source still ran
+ verify(policyEngine).runPolicy(eq(policy), any(), any(), any()); // healthy source still ran
verify(processedLedger, never()).deleteUnseen(any(), anyLong()); // history preserved
}
diff --git a/frontend/.storybook/a11y-baseline.json b/frontend/.storybook/a11y-baseline.json
index df46eb9dc4..c3fcfad6ea 100644
--- a/frontend/.storybook/a11y-baseline.json
+++ b/frontend/.storybook/a11y-baseline.json
@@ -2295,6 +2295,10 @@
"color-contrast",
"landmark-unique"
],
+ "editor/src/portal/views/Documents.stories.tsx :: Default": [
+ "color-contrast"
+ ],
+ "editor/src/portal/views/Documents.stories.tsx :: Empty": ["color-contrast"],
"editor/src/portal/views/Home.stories.tsx :: Enterprise Tier": [
"color-contrast",
"landmark-no-duplicate-banner",
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 4f70f2b813..b1043d03ee 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7200,6 +7200,7 @@ sensitiveTitle = "Sensitive — access required"
[portal.documents.table.columns]
action = "Pipeline / Action"
+actions = "Actions"
document = "Document"
product = "Product"
status = "Status"
@@ -7290,6 +7291,41 @@ description = "This view hit an unexpected error. Try again, or pick another sec
retry = "Try again"
title = "Something went wrong on this page"
+[portal.failures]
+occurrences = "{{count}} occurrences"
+runReference = "Run {{runId}}"
+subtitle = "Failures recorded from your policy runs, with the actions you can take."
+title = "Failures"
+
+[portal.failures.action]
+acknowledge = "Acknowledge"
+confirm = "Are you sure?"
+dismiss = "Dismiss"
+dismissSkipFile = "Skip this file"
+
+[portal.failures.disabled]
+closed = "This failure is already closed."
+unavailable = "Not available for this failure."
+
+[portal.failures.empty]
+description = "Policy runs that fail will appear here with the actions you can take."
+title = "No failures recorded"
+
+[portal.failures.kind.inputPasswordProtected]
+description = "The pipeline could not open the document because it is password-protected. Unlock it and run it again, or skip this file."
+title = "Password-protected document"
+
+[portal.failures.kind.unknown]
+description = "This run failed for a reason Stirling does not yet recognise. The raw message is shown below."
+title = "Unrecognised failure"
+
+[portal.failures.stage]
+blocked = "Blocked"
+input = "Input"
+internal = "Internal"
+never_ran = "Never ran"
+output = "Output"
+
[portal.home.download]
back = "Back"
body = "Download the desktop app or self-host the server."
@@ -7943,6 +7979,7 @@ paused = "Paused"
[portal.pipelines.table]
name = "Pipeline"
+open = "Open"
sources = "Sources"
status = "Status"
steps = "Steps"
@@ -8834,6 +8871,7 @@ unused = "Unused"
[portal.sources.table]
documents = "Documents"
+open = "Open"
source = "Source"
status = "Status"
usedBy = "Policies"
diff --git a/frontend/editor/src/core/ui/Table.css b/frontend/editor/src/core/ui/Table.css
index 696bbc8afb..3d759c1fcd 100644
--- a/frontend/editor/src/core/ui/Table.css
+++ b/frontend/editor/src/core/ui/Table.css
@@ -12,6 +12,21 @@
font-size: 0.8125rem;
}
+/* Header text kept for assistive tech only, so a column of controls can be named
+ without putting a heading above it. Defined here rather than borrowing a global
+ utility, since the portal loads its own stylesheet. */
+.sui-table__th-sr {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+ border: 0;
+}
+
.sui-table__th {
text-align: left;
font-weight: 600;
diff --git a/frontend/editor/src/core/ui/Table.tsx b/frontend/editor/src/core/ui/Table.tsx
index fcd50e5fd6..277362eab8 100644
--- a/frontend/editor/src/core/ui/Table.tsx
+++ b/frontend/editor/src/core/ui/Table.tsx
@@ -5,6 +5,12 @@ export interface TableColumn<T> {
/** Stable column id. */
key: string;
header: ReactNode;
+ /**
+ * Hides the header visually but keeps it for assistive tech. For a trailing column of controls
+ * or chevrons, where a visible heading would be noise but a blank one leaves the cells below it
+ * unlabelled.
+ */
+ headerHidden?: boolean;
/** Cell renderer for a row. */
render: (row: T) => ReactNode;
align?: "left" | "right" | "center";
@@ -25,6 +31,13 @@ export interface TableProps<T> {
* all rows interactive.
*/
isRowInteractive?: (row: T) => boolean;
+ /**
+ * Set when rows render controls of their own. The row keeps its click as a mouse shortcut but
+ * stops announcing itself as a button, because a button may not contain other controls and a
+ * {@code <tr role="button">} is no longer a row to a screen reader. That row control is then the
+ * keyboard path to the same action, so nothing is lost by leaving the row itself inert.
+ */
+ rowsContainControls?: boolean;
/** Rendered in place of the body when there are no rows. */
empty?: ReactNode;
className?: string;
@@ -42,6 +55,7 @@ export function Table<T>({
rowKey,
onRowClick,
isRowInteractive,
+ rowsContainControls = false,
empty,
className,
}: TableProps<T>) {
@@ -60,7 +74,11 @@ export function Table<T>({
className={`sui-table__th sui-table__th--${c.align ?? "left"}`}
style={c.width ? { width: c.width } : undefined}
>
- {c.header}
+ {c.headerHidden ? (
+ <span className="sui-table__th-sr">{c.header}</span>
+ ) : (
+ c.header
+ )}
</th>
))}
</tr>
@@ -76,6 +94,9 @@ export function Table<T>({
rows.map((row) => {
const rowInteractive =
interactive && (isRowInteractive?.(row) ?? true);
+ // Only a row that owns the whole interaction takes the button role and the keyboard
+ // handling that goes with it; see rowsContainControls.
+ const rowIsControl = rowInteractive && !rowsContainControls;
return (
<tr
key={rowKey(row)}
@@ -85,10 +106,10 @@ export function Table<T>({
: "sui-table__row"
}
onClick={rowInteractive ? () => onRowClick?.(row) : undefined}
- tabIndex={rowInteractive ? 0 : undefined}
- role={rowInteractive ? "button" : undefined}
+ tabIndex={rowIsControl ? 0 : undefined}
+ role={rowIsControl ? "button" : undefined}
onKeyDown={
- rowInteractive
+ rowIsControl
? (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
diff --git a/frontend/editor/src/portal/api/fileRunEvents.test.ts b/frontend/editor/src/portal/api/fileRunEvents.test.ts
new file mode 100644
index 0000000000..0e1729a891
--- /dev/null
+++ b/frontend/editor/src/portal/api/fileRunEvents.test.ts
@@ -0,0 +1,104 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * Contract tests for the api module itself. The component tests mock it wholesale,
+ * so they cannot catch mistakes in how it talks to the http client — a
+ * double-encoded body slipped through that gap once. These pin the call shape.
+ */
+
+const json = vi.fn();
+
+vi.mock("@portal/api/http", () => ({
+ apiClient: { local: { json: (...args: unknown[]) => json(...args) } },
+}));
+
+const { applyFileRunEventAction, fetchFileRunEvents } =
+ await import("@portal/api/fileRunEvents");
+
+describe("fileRunEvents api", () => {
+ beforeEach(() => json.mockReset());
+
+ describe("fetchFileRunEvents", () => {
+ it("requests the collection with no query when unfiltered", async () => {
+ json.mockResolvedValue({ events: [] });
+
+ await fetchFileRunEvents();
+
+ expect(json).toHaveBeenCalledWith("/api/v1/file-run-events");
+ });
+
+ it("serialises only the filters that were supplied", async () => {
+ json.mockResolvedValue({ events: [] });
+
+ await fetchFileRunEvents({ status: "NEW", limit: 10 });
+
+ const [path] = json.mock.calls[0] as [string];
+ const query = new URL(path, "http://localhost").searchParams;
+ expect(query.get("status")).toBe("NEW");
+ expect(query.get("limit")).toBe("10");
+ expect(query.has("kindId")).toBe(false);
+ });
+
+ it("never sends a team parameter, because the server derives it", async () => {
+ // The server derives the team, so asserted here to keep a param from creeping in.
+ json.mockResolvedValue({ events: [] });
+
+ await fetchFileRunEvents({ status: "NEW", kindId: "UNKNOWN", limit: 5 });
+
+ const [path] = json.mock.calls[0] as [string];
+ expect(path).not.toMatch(/team/i);
+ });
+
+ it("unwraps the response envelope", async () => {
+ json.mockResolvedValue({ events: [{ id: "a" }] });
+
+ await expect(fetchFileRunEvents()).resolves.toEqual([{ id: "a" }]);
+ });
+
+ it("tolerates a response with no events array", async () => {
+ json.mockResolvedValue(undefined);
+
+ await expect(fetchFileRunEvents()).resolves.toEqual([]);
+ });
+ });
+
+ describe("applyFileRunEventAction", () => {
+ it("passes body as an object, not a pre-serialised string", async () => {
+ // The regression this file exists for: apiClient stringifies `body`
+ // itself, so a string here would arrive double-encoded.
+ json.mockResolvedValue({ id: "fre-1" });
+
+ await applyFileRunEventAction("fre-1", "ACKNOWLEDGE");
+
+ const [, options] = json.mock.calls[0] as [
+ string,
+ { method: string; body: unknown },
+ ];
+ expect(typeof options.body).toBe("object");
+ expect(options.body).toEqual({ inputs: {} });
+ expect(options.method).toBe("POST");
+ });
+
+ it("forwards collected inputs", async () => {
+ json.mockResolvedValue({ id: "fre-1" });
+
+ await applyFileRunEventAction("fre-1", "ACKNOWLEDGE", {
+ password: "hunter2",
+ });
+
+ const [, options] = json.mock.calls[0] as [string, { body: unknown }];
+ expect(options.body).toEqual({ inputs: { password: "hunter2" } });
+ });
+
+ it("encodes ids into the path so an odd id cannot break the URL", async () => {
+ json.mockResolvedValue({ id: "x" });
+
+ await applyFileRunEventAction("a/b?c", "ACKNOWLEDGE");
+
+ const [path] = json.mock.calls[0] as [string];
+ expect(path).toBe(
+ "/api/v1/file-run-events/a%2Fb%3Fc/actions/ACKNOWLEDGE",
+ );
+ });
+ });
+});
diff --git a/frontend/editor/src/portal/api/fileRunEvents.ts b/frontend/editor/src/portal/api/fileRunEvents.ts
new file mode 100644
index 0000000000..8b52c7d3fc
--- /dev/null
+++ b/frontend/editor/src/portal/api/fileRunEvents.ts
@@ -0,0 +1,120 @@
+import { apiClient } from "@portal/api/http";
+
+/**
+ * Recorded policy and pipeline failures, mirroring the backend `FileRunEventView`.
+ *
+ * Two properties of the contract: the server sends i18n keys plus an English
+ * `defaultTitle` rather than rendered copy, so a client can display a kind it was
+ * not built with; and each row's `actions` arrive already resolved, so rendering
+ * buttons needs no knowledge of the rules.
+ */
+
+/** Where the fault lay. Widened server-side ahead of the kinds that need it. */
+export type FailureStage =
+ | "INPUT"
+ | "INTERNAL"
+ | "OUTPUT"
+ | "BLOCKED"
+ | "NEVER_RAN";
+
+export type FailureSeverity = "ERROR" | "WARNING" | "INFO";
+
+export type FailureRemedy =
+ | "TRANSIENT"
+ | "NEEDS_USER_INPUT"
+ | "NEEDS_FILE_FIX"
+ | "NEEDS_CONFIG_FIX"
+ | "NEEDS_SERVER_FIX"
+ | "PERMANENT";
+
+export type FailureScope = "FILE" | "RUN" | "POLICY" | "SOURCE" | "SERVER";
+
+export type FailureOrigin = "TOOL" | "POLICY" | "PIPELINE";
+
+export type FileRunEventStatus =
+ | "NEW"
+ | "ACKNOWLEDGED"
+ | "DISMISSED"
+ | "RESOLVED";
+
+/**
+ * One button as offered for one row. `id` is a plain string rather than a union
+ * because the server may know actions this build does not; the renderer skips them.
+ */
+export interface FailureActionOffer {
+ id: string;
+ labelKey: string;
+ enabled: boolean;
+ disabledReasonKey: string | null;
+}
+
+export interface FileRunEvent {
+ id: string;
+ kindId: string;
+ stage: FailureStage;
+ severity: FailureSeverity;
+ scope: FailureScope;
+ origin: FailureOrigin;
+ remedy: FailureRemedy;
+ titleKey: string;
+ descriptionKey: string;
+ /** English fallback, used when this build has no translation for `titleKey`. */
+ defaultTitle: string;
+ /** Raw failure message. For an unclassified failure this is the only detail. */
+ detail: string | null;
+ policyId: string | null;
+ runId: string | null;
+ /**
+ * Opaque reference, never a name. Only the owner's own client can resolve it to
+ * something readable, from its local file store.
+ */
+ fileId: string | null;
+ actor: string | null;
+ /** How many times this same failure has been seen; repeats fold into one row. */
+ occurrences: number;
+ status: FileRunEventStatus;
+ statusActor: string | null;
+ actions: FailureActionOffer[];
+ createdAt: number;
+ lastSeenAt: number;
+}
+
+export interface FileRunEventsResponse {
+ events: FileRunEvent[];
+}
+
+export interface ListFileRunEventsParams {
+ status?: FileRunEventStatus;
+ kindId?: string;
+ limit?: number;
+}
+
+/** GET /api/v1/file-run-events — the caller's team only; there is no team param. */
+export async function fetchFileRunEvents(
+ params: ListFileRunEventsParams = {},
+): Promise<FileRunEvent[]> {
+ const query = new URLSearchParams();
+ if (params.status) query.set("status", params.status);
+ if (params.kindId) query.set("kindId", params.kindId);
+ if (params.limit != null) query.set("limit", String(params.limit));
+ const suffix = query.toString() ? `?${query}` : "";
+
+ const response = await apiClient.local.json<FileRunEventsResponse>(
+ `/api/v1/file-run-events${suffix}`,
+ );
+ return response?.events ?? [];
+}
+
+/** POST /api/v1/file-run-events/{id}/actions/{actionId} — returns the updated row. */
+export async function applyFileRunEventAction(
+ eventId: string,
+ actionId: string,
+ inputs: Record<string, string> = {},
+): Promise<FileRunEvent> {
+ return apiClient.local.json<FileRunEvent>(
+ `/api/v1/file-run-events/${encodeURIComponent(eventId)}/actions/${encodeURIComponent(actionId)}`,
+ // A plain object, not a JSON string: apiClient serialises `body` itself, so
+ // pre-stringifying would double-encode it.
+ { method: "POST", body: { inputs } },
+ );
+}
diff --git a/frontend/editor/src/portal/components/documents/ReviewQueueTable.tsx b/frontend/editor/src/portal/components/documents/ReviewQueueTable.tsx
index bff13d0c4f..e63ea925c4 100644
--- a/frontend/editor/src/portal/components/documents/ReviewQueueTable.tsx
+++ b/frontend/editor/src/portal/components/documents/ReviewQueueTable.tsx
@@ -71,8 +71,11 @@ export function ReviewQueueTable({
</Chip>
)}
{d.sensitive && (
+ // role="img" so the label is allowed and the icon reads as one thing: aria-label
+ // is ignored on a bare span, leaving the padlock silent.
<span
className="portal-documents__lock"
+ role="img"
title={t("portal.documents.table.sensitiveTitle")}
aria-label={t("portal.documents.table.sensitiveLabel")}
>
@@ -136,7 +139,8 @@ export function ReviewQueueTable({
},
{
key: "actions",
- header: "",
+ header: t("portal.documents.table.columns.actions"),
+ headerHidden: true,
width: "3rem",
render: (d) => (
<Button
@@ -163,6 +167,8 @@ export function ReviewQueueTable({
rows={documents}
rowKey={(d) => d.id}
onRowClick={onRowClick}
+ // Every row carries its own actions button, which opens the same document.
+ rowsContainControls
empty={t("portal.documents.table.empty")}
/>
);
diff --git a/frontend/editor/src/portal/components/failures/FailureActionButtons.stories.tsx b/frontend/editor/src/portal/components/failures/FailureActionButtons.stories.tsx
new file mode 100644
index 0000000000..b63fec7220
--- /dev/null
+++ b/frontend/editor/src/portal/components/failures/FailureActionButtons.stories.tsx
@@ -0,0 +1,59 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import type { FailureActionOffer } from "@portal/api/fileRunEvents";
+import { FILE_RUN_EVENTS } from "@portal/mocks/fileRunEvents";
+import { FailureActionButtons } from "@portal/components/failures/FailureActionButtons";
+import "@portal/components/failures/failures.css";
+
+const OPEN_EVENT = FILE_RUN_EVENTS[0];
+
+const meta: Meta<typeof FailureActionButtons> = {
+ title: "Portal/Failures/FailureActionButtons",
+ component: FailureActionButtons,
+ parameters: { layout: "padded" },
+ args: { event: OPEN_EVENT, onAction: () => {} },
+};
+export default meta;
+type Story = StoryObj<typeof FailureActionButtons>;
+
+/**
+ * Labels come from the server's per-kind overrides, so a password failure reads
+ * "I'll unlock this" and "Skip this file" rather than the generic wording.
+ */
+export const PerKindLabels: Story = {};
+
+/** The generic labels, used by any kind that declares no override. */
+export const GenericLabels: Story = {
+ args: { event: FILE_RUN_EVENTS[1] },
+};
+
+/** A closed incident keeps its buttons, disabled with a reason, so the reviewer
+ * can still see what was possible. */
+export const Closed: Story = {
+ args: { event: FILE_RUN_EVENTS[2] },
+};
+
+/** An action mid-flight. */
+export const Busy: Story = {
+ args: { busyActionId: "ACKNOWLEDGE" },
+};
+
+/**
+ * An action id this build does not implement is skipped rather than rendered
+ * unwired, since the server can be newer than the client (notably on desktop).
+ */
+export const UnknownActionIsSkipped: Story = {
+ args: {
+ event: {
+ ...OPEN_EVENT,
+ actions: [
+ ...OPEN_EVENT.actions,
+ {
+ id: "REMEDIATE_AND_RETRY",
+ labelKey: "portal.failures.action.remediateAndRetry",
+ enabled: true,
+ disabledReasonKey: null,
+ } satisfies FailureActionOffer,
+ ],
+ },
+ },
+};
diff --git a/frontend/editor/src/portal/components/failures/FailureActionButtons.test.tsx b/frontend/editor/src/portal/components/failures/FailureActionButtons.test.tsx
new file mode 100644
index 0000000000..7982eb15ce
--- /dev/null
+++ b/frontend/editor/src/portal/components/failures/FailureActionButtons.test.tsx
@@ -0,0 +1,208 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ fireEvent,
+ render as baseRender,
+ screen,
+} from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { FailureActionButtons } from "@portal/components/failures/FailureActionButtons";
+import type {
+ FailureActionOffer,
+ FileRunEvent,
+} from "@portal/api/fileRunEvents";
+
+// @app/ui Button is a Mantine wrapper, so it needs the provider in the tree.
+const render = (
+ ui: Parameters<typeof baseRender>[0],
+ options?: Parameters<typeof baseRender>[1],
+) => baseRender(ui, { wrapper: MantineProvider, ...options });
+
+/**
+ * The renderer is driven entirely by what the server sent, so a new failure kind or
+ * label needs no change here. These pin that, plus the two rules the client owns:
+ * skip unknown actions, confirm the ones that close an incident.
+ */
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ // Mirrors i18next's contract closely enough to exercise the fallback logic:
+ // a known key resolves, an unknown key returns its defaultValue.
+ t: (key: string, options?: { defaultValue?: string } | string) => {
+ const known: Record<string, string> = {
+ "portal.failures.action.acknowledge": "Acknowledge",
+ "portal.failures.action.dismiss": "Dismiss",
+ "portal.failures.action.dismissSkipFile": "Skip this file",
+ "portal.failures.action.confirm": "Are you sure?",
+ "portal.failures.disabled.closed": "This failure is already closed.",
+ };
+ if (known[key]) return known[key];
+ if (typeof options === "string") return options;
+ if (options?.defaultValue) return options.defaultValue;
+ return key;
+ },
+ }),
+}));
+
+function offer(
+ overrides: Partial<FailureActionOffer> = {},
+): FailureActionOffer {
+ return {
+ id: "ACKNOWLEDGE",
+ labelKey: "portal.failures.action.acknowledge",
+ enabled: true,
+ disabledReasonKey: null,
+ ...overrides,
+ };
+}
+
+function event(actions: FailureActionOffer[]): FileRunEvent {
+ return {
+ id: "evt-1",
+ kindId: "UNKNOWN",
+ stage: "INTERNAL",
+ severity: "ERROR",
+ scope: "RUN",
+ origin: "POLICY",
+ remedy: "PERMANENT",
+ titleKey: "portal.failures.kind.unknown.title",
+ descriptionKey: "portal.failures.kind.unknown.description",
+ defaultTitle: "Unrecognised failure",
+ detail: "boom",
+ policyId: "p1",
+ runId: "r1",
+ fileId: "f-1",
+ actor: "[email protected]",
+ occurrences: 1,
+ status: "NEW",
+ statusActor: null,
+ actions,
+ createdAt: 0,
+ lastSeenAt: 0,
+ };
+}
+
+describe("FailureActionButtons", () => {
+ it("renders one button per declared action, labelled from the server's key", () => {
+ render(
+ <FailureActionButtons
+ event={event([
+ offer(),
+ offer({
+ id: "DISMISS",
+ labelKey: "portal.failures.action.dismissSkipFile",
+ }),
+ ])}
+ onAction={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByRole("button", { name: "Acknowledge" })).toBeTruthy();
+ // The kind's override wins over the generic label, without the client
+ // knowing which kinds override what.
+ expect(screen.getByRole("button", { name: "Skip this file" })).toBeTruthy();
+ });
+
+ it("skips an action id this build cannot perform instead of crashing", () => {
+ // The server may be newer than the client (notably on desktop). An
+ // unrenderable button is worse than none.
+ render(
+ <FailureActionButtons
+ event={event([
+ offer(),
+ offer({ id: "REMEDIATE_AND_RETRY", labelKey: "x" }),
+ ])}
+ onAction={vi.fn()}
+ />,
+ );
+
+ expect(screen.getAllByRole("button")).toHaveLength(1);
+ expect(screen.getByRole("button", { name: "Acknowledge" })).toBeTruthy();
+ });
+
+ it("renders nothing when no action is recognised", () => {
+ const { container } = render(
+ <FailureActionButtons
+ event={event([offer({ id: "APPROVE", labelKey: "x" })])}
+ onAction={vi.fn()}
+ />,
+ );
+
+ expect(container.querySelectorAll("button")).toHaveLength(0);
+ });
+
+ it("falls back to the generic label when the server's key is unknown to this build", () => {
+ render(
+ <FailureActionButtons
+ event={event([
+ offer({ labelKey: "portal.failures.action.brandNewKey" }),
+ ])}
+ onAction={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByRole("button", { name: "Acknowledge" })).toBeTruthy();
+ });
+
+ it("disables an action the server marked unusable and explains why", () => {
+ render(
+ <FailureActionButtons
+ event={event([
+ offer({
+ enabled: false,
+ disabledReasonKey: "portal.failures.disabled.closed",
+ }),
+ ])}
+ onAction={vi.fn()}
+ />,
+ );
+
+ const button = screen.getByRole("button", { name: /already closed/ });
+ expect(button.hasAttribute("disabled")).toBe(true);
+ });
+
+ it("dispatches a non-terminal action immediately", () => {
+ const onAction = vi.fn();
+ render(
+ <FailureActionButtons event={event([offer()])} onAction={onAction} />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Acknowledge" }));
+
+ expect(onAction).toHaveBeenCalledWith("ACKNOWLEDGE");
+ });
+
+ it("asks for confirmation before dispatching a terminal action", () => {
+ const onAction = vi.fn();
+ render(
+ <FailureActionButtons
+ event={event([
+ offer({ id: "DISMISS", labelKey: "portal.failures.action.dismiss" }),
+ ])}
+ onAction={onAction}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
+ // Dismiss closes the incident, so the first click only arms it.
+ expect(onAction).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole("button", { name: "Are you sure?" }));
+ expect(onAction).toHaveBeenCalledWith("DISMISS");
+ });
+
+ it("disables the action that is in flight", () => {
+ render(
+ <FailureActionButtons
+ event={event([offer()])}
+ onAction={vi.fn()}
+ busyActionId="ACKNOWLEDGE"
+ />,
+ );
+
+ expect(
+ screen
+ .getByRole("button", { name: "Acknowledge" })
+ .hasAttribute("disabled"),
+ ).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/portal/components/failures/FailureActionButtons.tsx b/frontend/editor/src/portal/components/failures/FailureActionButtons.tsx
new file mode 100644
index 0000000000..de8fcdbc24
--- /dev/null
+++ b/frontend/editor/src/portal/components/failures/FailureActionButtons.tsx
@@ -0,0 +1,96 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui";
+import type {
+ FailureActionOffer,
+ FileRunEvent,
+} from "@portal/api/fileRunEvents";
+
+/**
+ * Renders a row's action buttons from the data the server sent, knowing nothing about
+ * individual failure kinds. Two client-side rules: an id this build cannot handle is
+ * skipped rather than rendered unwired, and closing an incident confirms first.
+ */
+
+/** Actions this build can actually perform. Anything else is skipped. */
+const HANDLED_ACTIONS = new Set(["ACKNOWLEDGE", "DISMISS"]);
+
+/** Actions that close the incident, so they warrant a confirmation step. */
+const CONFIRMING_ACTIONS = new Set(["DISMISS"]);
+
+interface FailureActionButtonsProps {
+ event: FileRunEvent;
+ onAction: (actionId: string) => void | Promise<void>;
+ busyActionId?: string | null;
+}
+
+export function FailureActionButtons({
+ event,
+ onAction,
+ busyActionId,
+}: FailureActionButtonsProps) {
+ const { t } = useTranslation();
+ const [confirming, setConfirming] = useState<string | null>(null);
+
+ const renderable = event.actions.filter((action) =>
+ HANDLED_ACTIONS.has(action.id),
+ );
+ if (renderable.length === 0) return null;
+
+ const labelFor = (action: FailureActionOffer) =>
+ // The server's key first, falling back to the generic label for this action.
+ t(action.labelKey, {
+ defaultValue: t(
+ `portal.failures.action.${action.id.toLowerCase()}`,
+ action.id,
+ ),
+ });
+
+ return (
+ <div className="portal-failures__actions">
+ {renderable.map((action) => {
+ const isConfirming = confirming === action.id;
+ const busy = busyActionId === action.id;
+ const disabled = !action.enabled || busy;
+
+ return (
+ <Button
+ key={action.id}
+ variant={isConfirming ? "primary" : "secondary"}
+ disabled={disabled}
+ aria-label={
+ action.enabled
+ ? undefined
+ : `${labelFor(action)} — ${t(
+ action.disabledReasonKey ??
+ "portal.failures.disabled.unavailable",
+ "unavailable",
+ )}`
+ }
+ title={
+ action.enabled
+ ? undefined
+ : t(
+ action.disabledReasonKey ??
+ "portal.failures.disabled.unavailable",
+ "unavailable",
+ )
+ }
+ onClick={() => {
+ if (CONFIRMING_ACTIONS.has(action.id) && !isConfirming) {
+ setConfirming(action.id);
+ return;
+ }
+ setConfirming(null);
+ void onAction(action.id);
+ }}
+ >
+ {isConfirming
+ ? t("portal.failures.action.confirm", "Are you sure?")
+ : labelFor(action)}
+ </Button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/portal/components/failures/FileRunEventList.test.tsx b/frontend/editor/src/portal/components/failures/FileRunEventList.test.tsx
new file mode 100644
index 0000000000..1458a1d64d
--- /dev/null
+++ b/frontend/editor/src/portal/components/failures/FileRunEventList.test.tsx
@@ -0,0 +1,193 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { render as baseRender, screen, waitFor } from "@testing-library/react";
+import { PortalTestProviders } from "@portal/test/TestQueryProvider";
+import type { FileRunEvent } from "@portal/api/fileRunEvents";
+
+/**
+ * Tests for the list: the states it survives (loading, empty, no registry, refused),
+ * plus replacing a row in place after acting and re-reading when the server refuses.
+ */
+
+const fetchFileRunEvents = vi.fn();
+const applyFileRunEventAction = vi.fn();
+
+vi.mock("@portal/api/fileRunEvents", () => ({
+ fetchFileRunEvents: (...args: unknown[]) => fetchFileRunEvents(...args),
+ applyFileRunEventAction: (...args: unknown[]) =>
+ applyFileRunEventAction(...args),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ // Faithful to i18next: a known key resolves, an unknown key falls back to
+ // defaultValue. That is what exercises the server-key-then-generic chain.
+ t: (key: string, options?: { defaultValue?: string } | string) => {
+ const known: Record<string, string> = {
+ "portal.failures.kind.inputPasswordProtected.title":
+ "Password-protected document",
+ "portal.failures.action.acknowledge": "Acknowledge",
+ "portal.failures.empty.title": "No failures recorded",
+ "portal.failures.occurrences": "occurrences",
+ "portal.failures.runReference": "Run r1",
+ "portal.failures.stage.input": "Input",
+ };
+ if (known[key]) return known[key];
+ if (typeof options === "string") return options;
+ if (options?.defaultValue) return options.defaultValue;
+ return key;
+ },
+ }),
+}));
+
+// The list reads through the shared query hooks, and @app/ui needs Mantine.
+const render = (ui: Parameters<typeof baseRender>[0]) =>
+ baseRender(ui, { wrapper: PortalTestProviders });
+
+const { FileRunEventList } =
+ await import("@portal/components/failures/FileRunEventList");
+
+function event(overrides: Partial<FileRunEvent> = {}): FileRunEvent {
+ return {
+ id: "fre-1",
+ kindId: "INPUT_PASSWORD_PROTECTED",
+ stage: "INPUT",
+ severity: "ERROR",
+ scope: "FILE",
+ origin: "POLICY",
+ remedy: "NEEDS_USER_INPUT",
+ titleKey: "portal.failures.kind.inputPasswordProtected.title",
+ descriptionKey: "portal.failures.kind.inputPasswordProtected.description",
+ defaultTitle: "Password-protected document",
+ detail: "The PDF Document is passworded",
+ policyId: "p1",
+ runId: "r1",
+ fileId: "f-1",
+ actor: "[email protected]",
+ occurrences: 1,
+ status: "NEW",
+ statusActor: null,
+ actions: [
+ {
+ id: "ACKNOWLEDGE",
+ labelKey: "portal.failures.action.acknowledge",
+ enabled: true,
+ disabledReasonKey: null,
+ },
+ ],
+ createdAt: 0,
+ lastSeenAt: 0,
+ ...overrides,
+ };
+}
+
+describe("FileRunEventList", () => {
+ beforeEach(() => {
+ fetchFileRunEvents.mockReset();
+ applyFileRunEventAction.mockReset();
+ // The dev-panel test stubs import.meta.env.DEV, which would otherwise persist
+ // into every test after it.
+ vi.unstubAllEnvs();
+ });
+
+ it("renders a row's title, run reference and raw detail, but no document name", async () => {
+ fetchFileRunEvents.mockResolvedValue([event()]);
+
+ render(<FileRunEventList />);
+
+ expect(await screen.findByText("Password-protected document")).toBeTruthy();
+ // A run reference, not a document name: the record holds no file identity.
+ expect(screen.getByText("Run r1")).toBeTruthy();
+ // The raw message is shown, not swallowed: for an unclassified failure it is
+ // the only diagnostic available.
+ expect(screen.getByText("The PDF Document is passworded")).toBeTruthy();
+ });
+
+ it("shows the occurrence count only once a failure has repeated", async () => {
+ fetchFileRunEvents.mockResolvedValue([event({ occurrences: 1 })]);
+ const { unmount } = render(<FileRunEventList />);
+ await screen.findByText("Run r1");
+ expect(screen.queryByText(/occurrences/)).toBeNull();
+ unmount();
+
+ fetchFileRunEvents.mockResolvedValue([event({ occurrences: 14 })]);
+ render(<FileRunEventList />);
+ expect(await screen.findByText(/occurrences/)).toBeTruthy();
+ });
+
+ it("shows an empty state when there is nothing to triage", async () => {
+ fetchFileRunEvents.mockResolvedValue([]);
+
+ render(<FileRunEventList />);
+
+ expect(await screen.findByText("No failures recorded")).toBeTruthy();
+ });
+
+ it("renders nothing when the server has no failure registry", async () => {
+ // A core-only build has no such route, which is not worth showing a reviewer as
+ // an error, so the section stays silent.
+ fetchFileRunEvents.mockRejectedValue(new Error("404"));
+
+ const { container } = render(<FileRunEventList />);
+
+ await waitFor(() => {
+ expect(container.querySelector(".portal-failures__list")).toBeNull();
+ });
+ expect(screen.queryByText("No failures recorded")).toBeNull();
+ });
+
+ it("renders no heading at all for a caller the server refuses", async () => {
+ // Reviewing is leader-only, so a member's read returns 403. With no dev panel to
+ // frame, the whole section goes rather than leaving a bare heading.
+ vi.stubEnv("DEV", false);
+ fetchFileRunEvents.mockRejectedValue(new Error("403"));
+
+ const { container } = render(<FileRunEventList />);
+
+ await waitFor(() => {
+ expect(container.querySelector(".portal-failures")).toBeNull();
+ });
+ // No section, and specifically no heading: Mantine puts its <style> tags in
+ // the container, so "renders nothing" is asserted on our own output.
+ expect(screen.queryByRole("heading")).toBeNull();
+ expect(container.querySelector(".portal-failures__debug")).toBeNull();
+ });
+
+ it("replaces the acted-on row in place using the server's response", async () => {
+ fetchFileRunEvents.mockResolvedValue([event()]);
+ applyFileRunEventAction.mockResolvedValue(
+ event({ status: "ACKNOWLEDGED", statusActor: "[email protected]" }),
+ );
+
+ render(<FileRunEventList />);
+ const button = await screen.findByRole("button", {
+ name: "Acknowledge",
+ });
+ button.click();
+
+ await waitFor(() => {
+ expect(applyFileRunEventAction).toHaveBeenCalledWith(
+ "fre-1",
+ "ACKNOWLEDGE",
+ );
+ });
+ // Updated from the response rather than by refetching, so the list does not
+ // reload and jump under the reviewer.
+ expect(fetchFileRunEvents).toHaveBeenCalledTimes(1);
+ });
+
+ it("re-reads from the server when an action is refused", async () => {
+ // A 409 means someone else closed it first; the server's view wins.
+ fetchFileRunEvents.mockResolvedValue([event()]);
+ applyFileRunEventAction.mockRejectedValue(new Error("409"));
+
+ render(<FileRunEventList />);
+ const button = await screen.findByRole("button", {
+ name: "Acknowledge",
+ });
+ button.click();
+
+ await waitFor(() => {
+ expect(fetchFileRunEvents).toHaveBeenCalledTimes(2);
+ });
+ });
+});
diff --git a/frontend/editor/src/portal/components/failures/FileRunEventList.tsx b/frontend/editor/src/portal/components/failures/FileRunEventList.tsx
new file mode 100644
index 0000000000..9b68c53b4c
--- /dev/null
+++ b/frontend/editor/src/portal/components/failures/FileRunEventList.tsx
@@ -0,0 +1,184 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button, EmptyState, Skeleton, StatusBadge } from "@app/ui";
+import type { FileRunEvent, FailureSeverity } from "@portal/api/fileRunEvents";
+import {
+ useFileRunEvents,
+ useFileRunEventActions,
+} from "@portal/queries/fileRunEvents";
+import { FailureActionButtons } from "@portal/components/failures/FailureActionButtons";
+
+/**
+ * Recorded policy and pipeline failures, with the triage actions the server offered
+ * for each. Renders the section including its heading, or nothing at all, so one
+ * place decides whether the block exists; reviewing is leader-only and a refused
+ * read yields no section. Covers policy runs only, since the older watched-folder
+ * pipeline is not instrumented.
+ */
+
+const SEVERITY_TONE: Record<FailureSeverity, "danger" | "warning" | "info"> = {
+ ERROR: "danger",
+ WARNING: "warning",
+ INFO: "info",
+};
+
+export function FileRunEventList() {
+ const { t } = useTranslation();
+ const { data: events, error } = useFileRunEvents();
+ const { apply, refresh } = useFileRunEventActions();
+ const [busy, setBusy] = useState<{ id: string; action: string } | null>(null);
+ const [showJson, setShowJson] = useState(false);
+
+ // A build without the proprietary module has no such route, and a caller who is
+ // not a team leader gets a 403. Both mean there is nothing to show.
+ const unavailable = error !== null;
+
+ const act = async (event: FileRunEvent, actionId: string) => {
+ setBusy({ id: event.id, action: actionId });
+ try {
+ await apply(event.id, actionId);
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ // Dev-only inspector for hand-checking classification against real uploads.
+ // Vite folds `import.meta.env.DEV` to false, so builds drop this entirely.
+ const debugPanel = !import.meta.env.DEV ? null : (
+ <div className="portal-failures__debug">
+ <Button variant="secondary" size="sm" onClick={() => void refresh()}>
+ Refresh failures
+ </Button>
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => setShowJson((shown) => !shown)}
+ >
+ {showJson ? "Hide" : "Show"} raw JSON ({events?.length ?? 0})
+ </Button>
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() =>
+ void navigator.clipboard.writeText(
+ JSON.stringify(events ?? [], null, 2),
+ )
+ }
+ >
+ Copy JSON
+ </Button>
+ {showJson && (
+ <pre className="portal-failures__debug-json">
+ {JSON.stringify(events ?? [], null, 2)}
+ </pre>
+ )}
+ </div>
+ );
+
+ // Nothing to show and no dev panel to frame, so skip the heading too rather
+ // than leaving an empty "Failures" section.
+ if (unavailable && debugPanel === null) {
+ return null;
+ }
+
+ return (
+ <section className="portal-failures">
+ <h2 className="portal-failures__heading">
+ {t("portal.failures.title", "Failures")}
+ </h2>
+ <p className="portal-failures__sub">
+ {t(
+ "portal.failures.subtitle",
+ "Failures recorded from your policy runs, with the actions you can take.",
+ )}
+ </p>
+ {debugPanel}
+ {unavailable ? null : (
+ <FailureBody events={events} busy={busy} onAction={act} />
+ )}
+ </section>
+ );
+}
+
+/** What fills the section: loading, empty, or the rows. */
+function FailureBody({
+ events,
+ busy,
+ onAction,
+}: {
+ events: FileRunEvent[] | null;
+ busy: { id: string; action: string } | null;
+ onAction: (event: FileRunEvent, actionId: string) => void;
+}) {
+ const { t } = useTranslation();
+
+ if (events === null) {
+ return (
+ <div className="portal-failures__skeleton" aria-hidden>
+ {Array.from({ length: 3 }).map((_, i) => (
+ <Skeleton key={i} height="4rem" />
+ ))}
+ </div>
+ );
+ }
+
+ if (events.length === 0) {
+ return (
+ <EmptyState
+ title={t("portal.failures.empty.title", "No failures recorded")}
+ description={t(
+ "portal.failures.empty.description",
+ "Policy runs that fail will appear here with the actions you can take.",
+ )}
+ />
+ );
+ }
+
+ return (
+ <ul className="portal-failures__list">
+ {events.map((event) => (
+ <li key={event.id} className="portal-failures__row">
+ <div className="portal-failures__meta">
+ <StatusBadge tone={SEVERITY_TONE[event.severity]}>
+ {t(
+ `portal.failures.stage.${event.stage.toLowerCase()}`,
+ event.stage,
+ )}
+ </StatusBadge>
+ <span className="portal-failures__title">
+ {/* The server's key, with its English fallback for kinds this
+ build has no copy for. */}
+ {t(event.titleKey, { defaultValue: event.defaultTitle })}
+ </span>
+ {event.occurrences > 1 && (
+ <span className="portal-failures__count">
+ {t("portal.failures.occurrences", "{{count}} occurrences", {
+ count: event.occurrences,
+ })}
+ </span>
+ )}
+ </div>
+
+ {/* A reference, not a name. The record deliberately holds no document
+ identity, so a reviewer sees which run failed, never which file. */}
+ {event.runId && (
+ <div className="portal-failures__file">
+ {t("portal.failures.runReference", "Run {{runId}}", {
+ runId: event.runId,
+ })}
+ </div>
+ )}
+ {event.detail && (
+ <p className="portal-failures__detail">{event.detail}</p>
+ )}
+
+ <FailureActionButtons
+ event={event}
+ busyActionId={busy?.id === event.id ? busy.action : null}
+ onAction={(actionId) => onAction(event, actionId)}
+ />
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/frontend/editor/src/portal/components/failures/failures.css b/frontend/editor/src/portal/components/failures/failures.css
new file mode 100644
index 0000000000..0ac874dabc
--- /dev/null
+++ b/frontend/editor/src/portal/components/failures/failures.css
@@ -0,0 +1,113 @@
+/*
+ * Recorded failures list. Colours come from semantic tokens only; no literals.
+ * See core/theme/README.md.
+ */
+
+.portal-failures {
+ margin-top: var(--space-8, 2rem);
+}
+
+.portal-failures__heading {
+ font-size: 1.05rem;
+ font-weight: 600;
+ color: var(--c-text);
+ margin: 0;
+}
+
+.portal-failures__sub {
+ font-size: 0.85rem;
+ color: var(--c-text-muted);
+ margin: 0.2rem 0 1rem;
+}
+
+.portal-failures__skeleton {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.portal-failures__list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.6rem;
+}
+
+.portal-failures__row {
+ border: 1px solid var(--c-border);
+ border-radius: 8px;
+ background: var(--c-surface);
+ padding: 0.8rem 0.95rem;
+}
+
+.portal-failures__meta {
+ display: flex;
+ align-items: center;
+ gap: 0.55rem;
+ flex-wrap: wrap;
+}
+
+.portal-failures__title {
+ font-weight: 600;
+ font-size: 0.9rem;
+ color: var(--c-text);
+}
+
+.portal-failures__count {
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+}
+
+.portal-failures__file {
+ font-size: 0.82rem;
+ color: var(--c-text-muted);
+ margin-top: 0.3rem;
+}
+
+/* The raw failure message. Monospace because for an unclassified failure this is
+ a stack-trace-ish diagnostic, not prose. */
+.portal-failures__detail {
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 0.76rem;
+ color: var(--c-text-subtle);
+ background: var(--c-surface-sunken);
+ border-radius: 6px;
+ padding: 0.45rem 0.6rem;
+ margin: 0.5rem 0 0;
+ overflow-wrap: anywhere;
+}
+
+.portal-failures__actions {
+ display: flex;
+ gap: 0.45rem;
+ margin-top: 0.7rem;
+ flex-wrap: wrap;
+}
+
+/* ── Dev-only inspector (see FileRunEventList) ─────────────────────────────── */
+.portal-failures__debug {
+ display: flex;
+ gap: 0.4rem;
+ flex-wrap: wrap;
+ align-items: flex-start;
+ margin-bottom: 0.8rem;
+ padding: 0.5rem;
+ border: 1px dashed var(--c-border-strong);
+ border-radius: 6px;
+}
+
+.portal-failures__debug-json {
+ flex: 1 1 100%;
+ max-height: 26rem;
+ overflow: auto;
+ margin: 0.4rem 0 0;
+ padding: 0.5rem;
+ background: var(--c-surface-sunken);
+ border-radius: 4px;
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 0.7rem;
+ white-space: pre;
+ user-select: all;
+}
diff --git a/frontend/editor/src/portal/components/pipelines/PipelinesTable.tsx b/frontend/editor/src/portal/components/pipelines/PipelinesTable.tsx
index e0ac5970f6..ec68e061e7 100644
--- a/frontend/editor/src/portal/components/pipelines/PipelinesTable.tsx
+++ b/frontend/editor/src/portal/components/pipelines/PipelinesTable.tsx
@@ -84,7 +84,8 @@ export function PipelinesTable({ pipelines, onRowClick }: PipelinesTableProps) {
},
{
key: "open",
- header: "",
+ header: t("portal.pipelines.table.open"),
+ headerHidden: true,
align: "right",
width: "2.5rem",
render: () => (
diff --git a/frontend/editor/src/portal/components/policies/PolicyCatalogueTable.tsx b/frontend/editor/src/portal/components/policies/PolicyCatalogueTable.tsx
index f8d7ea9f9d..e2c8dc6b85 100644
--- a/frontend/editor/src/portal/components/policies/PolicyCatalogueTable.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicyCatalogueTable.tsx
@@ -129,6 +129,8 @@ export function PolicyCatalogueTable({
? undefined
: onOpen(entry)
}
+ // A category with no policy yet renders a "set up" button, which opens the same thing.
+ rowsContainControls
/>
);
}
diff --git a/frontend/editor/src/portal/components/sources/SourcesTable.tsx b/frontend/editor/src/portal/components/sources/SourcesTable.tsx
index 9d99a8c8ea..ad99eeb942 100644
--- a/frontend/editor/src/portal/components/sources/SourcesTable.tsx
+++ b/frontend/editor/src/portal/components/sources/SourcesTable.tsx
@@ -94,7 +94,8 @@ export function SourcesTable({ sources, onRowClick }: SourcesTableProps) {
},
{
key: "open",
- header: "",
+ header: t("portal.sources.table.open"),
+ headerHidden: true,
align: "right",
width: "2.5rem",
// The editor source has no page to open, so it shows no chevron.
diff --git a/frontend/editor/src/portal/mocks/fileRunEvents.ts b/frontend/editor/src/portal/mocks/fileRunEvents.ts
new file mode 100644
index 0000000000..31c97e1088
--- /dev/null
+++ b/frontend/editor/src/portal/mocks/fileRunEvents.ts
@@ -0,0 +1,114 @@
+/**
+ * Fixtures for recorded policy failures, for mock mode, Storybook and tests.
+ *
+ * Chosen to cover the states the UI handles rather than to look tidy: a classified
+ * failure with per-kind labels, an unclassified one, a repeat-folded incident, and
+ * a closed row whose actions come back disabled.
+ */
+
+import type { FileRunEvent } from "@portal/api/fileRunEvents";
+
+const HOUR = 3_600_000;
+
+/** Fixed base so fixtures are stable across renders and snapshots. */
+const NOW = Date.UTC(2026, 6, 31, 12, 0, 0);
+
+function acknowledgeOffer(enabled = true, labelKey?: string) {
+ return {
+ id: "ACKNOWLEDGE",
+ labelKey: labelKey ?? "portal.failures.action.acknowledge",
+ enabled,
+ disabledReasonKey: enabled ? null : "portal.failures.disabled.closed",
+ };
+}
+
+function dismissOffer(enabled = true, labelKey?: string) {
+ return {
+ id: "DISMISS",
+ labelKey: labelKey ?? "portal.failures.action.dismiss",
+ enabled,
+ disabledReasonKey: enabled ? null : "portal.failures.disabled.closed",
+ };
+}
+
+export const FILE_RUN_EVENTS: FileRunEvent[] = [
+ {
+ id: "fre-1",
+ kindId: "INPUT_PASSWORD_PROTECTED",
+ stage: "INPUT",
+ severity: "ERROR",
+ scope: "FILE",
+ origin: "POLICY",
+ remedy: "NEEDS_USER_INPUT",
+ titleKey: "portal.failures.kind.inputPasswordProtected.title",
+ descriptionKey: "portal.failures.kind.inputPasswordProtected.description",
+ defaultTitle: "Password-protected document",
+ detail: "The PDF Document is passworded and the password was not provided",
+ policyId: "policy-contract-redaction",
+ runId: "run-8841",
+ fileId: "f-8841a",
+ actor: "[email protected]",
+ occurrences: 1,
+ status: "NEW",
+ statusActor: null,
+ actions: [
+ acknowledgeOffer(true, "portal.failures.action.acknowledge"),
+ dismissOffer(true, "portal.failures.action.dismissSkipFile"),
+ ],
+ createdAt: NOW - HOUR,
+ lastSeenAt: NOW - HOUR,
+ },
+ {
+ id: "fre-2",
+ kindId: "UNKNOWN",
+ stage: "INTERNAL",
+ severity: "ERROR",
+ scope: "RUN",
+ origin: "POLICY",
+ remedy: "PERMANENT",
+ titleKey: "portal.failures.kind.unknown.title",
+ descriptionKey: "portal.failures.kind.unknown.description",
+ defaultTitle: "Unrecognised failure",
+ // An unclassified row's raw message is the whole diagnostic, so this is realistic.
+ detail:
+ "Policy run failed: Tool returned HTTP 500 INTERNAL_SERVER_ERROR for /api/v1/misc/ocr-pdf",
+ policyId: "policy-invoice-ocr",
+ runId: "run-8839",
+ fileId: "f-8839b",
+ actor: "[email protected]",
+ occurrences: 12,
+ status: "ACKNOWLEDGED",
+ statusActor: "[email protected]",
+ actions: [acknowledgeOffer(), dismissOffer()],
+ createdAt: NOW - 6 * HOUR,
+ lastSeenAt: NOW - 2 * HOUR,
+ },
+ {
+ id: "fre-3",
+ kindId: "INPUT_PASSWORD_PROTECTED",
+ stage: "INPUT",
+ severity: "ERROR",
+ scope: "FILE",
+ origin: "POLICY",
+ remedy: "NEEDS_USER_INPUT",
+ titleKey: "portal.failures.kind.inputPasswordProtected.title",
+ descriptionKey: "portal.failures.kind.inputPasswordProtected.description",
+ defaultTitle: "Password-protected document",
+ detail: "The PDF Document is passworded and the password was not provided",
+ policyId: "policy-contract-redaction",
+ runId: "run-8790",
+ fileId: "f-8790c",
+ actor: "[email protected]",
+ // Closed rows keep their actions, disabled with a reason, so the reviewer
+ // can still see what was possible.
+ occurrences: 3,
+ status: "DISMISSED",
+ statusActor: "[email protected]",
+ actions: [
+ acknowledgeOffer(false, "portal.failures.action.acknowledge"),
+ dismissOffer(false, "portal.failures.action.dismissSkipFile"),
+ ],
+ createdAt: NOW - 30 * HOUR,
+ lastSeenAt: NOW - 26 * HOUR,
+ },
+];
diff --git a/frontend/editor/src/portal/mocks/handlers/fileRunEvents.ts b/frontend/editor/src/portal/mocks/handlers/fileRunEvents.ts
new file mode 100644
index 0000000000..297298134e
--- /dev/null
+++ b/frontend/editor/src/portal/mocks/handlers/fileRunEvents.ts
@@ -0,0 +1,84 @@
+import { http, HttpResponse, delay } from "msw";
+import type { FileRunEvent } from "@portal/api/fileRunEvents";
+import { FILE_RUN_EVENTS } from "@portal/mocks/fileRunEvents";
+
+/**
+ * Mock backend for recorded policy failures. Stateful on purpose, so acting on a row
+ * visibly changes it the way the real backend does. State resets on reload.
+ */
+
+/** Mutable copy so a dispatched action is reflected in later reads. */
+let events: FileRunEvent[] = FILE_RUN_EVENTS.map((event) => ({ ...event }));
+
+/** Mirrors the server: a closed row keeps its actions but disables them all. */
+function closeActions(event: FileRunEvent): FileRunEvent["actions"] {
+ return event.actions.map((action) => ({
+ ...action,
+ enabled: false,
+ disabledReasonKey: "portal.failures.disabled.closed",
+ }));
+}
+
+export const fileRunEventsHandlers = [
+ http.get("*/api/v1/file-run-events", async ({ request }) => {
+ await delay(120);
+ const url = new URL(request.url);
+ const status = url.searchParams.get("status");
+ const kindId = url.searchParams.get("kindId");
+
+ const filtered = events.filter(
+ (event) =>
+ (!status || event.status === status) &&
+ (!kindId || event.kindId === kindId),
+ );
+ return HttpResponse.json({
+ events: [...filtered].sort((a, b) => b.lastSeenAt - a.lastSeenAt),
+ });
+ }),
+
+ http.post(
+ "*/api/v1/file-run-events/:eventId/actions/:actionId",
+ async ({ params }) => {
+ await delay(120);
+ const { eventId, actionId } = params as {
+ eventId: string;
+ actionId: string;
+ };
+
+ const existing = events.find((event) => event.id === eventId);
+ if (!existing) {
+ return HttpResponse.json({ detail: "No such event" }, { status: 404 });
+ }
+ // The real backend refuses an action the kind never declared, so the mock does too.
+ if (!existing.actions.some((action) => action.id === actionId)) {
+ return HttpResponse.json(
+ { detail: `Kind ${existing.kindId} does not offer ${actionId}` },
+ { status: 400 },
+ );
+ }
+ if (existing.status === "DISMISSED" || existing.status === "RESOLVED") {
+ return HttpResponse.json({ detail: "Already closed" }, { status: 409 });
+ }
+
+ const updated: FileRunEvent =
+ actionId === "DISMISS"
+ ? {
+ ...existing,
+ status: "DISMISSED",
+ statusActor: "[email protected]",
+ actions: closeActions(existing),
+ }
+ : {
+ ...existing,
+ status: "ACKNOWLEDGED",
+ // Acknowledging twice keeps the original owner.
+ statusActor: existing.statusActor ?? "[email protected]",
+ };
+
+ events = events.map((event) =>
+ event.id === updated.id ? updated : event,
+ );
+ return HttpResponse.json(updated);
+ },
+ ),
+];
diff --git a/frontend/editor/src/portal/mocks/handlers/index.ts b/frontend/editor/src/portal/mocks/handlers/index.ts
index 95621dce44..d5428b1853 100644
--- a/frontend/editor/src/portal/mocks/handlers/index.ts
+++ b/frontend/editor/src/portal/mocks/handlers/index.ts
@@ -15,6 +15,7 @@ import { documentsHandlers } from "@portal/mocks/handlers/documents";
import { editorDeployHandlers } from "@portal/mocks/handlers/editorDeploy";
import { linkHandlers } from "@portal/mocks/handlers/link";
import { integrationsHandlers } from "@portal/mocks/handlers/integrations";
+import { fileRunEventsHandlers } from "@portal/mocks/handlers/fileRunEvents";
export const handlers = [
...authHandlers,
@@ -34,6 +35,7 @@ export const handlers = [
...editorDeployHandlers,
...linkHandlers,
...integrationsHandlers,
+ ...fileRunEventsHandlers,
];
export { resetNotificationsStore } from "@portal/mocks/handlers/notifications";
diff --git a/frontend/editor/src/portal/queries/fileRunEvents.ts b/frontend/editor/src/portal/queries/fileRunEvents.ts
new file mode 100644
index 0000000000..2a39912494
--- /dev/null
+++ b/frontend/editor/src/portal/queries/fileRunEvents.ts
@@ -0,0 +1,76 @@
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { qk } from "@portal/queries/keys";
+import { toAsyncState } from "@portal/queries/adapters";
+import type { AsyncState } from "@portal/hooks/useAsync";
+import {
+ applyFileRunEventAction,
+ fetchFileRunEvents,
+ type FileRunEvent,
+} from "@portal/api/fileRunEvents";
+import { HttpError } from "@portal/api/http";
+
+/** How many rows one page of the review surface asks for. */
+const PAGE_SIZE = 50;
+
+/**
+ * Failures arrive from background sweeps, not from anything the reviewer did, so the list has to
+ * refresh itself or it silently goes stale. Paused while the tab is hidden, since nobody is
+ * reading it then.
+ */
+const POLL_INTERVAL_MS = 30_000;
+
+/**
+ * Answers that will not change by asking again: a build without the failure registry has no such
+ * route, and a member who is not a team leader may not read the queue. Anything else — a dropped
+ * connection, a restarting server, a gateway blip — is transient, and polling should ride it out
+ * rather than silently switching itself off for the rest of the session.
+ */
+function isPermanentRefusal(error: unknown): boolean {
+ return (
+ error instanceof HttpError && (error.status === 403 || error.status === 404)
+ );
+}
+
+/** Base query: recorded policy failures for the caller's team. */
+export function useFileRunEvents(): AsyncState<FileRunEvent[]> {
+ return toAsyncState(
+ useQuery({
+ queryKey: qk.fileRunEvents(),
+ queryFn: () => fetchFileRunEvents({ limit: PAGE_SIZE }),
+ // A build without the failure registry 404s and a non-leader gets a 403.
+ // Neither improves on retry, and the caller renders nothing either way.
+ retry: false,
+ // Give up polling only on those two, never on a transient failure: treating any error as
+ // permanent would let one dropped connection stop the list refreshing for the whole session.
+ refetchInterval: (query) =>
+ isPermanentRefusal(query.state.error) ? false : POLL_INTERVAL_MS,
+ refetchIntervalInBackground: false,
+ }),
+ );
+}
+
+/**
+ * Triage actions against the cached list. A success writes the server's own row
+ * back into the cache rather than refetching, so the list does not reload and jump
+ * under the reviewer; a refusal (a 409 when someone else closed it first) drops to
+ * an invalidate, because the server's view is the truth.
+ */
+export function useFileRunEventActions() {
+ const queryClient = useQueryClient();
+
+ const apply = async (eventId: string, actionId: string) => {
+ try {
+ const updated = await applyFileRunEventAction(eventId, actionId);
+ queryClient.setQueryData<FileRunEvent[]>(qk.fileRunEvents(), (rows) =>
+ (rows ?? []).map((row) => (row.id === updated.id ? updated : row)),
+ );
+ } catch {
+ await queryClient.invalidateQueries({ queryKey: qk.fileRunEvents() });
+ }
+ };
+
+ const refresh = () =>
+ queryClient.invalidateQueries({ queryKey: qk.fileRunEvents() });
+
+ return { apply, refresh };
+}
diff --git a/frontend/editor/src/portal/queries/keys.ts b/frontend/editor/src/portal/queries/keys.ts
index 18d9e1b0e7..6c29430cb4 100644
--- a/frontend/editor/src/portal/queries/keys.ts
+++ b/frontend/editor/src/portal/queries/keys.ts
@@ -16,6 +16,7 @@ export const qk = {
pipelines: () => ["portal", "pipelines"] as const,
fleetStats: () => ["portal", "fleetStats"] as const,
appConfig: () => ["portal", "appConfig"] as const,
+ fileRunEvents: () => ["portal", "fileRunEvents"] as const,
// Keyed on linkage: an unlinked account has no deal to read, so linking must not
// serve the unlinked (null) snapshot back from cache.
procurement: (linked: boolean) => ["portal", "procurement", linked] as const,
diff --git a/frontend/editor/src/portal/views/Documents.tsx b/frontend/editor/src/portal/views/Documents.tsx
index 8854d4db7f..74bc26d320 100644
--- a/frontend/editor/src/portal/views/Documents.tsx
+++ b/frontend/editor/src/portal/views/Documents.tsx
@@ -8,6 +8,8 @@ import {
type ReviewDocument,
} from "@portal/api/documents";
import { ReviewQueue } from "@portal/components/documents/ReviewQueue";
+import { FileRunEventList } from "@portal/components/failures/FileRunEventList";
+import "@portal/components/failures/failures.css";
import "@portal/views/Documents.css";
function DownloadIcon() {
@@ -104,6 +106,11 @@ export function Documents() {
</header>
<ReviewQueue documents={documents} loading={state.loading} />
+
+ {/* Recorded policy-run failures. Not mounted outside dev: the endpoints are live and
+ gated, but the surface itself is unfinished (no polling, no paging, no filters).
+ Vite folds this to false in a build, so neither the view nor its fetch ships. */}
+ {import.meta.env.DEV && <FileRunEventList />}
</div>
);
}