Skip to content

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

Remove dead policies code (#7783)

James Brunton235d8fde371c
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index e3cf94b56a..fa42c83b22 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -6996,45 +6996,6 @@ dismiss = "Dismiss overlay"
enforcingTitle = "Enforcing policy..."
viewAnyway = "View file (policy still enforcing)"
-[policyOption]
-autoRedactPhi = "Auto-redact PHI"
-blockExport = "Block export"
-ccpa = "CCPA"
-contracts = "Contracts"
-documents = "Documents"
-fedramp = "FedRAMP"
-financialReports = "Financial reports"
-flagForReview = "Flag for review"
-gdpr = "GDPR"
-hipaa = "HIPAA"
-hold = "Hold"
-hrRecords = "HR records"
-indefinite = "Indefinite"
-insurance = "Insurance"
-invoices = "Invoices"
-iso27001 = "ISO 27001"
-legalFilings = "Legal filings"
-medicalPhi = "Medical / PHI"
-never = "Never"
-ninetyDays = "90 days"
-oneYear = "1 year"
-p60 = "60%"
-p70 = "70%"
-p80 = "80%"
-p90 = "90%"
-p95 = "95%"
-pciDss = "PCI DSS"
-quarantineDocument = "Quarantine document"
-routeToBucket = "Route to bucket"
-s3Bucket = "S3 bucket"
-sevenYears = "7 years"
-sharePoint = "SharePoint"
-soc2 = "SOC 2"
-taxDocuments = "Tax documents"
-thirtyDays = "30 days"
-threeYears = "3 years"
-webhook = "Webhook"
-
[portal]
comingSoon = "Coming soon"
@@ -8663,7 +8624,6 @@ defaultName = "{{category}} Pipeline"
[portal.policies.card]
comingSoon = "Upgrade to Enterprise"
-notSetUp = "Not set up"
requiresAiEngine = "Requires AI engine"
[portal.policies.categories.classification]
@@ -8791,7 +8751,6 @@ onEveryUpload = "On every upload"
outputAsNewFile = "as a new file"
outputAsNewVersion = "as a new version"
recentActivity = "Recent activity"
-retry = "Retry"
showLess = "Show less"
showMore = "Show more"
sources = "Sources"
@@ -8802,7 +8761,6 @@ delete = "Delete"
editSettings = "Edit settings"
pause = "Pause"
resume = "Resume"
-runNow = "Run now"
[portal.policies.detail.clearHistory]
body = "This pipeline will forget every file it has already processed and reprocess everything currently in its sources on the next run. The files themselves are not changed. This cannot be undone."
@@ -9027,29 +8985,6 @@ docsEnforced = "Docs processed"
active = "Active"
paused = "Paused"
-[portal.policies.summary.active]
-description = "Enforcing on upload/export"
-label = "Active policies"
-
-[portal.policies.summary.categories]
-description = "Available to configure"
-label = "Categories"
-
-[portal.policies.summary.docsEnforced]
-description = "Across active policies"
-label = "Docs enforced"
-
-[portal.policies.summary.paused]
-description = "Configured but not firing"
-label = "Paused"
-
-[portal.policies.table]
-appliesTo = "Applies to"
-docs = "Docs enforced"
-enforces = "Enforces"
-policy = "Policy"
-status = "Status"
-
[portal.policies.wizard.actions]
cancel = "Cancel"
customise = "Customise"
@@ -9103,9 +9038,6 @@ setUp = "Set up {{category}} pipeline"
[portal.policies.wizard.workflow]
description = "Choose what this pipeline does to every document it processes."
-[portal.policySummary.action]
-setUp = "Set up"
-
[portal.processorFlow]
footnote = "Counts are over the last 24 hours. Flow speed is illustrative."
liveBadge = "Live"
diff --git a/frontend/editor/src/core/i18n/translationAudit.ts b/frontend/editor/src/core/i18n/translationAudit.ts
index 8545df99e0..e7ac246d2f 100644
--- a/frontend/editor/src/core/i18n/translationAudit.ts
+++ b/frontend/editor/src/core/i18n/translationAudit.ts
@@ -109,12 +109,6 @@ export const I18N_PROJECTS: TranslationProject[] = [
// "portal.policies.operations" - the shape heuristic treats that interpolation as one
// segment, so this whole catalogue-driven family is matched here instead.
/^portal\.policies\.operations\./,
- // Policy field labels + option display copy are looked up with keys
- // derived from catalogue data (t(`policies.field.${key}`),
- // t(`policyOption.${id}`)) in the PolicyFieldRows and setup wizards —
- // invisible to the static scan. The raw catalogue value is the fallback.
- /^policies\.field\./,
- /^policyOption\./,
// A failure's disabled reason arrives from the server as a key and is rendered with
// t(thatKey), so nothing in source names it, but the copy still has to exist.
/^portal\.failures\.disabled\./,
diff --git a/frontend/editor/src/core/ui/Modal.tsx b/frontend/editor/src/core/ui/Modal.tsx
index f782fe55ff..3c31acc6be 100644
--- a/frontend/editor/src/core/ui/Modal.tsx
+++ b/frontend/editor/src/core/ui/Modal.tsx
@@ -1,7 +1,8 @@
-import { useEffect, useId, type ReactNode } from "react";
+import { useEffect, useId, useRef, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { FocusTrap } from "@mantine/core";
import { Button } from "@app/ui/Button";
+import { useIsOverflowing } from "@app/hooks/useIsOverflowing";
import "@app/ui/Modal.css";
export type ModalWidth = "sm" | "md" | "lg" | "xl";
@@ -43,6 +44,11 @@ export function Modal({
children,
}: ModalProps) {
const titleId = useId();
+ const bodyRef = useRef<HTMLDivElement>(null);
+ // A body that overflows must be reachable by keyboard to scroll; only its non-focusable
+ // content (header close + footer live outside it). tabindex lands only when it scrolls, so
+ // fitting modals gain no stray tab stop (axe scrollable-region-focusable).
+ const bodyScrolls = useIsOverflowing(bodyRef);
useEffect(() => {
if (!open || disableEscapeClose) return;
@@ -152,7 +158,13 @@ export function Modal({
/>
</header>
)}
- <div className="sui-modal__body">{children}</div>
+ <div
+ ref={bodyRef}
+ className="sui-modal__body"
+ tabIndex={bodyScrolls ? 0 : undefined}
+ >
+ {children}
+ </div>
{footer && <footer className="sui-modal__footer">{footer}</footer>}
</div>
</FocusTrap>
diff --git a/frontend/editor/src/portal/api/pipelines.ts b/frontend/editor/src/portal/api/pipelines.ts
index 2b18798d45..69dcb0d3fe 100644
--- a/frontend/editor/src/portal/api/pipelines.ts
+++ b/frontend/editor/src/portal/api/pipelines.ts
@@ -3,6 +3,11 @@ import {
type SupportingFileBindings,
type ToolApiStep,
} from "@app/hooks/tools/shared/toolAutomation";
+import type {
+ PolicyRunView,
+ PolicyRunStatus,
+ RunOutputFile,
+} from "@app/policies/types";
/**
* Pipelines service layer: the backend contract.
@@ -132,37 +137,10 @@ export interface TriggerInfo {
supportedSourceTypes: string[];
}
-export type PolicyRunStatus =
- | "PENDING"
- | "RUNNING"
- | "WAITING_FOR_INPUT"
- | "COMPLETED"
- | "FAILED"
- | "CANCELLED";
-
-/** One file a run produced, downloadable via /api/v1/general/files/{fileId}. */
-export interface RunOutputFile {
- fileId: string;
- fileName: string | null;
-}
-
-/** A run's current state. Mirrors the backend `PolicyRunView`. */
-export interface PolicyRunView {
- runId: string;
- policyId: string | null;
- status: PolicyRunStatus;
- currentStep: number;
- stepCount: number;
- /** Human-readable failure message; set when status is FAILED. */
- error: string | null;
- errorCode: string | null;
- /**
- * Files the run produced, present once it completes. Whole-run, not per step: the backend keeps
- * one flat list, so nothing here can be attributed to an individual step.
- */
- outputs?: RunOutputFile[] | null;
- createdAt: number;
-}
+// One run view for the whole app: the builder test-run poll and the catalogue runs list read the
+// same backend PolicyRunView, so the type is defined once in the codec (imported above) and
+// re-exported here for callers that reach it through the pipelines API.
+export type { PolicyRunView, PolicyRunStatus, RunOutputFile };
/** GET /api/v1/policies/overview: KPI strip + one row per policy for the admin. */
export async function fetchPipelines(): Promise<PipelinesOverviewResponse> {
diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.ts
index 90bfffea8c..f622f34a07 100644
--- a/frontend/editor/src/portal/api/policies.ts
+++ b/frontend/editor/src/portal/api/policies.ts
@@ -29,15 +29,7 @@ import type {
WirePolicy,
} from "@app/policies/types";
-export type {
- PolicyActivityItem,
- PolicyDecodedState,
- PolicyRunView,
- PolicyStats,
- WireOutputOptions,
- WireOutputSpec,
- WirePolicy,
-} from "@app/policies/types";
+export type { PolicyRunView, WirePolicy } from "@app/policies/types";
// Re-export the wire step type under the legacy name components depend on.
export type { WirePipelineStep as PipelineStep } from "@app/policies/types";
@@ -46,9 +38,7 @@ export type { WirePipelineStep as PipelineStep } from "@app/policies/types";
/* Catalogue model — portal-specific */
/* ──────────────────────────────────────────────────────────────────────── */
-export type PolicyStatus = "active" | "paused";
-
-export type PolicyRowStatus = "active" | "paused" | "setup";
+type PolicyStatus = "active" | "paused";
export type PolicyFieldType = "toggle" | "select" | "chips" | "text";
@@ -130,15 +120,7 @@ export interface DecoratedPolicy {
activity: import("@app/policies/types").PolicyActivityItem[];
}
-export interface PoliciesSummary {
- active: number;
- paused: number;
- categories: number;
- docsEnforced: number;
-}
-
export interface PoliciesResponse {
- summary: PoliciesSummary;
catalogue: CatalogueEntry[];
}
@@ -156,7 +138,7 @@ export interface CatalogueEntry {
* i18n keys keyed by endpoint; labels stored steps in the detail view. Mostly
* {@link ToolEndpoint}s, plus the AI classify endpoint, which isn't part of the generated union.
*/
-export const ENDPOINT_LABELS: Partial<
+const ENDPOINT_LABELS: Partial<
Record<ToolEndpoint | "/api/v1/ai/tools/classify-and-label", string>
> = {
"/api/v1/security/auto-redact": "portal.policies.endpoints.autoRedact",
@@ -423,17 +405,6 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
},
};
-export const POLICY_DOC_TYPES: string[] = [
- "contracts",
- "invoices",
- "taxDocuments",
- "hrRecords",
- "insurance",
- "medicalPhi",
- "legalFilings",
- "financialReports",
-];
-
// ── Client-side catalogue assembly ───────────────────────────────────────────
function decoratePolicy(
@@ -517,25 +488,7 @@ export function assemblePolicies(
return { category, config: POLICY_CONFIG[category.id], policy };
});
- const active = wirePolicies.filter((p) => p.enabled).length;
- const paused = wirePolicies.filter((p) => !p.enabled).length;
- const enabledPolicyIds = new Set(
- wirePolicies.filter((p) => p.enabled).map((p) => p.id),
- );
- const docsEnforced = runs.filter(
- (r) =>
- r.status === "COMPLETED" &&
- r.policyId != null &&
- enabledPolicyIds.has(r.policyId),
- ).length;
- const summary: PoliciesSummary = {
- active,
- paused,
- categories: POLICY_CATEGORIES.length,
- docsEnforced,
- };
-
- return { summary, catalogue };
+ return { catalogue };
}
/**
@@ -613,13 +566,6 @@ export function parseSimplePolicy(
};
}
-/** GET /api/v1/policies/{id} — one stored policy's raw record. */
-export async function fetchPolicy(id: string): Promise<WirePolicy> {
- return apiClient.local.json<WirePolicy>(
- `/api/v1/policies/${encodeURIComponent(id)}`,
- );
-}
-
/**
* POST /api/v1/policies — create (blank id) or update (matched id). The
* backend stamps owner + teamId server-side and returns the stored record.
diff --git a/frontend/editor/src/portal/components/policies/CatalogueSummary.stories.tsx b/frontend/editor/src/portal/components/policies/CatalogueSummary.stories.tsx
deleted file mode 100644
index 75acb1cd2d..0000000000
--- a/frontend/editor/src/portal/components/policies/CatalogueSummary.stories.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import type { PoliciesResponse } from "@portal/api/policies";
-import { CatalogueSummary } from "@portal/components/policies/CatalogueSummary";
-
-const RESPONSE: PoliciesResponse = {
- summary: { active: 1, paused: 0, categories: 5, docsEnforced: 4821 },
- catalogue: [],
-};
-
-const meta: Meta<typeof CatalogueSummary> = {
- title: "Portal/Policies/CatalogueSummary",
- component: CatalogueSummary,
- parameters: { layout: "padded" },
- args: { data: RESPONSE, loading: false },
-};
-export default meta;
-type Story = StoryObj<typeof CatalogueSummary>;
-
-export const Default: Story = {};
-
-/** No data yet — every tile shows the em-dash placeholder. */
-export const Loading: Story = { args: { data: null, loading: true } };
diff --git a/frontend/editor/src/portal/components/policies/CatalogueSummary.tsx b/frontend/editor/src/portal/components/policies/CatalogueSummary.tsx
deleted file mode 100644
index c7e2fd4f26..0000000000
--- a/frontend/editor/src/portal/components/policies/CatalogueSummary.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { MetricCard, MetricStrip } from "@app/ui";
-import { PoliciesIcon } from "@portal/components/icons";
-import type { PoliciesResponse } from "@portal/api/policies";
-
-interface CatalogueSummaryProps {
- data: PoliciesResponse | null;
- loading: boolean;
-}
-
-/**
- * Summary strip above the catalogue. Labels are product copy (they describe
- * what each metric is, not its value) so the strip's structure stays stable
- * across loading / ready states; only the values flow from the API.
- */
-export function CatalogueSummary({ data, loading }: CatalogueSummaryProps) {
- const { t } = useTranslation();
- const s = loading ? undefined : data?.summary;
- return (
- <MetricStrip layout="row" leading={<PoliciesIcon size={22} />}>
- <MetricCard
- label={t("portal.policies.summary.active.label")}
- value={s ? s.active : "—"}
- description={t("portal.policies.summary.active.description")}
- />
- <MetricCard
- label={t("portal.policies.summary.paused.label")}
- value={s ? s.paused : "—"}
- description={t("portal.policies.summary.paused.description")}
- />
- <MetricCard
- label={t("portal.policies.summary.categories.label")}
- value={s ? s.categories : "—"}
- description={t("portal.policies.summary.categories.description")}
- />
- <MetricCard
- label={t("portal.policies.summary.docsEnforced.label")}
- value={s ? s.docsEnforced.toLocaleString() : "—"}
- description={t("portal.policies.summary.docsEnforced.description")}
- />
- </MetricStrip>
- );
-}
diff --git a/frontend/editor/src/portal/components/policies/PolicyCatalogueTable.tsx b/frontend/editor/src/portal/components/policies/PolicyCatalogueTable.tsx
deleted file mode 100644
index ae564ab1eb..0000000000
--- a/frontend/editor/src/portal/components/policies/PolicyCatalogueTable.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import { useMemo } from "react";
-import { useTranslation } from "react-i18next";
-import { column, DataTable, type DataTableColumn } from "@app/ui";
-import type { CatalogueEntry } from "@portal/api/policies";
-import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
-
-interface PolicyCatalogueTableProps {
- entries: CatalogueEntry[];
- onOpen: (entry: CatalogueEntry) => void;
- /** Setup is unavailable (e.g. the AI engine is off): shown, but not openable. */
- isLocked?: (entry: CatalogueEntry) => boolean;
- /** Chip text explaining why setup is locked (e.g. "Requires AI engine"). */
- lockedLabel?: string;
-}
-
-/**
- * The policy catalogue as a data table (Policy / Enforces / Applies to / Docs /
- * Status). The status column resolves per row to a state badge, an info chip
- * (coming soon / requires AI), or a "Set up" call to action.
- */
-export function PolicyCatalogueTable({
- entries,
- onOpen,
- isLocked,
- lockedLabel,
-}: PolicyCatalogueTableProps) {
- const { t } = useTranslation();
-
- const columns = useMemo<DataTableColumn<CatalogueEntry>[]>(
- () => [
- column.entity({
- key: "policy",
- header: t("portal.policies.table.policy", "Policy"),
- sortable: true,
- icon: (entry) => policyCategoryIcon(entry.category.id),
- primary: (entry) => t(entry.category.label),
- }),
- column.text({
- key: "enforces",
- header: t("portal.policies.table.enforces", "Enforces"),
- get: (entry) => entry.config.rules.map((r) => t(r)).join(", "),
- }),
- column.muted({
- key: "scope",
- header: t("portal.policies.table.appliesTo", "Applies to"),
- sortable: true,
- get: (entry) => t(entry.config.scopeLabel),
- }),
- column.number({
- key: "docs",
- header: t("portal.policies.table.docs", "Docs enforced"),
- sortable: true,
- get: (entry) => (entry.policy ? entry.policy.stats.enforced : null),
- format: (n) => n.toLocaleString(),
- }),
- column.badge({
- key: "status",
- header: t("portal.policies.table.status", "Status"),
- sortable: true,
- // Every state reads as one badge; the "set up" affordance is the row
- // itself (click + chevron), so there's no bespoke button in the cell.
- get: (entry) => {
- if (entry.category.comingSoon) {
- return {
- tone: "neutral",
- label: t("portal.policies.card.comingSoon"),
- };
- }
- if (isLocked?.(entry)) {
- return {
- tone: "neutral",
- label: lockedLabel ?? t("portal.policies.card.requiresAiEngine"),
- };
- }
- if (entry.policy) {
- const paused = entry.policy.state.status === "paused";
- return {
- tone: paused ? "warning" : "success",
- label: paused
- ? t("portal.policies.status.paused")
- : t("portal.policies.status.active"),
- };
- }
- return {
- tone: "neutral",
- label: t("portal.policySummary.action.setUp"),
- };
- },
- }),
- ],
- [t, onOpen, isLocked, lockedLabel],
- );
-
- return (
- <DataTable<CatalogueEntry>
- columns={columns}
- rows={entries}
- rowKey={(e) => e.category.id}
- onRowClick={onOpen}
- isRowInteractive={(e) =>
- !(e.category.comingSoon || (isLocked?.(e) ?? false))
- }
- rowAffordance="chevron"
- />
- );
-}
diff --git a/frontend/editor/src/portal/components/policies/PolicyCategoryCard.stories.tsx b/frontend/editor/src/portal/components/policies/PolicyCategoryCard.stories.tsx
deleted file mode 100644
index 139a88daaf..0000000000
--- a/frontend/editor/src/portal/components/policies/PolicyCategoryCard.stories.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import {
- POLICY_CATEGORIES,
- POLICY_CONFIG,
- decorateForStory,
-} from "@portal/components/policies/storyFixtures";
-import { PolicyCategoryCard } from "@portal/components/policies/PolicyCategoryCard";
-
-const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;
-const compliance = POLICY_CATEGORIES.find((c) => c.id === "compliance")!;
-
-const meta: Meta<typeof PolicyCategoryCard> = {
- title: "Portal/Policies/PolicyCategoryCard",
- component: PolicyCategoryCard,
- parameters: { layout: "padded" },
- args: { onOpen: () => {} },
-};
-export default meta;
-type Story = StoryObj<typeof PolicyCategoryCard>;
-
-/** A configured, active policy — shows live stats. */
-export const Configured: Story = {
- args: {
- entry: {
- category: security,
- config: POLICY_CONFIG.security,
- policy: decorateForStory("security"),
- },
- },
-};
-
-/** Not yet set up — shows the rule chips + "Set up" affordance. */
-export const NotSetUp: Story = {
- args: {
- entry: { category: security, config: POLICY_CONFIG.security, policy: null },
- },
-};
-
-/** Coming-soon category — locked and inert. */
-export const ComingSoon: Story = {
- args: {
- entry: {
- category: compliance,
- config: POLICY_CONFIG.compliance,
- policy: null,
- },
- },
-};
diff --git a/frontend/editor/src/portal/components/policies/PolicyCategoryCard.tsx b/frontend/editor/src/portal/components/policies/PolicyCategoryCard.tsx
deleted file mode 100644
index 58fee82d83..0000000000
--- a/frontend/editor/src/portal/components/policies/PolicyCategoryCard.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { Card, Chip, StatusBadge } from "@app/ui";
-import type { CatalogueEntry } from "@portal/api/policies";
-import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
-import "@portal/views/Policies.css";
-
-interface PolicyCategoryCardProps {
- entry: CatalogueEntry;
- onOpen: (entry: CatalogueEntry) => void;
- /** Setup is unavailable (e.g. the AI engine is off): shown, but not openable. */
- locked?: boolean;
- /** Chip text explaining why setup is locked (e.g. "Requires AI engine"). */
- lockedLabel?: string;
-}
-
-export function PolicyCategoryCard({
- entry,
- onOpen,
- locked = false,
- lockedLabel,
-}: PolicyCategoryCardProps) {
- const { t } = useTranslation();
- const { category, config, policy } = entry;
- const comingSoon = category.comingSoon === true;
- const openable = !comingSoon && !locked;
- const status = policy?.state.status;
- const enforces = config.rules.map((r) => t(r)).join(" · ");
-
- return (
- <Card
- className={
- "portal-policies__card" +
- (comingSoon || locked ? " portal-policies__card--locked" : "")
- }
- interactive={openable}
- onClick={openable ? () => onOpen(entry) : undefined}
- role={openable ? "button" : undefined}
- tabIndex={openable ? 0 : undefined}
- onKeyDown={
- openable
- ? (e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- onOpen(entry);
- }
- }
- : undefined
- }
- >
- <span className="portal-policies__cat-icon" aria-hidden>
- {policyCategoryIcon(category.id)}
- </span>
-
- <div className="portal-policies__card-identity">
- <h2 className="portal-policies__card-title">{t(category.label)}</h2>
- {enforces && (
- <span className="portal-policies__card-enforces">{enforces}</span>
- )}
- </div>
-
- {comingSoon ? (
- <Chip accent="neutral" size="sm">
- {t("portal.policies.card.comingSoon")}
- </Chip>
- ) : locked ? (
- <Chip accent="neutral" size="sm">
- {lockedLabel ?? t("portal.policies.card.requiresAiEngine")}
- </Chip>
- ) : policy ? (
- <div className="portal-policies__card-meta">
- <span className="portal-policies__card-statpair">
- <span className="portal-policies__card-statval">
- {policy.stats.enforced.toLocaleString()}
- </span>
- <span className="portal-policies__card-statlbl">
- {t("portal.policies.stats.docsEnforced")}
- </span>
- </span>
- <span className="portal-policies__card-statpair">
- <span className="portal-policies__card-statval">
- {policy.stats.dataProcessed}
- </span>
- <span className="portal-policies__card-statlbl">
- {t("portal.policies.stats.dataProcessed")}
- </span>
- </span>
- <StatusBadge
- tone={status === "paused" ? "warning" : "success"}
- size="sm"
- >
- {status === "paused"
- ? t("portal.policies.status.paused")
- : t("portal.policies.status.active")}
- </StatusBadge>
- </div>
- ) : (
- <Chip accent="default" size="sm">
- {t("portal.policies.card.notSetUp")}
- </Chip>
- )}
- </Card>
- );
-}
diff --git a/frontend/editor/src/portal/components/policies/PolicyDetailPanel.stories.tsx b/frontend/editor/src/portal/components/policies/PolicyDetailPanel.stories.tsx
index 541ea558b0..703c050f31 100644
--- a/frontend/editor/src/portal/components/policies/PolicyDetailPanel.stories.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicyDetailPanel.stories.tsx
@@ -9,10 +9,8 @@ const meta: Meta<typeof PolicyDetailPanel> = {
args: {
onClose: () => {},
onEdit: () => {},
- onRun: () => {},
onTogglePause: () => {},
onDelete: () => {},
- onRetry: () => {},
},
};
export default meta;
diff --git a/frontend/editor/src/portal/components/policies/PolicyDetailPanel.tsx b/frontend/editor/src/portal/components/policies/PolicyDetailPanel.tsx
index 961b6b789d..5e7576f1d6 100644
--- a/frontend/editor/src/portal/components/policies/PolicyDetailPanel.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicyDetailPanel.tsx
@@ -8,11 +8,7 @@ import {
StatTile,
StatusBadge,
} from "@app/ui";
-import {
- humanizeEndpoint,
- type DecoratedPolicy,
- type PolicyActivityItem,
-} from "@portal/api/policies";
+import { humanizeEndpoint, type DecoratedPolicy } from "@portal/api/policies";
import "@portal/views/Policies.css";
interface PolicyDetailPanelProps {
@@ -20,11 +16,9 @@ interface PolicyDetailPanelProps {
busy?: boolean;
onClose: () => void;
onEdit: () => void;
- onRun?: () => void;
onTogglePause: () => void;
onDelete: () => void;
onClearHistory?: () => void;
- onRetry?: (item: PolicyActivityItem) => void;
}
function CheckIcon() {
@@ -104,11 +98,9 @@ export function PolicyDetailPanel({
busy = false,
onClose,
onEdit,
- onRun,
onTogglePause,
onDelete,
onClearHistory,
- onRetry,
}: PolicyDetailPanelProps) {
const { t } = useTranslation();
const [confirmingClear, setConfirmingClear] = useState(false);
@@ -155,17 +147,6 @@ export function PolicyDetailPanel({
{t("portal.policies.detail.actions.delete")}
</Button>
)}
- {onRun && (
- <Button
- variant="secondary"
- size="sm"
- onClick={onRun}
- disabled={busy}
- style={canDelete ? undefined : { marginRight: "auto" }}
- >
- {t("portal.policies.detail.actions.runNow")}
- </Button>
- )}
{canClearHistory && (
<Button
variant="secondary"
@@ -295,16 +276,6 @@ export function PolicyDetailPanel({
<span className="portal-policies__activity-time">
{item.time}
</span>
- {item.status === "flagged" && onRetry && (
- <Button
- type="button"
- variant="quiet"
- className="portal-policies__link portal-policies__activity-retry"
- onClick={() => onRetry(item)}
- >
- {t("portal.policies.detail.retry")}
- </Button>
- )}
</div>
))}
</Card>
diff --git a/frontend/editor/src/portal/components/policies/PolicyFieldRow.stories.tsx b/frontend/editor/src/portal/components/policies/PolicyFieldRow.stories.tsx
deleted file mode 100644
index e6a8a4bb4d..0000000000
--- a/frontend/editor/src/portal/components/policies/PolicyFieldRow.stories.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import { useState } from "react";
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import type { PolicyField } from "@portal/api/policies";
-import { PolicyFieldRow } from "@portal/components/policies/PolicyFieldRow";
-
-const meta: Meta<typeof PolicyFieldRow> = {
- title: "Portal/Policies/PolicyFieldRow",
- component: PolicyFieldRow,
- parameters: { layout: "padded" },
-};
-export default meta;
-type Story = StoryObj<typeof PolicyFieldRow>;
-
-/** Renders the field and keeps its value in local state, exercising onChange. */
-function Controlled({ field }: { field: PolicyField }) {
- const [value, setValue] = useState(field.value);
- return <PolicyFieldRow field={field} value={value} onChange={setValue} />;
-}
-
-export const Toggle: Story = {
- render: () => (
- <Controlled
- field={{
- key: "auditTrail",
- label: "Audit trail",
- type: "toggle",
- value: true,
- }}
- />
- ),
-};
-
-export const Select: Story = {
- render: () => (
- <Controlled
- field={{
- key: "keepFor",
- label: "Keep for",
- type: "select",
- value: "7 years",
- options: ["30 days", "1 year", "7 years", "Indefinite"],
- }}
- />
- ),
-};
-
-export const Chips: Story = {
- render: () => (
- <Controlled
- field={{
- key: "frameworks",
- label: "Frameworks",
- type: "chips",
- value: ["HIPAA"],
- options: ["HIPAA", "GDPR", "SOC 2", "FedRAMP"],
- }}
- />
- ),
-};
-
-export const Text: Story = {
- render: () => (
- <Controlled
- field={{
- key: "webhookUrl",
- label: "Webhook URL",
- type: "text",
- value: "",
- }}
- />
- ),
-};
diff --git a/frontend/editor/src/portal/components/policies/PolicyFieldRow.tsx b/frontend/editor/src/portal/components/policies/PolicyFieldRow.tsx
deleted file mode 100644
index b3c0b2c622..0000000000
--- a/frontend/editor/src/portal/components/policies/PolicyFieldRow.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { Chip, FormField, Input, Select, ToggleSwitch } from "@app/ui";
-import type { PolicyField } from "@portal/api/policies";
-import "@portal/views/Policies.css";
-
-interface PolicyFieldRowProps {
- field: PolicyField;
- /** Effective current value (override or definition default). */
- value: boolean | string | string[];
- onChange: (value: boolean | string | string[]) => void;
-}
-
-/**
- * Renders one policy setting from the catalogue's `PolicyField`, dispatching on
- * `type`: toggle → ToggleSwitch, select → Select, chips → multi-select Chips,
- * text → Input. Controlled — the setup flow owns the value.
- */
-export function PolicyFieldRow({
- field,
- value,
- onChange,
-}: PolicyFieldRowProps) {
- const { t } = useTranslation();
- if (field.type === "toggle") {
- return (
- <div className="portal-policies__toggle-row">
- <ToggleSwitch
- checked={Boolean(value)}
- onChange={onChange}
- label={t(field.label)}
- />
- </div>
- );
- }
-
- if (field.type === "chips") {
- const selected = Array.isArray(value) ? value : [];
- const toggle = (opt: string) =>
- onChange(
- selected.includes(opt)
- ? selected.filter((o) => o !== opt)
- : [...selected, opt],
- );
- return (
- <FormField label={t(field.label)}>
- <div className="portal-policies__field-chips">
- {(field.options ?? []).map((opt) => (
- <Chip
- key={opt}
- accent={selected.includes(opt) ? "default" : "neutral"}
- size="sm"
- onClick={() => toggle(opt)}
- >
- {t(`policyOption.${opt}`, opt)}
- </Chip>
- ))}
- </div>
- </FormField>
- );
- }
-
- if (field.type === "select") {
- return (
- <FormField label={t(field.label)}>
- <Select
- inputSize="sm"
- value={typeof value === "string" ? value : ""}
- options={(field.options ?? []).map((o) => ({
- value: o,
- label: t(`policyOption.${o}`, o),
- }))}
- onChange={(value) => onChange(value ?? "")}
- />
- </FormField>
- );
- }
-
- return (
- <FormField label={t(field.label)}>
- <Input
- inputSize="sm"
- value={typeof value === "string" ? value : ""}
- onChange={(e) => onChange(e.target.value)}
- />
- </FormField>
- );
-}
diff --git a/frontend/editor/src/portal/components/policies/PolicyPurviewReadConfig.stories.tsx b/frontend/editor/src/portal/components/policies/PolicyPurviewReadConfig.stories.tsx
deleted file mode 100644
index 434fb5f7cb..0000000000
--- a/frontend/editor/src/portal/components/policies/PolicyPurviewReadConfig.stories.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { useState } from "react";
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import {
- PolicyPurviewReadConfig,
- type PurviewReadParams,
-} from "@portal/components/policies/PolicyPurviewReadConfig";
-
-const meta: Meta<typeof PolicyPurviewReadConfig> = {
- title: "Portal/Policies/PolicyPurviewReadConfig",
- component: PolicyPurviewReadConfig,
- parameters: { layout: "padded" },
- args: {
- parameters: { connectionId: "" },
- onChange: () => {},
- },
-};
-export default meta;
-type Story = StoryObj<typeof PolicyPurviewReadConfig>;
-
-/** Renders the config and keeps its parameters in local state, exercising onChange. */
-function Controlled({ parameters }: { parameters: PurviewReadParams }) {
- const [value, setValue] = useState(parameters);
- return <PolicyPurviewReadConfig parameters={value} onChange={setValue} />;
-}
-
-export const Empty: Story = {
- render: () => <Controlled parameters={{ connectionId: "" }} />,
-};
-
-export const ConnectionSelected: Story = {
- render: () => <Controlled parameters={{ connectionId: "2" }} />,
-};
diff --git a/frontend/editor/src/portal/components/policies/PolicyPurviewReadConfig.tsx b/frontend/editor/src/portal/components/policies/PolicyPurviewReadConfig.tsx
deleted file mode 100644
index 1b5c9ec7bc..0000000000
--- a/frontend/editor/src/portal/components/policies/PolicyPurviewReadConfig.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { FormField } from "@app/ui";
-import { ConnectionPicker } from "@portal/components/sources/ConnectionPicker";
-
-/**
- * Configures the "read a Purview label" step: which tenant to read against.
- *
- * This is the join-don't-beat primitive. Purview classifies documents; this reads the label it
- * applied so the rest of the policy can act on it - redact, watermark, route - which is the
- * PDF-specific work Purview does not do. Only the tenant matters here; the report the step emits
- * carries whatever label the document already holds.
- */
-export interface PurviewReadParams {
- connectionId: string;
-}
-
-interface PolicyPurviewReadConfigProps {
- parameters: PurviewReadParams;
- onChange: (parameters: PurviewReadParams) => void;
-}
-
-export function PolicyPurviewReadConfig({
- parameters,
- onChange,
-}: PolicyPurviewReadConfigProps) {
- const { t } = useTranslation();
- return (
- <div className="portal-policies__capability-config">
- <FormField
- label={t("portal.policies.config.purviewRead.fields.connection")}
- helperText={t(
- "portal.policies.config.purviewRead.fields.connectionHelp",
- )}
- required
- >
- <ConnectionPicker
- value={parameters.connectionId ?? ""}
- onChange={(id) => onChange({ ...parameters, connectionId: id })}
- integrationType="PURVIEW"
- createTypeId="purview"
- />
- </FormField>
- </div>
- );
-}
diff --git a/frontend/editor/src/portal/components/policies/stepOperations.test.ts b/frontend/editor/src/portal/components/policies/stepOperations.test.ts
index beedf4b1bb..9bf4866649 100644
--- a/frontend/editor/src/portal/components/policies/stepOperations.test.ts
+++ b/frontend/editor/src/portal/components/policies/stepOperations.test.ts
@@ -5,7 +5,6 @@ import {
buildStepParameters,
emptyOperationValues,
operationById,
- operationFormValid,
searchOperations,
} from "@portal/components/policies/stepOperations";
import { CREATABLE_CONNECTION_TYPES } from "@portal/components/sources/connectionTypes";
@@ -115,18 +114,10 @@ describe("buildStepParameters", () => {
});
describe("operation form", () => {
- it("seeds defaults and enforces required fields", () => {
+ it("seeds field defaults", () => {
const elastic = operationById("elasticIndex")!;
const seeded = emptyOperationValues(elastic);
-
expect(seeded.index).toBe("stirling-audit");
- expect(operationFormValid(elastic, seeded)).toBe(true);
- expect(operationFormValid(elastic, { index: " " })).toBe(false);
- });
-
- it("an operation with no fields is immediately valid", () => {
- const cloudmersive = operationById("cloudmersiveScan")!;
- expect(operationFormValid(cloudmersive, {})).toBe(true);
});
});
diff --git a/frontend/editor/src/portal/components/policies/stepOperations.ts b/frontend/editor/src/portal/components/policies/stepOperations.ts
index c1b7beb8c8..8ebb6ae5b8 100644
--- a/frontend/editor/src/portal/components/policies/stepOperations.ts
+++ b/frontend/editor/src/portal/components/policies/stepOperations.ts
@@ -747,15 +747,6 @@ export function emptyOperationValues(
return values;
}
-export function operationFormValid(
- op: StepOperation,
- values: Record<string, string>,
-): boolean {
- return (op.fields ?? []).every(
- (field) => !field.required || (values[field.key] ?? "").trim() !== "",
- );
-}
-
/**
* Turn a chosen operation plus the operator's answers into the parameters the
* `external-api-call` step takes.
diff --git a/frontend/editor/src/portal/mocks/handlers/policies.ts b/frontend/editor/src/portal/mocks/handlers/policies.ts
index 93ee64a07d..091f16761a 100644
--- a/frontend/editor/src/portal/mocks/handlers/policies.ts
+++ b/frontend/editor/src/portal/mocks/handlers/policies.ts
@@ -20,14 +20,6 @@ import type { PolicyRunView, WirePolicy } from "@app/policies/types";
let store: WirePolicy[] = seedPolicies();
let runs: PolicyRunView[] = seedPolicyRuns();
-export function resetPoliciesStore(
- seed?: WirePolicy[],
- seedRuns?: PolicyRunView[],
-): void {
- store = seed ? [...seed] : seedPolicies();
- runs = seedRuns ? [...seedRuns] : seedPolicyRuns();
-}
-
/**
* The catalogue (suggested-policy) records, for the unified Pipelines overview to merge in - the
* real backend keeps a single store, so its overview already sees these; the mock's two stores must
diff --git a/frontend/editor/src/portal/views/Policies.css b/frontend/editor/src/portal/views/Policies.css
index b62976fbe9..eab898c1b3 100644
--- a/frontend/editor/src/portal/views/Policies.css
+++ b/frontend/editor/src/portal/views/Policies.css
@@ -1,197 +1,3 @@
-.portal-policies {
- display: flex;
- flex-direction: column;
- gap: 1.25rem;
- padding: 1.5rem;
- max-width: 84rem;
- margin: 0 auto;
-}
-
-/* Header */
-.portal-policies__head {
- display: flex;
- flex-direction: column;
- gap: 0.25rem;
-}
-
-.portal-policies__title {
- margin: 0;
- font-size: 1.375rem;
- font-weight: 650;
- color: var(--c-text);
-}
-
-.portal-policies__sub {
- margin: 0;
- font-size: 0.8125rem;
- line-height: 1.5;
- color: var(--c-text-subtle);
- max-width: 46rem;
-}
-
-/* Category grid */
-.portal-policies__grid {
- display: flex;
- flex-direction: column;
- gap: 0.375rem;
-}
-
-/* Category row — locked (coming soon) */
-.portal-policies__row {
- display: flex;
- align-items: center;
- gap: 0.75rem;
- padding: 0.25rem 0.75rem;
- min-height: 2.25rem;
-}
-
-.portal-policies__row-name {
- flex: 1;
- font-size: 0.9375rem;
- font-weight: 600;
- color: var(--c-text-subtle);
-}
-
-/* "Set up" underline link inside the active-row button's rightSection */
-.portal-policies__setup-link {
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--c-accent-text);
- text-decoration: underline;
- text-underline-offset: 2px;
-}
-
-/* Category card — horizontal table row */
-.portal-policies__card {
- display: flex;
- flex-direction: row;
- align-items: center;
- gap: 0.75rem;
-}
-
-.portal-policies__card--locked {
- /* Recede via surface and ink rather than opacity, which would fade the
- card's own text below the contrast floor. */
- background: var(--c-surface-sunken);
- color: var(--c-text-muted);
-}
-
-.portal-policies__card-identity {
- display: flex;
- flex-direction: column;
- gap: 0.125rem;
- flex: 1;
- min-width: 0;
-}
-
-.portal-policies__card-enforces {
- font-size: 0.75rem;
- color: var(--c-text-subtle);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.portal-policies__card-meta {
- display: flex;
- align-items: center;
- gap: 2rem;
- flex-shrink: 0;
-}
-
-.portal-policies__card-statpair {
- display: flex;
- flex-direction: column;
- align-items: flex-end;
- gap: 0.0625rem;
-}
-
-.portal-policies__card-statval {
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--c-text);
- line-height: 1.2;
-}
-
-.portal-policies__card-statlbl {
- font-size: 0.6875rem;
- color: var(--c-text-subtle);
- line-height: 1.2;
-}
-
-.portal-policies__cat-icon {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 2rem;
- height: 2rem;
- flex-shrink: 0;
- font-size: 1.125rem;
- color: var(--c-text-muted);
-}
-
-.portal-policies__card-title {
- margin: 0;
- font-size: 0.9375rem;
- font-weight: 600;
- color: var(--c-text);
-}
-
-.portal-policies__card-blurb {
- font-size: 0.75rem;
- color: var(--c-text-subtle);
- line-height: 1.4;
-}
-
-.portal-policies__card-summary {
- margin: 0;
- font-size: 0.8125rem;
- line-height: 1.5;
- color: var(--c-text-muted);
-}
-
-.portal-policies__card-foot {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 0.5rem;
- margin-top: auto;
- flex-wrap: wrap;
-}
-
-.portal-policies__card-rules {
- display: flex;
- flex-wrap: wrap;
- gap: 0.375rem;
-}
-
-.portal-policies__card-cta {
- font-size: 0.75rem;
- font-weight: 600;
- color: var(--c-accent-text);
-}
-
-.portal-policies__chevron-right {
- transform: rotate(-90deg);
- display: block;
-}
-
-/* Configured-card stat footer */
-.portal-policies__card-stats {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 0.5rem;
- margin-top: auto;
- padding-top: 0.75rem;
- border-top: 1px solid var(--c-border-subtle);
-}
-
-@media (max-width: 30rem) {
- .portal-policies__card-stats {
- grid-template-columns: 1fr;
- }
-}
-
/* Wizard + detail shared chrome */
.portal-policies__wizard-title {
display: inline-flex;
@@ -412,11 +218,6 @@
white-space: nowrap;
}
-.portal-policies__activity-retry {
- flex-shrink: 0;
- font-size: 0.75rem;
-}
-
/* Error expand/collapse for long activity messages */
.portal-policies__activity-error {
display: block;
@@ -450,37 +251,5 @@
border-left: 1px solid var(--c-border-subtle);
}
-/* ── Catalogue table (replaces the stacked category cards) ──────────────── */
-.portal-policies__cell {
- display: flex;
- align-items: center;
- gap: 0.75rem;
- min-width: 0;
-}
-
-.portal-policies__cell-name {
- font-size: 0.9375rem;
- font-weight: 600;
- color: var(--c-text);
- min-width: 0;
-}
-
-.portal-policies__rulechips {
- display: flex;
- flex-wrap: wrap;
- gap: 0.3125rem;
-}
-
-.portal-policies__muted {
- font-size: 0.8125rem;
- color: var(--c-text-subtle);
-}
-
-.portal-policies__docs {
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--c-text);
- font-variant-numeric: tabular-nums;
-}
/* The .pcat-badge icon styles live with the PolicyCategoryIcon component
(PolicyCategoryIcon.css) so the Home policy summary picks them up too. */
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx
index 189945c8d2..6c5d322a28 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx
@@ -80,7 +80,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
classification: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-classification",
runOn: "upload",
order: 0,
@@ -90,7 +90,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
security: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-security",
runOn: securityRunOn.value,
order: 1,
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx
index 89ca278e97..4b013c465d 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx
@@ -18,7 +18,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
security: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-sec",
runOn: "upload",
order: 0,
@@ -26,7 +26,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
compliance: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-comp",
runOn: "upload",
order: 1,
@@ -34,7 +34,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
classification: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-cls",
runOn: "upload",
order: 2,
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx
index 87609dc1a3..7cad7095c2 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx
@@ -38,7 +38,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
security: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-1",
runOn: "upload",
outputMode: "new_version",
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx
index 6c09acead5..26515a38f5 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx
@@ -53,7 +53,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
classification: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-classification",
runOn: "upload",
order: 0,
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.reentry.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.reentry.test.tsx
index 56f05ab279..bfbab020fc 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.reentry.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.reentry.test.tsx
@@ -32,7 +32,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
security: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-security",
runOn: "upload",
order: 0,
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx
index d490d62476..47343abf8b 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx
@@ -14,7 +14,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
security: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-1",
runOn: "upload",
},
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.test.tsx
index 4631df9a6e..27788f5de5 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.test.tsx
@@ -56,7 +56,7 @@ vi.mock("@app/hooks/usePolicies", () => ({
classification: {
configured: true,
runsOnEditor: true,
- status: "active",
+ enabled: true,
backendId: "backend-classification",
runOn: runOn.value,
sources: ["editor"],
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts
index 20b419fc93..3c7458ee97 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts
@@ -53,7 +53,7 @@ export function usePolicyLocalPasses(): void {
for (const [categoryId, s] of Object.entries(policies)) {
const active =
s.configured &&
- s.status === "active" &&
+ s.enabled &&
s.backendId &&
s.runsOnEditor &&
(s.runOn ?? "upload") === "upload";
diff --git a/frontend/editor/src/proprietary/data/classificationPolicy.test.ts b/frontend/editor/src/proprietary/data/classificationPolicy.test.ts
index 52e152efb1..9af891c0d5 100644
--- a/frontend/editor/src/proprietary/data/classificationPolicy.test.ts
+++ b/frontend/editor/src/proprietary/data/classificationPolicy.test.ts
@@ -2,7 +2,6 @@ import { describe, it, expect } from "vitest";
import {
isClassificationCategory,
localVerdictNeedsEscalation,
- orderRewritesFirst,
orderedRewritingCategories,
policyDeliversOutputFiles,
policyRewritesDocument,
@@ -12,7 +11,7 @@ import type { PoliciesByCategory } from "@app/types/policies";
const rewriter = (order: number) =>
({
configured: true,
- status: "active",
+ enabled: true,
backendId: `backend-${order}`,
runsOnEditor: true,
runOn: "upload",
@@ -41,32 +40,6 @@ describe("policy capabilities", () => {
});
});
-describe("orderRewritesFirst", () => {
- it("moves annotating policies to the end, preserving other order", () => {
- expect(
- orderRewritesFirst(["classification", "security", "compliance"]),
- ).toEqual(["security", "compliance", "classification"]);
- });
-
- it("leaves an order without an annotating policy untouched", () => {
- expect(orderRewritesFirst(["security", "compliance"])).toEqual([
- "security",
- "compliance",
- ]);
- });
-
- it("is a no-op when the annotating policy is already last", () => {
- expect(orderRewritesFirst(["security", "classification"])).toEqual([
- "security",
- "classification",
- ]);
- });
-
- it("handles the annotating policy as the only one", () => {
- expect(orderRewritesFirst(["classification"])).toEqual(["classification"]);
- });
-});
-
describe("orderedRewritingCategories", () => {
it("lists only file-producing policies, ordered by order, excluding classification", () => {
const policies = {
@@ -84,7 +57,7 @@ describe("orderedRewritingCategories", () => {
it("excludes inactive, non-editor, export-triggered, and unconfigured policies", () => {
const mixed = {
security: rewriter(0),
- inactive: { ...rewriter(1), status: "paused" },
+ inactive: { ...rewriter(1), enabled: false },
notEditor: { ...rewriter(2), runsOnEditor: false },
onExport: { ...rewriter(3), runOn: "export" },
unconfigured: { ...rewriter(4), configured: false },
diff --git a/frontend/editor/src/proprietary/data/classificationPolicy.ts b/frontend/editor/src/proprietary/data/classificationPolicy.ts
index cf704d87d3..6befe744d7 100644
--- a/frontend/editor/src/proprietary/data/classificationPolicy.ts
+++ b/frontend/editor/src/proprietary/data/classificationPolicy.ts
@@ -44,14 +44,6 @@ export function policyRequiresAiEngine(categoryId: string): boolean {
return isClassificationCategory(categoryId);
}
-/** Order annotating policies last; everything else keeps the order it was given. */
-export function orderRewritesFirst(categoryIds: string[]): string[] {
- return [
- ...categoryIds.filter(policyRewritesDocument),
- ...categoryIds.filter((id) => !policyRewritesDocument(id)),
- ];
-}
-
/**
* The active editor upload policies the generic runner dispatches and chains, in run order. Only
* file-producing policies: an annotating policy (classification) has no output to chain onto and
@@ -65,7 +57,7 @@ export function orderedRewritingCategories(
.filter(
([id, s]) =>
s.configured &&
- s.status === "active" &&
+ s.enabled &&
Boolean(s.backendId) &&
s.runsOnEditor &&
(s.runOn ?? "upload") === "upload" &&
diff --git a/frontend/editor/src/proprietary/data/policyDefinitions.test.ts b/frontend/editor/src/proprietary/data/policyDefinitions.test.ts
deleted file mode 100644
index ee1864c45d..0000000000
--- a/frontend/editor/src/proprietary/data/policyDefinitions.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { POLICY_CATEGORIES, POLICY_CONFIG } from "@app/data/policyDefinitions";
-
-describe("policy definitions integrity", () => {
- it("every category has a matching config entry", () => {
- for (const cat of POLICY_CATEGORIES) {
- expect(POLICY_CONFIG[cat.id], `config for ${cat.id}`).toBeDefined();
- // A category may have no policy-level setting fields; fields is required
- // but can be empty.
- expect(Array.isArray(POLICY_CONFIG[cat.id].fields)).toBe(true);
- expect(POLICY_CONFIG[cat.id].rules.length).toBeGreaterThan(0);
- // Every preset seeds a real, non-empty pipeline (the category→steps map).
- expect(
- POLICY_CONFIG[cat.id].defaultOperations.length,
- `defaultOperations for ${cat.id}`,
- ).toBeGreaterThan(0);
- }
- });
- it("field keys are unique within each category", () => {
- for (const cat of POLICY_CATEGORIES) {
- const keys = POLICY_CONFIG[cat.id].fields.map((f) => f.key);
- expect(new Set(keys).size).toBe(keys.length);
- }
- });
-});
diff --git a/frontend/editor/src/proprietary/data/policyDefinitions.tsx b/frontend/editor/src/proprietary/data/policyDefinitions.tsx
index e725dff68b..cd36fc6493 100644
--- a/frontend/editor/src/proprietary/data/policyDefinitions.tsx
+++ b/frontend/editor/src/proprietary/data/policyDefinitions.tsx
@@ -1,22 +1,11 @@
/**
- * Static preset definitions for Policies — the categories, their editable
- * settings fields, scope labels, and the default tool pipeline each category
- * seeds a new policy with. Runtime activity + stats are derived live from the
- * user's real files, not defined here.
+ * Static preset definitions for Policies - the catalogue categories and the PII
+ * presets a Security policy's redact step seeds from. Runtime activity + stats
+ * are derived live from the user's real files, not defined here.
*/
-import DescriptionIcon from "@mui/icons-material/Description";
-import ComputerIcon from "@mui/icons-material/Computer";
-import PublicIcon from "@mui/icons-material/Public";
-import CloudIcon from "@mui/icons-material/Cloud";
-import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
-import FolderOpenIcon from "@mui/icons-material/FolderOpen";
import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
-import type {
- PolicyCategory,
- PolicyConfigDef,
- PolicySource,
-} from "@app/types/policies";
+import type { PolicyCategory } from "@app/types/policies";
const ICON_SX = { fontSize: "1rem" } as const;
@@ -138,228 +127,3 @@ export const DEFAULT_PII_PATTERNS: string[] = [
PII_PRESETS[0].pattern, // SSN
PII_PRESETS[1].pattern, // cards
];
-
-/** Per-category narrative + editable fields. */
-export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
- ingestion: {
- summary:
- "Classifies documents, extracts structured data, enforces naming, and normalizes pages.",
- rules: ["Classify", "Extract", "Name", "Normalize"],
- defaultOperations: [
- { operation: "ocr", parameters: {} },
- { operation: "flatten", parameters: {} },
- ],
- scopeLabel: "All PDFs on this device",
- // Policy-level controls only — the per-tool params (OCR level, extract
- // tables, naming, normalize, rotate...) live in the Workflow step.
- fields: [
- {
- label: "Min confidence",
- key: "minConfidence",
- type: "select",
- value: "p80",
- options: ["p60", "p70", "p80", "p90", "p95"],
- },
- {
- label: "Below threshold",
- key: "belowThreshold",
- type: "select",
- value: "flagForReview",
- options: ["flagForReview", "routeToBucket", "hold"],
- },
- ],
- },
- security: {
- summary:
- "Detects PII, encrypts, verifies authenticity, controls access, and certifies documents.",
- rules: ["Redact PII", "Remove JavaScript"],
- // Default chain: redact PII + remove JavaScript (via sanitize) on; watermark
- // is offered in the config page but off by default (not seeded here). Redact
- // ships with the high-risk PII regexes so it works out of the box.
- defaultOperations: [
- {
- operation: "redact",
- parameters: {
- mode: "automatic",
- useRegex: true,
- // Flatten to image so redacted text is truly removed, not just hidden
- // behind a box (heavier, but real redaction).
- convertPDFToImage: true,
- wordsToRedact: DEFAULT_PII_PATTERNS,
- },
- },
- {
- // Sanitize is fixed to JavaScript removal only (no per-policy config).
- operation: "sanitize",
- parameters: {
- removeJavaScript: true,
- removeEmbeddedFiles: false,
- removeMetadata: false,
- removeLinks: false,
- removeFonts: false,
- removeXMPMetadata: false,
- },
- },
- ],
- scopeLabel: "All PDFs on this device",
- // No policy-level setting fields: tool config lives in the Workflow step;
- // output naming + retries are set in the wizard.
- fields: [],
- },
- classification: {
- summary:
- "Classifies every uploaded document and writes the result to its metadata.",
- rules: ["Classify", "Tag metadata"],
- // Single backend step: classify the document via the AI engine and store the
- // result in the document's StirlingPDFClassification metadata field.
- defaultOperations: [{ operation: "classify", parameters: {} }],
- scopeLabel: "All PDFs on this device",
- fields: [],
- },
- compliance: {
- summary:
- "Validates documents against regulatory frameworks before they leave the system.",
- rules: ["Framework scan", "Enforce action", "Audit trail"],
- defaultOperations: [
- { operation: "sanitize", parameters: {} },
- { operation: "flatten", parameters: {} },
- ],
- scopeLabel: "All PDFs on this device",
- fields: [
- {
- label: "Frameworks",
- key: "frameworks",
- type: "chips",
- value: ["hipaa"],
- options: [
- "hipaa",
- "gdpr",
- "soc2",
- "fedramp",
- "pciDss",
- "ccpa",
- "iso27001",
- ],
- },
- {
- label: "When non-compliant",
- key: "onViolation",
- type: "select",
- value: "flagForReview",
- options: [
- "flagForReview",
- "blockExport",
- "autoRedactPhi",
- "quarantineDocument",
- ],
- },
- { label: "Audit trail", key: "auditTrail", type: "toggle", value: true },
- { label: "Access log", key: "accessLog", type: "toggle", value: true },
- ],
- },
- routing: {
- summary:
- "Routes documents to the right destination based on type and classification.",
- rules: ["Auto-classify", "Route to folder", "Webhook notify"],
- defaultOperations: [{ operation: "compress", parameters: {} }],
- scopeLabel: "All PDFs on this device",
- fields: [
- {
- label: "Destination",
- key: "destination",
- type: "select",
- value: "documents",
- options: ["documents", "s3Bucket", "sharePoint", "webhook"],
- },
- { label: "Webhook URL", key: "webhookUrl", type: "text", value: "" },
- { label: "Notify on route", key: "notify", type: "toggle", value: false },
- ],
- },
- retention: {
- summary:
- "Enforces how long documents are kept, when to archive, and when to delete.",
- rules: ["Retention hold", "Auto-archive", "Deletion block"],
- defaultOperations: [{ operation: "compress", parameters: {} }],
- scopeLabel: "All PDFs on this device",
- fields: [
- {
- label: "Keep for",
- key: "keepFor",
- type: "select",
- value: "sevenYears",
- options: [
- "thirtyDays",
- "oneYear",
- "threeYears",
- "sevenYears",
- "indefinite",
- ],
- },
- {
- label: "Archive after",
- key: "archiveAfter",
- type: "select",
- value: "never",
- options: ["thirtyDays", "ninetyDays", "oneYear", "never"],
- },
- {
- label: "Immutable hold",
- key: "immutableHold",
- type: "toggle",
- value: false,
- },
- ],
- },
-};
-
-/** Sources a policy can run over (wizard step 2). */
-export const POLICY_SOURCES: PolicySource[] = [
- {
- id: "editor",
- label: "Editor",
- desc: "Documents you save or export in Stirling",
- icon: <DescriptionIcon sx={ICON_SX} />,
- },
- {
- id: "device",
- label: "Entire device",
- desc: "All PDFs on this machine, retroactively",
- icon: <ComputerIcon sx={ICON_SX} />,
- },
- {
- id: "sharepoint",
- label: "SharePoint",
- desc: "Connected SharePoint libraries",
- icon: <PublicIcon sx={ICON_SX} />,
- },
- {
- id: "dropbox",
- label: "Dropbox",
- desc: "Connected Dropbox folders",
- icon: <CloudIcon sx={ICON_SX} />,
- },
- {
- id: "gmail",
- label: "Gmail",
- desc: "PDF attachments in email",
- icon: <EmailOutlinedIcon sx={ICON_SX} />,
- },
- {
- id: "gdrive",
- label: "Google Drive",
- desc: "Connected Drive folders",
- icon: <FolderOpenIcon sx={ICON_SX} />,
- },
-];
-
-/** Document types selectable when narrowing scope (gated behind classification). */
-export const POLICY_DOC_TYPES: string[] = [
- "contracts",
- "invoices",
- "taxDocuments",
- "hrRecords",
- "insurance",
- "medicalPhi",
- "legalFilings",
- "financialReports",
-];
diff --git a/frontend/editor/src/proprietary/hooks/usePolicies.test.ts b/frontend/editor/src/proprietary/hooks/usePolicies.test.ts
index 61d2cebc5f..1228532e91 100644
--- a/frontend/editor/src/proprietary/hooks/usePolicies.test.ts
+++ b/frontend/editor/src/proprietary/hooks/usePolicies.test.ts
@@ -2,73 +2,20 @@ import "fake-indexeddb/auto";
import { describe, it, expect, beforeEach, vi } from "vitest";
import { act, renderHook, waitFor } from "@testing-library/react";
-// Enable/delete create + remove the backing Watched Folders WatchedFolder
-// (IndexedDB); jsdom's crypto lacks randomUUID, used for folder ids.
-if (typeof globalThis.crypto?.randomUUID !== "function") {
- const orig = globalThis.crypto;
- vi.stubGlobal("crypto", {
- getRandomValues: orig?.getRandomValues?.bind(orig),
- randomUUID: () =>
- `p-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,
- });
-}
-
-// In-memory stand-in for the backend policy store, so the hook's persistence
-// path is exercised without a real server.
-const api = vi.hoisted(() => ({
- store: new Map<string, { id: string }>(),
- seq: 0,
-}));
+// In-memory stand-in for the backend policy store, so the hook's reconcile path
+// is exercised without a real server. The editor only reads policies now, so the
+// read (`listPolicies`) is all the hook touches.
+const api = vi.hoisted(() => ({ store: new Map<string, { id: string }>() }));
vi.mock("@app/services/policyApi", () => ({
listPolicies: vi.fn(async () => [...api.store.values()]),
- savePolicy: vi.fn(async (p: { id?: string }) => {
- const id = p.id && p.id.length > 0 ? p.id : `be-${++api.seq}`;
- const saved = { ...p, id };
- api.store.set(id, saved);
- return saved;
- }),
- getPolicy: vi.fn(async (id: string) => api.store.get(id)),
- deletePolicy: vi.fn(async (id: string) => {
- api.store.delete(id);
- }),
- runStoredPolicy: vi.fn(),
- runPolicyPipeline: vi.fn(),
- getPolicyRun: vi.fn(),
}));
import { usePolicies } from "@app/hooks/usePolicies";
-// A minimal wizard result (workflow already saved + mapped by the builder).
-const wizardResult = {
- automation: {
- id: "auto-1",
- name: "Test",
- operations: [{ operation: "compress", parameters: {} }],
- createdAt: "",
- updatedAt: "",
- },
- fieldValues: {},
- sources: [],
- runsOnEditor: true,
- scopeTypes: [],
- reviewerEmail: "[email protected]",
- folder: {
- runOn: "upload" as const,
- outputMode: "new_file" as const,
- outputName: "",
- outputNamePosition: "prefix" as const,
- maxRetries: 3,
- retryDelayMinutes: 5,
- },
- pipelineSteps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
- unresolvedOps: [],
-};
-
describe("usePolicies", () => {
beforeEach(() => {
localStorage.clear();
api.store.clear();
- api.seq = 0;
});
it("starts with every category unconfigured (no seed)", async () => {
@@ -79,80 +26,21 @@ describe("usePolicies", () => {
expect(result.current.policies.security.configured).toBe(false);
});
- it("enabling a policy persists it to the backend + marks it configured", async () => {
- const { result } = renderHook(() => usePolicies());
- await act(async () => {
- await result.current.enablePolicy("security", wizardResult);
- });
- await waitFor(() =>
- expect(result.current.policies.security.configured).toBe(true),
- );
- expect(result.current.policies.security.status).toBe("active");
- expect(result.current.policies.security.folderId).toBeTruthy();
- expect(result.current.policies.security.backendId).toBeTruthy();
- expect(result.current.policies.security.reviewerEmail).toBe(
- );
- // The mapped pipeline (endpoint path) reached the backend store.
- const stored = [...api.store.values()][0] as unknown as {
- steps: unknown[];
- };
- expect(stored.steps).toHaveLength(1);
- });
-
- it("reconciles configured policies from the backend on mount", async () => {
- // Enable on one instance (persists to the backend store)...
- const first = renderHook(() => usePolicies());
- await act(async () => {
- await first.result.current.enablePolicy("security", wizardResult);
- });
- // ...a fresh instance should pick it up from the backend.
- const second = renderHook(() => usePolicies());
- await waitFor(() =>
- expect(second.result.current.policies.security.configured).toBe(true),
- );
- expect(second.result.current.policies.security.backendId).toBeTruthy();
- });
-
- it("pausing then resuming flips status", async () => {
- const { result } = renderHook(() => usePolicies());
- await act(async () => {
- await result.current.enablePolicy("ingestion", wizardResult);
- });
- await act(async () => {
- await result.current.pausePolicy("ingestion");
- });
- expect(result.current.policies.ingestion.status).toBe("paused");
- await act(async () => {
- await result.current.resumePolicy("ingestion");
- });
- expect(result.current.policies.ingestion.status).toBe("active");
- });
+ it("reconciles a configured category policy from the backend on mount", async () => {
+ api.store.set("be-sec", {
+ id: "be-sec",
+ name: "Security",
+ enabled: true,
+ steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
+ output: { type: "inline", options: { categoryId: "security" } },
+ editor: { allowed: true, runOn: "upload" },
+ } as unknown as { id: string });
- it("deleting a policy reverts it + removes it from the backend", async () => {
const { result } = renderHook(() => usePolicies());
- await act(async () => {
- await result.current.enablePolicy("routing", wizardResult);
- });
await waitFor(() =>
- expect(result.current.policies.routing.configured).toBe(true),
+ expect(result.current.policies.security.configured).toBe(true),
);
- await act(async () => {
- await result.current.deletePolicy("routing");
- });
- expect(result.current.policies.routing.configured).toBe(false);
- expect(result.current.policies.routing.status).toBe("default");
- expect(result.current.policies.routing.folderId).toBeUndefined();
- expect(result.current.policies.routing.backendId).toBeUndefined();
- expect(api.store.size).toBe(0);
- });
-
- it("ensurePolicyFolder creates a backing folder for a folderless policy", async () => {
- const { result } = renderHook(() => usePolicies());
- await act(async () => {
- await result.current.ensurePolicyFolder("ingestion");
- });
- expect(result.current.policies.ingestion.folderId).toBeTruthy();
+ expect(result.current.policies.security.backendId).toBe("be-sec");
});
// A builder pipeline has no category tile, so the reconcile must key it by id to reach the map
@@ -208,7 +96,7 @@ describe("usePolicies", () => {
JSON.stringify({
"be-deleted": {
configured: true,
- status: "active",
+ enabled: true,
backendId: "be-deleted",
sources: ["editor"],
runsOnEditor: true,
diff --git a/frontend/editor/src/proprietary/hooks/usePolicies.ts b/frontend/editor/src/proprietary/hooks/usePolicies.ts
index 7bbbf42b80..d2e4b1072f 100644
--- a/frontend/editor/src/proprietary/hooks/usePolicies.ts
+++ b/frontend/editor/src/proprietary/hooks/usePolicies.ts
@@ -1,48 +1,25 @@
/**
- * State + actions for Policies. The backend (`/api/v1/policies`) is the source
- * of truth: on mount we reconcile the local cache against the stored policies,
- * and every lifecycle action (enable/save/pause/resume/delete) is mirrored to
- * the backend. localStorage is a fast-render cache + offline fallback; the
- * IndexedDB backing folder still holds the editable automation + run state.
+ * Read-only Policies state for the editor's enforcement path. The backend
+ * (`/api/v1/policies`) is the source of truth: on mount we reconcile the local
+ * cache against the stored policies. localStorage is a fast-render cache +
+ * offline fallback. Managing policies (create/edit/pause/delete) lives on the
+ * portal Pipelines page, not here; the editor only reads them and runs them.
*/
-import { useState, useEffect, useCallback, useRef } from "react";
+import { useState, useEffect, useRef } from "react";
import { useAppConfig } from "@app/contexts/AppConfigContext";
-import { useSaaSTeam } from "@app/contexts/SaaSTeamContext";
import {
loadPolicies,
onPoliciesChange,
updatePolicy,
- resetPolicy,
forgetPolicies,
- reorderPolicies as persistPolicyOrder,
} from "@app/services/policyStorage";
import { loadPolicyCatalog } from "@app/services/policyCatalog";
-import {
- createPolicyFolder,
- createPolicyFolderForAutomation,
- deletePolicyFolder,
- getPolicyAutomation,
- setPolicyFolderPaused,
- updatePolicyFolderSettings,
- updatePolicyOperations,
-} from "@app/services/policyFolders";
import {
fetchPoliciesByCategory,
decodedToState,
- findBackendId,
- persistPolicy,
- setPolicyEnabled,
- removePolicy,
} from "@app/services/policyBackend";
-import { reorderPolicies as reorderBackendPolicies } from "@app/services/policyApi";
-import { orderRewritesFirst } from "@app/data/classificationPolicy";
-import { type PolicyToStore } from "@app/services/policyPipeline";
-import type {
- PoliciesByCategory,
- PolicyConfigResult,
- PolicyWizardResult,
-} from "@app/types/policies";
+import type { PoliciesByCategory } from "@app/types/policies";
/** Cold-start reconcile retry budget + capped backoff (≈0.5s→5s, ~1 min total),
* enough to outlast a backend that starts a little after the frontend. */
@@ -50,34 +27,9 @@ const RECONCILE_MAX_ATTEMPTS = 15;
const reconcileRetryDelay = (attempt: number) =>
Math.min(500 * 2 ** attempt, 5000);
-/** Build the backend store-request for a category from a wizard result. */
-function toStoreRequest(
- categoryId: string,
- categoryLabel: string,
- result: PolicyWizardResult,
- enabled: boolean,
- backendId: string | undefined,
-): PolicyToStore {
- return {
- id: backendId,
- categoryId,
- name: `${categoryLabel} Policy`,
- enabled,
- automation: result.automation,
- pipelineSteps: result.pipelineSteps,
- sources: result.sources,
- runsOnEditor: result.runsOnEditor,
- scopeTypes: result.scopeTypes,
- reviewerEmail: result.reviewerEmail,
- fieldValues: result.fieldValues,
- folder: result.folder,
- };
-}
-
export function usePolicies() {
const [policies, setPolicies] = useState<PoliciesByCategory>(loadPolicies);
- const { config, refetch: refetchAppConfig } = useAppConfig();
- const { isTeamLeader } = useSaaSTeam();
+ const { refetch: refetchAppConfig } = useAppConfig();
useEffect(() => onPoliciesChange(() => setPolicies(loadPolicies())), []);
@@ -112,7 +64,7 @@ export function usePolicies() {
: {
...local[cat.id],
configured: false,
- status: "default",
+ enabled: false,
backendId: undefined,
};
}
@@ -144,276 +96,5 @@ export function usePolicies() {
};
}, []);
- /**
- * Enable a new policy from the wizard result: persist it to the backend (the
- * source of truth), then create the backing folder holding its editable
- * automation, and cache the result locally. Throws (surfacing in the wizard)
- * if the category is unknown or the backend save fails.
- */
- const enablePolicy = useCallback(
- async (id: string, result: PolicyWizardResult) => {
- const category = loadPolicyCatalog().categories.find((c) => c.id === id);
- if (!category) throw new Error(`Unknown policy category: ${id}`);
- // One policy per category, ever: reuse any existing backend record.
- const existingBackendId =
- loadPolicies()[id]?.backendId ??
- (await findBackendId(id).catch(() => undefined));
- const backendId = await persistPolicy(
- toStoreRequest(id, category.label, result, true, existingBackendId),
- );
- const folder = await createPolicyFolderForAutomation(
- category,
- result.automation.id,
- );
- await updatePolicyFolderSettings(folder.id, result.folder);
- updatePolicy(id, {
- configured: true,
- status: "active",
- folderId: folder.id,
- backendId,
- fieldValues: result.fieldValues,
- sources: result.sources,
- runsOnEditor: result.runsOnEditor,
- scopeTypes: result.scopeTypes,
- reviewerEmail: result.reviewerEmail,
- outputMode: result.folder.outputMode,
- outputName: result.folder.outputName,
- outputNamePosition: result.folder.outputNamePosition,
- runOn: result.folder.runOn,
- });
- },
- [],
- );
-
- /**
- * Save edits from the wizard. The workflow automation is updated in place by
- * the builder; persist the updated policy to the backend and the folder's
- * output/retry settings + the rest of the settings locally.
- */
- const savePolicyConfig = useCallback(
- async (id: string, result: PolicyWizardResult) => {
- const current = loadPolicies()[id];
- const category = loadPolicyCatalog().categories.find((c) => c.id === id);
- if (!category) throw new Error(`Unknown policy category: ${id}`);
- const backendId = await persistPolicy(
- toStoreRequest(
- id,
- category.label,
- result,
- current?.status !== "paused",
- current?.backendId,
- ),
- );
- if (current?.folderId) {
- await updatePolicyFolderSettings(current.folderId, result.folder);
- }
- updatePolicy(id, {
- backendId,
- fieldValues: result.fieldValues,
- sources: result.sources,
- runsOnEditor: result.runsOnEditor,
- scopeTypes: result.scopeTypes,
- reviewerEmail: result.reviewerEmail,
- outputMode: result.folder.outputMode,
- outputName: result.folder.outputName,
- outputNamePosition: result.folder.outputNamePosition,
- runOn: result.folder.runOn,
- });
- },
- [],
- );
-
- /**
- * Create-or-update a policy from the locked tool-config page. Unlike the
- * wizard path this works straight from the tool `operations` (the config page
- * owns the chain): it creates the backing folder + automation on first
- * configure, or updates the existing automation's operations on edit, then
- * mirrors the whole policy to the backend. One method serves both because a
- * preset policy has no separate "create" — you're just configuring it.
- */
- const commitPolicyConfig = useCallback(
- async (id: string, result: PolicyConfigResult) => {
- const category = loadPolicyCatalog().categories.find((c) => c.id === id);
- if (!category) throw new Error(`Unknown policy category: ${id}`);
- const current = loadPolicies()[id];
- // One policy per category, ever: reuse the existing backend record (even
- // if the local link was lost) so a save never creates a duplicate.
- const existingBackendId =
- current?.backendId ?? (await findBackendId(id).catch(() => undefined));
- let folderId = current?.folderId;
- if (folderId) {
- await updatePolicyOperations(folderId, result.operations);
- } else {
- const folder = await createPolicyFolder(category, result.operations);
- folderId = folder.id;
- }
- await updatePolicyFolderSettings(folderId, result.folder);
- // The saved automation (with its id) is the lossless round-trip blob.
- const automation = await getPolicyAutomation(folderId);
- const store: PolicyToStore = {
- id: existingBackendId,
- categoryId: id,
- name: `${category.label} Policy`,
- enabled: current?.status !== "paused",
- automation: automation ?? {
- id: "",
- name: `${category.label} Policy`,
- operations: result.operations,
- createdAt: "",
- updatedAt: "",
- },
- pipelineSteps: result.pipelineSteps,
- sources: result.sources,
- runsOnEditor: result.runsOnEditor,
- scopeTypes: result.scopeTypes,
- reviewerEmail: result.reviewerEmail,
- fieldValues: result.fieldValues,
- folder: result.folder,
- };
- const backendId = await persistPolicy(store);
- updatePolicy(id, {
- configured: true,
- status: current?.status === "paused" ? "paused" : "active",
- folderId,
- backendId,
- fieldValues: result.fieldValues,
- sources: result.sources,
- runsOnEditor: result.runsOnEditor,
- scopeTypes: result.scopeTypes,
- reviewerEmail: result.reviewerEmail,
- outputMode: result.folder.outputMode,
- outputName: result.folder.outputName,
- outputNamePosition: result.folder.outputNamePosition,
- runOn: result.folder.runOn,
- });
- },
- [],
- );
-
- const pausePolicy = useCallback(async (id: string) => {
- const current = loadPolicies()[id];
- if (current?.backendId) {
- await setPolicyEnabled(current.backendId, false).catch((err: unknown) => {
- if (
- (err as { response?: { status?: number } })?.response?.status === 404
- ) {
- updatePolicy(id, {
- backendId: undefined,
- configured: false,
- status: "default",
- });
- return;
- }
- throw err;
- });
- }
- if (current?.folderId) await setPolicyFolderPaused(current.folderId, true);
- updatePolicy(id, { status: "paused" });
- }, []);
-
- const resumePolicy = useCallback(async (id: string) => {
- const current = loadPolicies()[id];
- if (current?.backendId) {
- await setPolicyEnabled(current.backendId, true).catch((err: unknown) => {
- if (
- (err as { response?: { status?: number } })?.response?.status === 404
- ) {
- updatePolicy(id, {
- backendId: undefined,
- configured: false,
- status: "default",
- });
- return;
- }
- throw err;
- });
- }
- if (current?.folderId) await setPolicyFolderPaused(current.folderId, false);
- updatePolicy(id, { status: "active" });
- }, []);
-
- const deletePolicy = useCallback(async (id: string) => {
- const current = loadPolicies()[id];
- if (current?.backendId) await removePolicy(current.backendId);
- if (current?.folderId) await deletePolicyFolder(current.folderId);
- resetPolicy(id);
- }, []);
-
- /**
- * Persist a new execution order for the given categories (in the sequence
- * provided). The order is server-side and team-wide: it's mirrored to the
- * backend (mapping each category to its stored policy id) so it survives a
- * cleared browser and is shared by the whole team. The local cache is updated
- * first for an instant re-render; the next reconcile re-reads the server order.
- */
- const reorderPolicies = useCallback((orderedCategoryIds: string[]) => {
- // Annotating policies last, so the persisted order matches execution order
- // (see usePolicyAutoRun).
- const ordered = orderRewritesFirst(orderedCategoryIds);
- persistPolicyOrder(ordered);
- const current = loadPolicies();
- const backendIds = ordered
- .map((categoryId) => current[categoryId]?.backendId)
- .filter((id): id is string => !!id);
- if (backendIds.length > 0) {
- // Fire-and-forget: on failure (offline / not a team leader) the optimistic
- // local order stands until the next reconcile re-reads the server's order.
- void reorderBackendPolicies(backendIds).catch(() => {});
- }
- }, []);
-
- /**
- * Ensure a configured policy has a *valid* backing folder (its editable
- * pipeline) and return its id. Self-heals a stale `folderId` — one that no
- * longer resolves to a real folder (cleared storage, or a folder left in an
- * old IndexedDB after a rename/migration) — which would otherwise hang the
- * Edit-Settings view on a permanent "Loading…". When recreating, the backend's
- * stored automation is used if present so the configured pipeline survives;
- * otherwise it falls back to the preset.
- */
- const ensurePolicyFolder = useCallback(async (id: string) => {
- const state = loadPolicies()[id];
- const existing = state?.folderId;
- // A healthy backing folder resolves to an automation; if it does, keep it.
- if (existing && (await getPolicyAutomation(existing))) return existing;
- const catalog = loadPolicyCatalog();
- const category = catalog.categories.find((c) => c.id === id);
- const config = catalog.configs[id];
- if (!category || !config) return undefined;
- // Stale/missing folder → recreate. Prefer the backend's stored automation
- // (preserves the user's configured steps); else seed from the preset.
- let operations = config.defaultOperations;
- if (state?.backendId) {
- const decoded = await fetchPoliciesByCategory()
- .then((m) => m.get(id))
- .catch(() => undefined);
- if (decoded?.automation?.operations?.length) {
- operations = decoded.automation.operations;
- }
- }
- const folder = await createPolicyFolder(category, operations);
- updatePolicy(id, { folderId: folder.id });
- return folder.id;
- }, []);
-
- // Only a team leader (SaaS) or a global admin (self-hosted) may configure;
- // everyone else gets the read-only surface. Login disabled (single-user)
- // always can. Stays closed until config loads, so edit controls never flash
- // for users who can't use them.
- const canConfigure =
- config != null &&
- (!config.enableLogin || isTeamLeader || config.isAdmin === true);
-
- return {
- policies,
- canConfigure,
- enablePolicy,
- savePolicyConfig,
- commitPolicyConfig,
- pausePolicy,
- resumePolicy,
- deletePolicy,
- reorderPolicies,
- ensurePolicyFolder,
- };
+ return { policies };
}
diff --git a/frontend/editor/src/proprietary/policies/runs.ts b/frontend/editor/src/proprietary/policies/runs.ts
index 74f1449259..8eac88b766 100644
--- a/frontend/editor/src/proprietary/policies/runs.ts
+++ b/frontend/editor/src/proprietary/policies/runs.ts
@@ -47,7 +47,7 @@ function activityAction(run: PolicyRunView): string {
export function runsToActivity(runs: PolicyRunView[]): PolicyActivityItem[] {
return runs.map((run) => ({
- doc: run.outputs[0]?.fileName ?? "Policy run",
+ doc: run.outputs?.[0]?.fileName ?? "Policy run",
action: activityAction(run),
time: relativeTime(run.createdAt),
status: activityStatus(run),
diff --git a/frontend/editor/src/proprietary/policies/types.ts b/frontend/editor/src/proprietary/policies/types.ts
index 6dad09855b..6addb59ab9 100644
--- a/frontend/editor/src/proprietary/policies/types.ts
+++ b/frontend/editor/src/proprietary/policies/types.ts
@@ -70,6 +70,12 @@ export type PolicyRunStatus =
| "FAILED"
| "CANCELLED";
+/** One file a run produced, downloadable via /api/v1/general/files/{fileId}. */
+export interface RunOutputFile {
+ fileId: string;
+ fileName: string | null;
+}
+
export interface PolicyRunView {
runId: string;
policyId: string | null;
@@ -79,7 +85,7 @@ export interface PolicyRunView {
error: string | null;
errorCode?: string | null;
errorSubscribed?: boolean | null;
- outputs: { fileId: string; fileName: string }[];
+ outputs?: RunOutputFile[] | null;
/** Creation timestamp in epoch milliseconds. */
createdAt: number;
}
diff --git a/frontend/editor/src/proprietary/services/policyApi.ts b/frontend/editor/src/proprietary/services/policyApi.ts
index d93e51fa82..8215af2ee6 100644
--- a/frontend/editor/src/proprietary/services/policyApi.ts
+++ b/frontend/editor/src/proprietary/services/policyApi.ts
@@ -8,7 +8,6 @@
import apiClient from "@app/services/apiClient";
import { getPolicyOutputBaseUrl } from "@app/services/policyOutputBaseUrl";
import type {
- BackendPipelineDefinition,
BackendPolicy,
PolicyExecutionTarget,
PolicyRunView,
@@ -20,16 +19,6 @@ interface JobResponse {
result: unknown;
}
-// --- Policy config persistence (server-side store, JPA-backed) ---
-
-/** Create or update a policy; the backend assigns a blank id and returns it. */
-export async function savePolicy(
- policy: BackendPolicy,
-): Promise<BackendPolicy> {
- const res = await apiClient.post<BackendPolicy>("/api/v1/policies", policy);
- return res.data;
-}
-
/** List all stored policies. */
export async function listPolicies(): Promise<BackendPolicy[]> {
const res = await apiClient.get<BackendPolicy[]>("/api/v1/policies", {
@@ -38,28 +27,6 @@ export async function listPolicies(): Promise<BackendPolicy[]> {
return res.data;
}
-/** Fetch a stored policy by id. */
-export async function getPolicy(id: string): Promise<BackendPolicy> {
- const res = await apiClient.get<BackendPolicy>(
- `/api/v1/policies/${encodeURIComponent(id)}`,
- );
- return res.data;
-}
-
-/** Delete a stored policy by id. */
-export async function deletePolicy(id: string): Promise<void> {
- await apiClient.delete(`/api/v1/policies/${encodeURIComponent(id)}`);
-}
-
-/**
- * Persist the team's run order (server-side, shared by the whole team). Sends the
- * ordered backend policy ids; the backend maps position → order and ignores any
- * id outside the caller's team. Team-leader/admin only (403 otherwise).
- */
-export async function reorderPolicies(orderedIds: string[]): Promise<void> {
- await apiClient.put("/api/v1/policies/order", orderedIds);
-}
-
/**
* Run a stored policy by id; returns the run id. `fileId` is this workspace's own opaque id, recorded
* against any failure of the run. Only honoured for a single-document run, and never a filename.
@@ -83,28 +50,6 @@ export async function runStoredPolicy(
return res.data.jobId;
}
-// --- Ad-hoc pipeline runs (no stored policy) ---
-
-/**
- * Run an ad-hoc pipeline on the backend over the given documents. Returns the
- * run id; poll {@link getPolicyRun} for status + output file ids.
- */
-export async function runPolicyPipeline(
- definition: BackendPipelineDefinition,
- files: File[],
-): Promise<string> {
- const form = new FormData();
- for (const file of files) form.append("fileInput", file);
- // The backend binds this as a typed @RequestPart, so it must be an application/json part.
- form.append(
- "json",
- new Blob([JSON.stringify(definition)], { type: "application/json" }),
- );
- // No Content-Type: let the client set multipart/form-data with its boundary.
- const res = await apiClient.post<JobResponse>("/api/v1/policies/run", form);
- return res.data.jobId;
-}
-
/**
* Where a policy run executes, and thus the backend that holds its outputs.
*/
diff --git a/frontend/editor/src/proprietary/services/policyBackend.ts b/frontend/editor/src/proprietary/services/policyBackend.ts
index 2da5860476..2d51bdf3d8 100644
--- a/frontend/editor/src/proprietary/services/policyBackend.ts
+++ b/frontend/editor/src/proprietary/services/policyBackend.ts
@@ -1,20 +1,17 @@
/**
- * Backend source-of-truth layer for Policies. Wraps the raw `policyApi` client +
- * the `policyPipeline` mapper into category-shaped operations the hook can use:
- * fetch the stored policies (grouped by catalog category), persist one, flip its
- * enabled flag, and delete it.
+ * Backend source-of-truth read layer for Policies: fetch the stored policies
+ * (grouped by catalog category) and decode them onto the frontend's per-category
+ * state for the editor's enforcement path.
*
* The frontend is category-keyed (one policy per catalog category); the backend
* is a flat list with assigned ids. The bridge is `trigger.options.categoryId`,
- * which `policyPipeline` encodes on save and decodes on read.
+ * which `policyPipeline` decodes on read.
*/
import * as policyApi from "@app/services/policyApi";
import {
- buildBackendPolicy,
fromBackendPolicy,
type DecodedPolicy,
- type PolicyToStore,
} from "@app/services/policyPipeline";
import type { PolicyState } from "@app/types/policies";
@@ -51,7 +48,7 @@ export function decodedToState(
): PolicyState {
return {
configured: true,
- status: decoded.enabled ? "active" : "paused",
+ enabled: decoded.enabled,
name: decoded.name,
sources: decoded.sources,
runsOnEditor: decoded.runsOnEditor,
@@ -70,39 +67,3 @@ export function decodedToState(
isDefault: Boolean(decoded.categoryId),
};
}
-
-/**
- * The backend id of the stored policy for a category, if one exists. Used to
- * enforce one-policy-per-category: a save reuses this id (update) rather than
- * creating a duplicate, even if the local cache lost the link.
- */
-export async function findBackendId(
- categoryId: string,
-): Promise<string | undefined> {
- const byCategory = await fetchPoliciesByCategory();
- return byCategory.get(categoryId)?.id;
-}
-
-/** Persist a policy (create or update); returns the backend-assigned id. */
-export async function persistPolicy(store: PolicyToStore): Promise<string> {
- const saved = await policyApi.savePolicy(buildBackendPolicy(store));
- return saved.id;
-}
-
-/**
- * Flip a stored policy's `enabled` flag (pause/resume) — the backend gates
- * automatic triggering on it. Reads the current policy so the rest of its config
- * is preserved on the round-trip.
- */
-export async function setPolicyEnabled(
- backendId: string,
- enabled: boolean,
-): Promise<void> {
- const current = await policyApi.getPolicy(backendId);
- await policyApi.savePolicy({ ...current, enabled });
-}
-
-/** Delete a stored policy by its backend id. */
-export async function removePolicy(backendId: string): Promise<void> {
- await policyApi.deletePolicy(backendId);
-}
diff --git a/frontend/editor/src/proprietary/services/policyCatalog.ts b/frontend/editor/src/proprietary/services/policyCatalog.ts
index c4787430f5..bd4062f6b5 100644
--- a/frontend/editor/src/proprietary/services/policyCatalog.ts
+++ b/frontend/editor/src/proprietary/services/policyCatalog.ts
@@ -1,43 +1,22 @@
/**
- * The catalog of available policy *definitions* — the policy types, their
- * editable fields, the sources a policy can run over, and the document types
- * scope can be narrowed to. This is the single seam through which definitions
- * reach consumers: nothing imports the static definitions directly, everything
- * reads the catalog through {@link loadPolicyCatalog}.
+ * The catalog of available policy *definitions* — the policy categories in
+ * display order. This is the single seam through which definitions reach
+ * consumers: nothing imports the static definitions directly, everything reads
+ * the catalog through {@link loadPolicyCatalog}.
*
* Backed by the static `policyDefinitions` today; swap {@link loadPolicyCatalog}
* for a fetch to move definitions server-side without touching any component.
*/
-import {
- POLICY_CATEGORIES,
- POLICY_CONFIG,
- POLICY_SOURCES,
- POLICY_DOC_TYPES,
-} from "@app/data/policyDefinitions";
-import type {
- PolicyCategory,
- PolicyConfigDef,
- PolicySource,
-} from "@app/types/policies";
+import { POLICY_CATEGORIES } from "@app/data/policyDefinitions";
+import type { PolicyCategory } from "@app/types/policies";
export interface PolicyCatalog {
/** Available policy types, in display order. */
categories: PolicyCategory[];
- /** Per-category narrative + editable field definitions, keyed by category id. */
- configs: Record<string, PolicyConfigDef>;
- /** Sources a policy can run over (wizard step 2). */
- sources: PolicySource[];
- /** Document types scope can be narrowed to (gated behind classification). */
- docTypes: string[];
}
/** Load the policy catalog. Swap this for a backend fetch to go live. */
export function loadPolicyCatalog(): PolicyCatalog {
- return {
- categories: POLICY_CATEGORIES,
- configs: POLICY_CONFIG,
- sources: POLICY_SOURCES,
- docTypes: POLICY_DOC_TYPES,
- };
+ return { categories: POLICY_CATEGORIES };
}
diff --git a/frontend/editor/src/proprietary/services/policyExport.test.ts b/frontend/editor/src/proprietary/services/policyExport.test.ts
index 016c48f33a..8960b3f6bb 100644
--- a/frontend/editor/src/proprietary/services/policyExport.test.ts
+++ b/frontend/editor/src/proprietary/services/policyExport.test.ts
@@ -42,7 +42,7 @@ const { enforceExportPolicies } = await import("@app/services/policyExport");
const exportPolicy = (over: Partial<PolicyState>): PolicyState =>
({
configured: true,
- status: "active",
+ enabled: true,
backendId: "backend-1",
sources: [],
runsOnEditor: false,
diff --git a/frontend/editor/src/proprietary/services/policyExport.ts b/frontend/editor/src/proprietary/services/policyExport.ts
index ff1e25ad11..4b53201993 100644
--- a/frontend/editor/src/proprietary/services/policyExport.ts
+++ b/frontend/editor/src/proprietary/services/policyExport.ts
@@ -67,7 +67,7 @@ function activeExportPolicies(): ExportPolicy[] {
.filter(
([, s]) =>
s.configured &&
- s.status === "active" &&
+ s.enabled &&
s.backendId &&
s.runsOnEditor &&
s.runOn === "export",
diff --git a/frontend/editor/src/proprietary/services/policyFolders.test.ts b/frontend/editor/src/proprietary/services/policyFolders.test.ts
deleted file mode 100644
index 1a34a9414f..0000000000
--- a/frontend/editor/src/proprietary/services/policyFolders.test.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import "fake-indexeddb/auto";
-import { describe, it, expect, beforeEach, vi } from "vitest";
-
-// jsdom's crypto has no randomUUID, which watchedFolderStorage uses for folder ids.
-if (typeof globalThis.crypto?.randomUUID !== "function") {
- const orig = globalThis.crypto;
- vi.stubGlobal("crypto", {
- getRandomValues: orig?.getRandomValues?.bind(orig),
- randomUUID: () =>
- `p-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,
- });
-}
-
-import {
- createPolicyFolder,
- getPolicyOperations,
- updatePolicyOperations,
- setPolicyFolderPaused,
- deletePolicyFolder,
-} from "@app/services/policyFolders";
-import { watchedFolderStorage } from "@app/services/watchedFolderStorage";
-import { automationStorage } from "@app/services/automationStorage";
-import type { PolicyCategory } from "@app/types/policies";
-
-const category: PolicyCategory = {
- id: "security",
- label: "Security",
- icon: null,
- desc: "Detect PII, encrypt, verify.",
-};
-
-const steps = [
- { operation: "sanitize", parameters: {} },
- { operation: "addPassword", parameters: {} },
-];
-
-describe("policyFolders backing-folder layer", () => {
- beforeEach(async () => {
- // Clean slate between tests (fake-indexeddb persists within a run).
- for (const f of await watchedFolderStorage.getAllFolders()) {
- await watchedFolderStorage.deleteFolder(f.id);
- }
- for (const a of await automationStorage.getAllAutomations()) {
- await automationStorage.deleteAutomation(a.id);
- }
- });
-
- it("creates a folder + automation tagged with the policy category", async () => {
- const folder = await createPolicyFolder(category, steps);
- expect(folder.policyCategoryId).toBe("security");
- expect(folder.automationId).toBeTruthy();
-
- const ops = await getPolicyOperations(folder.id);
- expect(ops.map((o) => o.operation)).toEqual(["sanitize", "addPassword"]);
- });
-
- it("updates the steps through the backing automation", async () => {
- const folder = await createPolicyFolder(category, steps);
- await updatePolicyOperations(folder.id, [
- { operation: "compress", parameters: {} },
- ]);
- const ops = await getPolicyOperations(folder.id);
- expect(ops.map((o) => o.operation)).toEqual(["compress"]);
- });
-
- it("pauses/resumes via the backing folder flag", async () => {
- const folder = await createPolicyFolder(category, steps);
- await setPolicyFolderPaused(folder.id, true);
- expect((await watchedFolderStorage.getFolder(folder.id))?.isPaused).toBe(
- true,
- );
- await setPolicyFolderPaused(folder.id, false);
- expect((await watchedFolderStorage.getFolder(folder.id))?.isPaused).toBe(
- false,
- );
- });
-
- it("deletes the folder and its automation", async () => {
- const folder = await createPolicyFolder(category, steps);
- const automationId = folder.automationId;
- await deletePolicyFolder(folder.id);
- expect(await watchedFolderStorage.getFolder(folder.id)).toBeNull();
- expect(await automationStorage.getAutomation(automationId)).toBeNull();
- });
-});
diff --git a/frontend/editor/src/proprietary/services/policyFolders.ts b/frontend/editor/src/proprietary/services/policyFolders.ts
deleted file mode 100644
index 7f034f904c..0000000000
--- a/frontend/editor/src/proprietary/services/policyFolders.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-/**
- * Backing-folder layer for Policies. A configured policy's folder trigger,
- * editable steps, output and run-state all live in a Watched Folders
- * {@link WatchedFolder} (+ its {@link AutomationConfig}) — the policy reuses the
- * Watched Folders engine rather than re-implementing execution. This module is
- * the seam that creates and manages that backing record.
- *
- * The folder is tagged with `policyCategoryId` so the Watched Folders UI can
- * filter it out (it's owned by Policies). The backing automation also rides
- * along to the backend (in the saved policy's output.options) for round-trip;
- * this folder remains the locally-editable copy.
- */
-
-import { automationStorage } from "@app/services/automationStorage";
-import { watchedFolderStorage } from "@app/services/watchedFolderStorage";
-import type {
- AutomationConfig,
- AutomationOperation,
-} from "@app/types/automation";
-import type { WatchedFolder } from "@app/types/watchedFolders";
-import type { PolicyCategory, PolicyFolderSettings } from "@app/types/policies";
-
-/** Folder icon (a name string) used for each policy category's backing folder. */
-const CATEGORY_FOLDER_ICON: Record<string, string> = {
- ingestion: "StorageIcon",
- security: "SecurityIcon",
- compliance: "CheckIcon",
- routing: "SwapHorizIcon",
- retention: "StorageIcon",
-};
-
-const POLICY_FOLDER_ACCENT = "#3b82f6";
-
-/**
- * Create the backing folder for a policy: persist an automation from the given
- * steps, then a WatchedFolder (the folder trigger) referencing it, tagged with
- * the policy's category id. Returns the created folder.
- */
-export async function createPolicyFolder(
- category: PolicyCategory,
- operations: AutomationOperation[],
-): Promise<WatchedFolder> {
- const automation = await automationStorage.saveAutomation({
- name: `${category.label} Policy`,
- description: `Pipeline for the ${category.label} policy`,
- operations,
- });
- return watchedFolderStorage.createFolder({
- name: `${category.label} Policy`,
- description: category.desc,
- automationId: automation.id,
- icon: CATEGORY_FOLDER_ICON[category.id] ?? "WorkIcon",
- accentColor: POLICY_FOLDER_ACCENT,
- policyCategoryId: category.id,
- inputSource: "idb",
- });
-}
-
-/**
- * Create the backing folder for a policy from an *already-saved* automation
- * (e.g. one the workflow builder just created). Pairs with the wizard, where
- * AutomationCreation persists the automation and we link a folder to it.
- */
-export async function createPolicyFolderForAutomation(
- category: PolicyCategory,
- automationId: string,
-): Promise<WatchedFolder> {
- return watchedFolderStorage.createFolder({
- name: `${category.label} Policy`,
- description: category.desc,
- automationId,
- icon: CATEGORY_FOLDER_ICON[category.id] ?? "WorkIcon",
- accentColor: POLICY_FOLDER_ACCENT,
- policyCategoryId: category.id,
- inputSource: "idb",
- });
-}
-
-/** The policy's current steps, resolved through its backing folder's automation. */
-export async function getPolicyOperations(
- folderId: string,
-): Promise<AutomationOperation[]> {
- const folder = await watchedFolderStorage.getFolder(folderId);
- if (!folder) return [];
- const automation = await automationStorage.getAutomation(folder.automationId);
- return automation?.operations ?? [];
-}
-
-/** The policy's backing automation (its editable pipeline), via its folder. */
-export async function getPolicyAutomation(
- folderId: string,
-): Promise<AutomationConfig | null> {
- const folder = await watchedFolderStorage.getFolder(folderId);
- if (!folder) return null;
- return automationStorage.getAutomation(folder.automationId);
-}
-
-/** Replace the policy's steps by updating its backing automation. */
-export async function updatePolicyOperations(
- folderId: string,
- operations: AutomationOperation[],
-): Promise<void> {
- const folder = await watchedFolderStorage.getFolder(folderId);
- if (!folder) return;
- const automation = await automationStorage.getAutomation(folder.automationId);
- if (!automation) return;
- await automationStorage.updateAutomation({ ...automation, operations });
-}
-
-/** Apply output + retry settings to the policy's backing folder. */
-export async function updatePolicyFolderSettings(
- folderId: string,
- settings: PolicyFolderSettings,
-): Promise<void> {
- const folder = await watchedFolderStorage.getFolder(folderId);
- if (!folder) return;
- await watchedFolderStorage.updateFolder({ ...folder, ...settings });
-}
-
-/** Pause/resume the policy by toggling its backing folder's paused flag. */
-export async function setPolicyFolderPaused(
- folderId: string,
- paused: boolean,
-): Promise<void> {
- const folder = await watchedFolderStorage.getFolder(folderId);
- if (!folder) return;
- await watchedFolderStorage.updateFolder({ ...folder, isPaused: paused });
-}
-
-/** Delete the policy's backing folder and its automation. */
-export async function deletePolicyFolder(folderId: string): Promise<void> {
- const folder = await watchedFolderStorage.getFolder(folderId);
- if (folder) {
- await automationStorage.deleteAutomation(folder.automationId);
- }
- await watchedFolderStorage.deleteFolder(folderId);
-}
diff --git a/frontend/editor/src/proprietary/services/policyPipeline.test.ts b/frontend/editor/src/proprietary/services/policyPipeline.test.ts
index 9fbed8ba50..4e91b1d95b 100644
--- a/frontend/editor/src/proprietary/services/policyPipeline.test.ts
+++ b/frontend/editor/src/proprietary/services/policyPipeline.test.ts
@@ -1,150 +1,44 @@
import { describe, it, expect } from "vitest";
import {
- buildPipelineDefinition,
- buildBackendPolicy,
fromBackendPolicy,
+ type BackendPolicy,
} from "@app/services/policyPipeline";
-import type { ToolRegistry } from "@app/data/toolsTaxonomy";
-// Minimal registry: a static-endpoint tool and a function-endpoint tool.
-const registry = {
- compress: { operationConfig: { endpoint: "/api/v1/misc/compress-pdf" } },
- rotate: {
- operationConfig: {
- endpoint: (p: Record<string, unknown>) =>
- `/api/v1/general/rotate-pdf?angle=${p.angle}`,
- },
- },
-} as unknown as Partial<ToolRegistry>;
-
-describe("buildPipelineDefinition", () => {
- it("maps frontend operations to backend endpoint steps", () => {
- const { definition, unresolved } = buildPipelineDefinition(
- {
- name: "Secure Ingestion",
- operations: [
- { operation: "compress", parameters: {} },
- { operation: "rotate", parameters: { angle: 90 } },
- ],
- },
- registry,
- );
-
- expect(unresolved).toEqual([]);
- expect(definition.name).toBe("Secure Ingestion");
- expect(definition.outputs).toEqual([{ type: "inline", options: {} }]);
- expect(definition.steps).toEqual([
- { operation: "/api/v1/misc/compress-pdf", parameters: {} },
- {
- operation: "/api/v1/general/rotate-pdf?angle=90",
- parameters: { angle: 90 },
- },
- ]);
- });
-
- it("drops + reports operations with no resolvable endpoint", () => {
- const { definition, unresolved } = buildPipelineDefinition(
- {
- name: "X",
- operations: [
- { operation: "compress", parameters: {} },
- { operation: "notARealTool", parameters: {} },
- ],
- },
- registry,
- );
- expect(unresolved).toEqual(["notARealTool"]);
- expect(definition.steps).toHaveLength(1);
- });
-
- it("runs each tool's buildFormData so stored params match its endpoint", () => {
- // A redact-like tool whose UI param (wordsToRedact[]) is transformed into
- // the endpoint's field (listOfText) by buildFormData — the "marry up".
- const redactish = {
- redact: {
- operationConfig: {
- endpoint: () => "/api/v1/security/auto-redact",
- buildFormData: (
- p: { wordsToRedact?: string[]; useRegex?: boolean },
- file: File,
- ) => {
- const fd = new FormData();
- fd.append("fileInput", file);
- fd.append("listOfText", (p.wordsToRedact ?? []).join("\n"));
- fd.append("useRegex", String(p.useRegex ?? false));
- return fd;
- },
- },
- },
- } as unknown as Partial<ToolRegistry>;
-
- const { definition } = buildPipelineDefinition(
- {
- name: "Security",
- operations: [
- {
- operation: "redact",
- parameters: { wordsToRedact: ["SSN", "Account"], useRegex: true },
- },
- ],
- },
- redactish,
- );
-
- // The document field is dropped; the UI param became the endpoint field.
- expect(definition.steps[0]).toEqual({
- operation: "/api/v1/security/auto-redact",
- parameters: { listOfText: "SSN\nAccount", useRegex: "true" },
- });
- });
-});
-
-const samplePolicy = {
- categoryId: "security",
+const backendPolicy: BackendPolicy = {
+ id: "p1",
name: "Security",
+ owner: "",
enabled: true,
- automation: {
- id: "auto-1",
- name: "Security",
- operations: [{ operation: "compress", parameters: {} }],
- createdAt: "",
- updatedAt: "",
- },
- pipelineSteps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
- sources: [],
- runsOnEditor: true,
- scopeTypes: ["Contracts"],
- reviewerEmail: "[email protected]",
- fieldValues: { minConfidence: "80%" },
- folder: {
- runOn: "export" as const,
- outputMode: "new_version" as const,
- outputName: "secured",
- outputNamePosition: "suffix" as const,
- maxRetries: 2,
- retryDelayMinutes: 10,
+ trigger: null,
+ steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
+ output: {
+ type: "inline",
+ options: {
+ mode: "new_version",
+ name: "secured",
+ position: "suffix",
+ maxRetries: 2,
+ retryDelayMinutes: 10,
+ automation: {
+ id: "auto-1",
+ name: "Security",
+ operations: [{ operation: "compress", parameters: {} }],
+ createdAt: "",
+ updatedAt: "",
+ },
+ categoryId: "security",
+ sources: [],
+ scopeTypes: ["Contracts"],
+ reviewerEmail: "[email protected]",
+ fieldValues: { minConfidence: "80%" },
+ },
},
+ editor: { allowed: true, runOn: "export" },
};
-describe("buildBackendPolicy", () => {
- it("maps a frontend policy to the backend Policy shape", () => {
- const policy = buildBackendPolicy(samplePolicy);
- expect(policy.id).toBe(""); // blank → backend assigns
- expect(policy.name).toBe("Security");
- expect(policy.enabled).toBe(true);
- expect(policy.steps).toEqual([
- { operation: "/api/v1/misc/compress-pdf", parameters: {} },
- ]);
- // Manual-only policy: no server-side trigger, extras ride in output.options.
- expect(policy.trigger).toBeNull();
- expect(policy.output.options.categoryId).toBe("security");
- expect(policy.output.options.reviewerEmail).toBe("[email protected]");
- expect(policy.output.options.maxRetries).toBe(2);
- });
-
- it("round-trips losslessly through fromBackendPolicy", () => {
- const policy = buildBackendPolicy(samplePolicy);
- const decoded = fromBackendPolicy({ ...policy, id: "p1" });
+describe("fromBackendPolicy", () => {
+ it("decodes a stored policy's output.options bag into frontend settings", () => {
+ const decoded = fromBackendPolicy(backendPolicy);
expect(decoded.id).toBe("p1");
expect(decoded.categoryId).toBe("security");
expect(decoded.enabled).toBe(true);
@@ -153,9 +47,16 @@ describe("buildBackendPolicy", () => {
expect(decoded.scopeTypes).toEqual(["Contracts"]);
expect(decoded.reviewerEmail).toBe("[email protected]");
expect(decoded.fieldValues).toEqual({ minConfidence: "80%" });
- expect(decoded.folder).toEqual(samplePolicy.folder);
- expect(decoded.automation?.operations).toEqual(
- samplePolicy.automation.operations,
- );
+ expect(decoded.folder).toEqual({
+ runOn: "export",
+ outputMode: "new_version",
+ outputName: "secured",
+ outputNamePosition: "suffix",
+ maxRetries: 2,
+ retryDelayMinutes: 10,
+ });
+ expect(decoded.automation?.operations).toEqual([
+ { operation: "compress", parameters: {} },
+ ]);
});
});
diff --git a/frontend/editor/src/proprietary/services/policyPipeline.ts b/frontend/editor/src/proprietary/services/policyPipeline.ts
index 93bde7ecfd..252711547c 100644
--- a/frontend/editor/src/proprietary/services/policyPipeline.ts
+++ b/frontend/editor/src/proprietary/services/policyPipeline.ts
@@ -13,7 +13,6 @@
import { resolveRunOn, type PolicyRunOn } from "@app/policies/runOn";
import type { AutomationConfig } from "@app/types/automation";
-import type { ToolRegistry } from "@app/data/toolsTaxonomy";
import type { PolicyFolderSettings } from "@app/types/policies";
/** A single backend pipeline step: a tool endpoint path + its scalar params. */
@@ -29,14 +28,6 @@ export interface BackendOutputSpec {
options: Record<string, unknown>;
}
-/** The engine-level pipeline the `/run` endpoint accepts (as JSON). */
-export interface BackendPipelineDefinition {
- name: string;
- steps: BackendPipelineStep[];
- /** Destinations a run's files are delivered to; a single inline entry for one-off/editor runs. */
- outputs: BackendOutputSpec[];
-}
-
/** How a stored policy is triggered ("manual" | "folder" | "schedule" | "s3"). */
export interface BackendTriggerConfig {
type: string;
@@ -111,127 +102,6 @@ export interface PolicyRunView {
createdAt: number;
}
-/**
- * Operations that run as policy pipeline steps but are NOT user-facing tools, so
- * they have no tool-registry entry and never appear in the tool picker. Maps the
- * operation id straight to its backend endpoint.
- */
-const POLICY_OPERATION_ENDPOINTS: Record<string, string> = {
- // Document classification — dispatched only by the Classification policy.
- classify: "/api/v1/ai/tools/classify-and-label",
-};
-
-/** Resolve a frontend operation id to its backend tool endpoint path. */
-function resolveEndpoint(
- operation: string,
- parameters: Record<string, unknown>,
- toolRegistry: Partial<ToolRegistry>,
-): string | null {
- const config = toolRegistry[operation as keyof ToolRegistry]?.operationConfig;
- const endpoint = config?.endpoint;
- if (endpoint) {
- const resolved =
- typeof endpoint === "function" ? endpoint(parameters) : endpoint;
- if (resolved) return resolved;
- }
- // Policy-only operations have no registry entry; resolve them directly.
- return POLICY_OPERATION_ENDPOINTS[operation] ?? null;
-}
-
-/**
- * Convert a tool's UI parameters into the exact scalar form-fields its backend
- * endpoint expects, by running the same `buildFormData` the client-side runner
- * uses (the one source of truth for the request shape) and keeping its non-file
- * fields. This is what makes the stored steps "marry up" with the engine: e.g.
- * redact's `wordsToRedact: string[]` becomes the `listOfText` string the
- * /auto-redact endpoint reads. Falls back to the raw params if the tool has no
- * transform (or it throws), so tools without one are unaffected.
- */
-function toApiParameters(
- config: ToolRegistry[keyof ToolRegistry]["operationConfig"] | undefined,
- parameters: Record<string, unknown>,
-): Record<string, unknown> {
- const build = config?.buildFormData;
- if (typeof build !== "function") return parameters;
- const dummy = new File([], "input.pdf", { type: "application/pdf" });
- // buildFormData takes a File (single-file tools) or File[] (multi) — try both.
- for (const fileArg of [dummy, [dummy]]) {
- try {
- const formData = build(parameters, fileArg as never);
- const out: Record<string, unknown> = {};
- // Keep scalar fields; skip File entries (the document(s) the engine feeds
- // separately, and any supporting-file blobs).
- formData.forEach((value, key) => {
- if (typeof value === "string") out[key] = value;
- });
- return out;
- } catch {
- // Wrong file-arg shape for this tool — try the other, then give up.
- }
- }
- return parameters;
-}
-
-/**
- * Map a frontend automation to the backend pipeline definition. Steps whose
- * endpoint can't be resolved from the registry are dropped (and reported), so
- * the backend never receives an unrunnable operation id.
- */
-export function buildPipelineDefinition(
- automation: Pick<AutomationConfig, "name" | "operations">,
- toolRegistry: Partial<ToolRegistry>,
-): { definition: BackendPipelineDefinition; unresolved: string[] } {
- const unresolved: string[] = [];
- const steps: BackendPipelineStep[] = [];
- for (const op of automation.operations) {
- const parameters = (op.parameters ?? {}) as Record<string, unknown>;
- const endpoint = resolveEndpoint(op.operation, parameters, toolRegistry);
- if (!endpoint) {
- unresolved.push(op.operation);
- continue;
- }
- const config =
- toolRegistry[op.operation as keyof ToolRegistry]?.operationConfig;
- steps.push({
- operation: endpoint,
- parameters: toApiParameters(config, parameters),
- });
- }
- return {
- definition: {
- name: automation.name,
- steps,
- outputs: [{ type: "inline", options: {} }],
- },
- unresolved,
- };
-}
-
-/** A frontend policy ready to persist on the backend (the full settings set). */
-export interface PolicyToStore {
- /** Existing backend id (blank/omitted → create). */
- id?: string;
- /** The frontend catalog category this policy belongs to (1 policy per category). */
- categoryId: string;
- name: string;
- /** Active (enabled) vs paused/off. */
- enabled: boolean;
- /** Full frontend automation, stashed for a lossless UI round-trip. */
- automation: AutomationConfig;
- /**
- * The engine-runnable steps (endpoint paths), pre-built from `automation` via
- * the tool registry by the caller that has it (the wizard). The store layer
- * has no registry, so it receives these ready-made.
- */
- pipelineSteps: BackendPipelineStep[];
- sources: string[];
- runsOnEditor: boolean;
- scopeTypes: string[];
- reviewerEmail: string;
- fieldValues: Record<string, boolean | string | string[]>;
- folder: PolicyFolderSettings;
-}
-
/** The decoded policy read back from the backend. */
export interface DecodedPolicy {
id: string;
@@ -262,50 +132,6 @@ const DEFAULT_FOLDER: PolicyFolderSettings = {
retryDelayMinutes: 5,
};
-/**
- * Map a frontend policy to the backend {@link BackendPolicy} for persistence.
- * Policies are manual-only (client-driven): the editor fires runs on upload /
- * before export via /run, so `trigger` is null (a server-side folder-watch or
- * schedule trigger doesn't fit the in-editor model, and a null trigger skips
- * trigger validation on the backend). The backend models only
- * name/enabled/trigger/steps/output, so the policy-level extras (categoryId,
- * sources, scope, reviewer, fields) and the output + retry settings all ride in
- * `output.options`; the full frontend automation is stashed in
- * `output.options.automation` for a lossless UI round-trip (while `steps`
- * carries the endpoint-mapped pipeline the engine runs, pre-built by the caller).
- */
-export function buildBackendPolicy(input: PolicyToStore): BackendPolicy {
- return {
- id: input.id ?? "",
- name: input.name,
- owner: "",
- enabled: input.enabled,
- trigger: null,
- steps: input.pipelineSteps,
- output: {
- type: "inline",
- options: {
- mode: input.folder.outputMode,
- name: input.folder.outputName,
- position: input.folder.outputNamePosition,
- maxRetries: input.folder.maxRetries,
- retryDelayMinutes: input.folder.retryDelayMinutes,
- automation: input.automation,
- // Policy-level metadata (no trigger bag to hold it any more).
- categoryId: input.categoryId,
- sources: input.sources,
- scopeTypes: input.scopeTypes,
- reviewerEmail: input.reviewerEmail,
- fieldValues: input.fieldValues,
- },
- },
- editor: {
- allowed: input.runsOnEditor,
- runOn: input.folder.runOn,
- },
- };
-}
-
/** Decode a stored backend policy back into the frontend settings. */
export function fromBackendPolicy(policy: BackendPolicy): DecodedPolicy {
const output = policy.output.options;
diff --git a/frontend/editor/src/proprietary/services/policyStorage.test.ts b/frontend/editor/src/proprietary/services/policyStorage.test.ts
index 24f2b37af3..3f7dd48c11 100644
--- a/frontend/editor/src/proprietary/services/policyStorage.test.ts
+++ b/frontend/editor/src/proprietary/services/policyStorage.test.ts
@@ -2,7 +2,6 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
import {
loadPolicies,
updatePolicy,
- resetPolicy,
onPoliciesChange,
} from "@app/services/policyStorage";
@@ -14,17 +13,17 @@ describe("policyStorage", () => {
it("defaults every category to unconfigured (backend is the source of truth)", () => {
const p = loadPolicies();
expect(p.ingestion.configured).toBe(false);
- expect(p.ingestion.status).toBe("default");
+ expect(p.ingestion.enabled).toBe(false);
expect(p.security.configured).toBe(false);
- expect(p.security.status).toBe("default");
+ expect(p.security.enabled).toBe(false);
expect(p.retention.configured).toBe(false);
});
it("persists an update and reflects it on reload", () => {
- updatePolicy("security", { configured: true, status: "active" });
+ updatePolicy("security", { configured: true, enabled: true });
const reloaded = loadPolicies();
expect(reloaded.security.configured).toBe(true);
- expect(reloaded.security.status).toBe("active");
+ expect(reloaded.security.enabled).toBe(true);
// Other categories untouched.
expect(reloaded.retention.configured).toBe(false);
});
@@ -37,22 +36,10 @@ describe("policyStorage", () => {
expect(p.security.reviewerEmail).toBe("[email protected]");
});
- it("resetPolicy reverts a category to unconfigured default", () => {
- updatePolicy("compliance", {
- configured: true,
- status: "active",
- reviewerEmail: "[email protected]",
- });
- resetPolicy("compliance");
- const p = loadPolicies();
- expect(p.compliance.configured).toBe(false);
- expect(p.compliance.status).toBe("default");
- });
-
it("heals missing categories from corrupt/partial storage", () => {
localStorage.setItem(
"stirling-policies-state",
- JSON.stringify({ ingestion: { configured: true, status: "active" } }),
+ JSON.stringify({ ingestion: { configured: true, enabled: true } }),
);
const p = loadPolicies();
// Missing category gets a default rather than being undefined.
@@ -65,7 +52,7 @@ describe("policyStorage", () => {
localStorage.setItem(
"stirling-policies-state",
JSON.stringify({
- security: { configured: true, status: "active", sources: ["s3"] },
+ security: { configured: true, enabled: true, sources: ["s3"] },
}),
);
// Without the migration the default (true) would wrongly win.
@@ -76,7 +63,7 @@ describe("policyStorage", () => {
localStorage.setItem(
"stirling-policies-state",
JSON.stringify({
- security: { configured: true, status: "active", sources: ["editor"] },
+ security: { configured: true, enabled: true, sources: ["editor"] },
}),
);
expect(loadPolicies().security.runsOnEditor).toBe(true);
@@ -88,7 +75,7 @@ describe("policyStorage", () => {
JSON.stringify({
security: {
configured: true,
- status: "active",
+ enabled: true,
sources: ["editor"],
runsOnEditor: false,
},
@@ -100,10 +87,10 @@ describe("policyStorage", () => {
it("fires a change event on update", () => {
const cb = vi.fn();
const off = onPoliciesChange(cb);
- updatePolicy("routing", { status: "paused" });
+ updatePolicy("routing", { enabled: false });
expect(cb).toHaveBeenCalledTimes(1);
off();
- updatePolicy("routing", { status: "active" });
+ updatePolicy("routing", { enabled: true });
expect(cb).toHaveBeenCalledTimes(1); // not called after unsubscribe
});
});
diff --git a/frontend/editor/src/proprietary/services/policyStorage.ts b/frontend/editor/src/proprietary/services/policyStorage.ts
index 51d927c729..1b564e2ec0 100644
--- a/frontend/editor/src/proprietary/services/policyStorage.ts
+++ b/frontend/editor/src/proprietary/services/policyStorage.ts
@@ -17,7 +17,7 @@ function defaultState(categoryId: string): PolicyState {
// actually configured + active; this is just the empty local-cache shape.
return {
configured: false,
- status: "default",
+ enabled: false,
sources: ["editor"],
runsOnEditor: true,
scopeTypes: [],
@@ -113,24 +113,6 @@ export function updatePolicy(
return next;
}
-/**
- * Persist a new execution order. Assigns `order` 0..n-1 to the given categories in
- * the sequence provided, so after any reorder every listed policy has an explicit,
- * contiguous order (no reliance on the catalog-index default). Categories omitted
- * from the list keep their current order.
- */
-export function reorderPolicies(
- orderedCategoryIds: string[],
-): PoliciesByCategory {
- const current = loadPolicies();
- const next: PoliciesByCategory = { ...current };
- orderedCategoryIds.forEach((id, index) => {
- if (next[id]) next[id] = { ...next[id], order: index };
- });
- persist(next);
- return next;
-}
-
/**
* Drop cached entries entirely (no default seeded back). For builder pipelines the backend has
* deleted: keyed by their own id, they have no built-in category to fall back to, so a left-behind
@@ -151,18 +133,6 @@ export function forgetPolicies(ids: string[]): PoliciesByCategory {
return next;
}
-/** Reset a category to its unconfigured default (the "Delete policy" action). */
-export function resetPolicy(categoryId: string): PoliciesByCategory {
- return updatePolicy(categoryId, {
- ...defaultState(categoryId),
- configured: false,
- status: "default",
- // Drop the backing-folder + backend links (the caller deletes those).
- folderId: undefined,
- backendId: undefined,
- });
-}
-
/** Subscribe to policy-state changes (same-tab). Returns an unsubscribe fn. */
export function onPoliciesChange(cb: () => void): () => void {
if (typeof window === "undefined") return () => {};
diff --git a/frontend/editor/src/proprietary/types/policies.ts b/frontend/editor/src/proprietary/types/policies.ts
index 6e178b15d4..4955ae20c1 100644
--- a/frontend/editor/src/proprietary/types/policies.ts
+++ b/frontend/editor/src/proprietary/types/policies.ts
@@ -9,26 +9,6 @@
*/
import type { ReactNode } from "react";
-import type {
- AutomationConfig,
- AutomationOperation,
-} from "@app/types/automation";
-
-/** Lifecycle status of a policy category for the current user/org. */
-export type PolicyStatus = "default" | "active" | "paused";
-
-/** A configurable field within a policy's settings. */
-export type PolicyFieldType = "toggle" | "select" | "chips" | "text";
-
-export interface PolicyField {
- label: string;
- key: string;
- type: PolicyFieldType;
- /** Current value: boolean (toggle), string (select/text), string[] (chips). */
- value: boolean | string | string[];
- /** Options for select/chips. */
- options?: string[];
-}
/** Static definition of a policy category (the "what it does"). */
export interface PolicyCategory {
@@ -55,70 +35,13 @@ export interface PolicyCategory {
requiresAiEngine?: boolean;
}
-/**
- * The three-up summary stats shown at the foot of a configured policy's detail,
- * derived live from the user's uploaded files.
- */
-export interface PolicyStats {
- /** Documents enforced (rendered with toLocaleString). */
- enforced: number;
- /** Human-formatted data-processed figure, e.g. "2.3 GB". */
- dataProcessed: string;
- /** Human-formatted active-for figure, e.g. "12d", or "—" when idle. */
- activeFor: string;
-}
-
-/** The narrative + field configuration backing a category. */
-export interface PolicyConfigDef {
- /** One-line summary of what the policy enforces. */
- summary: string;
- /** Pipeline-like rule chips shown in the "Enforces" section. */
- rules: string[];
- /** Human label for the scope this policy applies to. */
- scopeLabel: string;
- /** Editable settings fields. */
- fields: PolicyField[];
- /**
- * The preset pipeline this category seeds a new policy with — the real,
- * editable tool steps (same shape as the backend's `PipelineStep` and the
- * Watch Folders automation `operations`). Configuring a policy starts from
- * these and the user can edit them.
- */
- defaultOperations: AutomationOperation[];
-}
-
-/** A document a source can ingest, used in the wizard's "Sources" step. */
-export interface PolicySource {
- id: string;
- label: string;
- desc: string;
- icon: ReactNode;
-}
-
-/** An entry in a policy's recent-activity feed (derived from real uploads). */
-export interface PolicyActivityItem {
- /** Document the policy acted on. */
- doc: string;
- /** What the policy did, e.g. "Classified as Contract • 3 tables extracted". */
- action: string;
- /** Relative timestamp, e.g. "2h ago". */
- time: string;
- /**
- * "enforced" (clean green), "flagged" (needs review, amber), or "processing"
- * (in progress — enforcement currently running, blue).
- */
- status: "enforced" | "flagged" | "processing";
- /** The backend run this row reflects — used to offer Retry on a failed run. */
- runId?: string;
- /** The file the run acted on — needed to re-run it on Retry. */
- fileId?: string;
-}
-
/** Per-category runtime state held in the local cache. */
export interface PolicyState {
configured: boolean;
- status: PolicyStatus;
- /** Selected sources (ids from POLICY_SOURCES). */
+ /** Whether the backend policy is enabled (fires on the editor). Meaningful only
+ * when `configured`; false otherwise. Mirrors the backend `Policy.enabled`. */
+ enabled: boolean;
+ /** Selected source ids. */
sources: string[];
/** The policy's own name. Set for builder pipelines, which have no built-in category label. */
name?: string;
@@ -185,52 +108,3 @@ export interface PolicyFolderSettings {
maxRetries: number;
retryDelayMinutes: number;
}
-
-/** Everything the shared policy wizard collects, handed back on submit. */
-export interface PolicyWizardResult {
- /** The saved workflow automation (created on setup, updated in place on edit). */
- automation: AutomationConfig;
- fieldValues: Record<string, boolean | string | string[]>;
- sources: string[];
- runsOnEditor: boolean;
- scopeTypes: string[];
- reviewerEmail: string;
- /** Output + retry settings for the backing folder. */
- folder: PolicyFolderSettings;
- /**
- * Backend pipeline steps (each `operation` is a tool ENDPOINT path), built
- * from the workflow via the tool registry in the wizard's Workflow step — the
- * hook persists these to the backend without needing the registry itself.
- * Structurally matches policyPipeline's `BackendPipelineStep` (inlined here to
- * avoid a types↔services import cycle).
- */
- pipelineSteps: {
- operation: string;
- parameters: Record<string, unknown>;
- fileParameters?: Record<string, string>;
- }[];
- /** Operation ids whose endpoint couldn't be resolved (dropped from steps). */
- unresolvedOps: string[];
-}
-
-/**
- * What the locked tool-config page hands back on save. Unlike the wizard's
- * result it carries the tool `operations` directly (the page owns a fixed,
- * configure-only chain — there's no separate saved automation), plus the
- * endpoint-mapped pipeline steps. Used for both first-time configure and edits
- * of a preset policy.
- */
-export interface PolicyConfigResult {
- /** The enabled tools (in order) as automation operations. */
- operations: AutomationOperation[];
- /** Endpoint-mapped backend steps built from `operations` via the registry. */
- pipelineSteps: PolicyWizardResult["pipelineSteps"];
- /** Operation ids whose endpoint couldn't be resolved (dropped from steps). */
- unresolvedOps: string[];
- fieldValues: Record<string, boolean | string | string[]>;
- sources: string[];
- runsOnEditor: boolean;
- scopeTypes: string[];
- reviewerEmail: string;
- folder: PolicyFolderSettings;
-}