#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Rename the policy key from categoryId, so it stops reading as classification (#7799)
EthanHealy0141b1bb478984
diff --git a/.gitignore b/.gitignoreindex 03a65905e1..ef63336c40 100644--- a/.gitignore+++ b/.gitignore@@ -272,6 +272,8 @@ id_ed25519.pub# node_modulesnode_modules/+# A symlink named node_modules is a file, which the slash form does not match.+node_modules# weasyPrint**/LOCAL_APPDATA_FONTCONFIG_CACHE/**diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsxindex 67fe37cfc2..d0a87d8221 100644--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx@@ -556,7 +556,7 @@ const FileEditorThumbnail = ({zIndex={2}onDismiss={() => setEnforcingDismissed(true)}accentVar={enforcingPolicy?.accentColor}- categoryId={enforcingPolicy?.id}+ policyKey={enforcingPolicy?.id}/>{/* Thumbnail image or loading state */}diff --git a/frontend/editor/src/core/components/policies/policyCategoryIcon.tsx b/frontend/editor/src/core/components/policies/policyCategoryIcon.tsxindex bf50c76037..142dfcdaf8 100644--- a/frontend/editor/src/core/components/policies/policyCategoryIcon.tsx+++ b/frontend/editor/src/core/components/policies/policyCategoryIcon.tsx@@ -27,10 +27,10 @@ const FALLBACK_ICON = LabelOutlinedIcon;// Defaults to inheriting the surrounding font-size so a wrapping box controls size.export function policyCategoryIcon(- categoryId: string,+ policyKey: string,sx: SxProps<Theme> = { fontSize: "inherit" },className?: string,): ReactNode {- const Icon = POLICY_CATEGORY_ICONS[categoryId] ?? FALLBACK_ICON;+ const Icon = POLICY_CATEGORY_ICONS[policyKey] ?? FALLBACK_ICON;return <Icon sx={sx} className={className} />;}diff --git a/frontend/editor/src/core/components/policies/policyRunStore.ts b/frontend/editor/src/core/components/policies/policyRunStore.tsindex 798149a911..17bbdc36ca 100644--- a/frontend/editor/src/core/components/policies/policyRunStore.ts+++ b/frontend/editor/src/core/components/policies/policyRunStore.ts@@ -5,7 +5,7 @@export interface PolicyRunRecord {runId: string;- categoryId: string;+ policyKey: string;fileId: string;fileName: string;status: string;diff --git a/frontend/editor/src/core/components/shared/PolicyEnforcingOverlay.tsx b/frontend/editor/src/core/components/shared/PolicyEnforcingOverlay.tsxindex cdb51952f0..8bc24914f2 100644--- a/frontend/editor/src/core/components/shared/PolicyEnforcingOverlay.tsx+++ b/frontend/editor/src/core/components/shared/PolicyEnforcingOverlay.tsx@@ -5,7 +5,7 @@ export function PolicyEnforcingOverlay(_props: {/** CSS colour var for the enforcing policy's accent; tints the icon/spinner. */accentVar?: string;/** Category of the enforcing policy — picks its icon in the real overlay. */- categoryId?: string;+ policyKey?: string;/** Shows a dismiss control in the real overlay, so a run that never settles* can't leave the surface underneath permanently unclickable. */onDismiss?: () => void;diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.tsindex f622f34a07..498b82658d 100644--- a/frontend/editor/src/portal/api/policies.ts+++ b/frontend/editor/src/portal/api/policies.ts@@ -412,8 +412,8 @@ function decoratePolicy(runs: PolicyRunView[],isDefault: boolean,): DecoratedPolicy | null {- const category = POLICY_CATEGORIES.find((c) => c.id === decoded.categoryId);- const config = POLICY_CONFIG[decoded.categoryId];+ const category = POLICY_CATEGORIES.find((c) => c.id === decoded.policyKey);+ const config = POLICY_CONFIG[decoded.policyKey];if (!category || !config) return null;const policyRuns = runs.filter((r) => r.policyId === decoded.id);@@ -475,8 +475,8 @@ export function assemblePolicies(>();for (const wire of wirePolicies) {const decoded = fromWirePolicy(wire);- if (decoded.categoryId) {- decodedByCategory.set(decoded.categoryId, { decoded, isDefault: false });+ if (decoded.policyKey) {+ decodedByCategory.set(decoded.policyKey, { decoded, isDefault: false });}}@@ -634,7 +634,7 @@ export function buildWireFromSetup(enabled,required: result.required,extraOptions: result.extraOptions,- categoryId: entry.category.id,+ policyKey: entry.category.id,sources: result.sources,runsOnEditor: result.runsOnEditor,scopeTypes: result.scopeTypes,diff --git a/frontend/editor/src/portal/api/processorFlow.ts b/frontend/editor/src/portal/api/processorFlow.tsindex 1ab2f72c62..5795f78d63 100644--- a/frontend/editor/src/portal/api/processorFlow.ts+++ b/frontend/editor/src/portal/api/processorFlow.ts@@ -80,7 +80,7 @@ function buildPolicies(const decoded = wirePolicies.map(fromWirePolicy);return POLICY_CATEGORIES.map((cat) => {- const dp = decoded.find((p) => p.categoryId === cat.id);+ const dp = decoded.find((p) => p.policyKey === cat.id);const configured = Boolean(dp?.enabled);const state: FlowPolicyState = configured? "active"diff --git a/frontend/editor/src/portal/components/policies/storyFixtures.ts b/frontend/editor/src/portal/components/policies/storyFixtures.tsindex 4573f06c9b..f0389ddc4b 100644--- a/frontend/editor/src/portal/components/policies/storyFixtures.ts+++ b/frontend/editor/src/portal/components/policies/storyFixtures.ts@@ -16,9 +16,9 @@ import { seedPolicies, seedPolicyRuns } from "@portal/mocks/policies";export { POLICY_CATEGORIES, POLICY_CONFIG };/** A decorated, active policy for a category, mirroring assemblePolicies(). */-export function decorateForStory(categoryId: string): DecoratedPolicy {- const category = POLICY_CATEGORIES.find((c) => c.id === categoryId)!;- const config = POLICY_CONFIG[categoryId];+export function decorateForStory(policyKey: string): DecoratedPolicy {+ const category = POLICY_CATEGORIES.find((c) => c.id === policyKey)!;+ const config = POLICY_CONFIG[policyKey];// Use the seeded security policy for any category (story only needs the shape).const wire = seedPolicies()[0];diff --git a/frontend/editor/src/portal/mocks/handlers/policies.ts b/frontend/editor/src/portal/mocks/handlers/policies.tsindex 091f16761a..4de45b95a6 100644--- a/frontend/editor/src/portal/mocks/handlers/policies.ts+++ b/frontend/editor/src/portal/mocks/handlers/policies.ts@@ -30,12 +30,12 @@ export function getCataloguePolicies(): WirePolicy[] {}let idCounter = 0;-function nextId(categoryId: string): string {+function nextId(policyKey: string): string {idCounter += 1;- return `pol_${categoryId}_${Date.now().toString(36)}_${idCounter}`;+ return `pol_${policyKey}_${Date.now().toString(36)}_${idCounter}`;}-function categoryId(wire: WirePolicy): string {+function policyKey(wire: WirePolicy): string {return wire.output?.options?.categoryId ?? "";}@@ -62,10 +62,10 @@ export const policiesHandlers = [http.post("/api/v1/policies", async ({ request }) => {await delay(120);const incoming = (await request.json()) as WirePolicy;- const catId = categoryId(incoming);+ const catId = policyKey(incoming);const existing = incoming.id? store.find((p) => p.id === incoming.id)- : store.find((p) => categoryId(p) === catId);+ : store.find((p) => policyKey(p) === catId);const id = existing?.id ?? nextId(catId);const saved: WirePolicy = {...incoming,diff --git a/frontend/editor/src/portal/search/entitySearch.tsx b/frontend/editor/src/portal/search/entitySearch.tsxindex c33b920e7b..f0338bd620 100644--- a/frontend/editor/src/portal/search/entitySearch.tsx+++ b/frontend/editor/src/portal/search/entitySearch.tsx@@ -208,7 +208,7 @@ export function rankPortalPolicyResults(entries: CatalogueEntry[],trimmed: string,t: Translate,- openPolicy: (categoryId: string) => void,+ openPolicy: (policyKey: string) => void,limit = ENTITY_GROUP_LIMIT,): SuperSearchResult[] {return rankByFuzzy(@@ -312,9 +312,9 @@ export function buildProcessorEntityGroups(entities.policies,trimmed,t,- (categoryId) =>+ (policyKey) =>navigate(- `${toPortalPath(VIEW_PATHS.pipelines)}?setup=${encodeURIComponent(categoryId)}`,+ `${toPortalPath(VIEW_PATHS.pipelines)}?setup=${encodeURIComponent(policyKey)}`,),ENTITY_GROUP_LIMIT,)diff --git a/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts b/frontend/editor/src/proprietary/components/policies/classificationLocalPass.tsindex b02f39e2c3..e6d2547740 100644--- a/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts+++ b/frontend/editor/src/proprietary/components/policies/classificationLocalPass.ts@@ -18,7 +18,7 @@ import type { FileId } from "@app/types/file";import type { StirlingFile } from "@app/types/fileContext";import type { HeuristicConfidence } from "@app/services/heuristic/types";import {- CLASSIFICATION_CATEGORY_ID,+ CLASSIFICATION_POLICY_KEY,localVerdictNeedsEscalation,} from "@app/data/classificationPolicy";import type { LocalPass } from "@app/components/policies/policyLocalPass";@@ -86,11 +86,11 @@ async function classifyStub(// Read before recordRunStart, which takes the dispatch key itself and would otherwise always// answer "already dispatched", silently stopping metering.- const alreadyMetered = isDispatched(CLASSIFICATION_CATEGORY_ID, fileId);- const runId = `local-${CLASSIFICATION_CATEGORY_ID}-${fileId}-${Date.now()}`;+ const alreadyMetered = isDispatched(CLASSIFICATION_POLICY_KEY, fileId);+ const runId = `local-${CLASSIFICATION_POLICY_KEY}-${fileId}-${Date.now()}`;recordRunStart({runId,- categoryId: CLASSIFICATION_CATEGORY_ID,+ policyKey: CLASSIFICATION_POLICY_KEY,fileId: fileId as string,fileName,fileSize,@@ -126,7 +126,7 @@ async function classifyStub(labels,});}- markDispatched(CLASSIFICATION_CATEGORY_ID, fileId);+ markDispatched(CLASSIFICATION_POLICY_KEY, fileId);// Labels, no output file - the same settle shape the server-run classification uses.updateRun(runId, {status: "COMPLETED",diff --git a/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts b/frontend/editor/src/proprietary/components/policies/policyLocalPass.tsindex a8bfec2c12..e0deda6fa2 100644--- a/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts+++ b/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts@@ -7,7 +7,7 @@import type { FileId } from "@app/types/file";import type { StirlingFileStub } from "@app/types/fileContext";-import { CLASSIFICATION_CATEGORY_ID } from "@app/data/classificationPolicy";+import { CLASSIFICATION_POLICY_KEY } from "@app/data/classificationPolicy";import { classificationLocalPass } from "@app/components/policies/classificationLocalPass";export interface LocalPassResult {@@ -28,7 +28,7 @@ export interface LocalPass {}/** The local fast path a policy declares, if any. The default (most policies) is none. */-export function localPassFor(categoryId: string): LocalPass | undefined {- if (categoryId === CLASSIFICATION_CATEGORY_ID) return classificationLocalPass;+export function localPassFor(policyKey: string): LocalPass | undefined {+ if (policyKey === CLASSIFICATION_POLICY_KEY) return classificationLocalPass;return undefined;}diff --git a/frontend/editor/src/proprietary/components/policies/policyRunSettles.test.ts b/frontend/editor/src/proprietary/components/policies/policyRunSettles.test.tsindex c3c6be7137..df77d38273 100644--- a/frontend/editor/src/proprietary/components/policies/policyRunSettles.test.ts+++ b/frontend/editor/src/proprietary/components/policies/policyRunSettles.test.ts@@ -9,7 +9,7 @@ import type { PolicyRunRecord } from "@app/components/policies/policyRunStore";*/const run = (overrides: Partial<PolicyRunRecord> = {}): PolicyRunRecord => ({runId: "r",- categoryId: "security",+ policyKey: "security",fileId: "f",fileName: "f.pdf",fileSize: 1,@@ -44,7 +44,7 @@ describe("finishedWithNothingToDeliver", () => {it("leaves classification alone - it settles via its own label path", () => {expect(- finishedWithNothingToDeliver(run({ categoryId: "classification" })),+ finishedWithNothingToDeliver(run({ policyKey: "classification" })),).toBe(false);});});diff --git a/frontend/editor/src/proprietary/components/policies/policyRunStore.test.ts b/frontend/editor/src/proprietary/components/policies/policyRunStore.test.tsindex dce75563fd..5a099e62c4 100644--- a/frontend/editor/src/proprietary/components/policies/policyRunStore.test.ts+++ b/frontend/editor/src/proprietary/components/policies/policyRunStore.test.ts@@ -1,6 +1,6 @@-import { describe, it, expect, beforeEach } from "vitest";+import { describe, it, expect, beforeEach, vi } from "vitest";import {- appliedCategoriesFor,+ appliedPoliciesFor,dispatchKey,getRun,isDispatched,@@ -15,7 +15,7 @@ import {function rec(over: Partial<PolicyRunRecord>): PolicyRunRecord {return {runId: "r1",- categoryId: "security",+ policyKey: "security",fileId: "f1",fileName: "f.pdf",fileSize: 10,@@ -39,6 +39,25 @@ describe("policyRunStore", () => {resetPolicyRuns();});+ it("reads a run recorded before the key was renamed", async () => {+ // Persisted records predate policyKey; without the migration their policy is undefined, so+ // the badge disappears and the chain re-runs from the start. The store reads storage at+ // import, so this asserts against a fresh one rather than the module already loaded.+ localStorage.setItem(+ "stirling-policy-runs",+ JSON.stringify({+ runs: [{ ...rec({}), policyKey: undefined, categoryId: "security" }],+ dispatched: [],+ waveStartedAt: 0,+ }),+ );+ vi.resetModules();++ const fresh = await import("@app/components/policies/policyRunStore");++ expect(fresh.getRun("r1")?.policyKey).toBe("security");+ });+it("records a run start and marks the (policy, file) pair dispatched", () => {expect(isDispatched("security", "f1")).toBe(false);recordRunStart(rec({}));@@ -85,22 +104,22 @@ describe("policyRunStore", () => {});it("a real backend run still claims the dispatch key", () => {- recordRunStart(rec({ runId: "srv-1", categoryId: "classification" }));+ recordRunStart(rec({ runId: "srv-1", policyKey: "classification" }));expect(isDispatched("classification", "f1")).toBe(true);});- describe("appliedCategoriesFor", () => {+ describe("appliedPoliciesFor", () => {it("walks a rewriting chain back to the uploaded document", () => {recordRunStart(- rec({ runId: "r-w", categoryId: "watermark", fileId: "f1" }),+ rec({ runId: "r-w", policyKey: "watermark", fileId: "f1" }),);updateRun("r-w", { status: "COMPLETED", outputFileIds: ["f2"] });recordRunStart(- rec({ runId: "r-s", categoryId: "security", fileId: "f2" }),+ rec({ runId: "r-s", policyKey: "security", fileId: "f2" }),);updateRun("r-s", { status: "COMPLETED", outputFileIds: ["f3"] });- expect([...appliedCategoriesFor("f3")].sort()).toEqual([+ expect([...appliedPoliciesFor("f3")].sort()).toEqual(["security","watermark",]);@@ -108,11 +127,11 @@ describe("policyRunStore", () => {it("counts an annotating run, which names its input as its own output", () => {recordRunStart(- rec({ runId: "r-c", categoryId: "classification", fileId: "f1" }),+ rec({ runId: "r-c", policyKey: "classification", fileId: "f1" }),);updateRun("r-c", { status: "COMPLETED", outputFileIds: ["f1"] });- expect([...appliedCategoriesFor("f1")]).toEqual(["classification"]);+ expect([...appliedPoliciesFor("f1")]).toEqual(["classification"]);});it("does not count a browser-local pass as the policy having run", () => {@@ -121,7 +140,7 @@ describe("policyRunStore", () => {recordRunStart(rec({runId: "local-c",- categoryId: "classification",+ policyKey: "classification",fileId: "f1",target: "local",browserLocal: true,@@ -129,22 +148,22 @@ describe("policyRunStore", () => {);updateRun("local-c", { status: "COMPLETED", outputFileIds: ["f1"] });- expect(appliedCategoriesFor("f1").size).toBe(0);+ expect(appliedPoliciesFor("f1").size).toBe(0);});it("keeps climbing past an annotating run rather than stalling on it", () => {// The annotating run's output IS its input, so the walk must not treat that as a// lineage step - otherwise the cursor never moves and earlier policies are missed.recordRunStart(- rec({ runId: "r-w", categoryId: "watermark", fileId: "f1" }),+ rec({ runId: "r-w", policyKey: "watermark", fileId: "f1" }),);updateRun("r-w", { status: "COMPLETED", outputFileIds: ["f2"] });recordRunStart(- rec({ runId: "r-c", categoryId: "classification", fileId: "f2" }),+ rec({ runId: "r-c", policyKey: "classification", fileId: "f2" }),);updateRun("r-c", { status: "COMPLETED", outputFileIds: ["f2"] });- expect([...appliedCategoriesFor("f2")].sort()).toEqual([+ expect([...appliedPoliciesFor("f2")].sort()).toEqual(["classification","watermark",]);@@ -152,11 +171,11 @@ describe("policyRunStore", () => {it("ignores a run that failed, so it stays eligible to run again", () => {recordRunStart(- rec({ runId: "r-f", categoryId: "security", fileId: "f1" }),+ rec({ runId: "r-f", policyKey: "security", fileId: "f1" }),);updateRun("r-f", { status: "FAILED", outputFileIds: ["f2"] });- expect(appliedCategoriesFor("f2").size).toBe(0);+ expect(appliedPoliciesFor("f2").size).toBe(0);});});diff --git a/frontend/editor/src/proprietary/components/policies/policyRunStore.ts b/frontend/editor/src/proprietary/components/policies/policyRunStore.tsindex 94f7ae2a0d..e5e26b1a32 100644--- a/frontend/editor/src/proprietary/components/policies/policyRunStore.ts+++ b/frontend/editor/src/proprietary/components/policies/policyRunStore.ts@@ -3,7 +3,7 @@** The auto-run controller fires a backend run for each enabled policy × each* newly-uploaded file and records it here; the detail view's activity feed reads- * from it. `dispatched` keys (`categoryId:fileId`) ensure a given file is only+ * from it. `dispatched` keys (`policyKey:fileId`) ensure a given file is only* ever run once per policy, surviving remounts via localStorage.** Read with {@code useSyncExternalStore}; mutated by the controller.@@ -17,7 +17,7 @@ import type {export interface PolicyRunRecord {runId: string;- categoryId: string;+ policyKey: string;fileId: string;fileName: string;fileSize: number;@@ -128,6 +128,10 @@ function read(): RunState {runs: Array.isArray(parsed.runs)? parsed.runs.map((r) => ({...r,+ // Records written before the rename carry the key as `categoryId`. Without this+ // their policy is undefined, so badges vanish and a retry re-runs the whole chain.+ policyKey:+ r.policyKey ?? (r as { categoryId?: string }).categoryId ?? "",outputs: Array.isArray(r.outputs) ? r.outputs : [],importedFileIds: Array.isArray(r.importedFileIds)? r.importedFileIds@@ -202,17 +206,17 @@ export function hasInFlightPolicyRuns(): boolean {}/** Key identifying a single (policy, file) run attempt. */-export function dispatchKey(categoryId: string, fileId: string): string {- return `${categoryId}:${fileId}`;+export function dispatchKey(policyKey: string, fileId: string): string {+ return `${policyKey}:${fileId}`;}/** Whether this (policy, file) pair has already been dispatched. */-export function isDispatched(categoryId: string, fileId: string): boolean {- return state.dispatched.includes(dispatchKey(categoryId, fileId));+export function isDispatched(policyKey: string, fileId: string): boolean {+ return state.dispatched.includes(dispatchKey(policyKey, fileId));}/** Walked back through this document's lineage. Only a COMPLETED server run counts as applied. */-export function appliedCategoriesFor(fileId: string): Set<string> {+export function appliedPoliciesFor(fileId: string): Set<string> {const applied = new Set<string>();let cursor: string | null = fileId;// A lineage cannot outrun the recorded runs, and the bound also breaks a hand-edited cycle.@@ -224,7 +228,7 @@ export function appliedCategoriesFor(fileId: string): Set<string> {// A local first pass is not the policy's run: counting it would skip the escalation.if (run.status !== "COMPLETED" || run.browserLocal) continue;if (!(run.outputFileIds ?? []).includes(child)) continue;- applied.add(run.categoryId);+ applied.add(run.policyKey);// An annotating run names its input as its own output, so it adds no lineage step.if (run.fileId !== child) cursor = run.fileId;}@@ -234,7 +238,7 @@ export function appliedCategoriesFor(fileId: string): Set<string> {/** Record a newly-dispatched run (marks it dispatched + adds the record). */export function recordRunStart(record: PolicyRunRecord) {- const key = dispatchKey(record.categoryId, record.fileId);+ const key = dispatchKey(record.policyKey, record.fileId);// A run recorded while nothing else is in flight begins a fresh wave, so the// progress counts reset to this upload instead of accumulating across every// past upload persisted in localStorage.@@ -264,8 +268,8 @@ export function addReconciledRun(record: PolicyRunRecord) {}/** Mark a (policy, file) pair dispatched without a run (e.g. dispatch failed). */-export function markDispatched(categoryId: string, fileId: string) {- const key = dispatchKey(categoryId, fileId);+export function markDispatched(policyKey: string, fileId: string) {+ const key = dispatchKey(policyKey, fileId);if (state.dispatched.includes(key)) return;state = { ...state, dispatched: [...state.dispatched, key] };emit();diff --git a/frontend/editor/src/proprietary/components/policies/policyStatus.ts b/frontend/editor/src/proprietary/components/policies/policyStatus.tsindex d06a8bdea8..ba6a1baa23 100644--- a/frontend/editor/src/proprietary/components/policies/policyStatus.ts+++ b/frontend/editor/src/proprietary/components/policies/policyStatus.ts@@ -25,6 +25,6 @@ const BADGE_ACCENT: Record<string, string> = {* CSS colour var for a policy category's badge accent (blue for unknown* categories) — the tint used by the file badges and the enforcement overlay.*/-export function policyAccentVar(categoryId: string): string {- return `var(--color-${BADGE_ACCENT[categoryId] ?? "blue"})`;+export function policyAccentVar(policyKey: string): string {+ return `var(--color-${BADGE_ACCENT[policyKey] ?? "blue"})`;}diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsxindex 6c5d322a28..3c965d878d 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx@@ -295,9 +295,9 @@ describe("policy auto-run — 61-file batch through a Security → Classificatioawait runUntilSettled(FILE_COUNT * 2);const classification = latestRuns.filter(- (r) => r.categoryId === "classification",+ (r) => r.policyKey === "classification",);- const security = latestRuns.filter((r) => r.categoryId === "security");+ const security = latestRuns.filter((r) => r.policyKey === "security");expect(classification).toHaveLength(FILE_COUNT);expect(security).toHaveLength(FILE_COUNT);@@ -348,7 +348,7 @@ describe("policy auto-run — 61-file batch through a Security → Classificatioawait vi.waitFor(() => {const security = latestRuns.filter(- (r) => r.categoryId === "security" && r.imported,+ (r) => r.policyKey === "security" && r.imported,);expect(security).toHaveLength(FILE_COUNT);},@@ -374,7 +374,7 @@ describe("policy auto-run — 61-file batch through a Security → Classificatioawait vi.waitFor(() => {const classification = latestRuns.filter(- (r) => r.categoryId === "classification" && r.imported,+ (r) => r.policyKey === "classification" && r.imported,);expect(classification).toHaveLength(FILE_COUNT);},@@ -383,7 +383,7 @@ describe("policy auto-run — 61-file batch through a Security → Classificatio});// The export policy did not run on upload; nothing versioned in place.- expect(latestRuns.filter((r) => r.categoryId === "security")).toHaveLength(+ expect(latestRuns.filter((r) => r.policyKey === "security")).toHaveLength(0,);expect(mocks.consumeSilentCalls).toBe(0);diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsxindex 4b013c465d..9a62ea208d 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx@@ -77,13 +77,13 @@ function setFileStubs(next: typeof fileStubs) {function completeRun(runId: string,- categoryId: string,+ policyKey: string,fileId: string,outputFileIds: string[],) {recordRunStart({runId,- categoryId,+ policyKey,fileId,fileName: "doc.pdf",fileSize: 100,@@ -192,7 +192,7 @@ describe("auto-run ordered chaining", () => {// A browser-local heuristic run and a real server run, both left in flight.recordRunStart({runId: "local-1",- categoryId: "classification",+ policyKey: "classification",fileId: "f1",fileName: "d.pdf",fileSize: 1,@@ -205,7 +205,7 @@ describe("auto-run ordered chaining", () => {});recordRunStart({runId: "srv-1",- categoryId: "security",+ policyKey: "security",fileId: "f2",fileName: "d.pdf",fileSize: 1,diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsxindex 7cad7095c2..28853e84aa 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx@@ -77,7 +77,7 @@ import {function recordCompletedRun() {recordRunStart({runId: "run-1",- categoryId: "security",+ policyKey: "security",fileId: "file-1",fileName: "doc.pdf",fileSize: 1234,diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsxindex 26515a38f5..42e1b0fa06 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx@@ -146,7 +146,7 @@ beforeEach(() => {// for it to pick up rather than driving a dispatch.recordRunStart({runId: "run-0",- categoryId: "classification",+ policyKey: "classification",fileId: "file-0",fileName: "doc.pdf",fileSize: 100,diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsxindex 47343abf8b..8f148aa00e 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx@@ -86,7 +86,7 @@ describe("auto-run queue-rejection retry", () => {recordRunStart({runId: "run-1",- categoryId: "security",+ policyKey: "security",fileId: "file-1",fileName: "doc.pdf",fileSize: 1234,diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.tsindex c2d7f5a994..0ed36afa09 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts@@ -38,12 +38,12 @@ import type { FileId } from "@app/types/file";import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";import { readClassificationLabelsFromFile } from "@app/services/fileClassification";import {- orderedRewritingCategories,+ orderedRewritingPolicies,policyDeliversOutputFiles,} from "@app/data/classificationPolicy";import { runPolicyOnFile } from "@app/services/policyDispatch";import type { StirlingFile, StirlingFileStub } from "@app/types/fileContext";-import type { PoliciesByCategory } from "@app/types/policies";+import type { PoliciesByKey } from "@app/types/policies";import { usePolicies } from "@app/hooks/usePolicies";import {addReconciledRun,@@ -117,7 +117,7 @@ export function finishedWithNothingToDeliver(run: PolicyRunRecord): boolean {!run.imported &&(run.outputs?.length ?? 0) === 0 &&// An annotating policy settles on labels, not an output file.- policyDeliversOutputFiles(run.categoryId)+ policyDeliversOutputFiles(run.policyKey));}@@ -155,8 +155,8 @@ export function usePolicyAutoRun(): void {// accumulate instead of racing to fork the same version. Annotating policies (classification) are// absent by design: they run themselves (local pass, then AI escalation), so the engine never sees// their two ways to run.- const orderedUploadCategories = useMemo(- () => orderedRewritingCategories(policies),+ const orderedUploadPolicyKeys = useMemo(+ () => orderedRewritingPolicies(policies),[policies],);@@ -185,9 +185,9 @@ export function usePolicyAutoRun(): void {if (!rec) return;// A reconciled run has no local fileId to re-dispatch; leave it failed.if (!rec.fileId) return;- const key = dispatchKey(rec.categoryId, rec.fileId);+ const key = dispatchKey(rec.policyKey, rec.fileId);const attempts = queueRetries.current.get(key) ?? 0;- const backendId = policiesRef.current[rec.categoryId]?.backendId;+ const backendId = policiesRef.current[rec.policyKey]?.backendId;if (attempts >= MAX_QUEUE_RETRIES || !backendId) {queueRetries.current.delete(key);return;@@ -199,7 +199,7 @@ export function usePolicyAutoRun(): void {() => {removeRun(runId);void runPolicyOnFile(- rec.categoryId,+ rec.policyKey,backendId,rec.fileId as FileId,rec.fileName,@@ -220,7 +220,7 @@ export function usePolicyAutoRun(): void {const finished = getRun(view.runId);if (finished) {queueRetries.current.delete(- dispatchKey(finished.categoryId, finished.fileId),+ dispatchKey(finished.policyKey, finished.fileId),);}// Read now rather than leaving them a poll interval to hear about their own upload.@@ -237,9 +237,9 @@ export function usePolicyAutoRun(): void {// Fire only the FIRST upload policy per file; the chaining effect below runs the rest// on each previous output, so policies apply cumulatively in order.useEffect(() => {- const firstCategory = orderedUploadCategories[0];- if (!firstCategory) return;- const backendId = policies[firstCategory]?.backendId;+ const firstPolicyKey = orderedUploadPolicyKeys[0];+ if (!firstPolicyKey) return;+ const backendId = policies[firstPolicyKey]?.backendId;if (!backendId) return;for (const stub of fileStubs) {// Input-mode policies cover uploads only; tool-produced files are left to@@ -249,22 +249,22 @@ export function usePolicyAutoRun(): void {// about to decrypt, bill for it, and leave a row about a version soon replaced. Skipping// the prompt releases it, so a document nobody unlocks still records its failure.if (isAwaitingUnlock(stub.id)) continue;- const key = dispatchKey(firstCategory, stub.id);+ const key = dispatchKey(firstPolicyKey, stub.id);// Skip if already run (persisted) or in flight - the in-memory guard covers the async wait.if (- isDispatched(firstCategory, stub.id) ||+ isDispatched(firstPolicyKey, stub.id) ||dispatching.current.has(key)) {continue;}dispatching.current.add(key);- void runPolicyOnFile(firstCategory, backendId, stub.id, stub.name)+ void runPolicyOnFile(firstPolicyKey, backendId, stub.id, stub.name).catch(() => {// Backstop: runPolicyOnFile handles its own failures.}).finally(() => dispatching.current.delete(key));}- }, [fileStubs, policies, orderedUploadCategories, unlocksVersion]);+ }, [fileStubs, policies, orderedUploadPolicyKeys, unlocksVersion]);// Once a run's output lands, fire the next upload policy on it - success only, once per// run. isDispatched guards re-dispatch across reloads.@@ -272,26 +272,26 @@ export function usePolicyAutoRun(): void {for (const run of runs) {if (run.status !== "COMPLETED" || !run.imported) continue;if (chained.current.has(run.runId)) continue;- const nextCategory = nextUploadCategory(- orderedUploadCategories,- run.categoryId,+ const nextPolicyKey = nextUploadPolicyKey(+ orderedUploadPolicyKeys,+ run.policyKey,);const outputIds = run.outputFileIds ?? [];- if (!nextCategory || outputIds.length === 0) {+ if (!nextPolicyKey || outputIds.length === 0) {// End of the chain (or nothing to chain onto): don't revisit this run.chained.current.add(run.runId);continue;}- const backendId = policies[nextCategory]?.backendId;+ const backendId = policies[nextPolicyKey]?.backendId;// Next policy not ready yet (still reconciling) — retry when policies change.if (!backendId) continue;chained.current.add(run.runId);// Chain onto EVERY output: a run that produced several files (split, ZIP-unpacked)// would otherwise silently skip the next policy on outputs 2..N.for (const outputId of outputIds) {- if (isDispatched(nextCategory, outputId as FileId)) continue;+ if (isDispatched(nextPolicyKey, outputId as FileId)) continue;void runPolicyOnFile(- nextCategory,+ nextPolicyKey,backendId,outputId as FileId,run.fileName,@@ -299,7 +299,7 @@ export function usePolicyAutoRun(): void {).catch(() => {});}}- }, [runs, policies, orderedUploadCategories]);+ }, [runs, policies, orderedUploadPolicyKeys]);// Poll each in-flight run to a terminal state. A browser-local run (the classification heuristic's// first pass) has no server run behind it, so polling it 404s and would flip its success to FAILED.@@ -321,7 +321,7 @@ export function usePolicyAutoRun(): void {// Import each completed run's outputs once, so the enforced file appears in the app.useEffect(() => {for (const run of runs) {- const deliversFiles = policyDeliversOutputFiles(run.categoryId);+ const deliversFiles = policyDeliversOutputFiles(run.policyKey);if (run.status !== "COMPLETED" ||run.imported ||@@ -347,23 +347,23 @@ export function usePolicyAutoRun(): void {continue;}// Output mode: a new file, or a new version of the input (needs its stub in the workspace).- const outputMode = policies[run.categoryId]?.outputMode ?? "new_version";- const outputName = policies[run.categoryId]?.outputName ?? "";- const outputNamePosition = policies[run.categoryId]?.outputNamePosition;+ const outputMode = policies[run.policyKey]?.outputMode ?? "new_version";+ const outputName = policies[run.policyKey]?.outputName ?? "";+ const outputNamePosition = policies[run.policyKey]?.outputNamePosition;const parentStub = fileStubsRef.current.find((s) => (s.id as string) === run.fileId,);void importOutputs(run, {addFiles,consumeFiles,- policyName: policies[run.categoryId]?.name,+ policyName: policies[run.policyKey]?.name,updateStirlingFileStub,bumpRevision,outputMode,outputName,outputNamePosition,parentStub,- firstUploadCategory: orderedUploadCategories[0],+ firstUploadPolicyKey: orderedUploadPolicyKeys[0],}).finally(() => importing.current.delete(run.runId));}// NB: fileStubs is read via a ref, not a dependency, so a delivery's own workspace@@ -374,7 +374,7 @@ export function usePolicyAutoRun(): void {consumeFiles,updateStirlingFileStub,policies,- orderedUploadCategories,+ orderedUploadPolicyKeys,]);// The server owns runs, so rediscover any this client never recorded and let the effects@@ -417,7 +417,7 @@ interface ImportContext {parentStub: StirlingFileStub | undefined;/** The only policy the dispatch effect fires; every output is marked dispatched for it* so a downstream output is never mistaken for a fresh upload and re-enforced. */- firstUploadCategory: string | undefined;+ firstUploadPolicyKey: string | undefined;}/**@@ -439,18 +439,16 @@ function applyOutputName(}/** Next upload policy in the chain, or undefined if last or no longer eligible. */-function nextUploadCategory(- orderedUploadCategories: string[],- categoryId: string,+function nextUploadPolicyKey(+ orderedUploadPolicyKeys: string[],+ policyKey: string,): string | undefined {- const index = orderedUploadCategories.indexOf(categoryId);+ const index = orderedUploadPolicyKeys.indexOf(policyKey);if (index < 0) return undefined;- return orderedUploadCategories[index + 1];+ return orderedUploadPolicyKeys[index + 1];}-async function reconcileServerRuns(- policies: PoliciesByCategory,-): Promise<void> {+async function reconcileServerRuns(policies: PoliciesByKey): Promise<void> {let serverRuns;try {serverRuns = await listPolicyRuns();@@ -465,11 +463,11 @@ async function reconcileServerRuns(error: view.error,});// No-ops if already tracked, so this only adopts runs we'd otherwise have lost.- const categoryId = categoryForPolicy(view.policyId, policies);- if (!categoryId) continue;+ const policyKey = policyKeyForBackendId(view.policyId, policies);+ if (!policyKey) continue;addReconciledRun({runId: view.runId,- categoryId,+ policyKey,// Server-only run: never recorded here, so it can't be tied to a file (and isn't retried).fileId: "",fileName: view.outputs[0]?.fileName ?? "",@@ -487,10 +485,10 @@ async function reconcileServerRuns(}}-/** The category whose configured policy produced this run, if any. */-function categoryForPolicy(+/** The key of the configured policy that produced this run, if any. */+function policyKeyForBackendId(policyId: string | null,- policies: PoliciesByCategory,+ policies: PoliciesByKey,): string | undefined {if (!policyId) return undefined;return Object.entries(policies).find(@@ -681,9 +679,12 @@ async function importOutputs(// re-runs on it, versioning/duplicating endlessly. Forward chaining is// unaffected: it only ever fires categories AFTER the producer, never the first.const markHandled = (id: string) => {- markDispatched(run.categoryId, id);- if (ctx.firstUploadCategory && ctx.firstUploadCategory !== run.categoryId) {- markDispatched(ctx.firstUploadCategory, id);+ markDispatched(run.policyKey, id);+ if (+ ctx.firstUploadPolicyKey &&+ ctx.firstUploadPolicyKey !== run.policyKey+ ) {+ markDispatched(ctx.firstUploadPolicyKey, id);}};diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.tsindex 3c7458ee97..5613360350 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts+++ b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts@@ -25,7 +25,7 @@ import type { StirlingFileStub } from "@app/types/fileContext";const LOCAL_PASS_BATCH = 3;interface ActivePass {- categoryId: string;+ policyKey: string;backendId: string;pass: LocalPass;/** When true, the server run is skipped while the AI engine is off (nothing to escalate to). */@@ -50,7 +50,7 @@ export function usePolicyLocalPasses(): void {// Active editor upload policies that declare a local fast path.const passes = useMemo<ActivePass[]>(() => {const out: ActivePass[] = [];- for (const [categoryId, s] of Object.entries(policies)) {+ for (const [policyKey, s] of Object.entries(policies)) {const active =s.configured &&s.enabled &&@@ -58,13 +58,13 @@ export function usePolicyLocalPasses(): void {s.runsOnEditor &&(s.runOn ?? "upload") === "upload";if (!active) continue;- const pass = localPassFor(categoryId);+ const pass = localPassFor(policyKey);if (!pass) continue;out.push({- categoryId,+ policyKey,backendId: s.backendId as string,pass,- requiresAiEngine: policyRequiresAiEngine(categoryId),+ requiresAiEngine: policyRequiresAiEngine(policyKey),});}return out;@@ -72,15 +72,15 @@ export function usePolicyLocalPasses(): void {useEffect(() => {if (configLoading || passes.length === 0) return;- const claimKey = (categoryId: string, s: StirlingFileStub) =>- `${categoryId}:${s.id as string}:${s.lastModified ?? 0}`;+ const claimKey = (policyKey: string, s: StirlingFileStub) =>+ `${policyKey}:${s.id as string}:${s.lastModified ?? 0}`;// Collect one idle batch of pending (pass, file) work across all passes.const batch: { active: ActivePass; stub: StirlingFileStub }[] = [];outer: for (const active of passes) {for (const stub of fileStubs) {if (batch.length >= LOCAL_PASS_BATCH) break outer;if (!active.pass.eligible(stub)) continue;- if (claimed.current.has(claimKey(active.categoryId, stub))) continue;+ if (claimed.current.has(claimKey(active.policyKey, stub))) continue;batch.push({ active, stub });}}@@ -92,7 +92,7 @@ export function usePolicyLocalPasses(): void {void (async () => {let wrote = false;for (const { active, stub } of batch) {- const key = claimKey(active.categoryId, stub);+ const key = claimKey(active.policyKey, stub);// Re-validate at execution time - another batch may have claimed it since.if (claimed.current.has(key)) continue;claimed.current.add(key);@@ -114,7 +114,7 @@ export function usePolicyLocalPasses(): void {!(active.requiresAiEngine && !aiEnabled)) {void runPolicyOnFile(- active.categoryId,+ active.policyKey,active.backendId,stub.id,stub.name,diff --git a/frontend/editor/src/proprietary/components/shared/PolicyEnforcingOverlay.tsx b/frontend/editor/src/proprietary/components/shared/PolicyEnforcingOverlay.tsxindex 048bca15ac..860247d60c 100644--- a/frontend/editor/src/proprietary/components/shared/PolicyEnforcingOverlay.tsx+++ b/frontend/editor/src/proprietary/components/shared/PolicyEnforcingOverlay.tsx@@ -26,7 +26,7 @@ interface PolicyEnforcingOverlayProps {accentVar?: string;/** Category of the enforcing policy — picks its shared icon (shield for* security, label for classification, …); generic shield when unknown. */- categoryId?: string;+ policyKey?: string;}/**@@ -39,7 +39,7 @@ export function PolicyEnforcingOverlay({zIndex = 200,onDismiss,accentVar,- categoryId,+ policyKey,}: PolicyEnforcingOverlayProps) {const { t } = useTranslation();if (!enforcing) return null;@@ -92,8 +92,8 @@ export function PolicyEnforcingOverlay({: undefined}>- {categoryId ? (- policyCategoryIcon(categoryId, { fontSize: 26 })+ {policyKey ? (+ policyCategoryIcon(policyKey, { fontSize: 26 })) : (<ShieldOutlinedIcon style={{ fontSize: 26 }} />)}diff --git a/frontend/editor/src/proprietary/components/viewer/PolicyEnforcementOverlay.tsx b/frontend/editor/src/proprietary/components/viewer/PolicyEnforcementOverlay.tsxindex 71d5294f2d..539cf713d0 100644--- a/frontend/editor/src/proprietary/components/viewer/PolicyEnforcementOverlay.tsx+++ b/frontend/editor/src/proprietary/components/viewer/PolicyEnforcementOverlay.tsx@@ -55,7 +55,7 @@ export function PolicyEnforcementOverlay({ runs }: Props) {// close button there, and the badge must never swallow its clicks.right: 56,zIndex: 1100,- color: policyAccentVar(inFlight.categoryId),+ color: policyAccentVar(inFlight.policyKey),}}><AutorenewIcon style={{ fontSize: 16 }} />@@ -70,8 +70,8 @@ export function PolicyEnforcementOverlay({ runs }: Props) {zIndex={1100}progress={progress}onDismiss={() => setDismissed(true)}- accentVar={policyAccentVar(inFlight.categoryId)}- categoryId={inFlight.categoryId}+ accentVar={policyAccentVar(inFlight.policyKey)}+ policyKey={inFlight.policyKey}/>);}diff --git a/frontend/editor/src/proprietary/components/viewer/Viewer.tsx b/frontend/editor/src/proprietary/components/viewer/Viewer.tsxindex d5a2e7537d..1862911eca 100644--- a/frontend/editor/src/proprietary/components/viewer/Viewer.tsx+++ b/frontend/editor/src/proprietary/components/viewer/Viewer.tsx@@ -8,7 +8,7 @@ import {usePolicyRuns,type PolicyRunRecord,} from "@app/components/policies/policyRunStore";-import { isClassificationCategory } from "@app/data/classificationPolicy";+import { isClassificationPolicy } from "@app/data/classificationPolicy";import { PolicyEnforcementOverlay } from "@app/components/viewer/PolicyEnforcementOverlay";type SignatureOverlayPassThrough = Pick<@@ -31,7 +31,7 @@ const Viewer = (props: ViewerProps & SignatureOverlayPassThrough) => {(r: PolicyRunRecord) =>r.fileId === activeFileId &&// Classification runs async and must never block the viewer.- !isClassificationCategory(r.categoryId) &&+ !isClassificationPolicy(r.policyKey) &&(POLICY_IN_FLIGHT_STATUSES.includes(r.status) || r.retrying === true),): [];diff --git a/frontend/editor/src/proprietary/data/classificationPolicy.test.ts b/frontend/editor/src/proprietary/data/classificationPolicy.test.tsindex 9af891c0d5..65479052a7 100644--- a/frontend/editor/src/proprietary/data/classificationPolicy.test.ts+++ b/frontend/editor/src/proprietary/data/classificationPolicy.test.ts@@ -1,12 +1,12 @@import { describe, it, expect } from "vitest";import {- isClassificationCategory,+ isClassificationPolicy,localVerdictNeedsEscalation,- orderedRewritingCategories,+ orderedRewritingPolicies,policyDeliversOutputFiles,policyRewritesDocument,} from "@app/data/classificationPolicy";-import type { PoliciesByCategory } from "@app/types/policies";+import type { PoliciesByKey } from "@app/types/policies";const rewriter = (order: number) =>({@@ -16,13 +16,13 @@ const rewriter = (order: number) =>runsOnEditor: true,runOn: "upload",order,- }) as unknown as PoliciesByCategory[string];+ }) as unknown as PoliciesByKey[string];-describe("isClassificationCategory", () => {+describe("isClassificationPolicy", () => {it("recognises the classification category and nothing else", () => {- expect(isClassificationCategory("classification")).toBe(true);- expect(isClassificationCategory("security")).toBe(false);- expect(isClassificationCategory("")).toBe(false);+ expect(isClassificationPolicy("classification")).toBe(true);+ expect(isClassificationPolicy("security")).toBe(false);+ expect(isClassificationPolicy("")).toBe(false);});});@@ -40,15 +40,15 @@ describe("policy capabilities", () => {});});-describe("orderedRewritingCategories", () => {+describe("orderedRewritingPolicies", () => {it("lists only file-producing policies, ordered by order, excluding classification", () => {const policies = {classification: rewriter(0), // annotating: excluded despite being activesecurity: rewriter(2),compliance: rewriter(1),- } as unknown as PoliciesByCategory;+ } as unknown as PoliciesByKey;// classification is filtered by policyDeliversOutputFiles, not by the shape above.- expect(orderedRewritingCategories(policies)).toEqual([+ expect(orderedRewritingPolicies(policies)).toEqual(["compliance","security",]);@@ -62,15 +62,15 @@ describe("orderedRewritingCategories", () => {onExport: { ...rewriter(3), runOn: "export" },unconfigured: { ...rewriter(4), configured: false },noBackend: { ...rewriter(5), backendId: undefined },- } as unknown as PoliciesByCategory;- expect(orderedRewritingCategories(mixed)).toEqual(["security"]);+ } as unknown as PoliciesByKey;+ expect(orderedRewritingPolicies(mixed)).toEqual(["security"]);});it("is empty when classification is the only policy", () => {const only = {classification: rewriter(0),- } as unknown as PoliciesByCategory;- expect(orderedRewritingCategories(only)).toEqual([]);+ } as unknown as PoliciesByKey;+ expect(orderedRewritingPolicies(only)).toEqual([]);});});diff --git a/frontend/editor/src/proprietary/data/classificationPolicy.ts b/frontend/editor/src/proprietary/data/classificationPolicy.tsindex 6befe744d7..eb7811dd94 100644--- a/frontend/editor/src/proprietary/data/classificationPolicy.ts+++ b/frontend/editor/src/proprietary/data/classificationPolicy.ts@@ -1,47 +1,47 @@/*** Everything specific to the built-in Classification policy, in one module. The generic policy runner- * dispatches and chains only file-producing policies (see {@link orderedRewritingCategories}), and the+ * dispatches and chains only file-producing policies (see {@link orderedRewritingPolicies}), and the* generic local-pass engine runs whatever browser-side fast path a policy declares. Classification's* fast path (its heuristic) lives in classificationLocalPass; the capability answers below let the* generic engines treat it without naming it. A second annotating policy is a change here, not there.*- * These are still keyed on the category id rather than a property each policy declares. That is+ * These are still keyed on the policy key rather than a property each policy declares. That is* deliberate for now: policies are becoming pipelines with labels behind a separate enforcement- * layer, which removes the category concept these would be declared against. Classification also+ * layer, which removes the keyed-policy concept these would be declared against. Classification also* stays genuinely privileged - it is the only policy with a browser-side implementation, so it can* answer without the server. Ordering and output shape belong in that rework (an in-place output* mode, and a run result that can carry findings as well as files), not in a flag added here first.*/import type { ClassificationConfidence } from "@app/types/fileContext";-import type { PoliciesByCategory } from "@app/types/policies";+import type { PoliciesByKey } from "@app/types/policies";-/** Catalogue category id of the built-in Classification policy. */-export const CLASSIFICATION_CATEGORY_ID = "classification";+/** Key of the built-in Classification policy. */+export const CLASSIFICATION_POLICY_KEY = "classification";-export function isClassificationCategory(categoryId: string): boolean {- return categoryId === CLASSIFICATION_CATEGORY_ID;+export function isClassificationPolicy(policyKey: string): boolean {+ return policyKey === CLASSIFICATION_POLICY_KEY;}/*** Whether the policy rewrites the document rather than only annotating it. Annotating policies are* ordered last: a rewriting one after them would fork from the pre-annotation version.*/-export function policyRewritesDocument(categoryId: string): boolean {- return !isClassificationCategory(categoryId);+export function policyRewritesDocument(policyKey: string): boolean {+ return !isClassificationPolicy(policyKey);}/** Whether a completed run is expected to deliver output files (annotators deliver labels). */-export function policyDeliversOutputFiles(categoryId: string): boolean {- return policyRewritesDocument(categoryId);+export function policyDeliversOutputFiles(policyKey: string): boolean {+ return policyRewritesDocument(policyKey);}/*** Whether the policy's server run needs the AI engine. The local-pass engine skips dispatching such* a run when the engine is off - there is nothing to escalate to, and the local verdict stands.*/-export function policyRequiresAiEngine(categoryId: string): boolean {- return isClassificationCategory(categoryId);+export function policyRequiresAiEngine(policyKey: string): boolean {+ return isClassificationPolicy(policyKey);}/**@@ -50,9 +50,7 @@ export function policyRequiresAiEngine(categoryId: string): boolean {* runs itself, so it is intentionally absent here. Both the runner and the classification policy* read this - the runner to sequence the chain, classification to know when that chain is done.*/-export function orderedRewritingCategories(- policies: PoliciesByCategory,-): string[] {+export function orderedRewritingPolicies(policies: PoliciesByKey): string[] {return Object.entries(policies).filter(([id, s]) =>diff --git a/frontend/editor/src/proprietary/hooks/usePolicies.ts b/frontend/editor/src/proprietary/hooks/usePolicies.tsindex d2e4b1072f..736638d34b 100644--- a/frontend/editor/src/proprietary/hooks/usePolicies.ts+++ b/frontend/editor/src/proprietary/hooks/usePolicies.ts@@ -19,7 +19,7 @@ import {fetchPoliciesByCategory,decodedToState,} from "@app/services/policyBackend";-import type { PoliciesByCategory } from "@app/types/policies";+import type { PoliciesByKey } 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. */@@ -28,7 +28,7 @@ const reconcileRetryDelay = (attempt: number) =>Math.min(500 * 2 ** attempt, 5000);export function usePolicies() {- const [policies, setPolicies] = useState<PoliciesByCategory>(loadPolicies);+ const [policies, setPolicies] = useState<PoliciesByKey>(loadPolicies);const { refetch: refetchAppConfig } = useAppConfig();useEffect(() => onPoliciesChange(() => setPolicies(loadPolicies())), []);@@ -56,7 +56,7 @@ export function usePolicies() {}if (cancelled) return;const local = loadPolicies();- const reconciled: PoliciesByCategory = {};+ const reconciled: PoliciesByKey = {};for (const cat of loadPolicyCatalog().categories) {const decoded = byCategory.get(cat.id);reconciled[cat.id] = decodeddiff --git a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.tsindex 2364321213..00dbea669c 100644--- a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts+++ b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts@@ -14,7 +14,7 @@ const labels = new Map([function run(overrides: Partial<PolicyRunRecord>): PolicyRunRecord {return {runId: "r",- categoryId: "security",+ policyKey: "security",fileId: "in",fileName: "in.pdf",fileSize: 1,@@ -73,8 +73,8 @@ describe("buildPolicyBadgeMap — badge follows the document onto derived files"it("MERGE output inherits every input's badge", () => {const map = buildPolicyBadgeMap([- run({ runId: "r1", categoryId: "security", outputFileIds: ["a"] }),- run({ runId: "r2", categoryId: "watermark", outputFileIds: ["b"] }),+ run({ runId: "r1", policyKey: "security", outputFileIds: ["a"] }),+ run({ runId: "r2", policyKey: "watermark", outputFileIds: ["b"] }),],[{ id: "merged", sourceFileIds: ["a", "b"] }],labels,@@ -100,7 +100,7 @@ describe("buildPolicyBadgeMap — badge follows the document onto derived files"const map = buildPolicyBadgeMap([run({- categoryId: "classification",+ policyKey: "classification",fileId: "in",outputFileIds: ["in"],imported: true,@@ -184,7 +184,7 @@ describe("buildPolicyBadgeMap — in-flight indicators", () => {const map = buildPolicyBadgeMap([run({- categoryId: "classification",+ policyKey: "classification",status: "RUNNING",outputFileIds: [],}),diff --git a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.tsindex 85b2249cbb..af8efcabba 100644--- a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts+++ b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts@@ -4,7 +4,7 @@ import type { PolicyRunRecord } from "@app/components/policies/policyRunStore";import { useAllFiles } from "@app/contexts/FileContext";import { loadPolicyCatalog } from "@app/services/policyCatalog";import { policyAccentVar } from "@app/components/policies/policyStatus";-import { isClassificationCategory } from "@app/data/classificationPolicy";+import { isClassificationPolicy } from "@app/data/classificationPolicy";import type { FileItemPolicyRef } from "@app/components/shared/PolicyBadges";/** Minimal provenance shape needed to resolve a file's inherited badges. */@@ -43,15 +43,15 @@ export function buildPolicyBadgeMap(// Direct badges: a file that IS a policy run's output.const directByFile = new Map<string, FileItemPolicyRef[]>();for (const run of runs) {- const name = labelById.get(run.categoryId);+ const name = labelById.get(run.policyKey);if (!name) continue;for (const fileId of run.outputFileIds ?? []) {const list = directByFile.get(fileId) ?? [];- if (!list.some((p) => p.id === run.categoryId)) {+ if (!list.some((p) => p.id === run.policyKey)) {list.push({- id: run.categoryId,+ id: run.policyKey,name,- accentColor: policyAccentVar(run.categoryId),+ accentColor: policyAccentVar(run.policyKey),});directByFile.set(fileId, list);}@@ -100,20 +100,20 @@ export function buildPolicyBadgeMap(const settled =run.imported || run.status === "FAILED" || run.status === "CANCELLED";if (settled && !run.retrying) continue;- const name = labelById.get(run.categoryId);+ const name = labelById.get(run.policyKey);if (!name) continue;- const inFlightFlag = isClassificationCategory(run.categoryId)+ const inFlightFlag = isClassificationPolicy(run.policyKey)? ("background" as const): ("enforcing" as const);const list = result.get(run.fileId) ?? [];- const existing = list.find((p) => p.id === run.categoryId);+ const existing = list.find((p) => p.id === run.policyKey);if (existing) {existing[inFlightFlag] = true;} else {list.push({- id: run.categoryId,+ id: run.policyKey,name,- accentColor: policyAccentVar(run.categoryId),+ accentColor: policyAccentVar(run.policyKey),[inFlightFlag]: true,});result.set(run.fileId, list);diff --git a/frontend/editor/src/proprietary/policies/codec.test.ts b/frontend/editor/src/proprietary/policies/codec.test.tsindex 70d704cc3e..4b1b03b897 100644--- a/frontend/editor/src/proprietary/policies/codec.test.ts+++ b/frontend/editor/src/proprietary/policies/codec.test.ts@@ -7,7 +7,7 @@ const FULL_STATE: PolicyDecodedState = {name: "Security Policy",enabled: true,required: true,- categoryId: "security",+ policyKey: "security",sources: ["editor", "gdrive"],runsOnEditor: true,scopeTypes: ["Contracts", "Invoices"],@@ -86,7 +86,7 @@ describe("fromWirePolicy → round-trip", () => {const decoded = fromWirePolicy(wire);expect(decoded.id).toBe(FULL_STATE.id);expect(decoded.required).toBe(FULL_STATE.required);- expect(decoded.categoryId).toBe(FULL_STATE.categoryId);+ expect(decoded.policyKey).toBe(FULL_STATE.policyKey);expect(decoded.sources).toEqual(FULL_STATE.sources);expect(decoded.scopeTypes).toEqual(FULL_STATE.scopeTypes);expect(decoded.reviewerEmail).toBe(FULL_STATE.reviewerEmail);@@ -116,7 +116,7 @@ describe("fromWirePolicy → round-trip", () => {it("defaults a missing runOn to upload for other categories", () => {const wire = withNoStoredRunOn({...FULL_STATE,- categoryId: "classification",+ policyKey: "classification",});expect(fromWirePolicy(wire).runOn).toBe("upload");});@@ -180,13 +180,33 @@ describe("fromWirePolicy → round-trip", () => {steps: [],output: { type: "inline", options: {} },});- expect(decoded.categoryId).toBe("");+ expect(decoded.policyKey).toBe("");expect(decoded.sources).toEqual([]);expect(decoded.runsOnEditor).toBe(false);expect(decoded.runOn).toBe("upload");expect(decoded.outputMode).toBe("new_version");});+ it("decodes a policy stored before the in-memory rename", () => {+ // The wire key is frozen as categoryId and every stored policy already carries it, so a+ // decode that looked for policyKey would read every existing policy as unconfigured.+ const decoded = fromWirePolicy({+ id: "legacy",+ name: "Security Policy",+ enabled: true,+ trigger: null,+ steps: [],+ output: { type: "inline", options: { categoryId: "security" } },+ });+ expect(decoded.policyKey).toBe("security");+ });++ it("writes the key back under the name the backend reads", () => {+ expect(toWirePolicy(FULL_STATE).output.options).toMatchObject({+ categoryId: "security",+ });+ });+it("defaults fieldValues to empty object when missing", () => {const wire = toWirePolicy(FULL_STATE);delete (wire.output.options as Record<string, unknown>).fieldValues;diff --git a/frontend/editor/src/proprietary/policies/codec.ts b/frontend/editor/src/proprietary/policies/codec.tsindex 44117a2591..6c4d923e03 100644--- a/frontend/editor/src/proprietary/policies/codec.ts+++ b/frontend/editor/src/proprietary/policies/codec.ts@@ -43,7 +43,7 @@ export function toWirePolicy(state: PolicyDecodedState): WirePolicy {position: state.outputNamePosition,maxRetries: state.maxRetries,retryDelayMinutes: state.retryDelayMinutes,- categoryId: state.categoryId,+ categoryId: state.policyKey,sources: state.sources,scopeTypes: state.scopeTypes,reviewerEmail: state.reviewerEmail,@@ -78,13 +78,13 @@ export function fromWirePolicy(policy: WirePolicy): PolicyDecodedState {: raw.position === "auto-number"? "auto-number": "prefix";- const categoryId = str(raw.categoryId);+ const policyKey = str(raw.categoryId);return {id: policy.id,name: policy.name,enabled: policy.enabled,required: policy.required ?? false,- categoryId,+ policyKey,sources: Array.isArray(raw.sources) ? raw.sources : [],runsOnEditor: policy.editor?.allowed === true,scopeTypes: Array.isArray(raw.scopeTypes) ? raw.scopeTypes : [],@@ -95,7 +95,7 @@ export function fromWirePolicy(policy: WirePolicy): PolicyDecodedState {// to the legacy options bag otherwise so the wizard still shows what was chosen.runOn: resolveRunOn(policy.editor?.allowed ? policy.editor.runOn : raw.runOn,- categoryId,+ policyKey,),outputMode: raw.mode === "new_file" ? "new_file" : "new_version",outputName: str(raw.name),diff --git a/frontend/editor/src/proprietary/policies/runOn.ts b/frontend/editor/src/proprietary/policies/runOn.tsindex bbb63d2501..f47d2be9e6 100644--- a/frontend/editor/src/proprietary/policies/runOn.ts+++ b/frontend/editor/src/proprietary/policies/runOn.ts@@ -6,15 +6,15 @@ const DEFAULT_RUN_ON: Record<string, PolicyRunOn> = {security: "export",};-export function defaultRunOn(categoryId: string | undefined): PolicyRunOn {- return DEFAULT_RUN_ON[categoryId ?? ""] ?? "upload";+export function defaultRunOn(policyKey: string | undefined): PolicyRunOn {+ return DEFAULT_RUN_ON[policyKey ?? ""] ?? "upload";}/** An explicitly saved value wins; anything else falls back to the default. */export function resolveRunOn(value: unknown,- categoryId: string | undefined,+ policyKey: string | undefined,): PolicyRunOn {if (value === "export" || value === "upload") return value;- return defaultRunOn(categoryId);+ return defaultRunOn(policyKey);}diff --git a/frontend/editor/src/proprietary/policies/types.ts b/frontend/editor/src/proprietary/policies/types.tsindex 6addb59ab9..ded698e382 100644--- a/frontend/editor/src/proprietary/policies/types.ts+++ b/frontend/editor/src/proprietary/policies/types.ts@@ -24,6 +24,11 @@ export interface WireOutputOptions {position: "prefix" | "suffix" | "auto-number";maxRetries?: number;retryDelayMinutes?: number;+ /**+ * Frozen as `categoryId`: the backend reads this key by name (the classification+ * seeder, JpaPolicyStore's editor-config lift, PolicyOverviewService), and every+ * stored policy already carries it. In memory it is `policyKey`; the codecs translate.+ */categoryId: string;sources: string[];scopeTypes: string[];@@ -99,7 +104,7 @@ export interface PolicyDecodedState {enabled: boolean;/** Org-mandated policy; first-class on the record, not part of the options bag. */required: boolean;- categoryId: string;+ policyKey: string;sources: string[];/*** Whether the editor runs this policy per file. Its own field, not derived fromdiff --git a/frontend/editor/src/proprietary/services/notificationPolicyRetry.test.ts b/frontend/editor/src/proprietary/services/notificationPolicyRetry.test.tsindex 68a161e846..ff37e60fe2 100644--- a/frontend/editor/src/proprietary/services/notificationPolicyRetry.test.ts+++ b/frontend/editor/src/proprietary/services/notificationPolicyRetry.test.ts@@ -77,7 +77,7 @@ describe("rerunPolicy", () => {expect(getRun("run-1")).toMatchObject({runId: "run-1",// The category the import step needs, and what the chain continues from.- categoryId: "security",+ policyKey: "security",// The document that failed is still the document in the workspace, so the output belongs to it.fileId: "f-1",fileName: "invoice.pdf",@@ -223,16 +223,16 @@ describe("rechainPolicyOnDocument rejoining the chain", () => {};}- /** A completed run of `categoryId` that turned `fileId` into `outputFileId`. */+ /** A completed run of `policyKey` that turned `fileId` into `outputFileId`. */function completedRun(runId: string,- categoryId: string,+ policyKey: string,fileId: string,outputFileId: string,) {recordRunStart({runId,- categoryId,+ policyKey,fileId,fileName: "invoice.pdf",fileSize: 1,@@ -274,7 +274,7 @@ describe("rechainPolicyOnDocument rejoining the chain", () => {// Filed under the resumed policy's category, so security still runs on watermark's output.expect(runStoredPolicy).toHaveBeenCalledWith("pol-w", [unlocked], "f-1");expect(getRun("run-1")).toMatchObject({- categoryId: "watermark",+ policyKey: "watermark",fileId: "f-unlocked",});});diff --git a/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts b/frontend/editor/src/proprietary/services/notificationPolicyRetry.tsindex a893e8564a..bb6b31beed 100644--- a/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts+++ b/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts@@ -1,8 +1,8 @@import {- appliedCategoriesFor,+ appliedPoliciesFor,recordRunStart,} from "@app/components/policies/policyRunStore";-import { orderedRewritingCategories } from "@app/data/classificationPolicy";+import { orderedRewritingPolicies } from "@app/data/classificationPolicy";import { fileStorage } from "@app/services/fileStorage";import { loadPolicies } from "@app/services/policyStorage";import {@@ -56,10 +56,10 @@ export async function rechainPolicyOnDocument(return submit(target, document, workspaceFileId, resumePointFor(target));}-/** Which policy a retry should actually run, and the category to file its run under. */+/** Which policy a retry should actually run, and the key to file its run under. */interface ChainEntry {policyId: string;- categoryId: string;+ policyKey: string;}/**@@ -68,17 +68,17 @@ interface ChainEntry {*/function resumePointFor(target: PolicyRetryTarget): ChainEntry | null {const policies = loadPolicies();- const chain = orderedRewritingCategories(policies);- const failed = categoryForPolicy(target.policyId);+ const chain = orderedRewritingPolicies(policies);+ const failed = policyKeyForBackendId(target.policyId);if (!failed || !chain.includes(failed)) return null;- const applied = appliedCategoriesFor(target.fileId);- const categoryId = chain.find((category) => !applied.has(category));- if (!categoryId) return null;+ const applied = appliedPoliciesFor(target.fileId);+ const policyKey = chain.find((key) => !applied.has(key));+ if (!policyKey) return null;const policyId = Object.entries(policies).find(- ([id]) => id === categoryId,+ ([id]) => id === policyKey,)?.[1]?.backendId;- return policyId ? { policyId, categoryId } : null;+ return policyId ? { policyId, policyKey } : null;}/** Recorded because `usePolicyAutoRun` polls the store; an unrecorded run delivers nothing. */@@ -89,7 +89,7 @@ async function submit(resume: ChainEntry | null = null,): Promise<PolicyRerunOutcome> {// Resolved before the run, so a lookup that throws cannot leave a live run unrecorded.- const categoryId = resume?.categoryId ?? categoryForPolicy(target.policyId);+ const policyKey = resume?.policyKey ?? policyKeyForBackendId(target.policyId);// At the resume point where there is one, so the rest of the chain carries on from there.const policyId = resume?.policyId ?? target.policyId;const runTarget = resolvePolicyRunTarget();@@ -102,12 +102,12 @@ async function submit(}// The run already went, so it is left to run: refusing now only wastes a second submission.- if (!categoryId || !workspaceFileId) return { ok: true, tracked: false };+ if (!policyKey || !workspaceFileId) return { ok: true, tracked: false };- // Marks (category, file) dispatched as it records: the pair has run once, and this is it again.+ // Marks (policy, file) dispatched as it records: the pair has run once, and this is it again.recordRunStart({runId,- categoryId,+ policyKey,fileId: workspaceFileId,fileName: document.name,fileSize: document.size,@@ -121,7 +121,7 @@ async function submit(}/** Non-hook read: `usePolicies` needs contexts the bell's shell may not have. */-function categoryForPolicy(policyId: string): string | undefined {+function policyKeyForBackendId(policyId: string): string | undefined {try {return Object.entries(loadPolicies()).find(([, state]) => state.backendId === policyId,diff --git a/frontend/editor/src/proprietary/services/policyBackend.test.ts b/frontend/editor/src/proprietary/services/policyBackend.test.tsindex 54c84c2675..5315fb77c2 100644--- a/frontend/editor/src/proprietary/services/policyBackend.test.ts+++ b/frontend/editor/src/proprietary/services/policyBackend.test.ts@@ -12,7 +12,7 @@ vi.mock("@app/services/policyApi", () => ({/** A stored policy in the shape the backend returns. */const policy = (id: string,- categoryId?: string,+ policyKey?: string,editor?: { allowed: boolean; runOn?: "upload" | "export" },) => ({id,@@ -22,7 +22,7 @@ const policy = (steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],output: {type: "inline",- options: { ...(categoryId ? { categoryId } : {}) },+ options: { ...(policyKey ? { categoryId: policyKey } : {}) },},outputIds: [],editor: {diff --git a/frontend/editor/src/proprietary/services/policyBackend.ts b/frontend/editor/src/proprietary/services/policyBackend.tsindex 2d51bdf3d8..01d4250636 100644--- a/frontend/editor/src/proprietary/services/policyBackend.ts+++ b/frontend/editor/src/proprietary/services/policyBackend.ts@@ -3,9 +3,9 @@* (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` decodes on read.+ * The frontend is keyed by policy (one policy per catalog entry); the backend is a+ * flat list with assigned ids. The bridge is `output.options.categoryId`, which+ * `policyPipeline` decodes on read.*/import * as policyApi from "@app/services/policyApi";@@ -18,7 +18,7 @@ import type { PolicyState } from "@app/types/policies";/*** Fetch every stored policy and decode it, keyed by its catalog category. If two* stored policies share a category (shouldn't happen — one per category), the- * last one wins; policies with no recognised categoryId are skipped.+ * last one wins; policies with no recognised key are skipped.*/export async function fetchPoliciesByCategory(): Promise<Map<string, DecodedPolicy>@@ -31,7 +31,7 @@ export async function fetchPoliciesByCategory(): Promise<const decoded = fromBackendPolicy(policy);// A pipeline built on the Pipelines page has no category tile, so it keys by its own id// rather than being dropped - one set to run on the editor still has to reach the auto-run.- const key = decoded.categoryId || decoded.id;+ const key = decoded.policyKey || decoded.id;if (key) byCategory.set(key, { ...decoded, order: index });});return byCategory;@@ -64,6 +64,6 @@ export function decodedToState(// Server-side run-order position (team-wide); drives the settings reorder list.order: decoded.order,// Catalog-category policies are built-in defaults (not deletable); a builder pipeline is not.- isDefault: Boolean(decoded.categoryId),+ isDefault: Boolean(decoded.policyKey),};}diff --git a/frontend/editor/src/proprietary/services/policyDispatch.ts b/frontend/editor/src/proprietary/services/policyDispatch.tsindex 43508a11f5..db8e8271cd 100644--- a/frontend/editor/src/proprietary/services/policyDispatch.ts+++ b/frontend/editor/src/proprietary/services/policyDispatch.ts@@ -29,7 +29,7 @@ const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));/** Resolve the file's bytes, fire a backend run, and record it. */export async function runPolicyOnFile(- categoryId: string,+ policyKey: string,backendId: string,fileId: FileId,fileName: string,@@ -58,7 +58,7 @@ export async function runPolicyOnFile(}if (!file) {// File genuinely gone (removed before it could run) — mark so we don't loop.- markDispatched(categoryId, fileId);+ markDispatched(policyKey, fileId);return;}// Bounded upload window — see MAX_CONCURRENT_DISPATCHES. Only the POST is@@ -72,7 +72,7 @@ export async function runPolicyOnFile(// recordRunStart marks this (policy, file) dispatched as it records the run.recordRunStart({runId,- categoryId,+ policyKey,fileId,fileName,fileSize: file.size,@@ -87,10 +87,10 @@ export async function runPolicyOnFile(// the absent run simply won't appear in the activity feed. If the backend did// start a run we never recorded, reconcileServerRuns rediscovers it.console.debug(- `[PolicyAutoRun] Failed to dispatch policy ${categoryId} (${backendId}):`,+ `[PolicyAutoRun] Failed to dispatch policy ${policyKey} (${backendId}):`,err,);- markDispatched(categoryId, fileId);+ markDispatched(policyKey, fileId);} finally {releaseDispatchSlot();}diff --git a/frontend/editor/src/proprietary/services/policyExport.test.ts b/frontend/editor/src/proprietary/services/policyExport.test.tsindex 8960b3f6bb..8452698476 100644--- a/frontend/editor/src/proprietary/services/policyExport.test.ts+++ b/frontend/editor/src/proprietary/services/policyExport.test.ts@@ -1,9 +1,9 @@import { describe, it, expect, vi, beforeEach } from "vitest";-import type { PoliciesByCategory, PolicyState } from "@app/types/policies";+import type { PoliciesByKey, PolicyState } from "@app/types/policies";// Which policies export-time enforcement picks up: the policy's own editor flag, not its scope.-const loadPolicies = vi.fn<() => PoliciesByCategory>();+const loadPolicies = vi.fn<() => PoliciesByKey>();vi.mock("@app/services/policyStorage", () => ({loadPolicies: () => loadPolicies(),}));@@ -69,7 +69,7 @@ describe("export-time policy selection", () => {runsOnEditor: true,backendId: "backend-editor",}),- } as unknown as PoliciesByCategory);+ } as unknown as PoliciesByKey);await enforceExportPolicies([pdf()], ["file-1"]);@@ -83,7 +83,7 @@ describe("export-time policy selection", () => {runsOnEditor: false,backendId: "backend-swept",}),- } as unknown as PoliciesByCategory);+ } as unknown as PoliciesByKey);await enforceExportPolicies([pdf()], ["file-1"]);@@ -98,7 +98,7 @@ describe("export-time policy selection", () => {runsOnEditor: true,backendId: "backend-security",}),- } as unknown as PoliciesByCategory);+ } as unknown as PoliciesByKey);await enforceExportPolicies([pdf()], ["file-1"]);@@ -117,7 +117,7 @@ describe("export-time policy selection", () => {backendId: "backend-first",order: 0,}),- } as unknown as PoliciesByCategory);+ } as unknown as PoliciesByKey);await enforceExportPolicies([pdf()], ["file-1"]);diff --git a/frontend/editor/src/proprietary/services/policyExport.ts b/frontend/editor/src/proprietary/services/policyExport.tsindex 4b53201993..4c1d54427b 100644--- a/frontend/editor/src/proprietary/services/policyExport.ts+++ b/frontend/editor/src/proprietary/services/policyExport.ts@@ -42,7 +42,7 @@ const isPdf = (f: File) =>f.type === "application/pdf" || /\.pdf$/i.test(f.name);interface ExportPolicy {- categoryId: string;+ policyKey: string;backendId: string;label: string;outputMode: "new_file" | "new_version";@@ -76,7 +76,7 @@ function activeExportPolicies(): ExportPolicy[] {// then a flatten is not a flatten then a watermark), so both paths must agree on the sequence..sort(([, a], [, b]) => (a.order ?? 0) - (b.order ?? 0)).map(([id, s]) => ({- categoryId: id,+ policyKey: id,backendId: s.backendId as string,// A builder pipeline has no built-in category, so it labels by its own name.label: labels.get(id) ?? s.name ?? "Policy",@@ -161,7 +161,7 @@ export async function enforceExportPolicies(// non-idempotent policy would stack watermarks/flattens. Editing produces a// new file id that isn't dispatched, so an edited file enforces afresh.const pendingFor = (fileId: string | undefined) =>- active.filter((p) => !(fileId && isDispatched(p.categoryId, fileId)));+ active.filter((p) => !(fileId && isDispatched(p.policyKey, fileId)));if (!targets.some((i) => pendingFor(fileIds?.[i]).length > 0)) return files;const names = active.map((p) => p.label).join(", ");@@ -206,12 +206,12 @@ export async function enforceExportPolicies(let current = file;// The last "new version" policy's output is what versions the editor// file (recording every policy would double-consume the same input).- let versionRun: (PolicyRunResult & { categoryId: string }) | undefined;+ let versionRun: (PolicyRunResult & { policyKey: string }) | undefined;for (const policy of toRun) {const result = await runToCompletion(policy.backendId, current);current = result.file;if (policy.outputMode === "new_version" && fileId) {- versionRun = { ...result, categoryId: policy.categoryId };+ versionRun = { ...result, policyKey: policy.policyKey };}}out[i] = current;@@ -224,7 +224,7 @@ export async function enforceExportPolicies(if (versionRun && fileId) {recordRunStart({runId: versionRun.runId,- categoryId: versionRun.categoryId,+ policyKey: versionRun.policyKey,fileId,fileName: file.name,fileSize: file.size,diff --git a/frontend/editor/src/proprietary/services/policyPipeline.test.ts b/frontend/editor/src/proprietary/services/policyPipeline.test.tsindex 4e91b1d95b..b07a21908c 100644--- a/frontend/editor/src/proprietary/services/policyPipeline.test.ts+++ b/frontend/editor/src/proprietary/services/policyPipeline.test.ts@@ -40,7 +40,7 @@ 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.policyKey).toBe("security");expect(decoded.enabled).toBe(true);expect(decoded.sources).toEqual([]);expect(decoded.runsOnEditor).toBe(true);diff --git a/frontend/editor/src/proprietary/services/policyPipeline.ts b/frontend/editor/src/proprietary/services/policyPipeline.tsindex 252711547c..b68d283973 100644--- a/frontend/editor/src/proprietary/services/policyPipeline.ts+++ b/frontend/editor/src/proprietary/services/policyPipeline.ts@@ -105,8 +105,8 @@ export interface PolicyRunView {/** The decoded policy read back from the backend. */export interface DecodedPolicy {id: string;- /** The catalog category this policy maps to (from trigger.options.categoryId). */- categoryId: string;+ /** The policy this record belongs to, read from `output.options.categoryId`. */+ policyKey: string;name: string;enabled: boolean;/** Null if the stored policy carried no automation blob. */@@ -143,10 +143,10 @@ export function fromBackendPolicy(policy: BackendPolicy): DecodedPolicy {typeof v === "string" ? v : fallback;const num = (v: unknown, fallback: number) =>typeof v === "number" ? v : fallback;- const categoryId = str(meta.categoryId);+ const policyKey = str(meta.categoryId);return {id: policy.id,- categoryId,+ policyKey,name: policy.name,enabled: policy.enabled,automation: (output.automation as AutomationConfig | undefined) ?? null,@@ -159,7 +159,7 @@ export function fromBackendPolicy(policy: BackendPolicy): DecodedPolicy {(meta.fieldValues as DecodedPolicy["fieldValues"] | undefined) ?? {},runsOnEditor: editor?.allowed === true,folder: {- runOn: resolveRunOn(editor?.runOn, categoryId),+ runOn: resolveRunOn(editor?.runOn, policyKey),// Legacy/missing output.mode defaults to new_version, not new_file.outputMode: output.mode === "new_file" ? "new_file" : "new_version",outputName: str(output.name),diff --git a/frontend/editor/src/proprietary/services/policyStorage.ts b/frontend/editor/src/proprietary/services/policyStorage.tsindex 1b564e2ec0..01cd7ebe84 100644--- a/frontend/editor/src/proprietary/services/policyStorage.ts+++ b/frontend/editor/src/proprietary/services/policyStorage.ts@@ -7,12 +7,12 @@import { loadPolicyCatalog } from "@app/services/policyCatalog";import { defaultRunOn } from "@app/policies/runOn";-import type { PoliciesByCategory, PolicyState } from "@app/types/policies";+import type { PoliciesByKey, PolicyState } from "@app/types/policies";const STORAGE_KEY = "stirling-policies-state";export const POLICIES_CHANGE_EVENT = "stirling:policies-changed";-function defaultState(categoryId: string): PolicyState {+function defaultState(policyKey: string): PolicyState {// Unconfigured by default. The backend is the source of truth for what's// actually configured + active; this is just the empty local-cache shape.return {@@ -28,7 +28,7 @@ function defaultState(categoryId: string): PolicyState {outputMode: "new_version",// No rename by default — the output keeps the input's filename.outputName: "",- runOn: defaultRunOn(categoryId),+ runOn: defaultRunOn(policyKey),// Every catalog category is a shipped, built-in policy → default (not// deletable).isDefault: true,@@ -40,20 +40,20 @@ function defaultState(categoryId: string): PolicyState {const STALE_REVIEWER_EMAIL = "[email protected]";/** Read the full policy state, seeding + healing any missing categories. */-export function loadPolicies(): PoliciesByCategory {- let parsed: Partial<PoliciesByCategory> = {};+export function loadPolicies(): PoliciesByKey {+ let parsed: Partial<PoliciesByKey> = {};try {const raw =typeof localStorage !== "undefined"? localStorage.getItem(STORAGE_KEY): null;- if (raw) parsed = JSON.parse(raw) as Partial<PoliciesByCategory>;+ if (raw) parsed = JSON.parse(raw) as Partial<PoliciesByKey>;} catch {// Corrupt/unavailable storage — fall back to seed.}// Always reconcile against the current category list so a newly-added// category gets a default rather than being undefined.- const out: PoliciesByCategory = {};+ const out: PoliciesByKey = {};loadPolicyCatalog().categories.forEach((cat, index) => {const stored = parsed[cat.id];const merged = { ...defaultState(cat.id), ...(stored ?? {}) };@@ -80,7 +80,7 @@ export function loadPolicies(): PoliciesByCategory {return out;}-function persist(state: PoliciesByCategory): void {+function persist(state: PoliciesByKey): void {try {if (typeof localStorage !== "undefined") {localStorage.setItem(STORAGE_KEY, JSON.stringify(state));@@ -95,17 +95,17 @@ function persist(state: PoliciesByCategory): void {/** Merge a partial update into one category's state and persist. */export function updatePolicy(- categoryId: string,+ policyKey: string,patch: Partial<PolicyState>,-): PoliciesByCategory {+): PoliciesByKey {const current = loadPolicies();- const next: PoliciesByCategory = {+ const next: PoliciesByKey = {...current,// Fall back to defaults so a not-yet-seeded category id still yields a// complete PolicyState rather than a partial.- [categoryId]: {- ...defaultState(categoryId),- ...current[categoryId],+ [policyKey]: {+ ...defaultState(policyKey),+ ...current[policyKey],...patch,},};@@ -119,10 +119,10 @@ export function updatePolicy(* entry keeps a dead backendId that the auto-run still tries to dispatch. Built-in categories are* never forgotten - they reseed on the next read anyway.*/-export function forgetPolicies(ids: string[]): PoliciesByCategory {+export function forgetPolicies(ids: string[]): PoliciesByKey {const current = loadPolicies();const catalogIds = new Set(loadPolicyCatalog().categories.map((c) => c.id));- const next: PoliciesByCategory = { ...current };+ const next: PoliciesByKey = { ...current };let removed = false;for (const id of ids) {if (catalogIds.has(id) || !(id in next)) continue;diff --git a/frontend/editor/src/proprietary/types/policies.ts b/frontend/editor/src/proprietary/types/policies.tsindex 4955ae20c1..2e74a924fa 100644--- a/frontend/editor/src/proprietary/types/policies.ts+++ b/frontend/editor/src/proprietary/types/policies.ts@@ -93,7 +93,7 @@ export interface PolicyState {isDefault?: boolean;}-export type PoliciesByCategory = Record<string, PolicyState>;+export type PoliciesByKey = Record<string, PolicyState>;/*** Output + retry settings applied by the Watch Folders engine to a policy's