From 7c2d14ea2d0d8d33ce8321191ca8b7c960a55fdc Mon Sep 17 00:00:00 2001 From: Jorim Theuns Date: Mon, 30 Nov 2026 11:08:34 +0100 Subject: [PATCH 1/2] fix: redact PII on manual Verify artifact edits in anonymised projects --- dembrane/platform/PACKAGES.md | 6 +- dembrane/platform/bun.lock | 1 + .../platform/packages/verify/package.json | 1 + .../platform/packages/verify/src/service.ts | 54 +++++- .../verify/test/manual-edit-redaction.test.ts | 168 ++++++++++++++++++ .../test/prompt-privacy.integration.test.ts | 34 ++++ 6 files changed, 255 insertions(+), 9 deletions(-) create mode 100644 dembrane/platform/packages/verify/test/manual-edit-redaction.test.ts diff --git a/dembrane/platform/PACKAGES.md b/dembrane/platform/PACKAGES.md index 6c76efecc..bc10da1e8 100644 --- a/dembrane/platform/PACKAGES.md +++ b/dembrane/platform/PACKAGES.md @@ -21,7 +21,7 @@ Most namespaces use core, observability, db, http, access, queue, legacy-shape, - **analysis** (in 5, out 11): The analysis engine: recipes, runs, snapshots and revisions that maps and popcorn build on. Used by popcorn, map, present, api and 1 more. Uses realtime, llm. - **notifications** (in 5, out 5): In-app notifications and announcements, and the Notifier other namespaces emit through. Used by account, agentic, reports, api and 1 more. Uses only the common ones. - **samples** (in 5, out 5): Sample data: the best-practices sample every workspace gets its own copy of, and the Millbrook (sample) workspace in the Acme Civic (sample) org that every PR preview carries. Used by account, tenancy, api, migrate and 1 more. Uses config, llm. -- **conversations** (in 5, out 18): Conversations, the participant portal, the audio pipeline, live monitoring and search. Used by agentic, verify, agent-access, api and 1 more. Uses projects, webhooks, prompts, transcription, audio and 4 more. +- **conversations** (in 5, out 18): Conversations, the participant portal, the audio pipeline, live monitoring and search. Used by agentic, verify, agent-access, api and 1 more. Uses projects, webhooks, prompts, audio, transcription and 4 more. - **account** (in 4, out 16): The signed-in user's own account: profile, onboarding, settings, invites, transactional email. Used by accounts, reports, api, worker. Uses tenancy, notifications, samples, billing, auth and 4 more. - **popcorn** (in 4, out 14): Popcorn: one live deck per project, refreshed on a tick, with demos and translations. Used by accounts, present, api, worker. Uses analysis, analytics, realtime, config, llm. - **tenancy** (in 3, out 14): Orgs and workspaces: members, settings, access requests, support access, project shares. Used by account, api, worker. Uses samples, billing, projects, mail, i18n and 1 more. @@ -34,7 +34,7 @@ Most namespaces use core, observability, db, http, access, queue, legacy-shape, - **present** (in 2, out 12): Present: the published, audience-facing view of a popcorn deck and a map. Used by api, worker. Uses map, popcorn, analysis, realtime. - **pricing** (in 2, out 8): The pricing configurator and the bookings it forwards. Used by api, worker. Uses storage. - **reports** (in 2, out 13): Report generation and the report timeline. Used by api, worker. Uses account, notifications, projects, webhooks, llm. -- **verify** (in 2, out 13): Verification topics and artifacts participants see in the portal. Used by api, migrate. Uses conversations, projects, prompts, i18n, llm. +- **verify** (in 2, out 14): Verification topics and artifacts participants see in the portal. Used by api, migrate. Uses conversations, projects, prompts, transcription, i18n and 1 more. - **agent-access** (in 1, out 11): Outside AI agents reaching dembrane: the MCP server, OAuth, and the tools it exposes. Used by api. Uses conversations, webhooks, analytics, realtime. - **staff** (in 1, out 13): The staff console: support tools, billing rollups, privacy exports and erasure. Used by api. Uses billing, metering, mail, i18n, storage. - **stats** (in 1, out 4): Public usage numbers the website shows. Used by api. Uses only the common ones. @@ -59,8 +59,8 @@ Most namespaces use core, observability, db, http, access, queue, legacy-shape, - **analytics** (in 8, out 1): Product analytics capture (PostHog). Used by conversations, popcorn, accounts, chats and 4 more. Uses observability. - **mail** (in 8, out 0): Sending email (SendGrid, or memory in tests). Used by billing, account, tenancy, accounts and 4 more. Uses nothing. - **audio** (in 4, out 0): ffmpeg and ffprobe wrappers, audio formats, and the client for the media app. Used by conversations, api, media, worker. Uses nothing. +- **transcription** (in 4, out 3): Speech to text with Gemini, plus PII redaction and a fake for tests. Used by conversations, verify, api, worker. Uses prompts, llm, observability. - **prompts** (in 3, out 0): The Jinja prompt templates carried over from Python, rendered the same way. Used by transcription, conversations, verify. Uses nothing. -- **transcription** (in 3, out 3): Speech to text with Gemini, plus PII redaction and a fake for tests. Used by conversations, api, worker. Uses prompts, llm, observability. - **auth** (in 3, out 2): Sign-in and sessions (Better Auth) and the identity sync from Directus. Used by account, api, migrate. Uses db, core. - **metering** (in 3, out 6): What each model call cost: one log line and one model_call row per call, which the obs views aggregate. Used by staff, api, worker. Uses allowance, llm, queue, db, core and 1 more. diff --git a/dembrane/platform/bun.lock b/dembrane/platform/bun.lock index c06ca8c3d..947043b78 100644 --- a/dembrane/platform/bun.lock +++ b/dembrane/platform/bun.lock @@ -837,6 +837,7 @@ "@dembrane/projects": "workspace:*", "@dembrane/prompts": "workspace:*", "@dembrane/ratelimit": "workspace:*", + "@dembrane/transcription": "workspace:*", "ai": "^7.0.118", "drizzle-orm": "^0.45.3", "hono": "^4.9.0", diff --git a/dembrane/platform/packages/verify/package.json b/dembrane/platform/packages/verify/package.json index fc606ccf1..ee5702fca 100644 --- a/dembrane/platform/packages/verify/package.json +++ b/dembrane/platform/packages/verify/package.json @@ -31,6 +31,7 @@ "@dembrane/projects": "workspace:*", "@dembrane/prompts": "workspace:*", "@dembrane/ratelimit": "workspace:*", + "@dembrane/transcription": "workspace:*", "ai": "^7.0.118", "drizzle-orm": "^0.45.3", "hono": "^4.9.0" diff --git a/dembrane/platform/packages/verify/src/service.ts b/dembrane/platform/packages/verify/src/service.ts index 529520abe..61ce29d59 100644 --- a/dembrane/platform/packages/verify/src/service.ts +++ b/dembrane/platform/packages/verify/src/service.ts @@ -18,6 +18,7 @@ import { modelErrorShape, speechHint } from "@dembrane/llm"; import { withPayer } from "@dembrane/observability"; import { PROJECT_TEMPLATES } from "@dembrane/projects"; import { renderPrompt } from "@dembrane/prompts"; +import { regexRedactPii } from "@dembrane/transcription"; import { type FilePart, generateText, type TextPart } from "ai"; import { DEFAULT_TOPIC_KEY, defaultTopicPrompt } from "./defaults"; import { type ArtifactRow, type VerifyStorage, verifyStorage } from "./storage"; @@ -251,7 +252,11 @@ function artifactView(a: ArtifactRow, fallbackConversation: string) { * The portal's capability on a conversation (Q7): a participant token, when sent, must * name it; without one the conversation id still works unless tokens are required. */ -function checkToken(ctx: Ctx, header: string | undefined, conversationId: string) { +function checkToken( + ctx: { readonly d: Pick }, + header: string | undefined, + conversationId: string, +) { ctx.d.tokens.check(header, conversationId); } @@ -291,7 +296,14 @@ export async function getArtifact(ctx: Ctx, artifactId: string, token: string | * project too, and the project must have verify switched on. The Python API checked * none of these. */ -async function verifiableConversation(ctx: Ctx, conversationId: string, token: string | undefined) { +async function verifiableConversation( + ctx: { + readonly d: Pick; + readonly store: Pick; + }, + conversationId: string, + token: string | undefined, +) { const row = await ctx.store.conversation(conversationId); if (!row || row.conversation.deleted_at || !row.project || row.project.deleted_at) throw new NotFoundError("conversation.not_found"); @@ -330,7 +342,10 @@ function audioChunks(chunks: Chunk[], after: number | null): Chunk[] { }); } -async function audioParts(ctx: Ctx, chunks: Chunk[]) { +async function audioParts( + ctx: { readonly d: Pick }, + chunks: Chunk[], +) { const out: (TextPart | FilePart)[] = []; for (const c of chunks) { out.push({ type: "text", text: `Audio chunk ${c.id} captured at ${pyIsoformat(c.timestamp)}` }); @@ -352,7 +367,7 @@ async function audioParts(ctx: Ctx, chunks: Chunk[]) { } async function complete( - ctx: Ctx, + ctx: { readonly d: Pick }, system: string, content: (TextPart | FilePart)[], failure: string, @@ -580,8 +595,32 @@ export async function generateArtifact( return { artifact_list: [artifactView(created, conv.id)] }; } +export interface VerifiableProject extends VerifyProject { + readonly deleted_at: string | null; + readonly is_verify_enabled: boolean | null; +} + +export interface UpdateArtifactCtx { + readonly d: Pick< + VerifyDeps, + "db" | "audio" | "audioUrls" | "models" | "tokens" | "logger" | "now" + >; + readonly store: { + artifact(id: string): Promise; + conversation(id: string): Promise<{ + conversation: { readonly id: string; readonly deleted_at: string | null }; + project: VerifiableProject | null; + } | null>; + chunks(conversationId: string): ReturnType; + updateArtifact( + id: string, + fields: { content?: string; approved_at?: string }, + ): Promise; + }; +} + export async function updateArtifact( - ctx: Ctx, + ctx: UpdateArtifactCtx, artifactId: string, body: { useConversation: { conversationId: string; timestamp: Date } | null; @@ -644,7 +683,10 @@ export async function updateArtifact( "Failed to revise verification artifact", project.language || "en", ); - } else if (body.content !== null) updates.content = body.content; + } else if (body.content !== null) { + updates.content = + project.anonymize_transcripts === true ? regexRedactPii(body.content) : body.content; + } if (!Object.keys(updates).length) throw new BadRequestError("request.nothing_to_update", { message: "No valid fields to update", diff --git a/dembrane/platform/packages/verify/test/manual-edit-redaction.test.ts b/dembrane/platform/packages/verify/test/manual-edit-redaction.test.ts new file mode 100644 index 000000000..0a00d21d1 --- /dev/null +++ b/dembrane/platform/packages/verify/test/manual-edit-redaction.test.ts @@ -0,0 +1,168 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Writable } from "node:stream"; +import { AudioUrls, ParticipantTokens } from "@dembrane/conversations"; +import { createDb } from "@dembrane/db"; +import { fakeModels } from "@dembrane/llm"; +import { createLogger } from "@dembrane/observability"; +import { FilesystemStorage } from "@dembrane/storage"; +import { type UpdateArtifactCtx, updateArtifact } from "../src/service"; +import type { ArtifactRow } from "../src/storage"; + +const PROJECT_ID = "f9100000-0000-4000-8000-000000000001"; +const CONVERSATION_ID = "c9200000-0000-4000-8000-000000000001"; +const ARTIFACT_ID = "a9300000-0000-4000-8000-000000000001"; + +const PII_INPUT = + "Contact jan@example.nl or +31 6 12345678 (alt 06-87654321), postcode 1234 AB, IBAN NL91 ABNA 0417 1643 0012, BSN 123456789."; +const PII_REDACTED = + "Contact or (alt ), postcode , IBAN , BSN ."; + +const database = createDb({ url: "postgres://unused:unused@127.0.0.1:1/unused", poolMax: 1 }); +const audio = new FilesystemStorage( + mkdtempSync(join(tmpdir(), "verify-redact-")), + "http://t", + "/a", +); +const logger = createLogger( + { service: "t", release: "r", env: "test", level: "error" }, + new Writable({ write: (_c, _e, cb) => cb() }), +); + +afterAll(async () => { + await database.close(); +}); + +function setup(anonymizeTranscripts: boolean | null) { + let stored: ArtifactRow = { + id: ARTIFACT_ID, + conversation_id: CONVERSATION_ID, + key: "agreements", + topic_label: "Agreements", + content: "Initial draft", + approved_at: null, + date_created: "2026-11-30T10:00:00.000Z", + last_updated_at: null, + read_aloud_stream_url: "", + user_created: null, + user_updated: null, + }; + let lastWrite: { content?: string; approved_at?: string } | null = null; + + const ctx: UpdateArtifactCtx = { + d: { + db: database.db, + audio, + audioUrls: new AudioUrls("http://s3.test", "bucket"), + models: fakeModels({ text: "unused" }), + tokens: new ParticipantTokens("s".repeat(48), false), + logger, + now: () => new Date("2026-11-30T12:00:00Z"), + }, + store: { + async artifact(id) { + return id === ARTIFACT_ID ? stored : null; + }, + async conversation(id) { + if (id !== CONVERSATION_ID) return null; + return { + conversation: { id: CONVERSATION_ID, deleted_at: null }, + project: { + id: PROJECT_ID, + name: "Park feedback", + language: "en", + context: null, + default_conversation_transcript_prompt: null, + anonymize_transcripts: anonymizeTranscripts, + template_key: null, + deleted_at: null, + is_verify_enabled: true, + }, + }; + }, + async chunks() { + return []; + }, + async updateArtifact(id, fields) { + if (id !== ARTIFACT_ID) return null; + lastWrite = { ...fields }; + stored = { + ...stored, + ...(fields.content !== undefined ? { content: fields.content } : {}), + ...(fields.approved_at !== undefined ? { approved_at: fields.approved_at } : {}), + }; + return stored; + }, + }, + }; + + return { + ctx, + stored: () => stored, + lastWrite: () => lastWrite, + }; +} + +describe("manual Verify artifact edit PII redaction", () => { + test("redacts PII before storing and returning when anonymize_transcripts is true", async () => { + const { ctx, stored, lastWrite } = setup(true); + const result = await updateArtifact( + ctx, + ARTIFACT_ID, + { + useConversation: null, + content: PII_INPUT, + approvedAt: "2026-11-30T12:00:00Z", + }, + undefined, + ); + + expect(lastWrite()?.content).toBe(PII_REDACTED); + expect(stored().content).toBe(PII_REDACTED); + expect(result.content).toBe(PII_REDACTED); + expect(result.content).not.toContain("jan@example.nl"); + expect(result.content).not.toContain("12345678"); + expect(result.content).not.toContain("87654321"); + expect(result.content).not.toContain("1234 AB"); + expect(result.content).not.toContain("NL91 ABNA"); + expect(result.content).not.toContain("123456789"); + }); + + test("leaves manual edits unchanged when anonymize_transcripts is false", async () => { + const { ctx, stored, lastWrite } = setup(false); + const result = await updateArtifact( + ctx, + ARTIFACT_ID, + { + useConversation: null, + content: PII_INPUT, + approvedAt: null, + }, + undefined, + ); + + expect(lastWrite()?.content).toBe(PII_INPUT); + expect(stored().content).toBe(PII_INPUT); + expect(result.content).toBe(PII_INPUT); + }); + + test("leaves manual edits unchanged when anonymize_transcripts is null", async () => { + const { ctx, stored, lastWrite } = setup(null); + const result = await updateArtifact( + ctx, + ARTIFACT_ID, + { + useConversation: null, + content: PII_INPUT, + approvedAt: null, + }, + undefined, + ); + + expect(lastWrite()?.content).toBe(PII_INPUT); + expect(stored().content).toBe(PII_INPUT); + expect(result.content).toBe(PII_INPUT); + }); +}); diff --git a/dembrane/platform/packages/verify/test/prompt-privacy.integration.test.ts b/dembrane/platform/packages/verify/test/prompt-privacy.integration.test.ts index 9b6304952..72896e473 100644 --- a/dembrane/platform/packages/verify/test/prompt-privacy.integration.test.ts +++ b/dembrane/platform/packages/verify/test/prompt-privacy.integration.test.ts @@ -177,6 +177,40 @@ run("verify prompt privacy", () => { expect(written).not.toContain(SAID); }); + test("manual edits redact PII when anonymize_transcripts is true and keep text when false", async () => { + const [artifact] = await sql<{ id: string }[]>` + select id from conversation_artifact where conversation_id = ${conversation} limit 1`; + const input = "Mail jan@example.nl or call 06-12345678, postcode 1234 AB."; + const redacted = + "Mail or call , postcode ."; + + await sql`update project set anonymize_transcripts = true where id = ${project}`; + try { + const resOn = await send(ok, `/api/verify/artifact/${artifact?.id}`, "PUT", { + content: input, + }); + expect(resOn.status).toBe(200); + const bodyOn = (await resOn.json()) as { content: string }; + expect(bodyOn.content).toBe(redacted); + const [rowOn] = await sql<{ content: string | null }[]>` + select content from conversation_artifact where id = ${artifact?.id ?? ""}`; + expect(rowOn?.content).toBe(redacted); + + await sql`update project set anonymize_transcripts = false where id = ${project}`; + const resOff = await send(ok, `/api/verify/artifact/${artifact?.id}`, "PUT", { + content: input, + }); + expect(resOff.status).toBe(200); + const bodyOff = (await resOff.json()) as { content: string }; + expect(bodyOff.content).toBe(input); + const [rowOff] = await sql<{ content: string | null }[]>` + select content from conversation_artifact where id = ${artifact?.id ?? ""}`; + expect(rowOff?.content).toBe(input); + } finally { + await sql`update project set anonymize_transcripts = false where id = ${project}`; + } + }); + test("the logs of the whole run never held the email", () => { expect(logs.join("")).not.toContain(EMAIL); }); From f5ef6900cdffde6f131f80fb53124c1f3834dc1d Mon Sep 17 00:00:00 2001 From: Usama Date: Wed, 2 Dec 2026 17:36:31 +0500 Subject: [PATCH 2/2] fix(verify): redact names too in hand edits on anonymised projects The regex pass alone let names through. After it, a fast model call names the personal details left and code replaces exactly those spans (any casing, whole words, capitalised name parts too, never a joining word like van/los/des alone), so the markdown and the rest of the text stay as typed. - Only edited text is checked; approving the unedited draft makes no call. - A failed or non-JSON answer (after one retry) saves nothing: verify.generation_failed. - content is capped at 20,000 characters and the check is rate limited per conversation (20 per 10 minutes), since it runs outside the AI allowance. --- .../src/lib/errors/catalog/verify.gen.ts | 2 +- .../packages/core/src/catalog/verify.ts | 2 +- .../platform/packages/verify/src/routes.ts | 2 +- .../platform/packages/verify/src/service.ts | 134 ++++++++- .../verify/test/manual-edit-redaction.test.ts | 261 +++++++++++++++--- .../test/prompt-privacy.integration.test.ts | 10 +- .../verify/test/verify.integration.test.ts | 9 + 7 files changed, 367 insertions(+), 53 deletions(-) diff --git a/dembrane/frontend/src/lib/errors/catalog/verify.gen.ts b/dembrane/frontend/src/lib/errors/catalog/verify.gen.ts index ecf6e5640..d6e6d06b7 100644 --- a/dembrane/frontend/src/lib/errors/catalog/verify.gen.ts +++ b/dembrane/frontend/src/lib/errors/catalog/verify.gen.ts @@ -52,7 +52,7 @@ export const verify = { action: "retry", detail: "Failed to generate verification artifact", description: - "The model call behind an artefact (made or revised) failed; sent as a 500 with the old text.", + "The model call behind an artefact (made, revised, or a hand edit redacted on an anonymised project) failed; sent as a 500 with the old text.", }, "verify.content_conflict": { action: "fix_input", diff --git a/dembrane/platform/packages/core/src/catalog/verify.ts b/dembrane/platform/packages/core/src/catalog/verify.ts index 01431a0f2..3e92b2b13 100644 --- a/dembrane/platform/packages/core/src/catalog/verify.ts +++ b/dembrane/platform/packages/core/src/catalog/verify.ts @@ -50,7 +50,7 @@ export const verify = { action: "retry", detail: "Failed to generate verification artifact", description: - "The model call behind an artefact (made or revised) failed; sent as a 500 with the old text.", + "The model call behind an artefact (made, revised, or a hand edit redacted on an anonymised project) failed; sent as a 500 with the old text.", }, "verify.content_conflict": { action: "fix_input", diff --git a/dembrane/platform/packages/verify/src/routes.ts b/dembrane/platform/packages/verify/src/routes.ts index a7c621c88..0c7169612 100644 --- a/dembrane/platform/packages/verify/src/routes.ts +++ b/dembrane/platform/packages/verify/src/routes.ts @@ -46,7 +46,7 @@ const useConversation = nested( // ignored by pydantic 2, so approved_at and use_conversation were silently dropped. const updateArtifactBody = model({ useConversation: optional(nullable(useConversation), null), - content: optional(nullable(str()), null), + content: optional(nullable(str({ max: 20_000 })), null), approvedAt: optional(nullable(str()), null), }); diff --git a/dembrane/platform/packages/verify/src/service.ts b/dembrane/platform/packages/verify/src/service.ts index 61ce29d59..8452afab3 100644 --- a/dembrane/platform/packages/verify/src/service.ts +++ b/dembrane/platform/packages/verify/src/service.ts @@ -18,6 +18,7 @@ import { modelErrorShape, speechHint } from "@dembrane/llm"; import { withPayer } from "@dembrane/observability"; import { PROJECT_TEMPLATES } from "@dembrane/projects"; import { renderPrompt } from "@dembrane/prompts"; +import type { Limit } from "@dembrane/ratelimit"; import { regexRedactPii } from "@dembrane/transcription"; import { type FilePart, generateText, type TextPart } from "ai"; import { DEFAULT_TOPIC_KEY, defaultTopicPrompt } from "./defaults"; @@ -603,7 +604,7 @@ export interface VerifiableProject extends VerifyProject { export interface UpdateArtifactCtx { readonly d: Pick< VerifyDeps, - "db" | "audio" | "audioUrls" | "models" | "tokens" | "logger" | "now" + "db" | "audio" | "audioUrls" | "models" | "tokens" | "limiter" | "logger" | "now" >; readonly store: { artifact(id: string): Promise; @@ -639,7 +640,7 @@ export async function updateArtifact( if (!artifact.conversation_id) throw new NotFoundError("conversation.not_found"); const row = await verifiableConversation(ctx, artifact.conversation_id, token); const project = row.project as NonNullable; - // Only a revision calls the model; hand edits and approvals always work. + // Only a revision spends the AI allowance; hand edits and approvals always work. if (body.useConversation) await requirePortalAi(ctx.d.db, project.id, ctx.d.now()); const updates: { content?: string; approved_at?: string } = {}; if (body.approvedAt !== null) updates.approved_at = body.approvedAt; @@ -684,8 +685,13 @@ export async function updateArtifact( project.language || "en", ); } else if (body.content !== null) { + // The stored text is the model's draft or an edit already redacted, so only a change + // needs the check. + const edited = body.content !== (artifact.content ?? "") && body.content.trim() !== ""; updates.content = - project.anonymize_transcripts === true ? regexRedactPii(body.content) : body.content; + edited && project.anonymize_transcripts === true + ? await redactEdit(ctx, artifact.conversation_id, body.content) + : body.content; } if (!Object.keys(updates).length) throw new BadRequestError("request.nothing_to_update", { @@ -700,4 +706,126 @@ export async function updateArtifact( }; } +const EDIT_PII_SYSTEM = `You find personal details in text a participant typed. +Answer with JSON only: {"spans":[{"text":"...","kind":"..."}]} +- "text" is copied exactly from the input, character for character, without the surrounding words. +- "kind" is one of: name, email, phone, address, username, id, iban, card, license_plate. +- Include names of people (first, last or full names), email addresses, phone numbers, street addresses and postcodes, usernames and handles, national ID or passport numbers, IBANs, card numbers and licence plates. +- Leave out names of places, organisations, products and events, job titles, dates, years, amounts and counts. +- Placeholders such as are already safe; leave them out. +- When there are none, answer {"spans":[]}.`; + +export const EDIT_REDACTION_LIMIT: Limit = { + name: "verify.edit_redaction", + capacity: 20, + windowSeconds: 600, +}; + +// Joining words of names (Dutch, German, Spanish, Portuguese, French, Italian, Arabic), +// never redacted on their own: "los" of "Carlos de los Santos" stays elsewhere. +const NAME_PARTICLES = new Set( + ( + "van von der den ter ten het aan uit vom zum zur und " + + "del los las dos das des les une " + + "dei dal dai dall dalla dalle degli delle della dello " + + "bin ibn bint abu" + ).split(" "), +); + +const PLACEHOLDER: Record = { + name: "", + email: "", + phone: "", + address: "", + username: "", + id: "", + iban: "", + card: "", + license_plate: "", +}; + +/** The spans the model named, or null when its answer is not the JSON asked for. */ +function parseSpans(raw: string): { text: string; kind: string }[] | null { + const body = raw + .trim() + .replace(/^```(?:json)?\s*/i, "") + .replace(/```$/, ""); + try { + const spans = (JSON.parse(body) as { spans?: unknown }).spans; + if (!Array.isArray(spans)) return null; + return spans.filter( + (x): x is { text: string; kind: string } => + typeof x?.text === "string" && typeof x?.kind === "string", + ); + } catch { + return null; + } +} + +/** + * A participant's hand edit on an anonymised project: the regex pass transcripts get, then + * the model names the personal details left (names above all) and code replaces exactly + * those, so the markdown and the rest of the words stay as typed. Not gated on the AI + * allowance: privacy is not a feature. Any failure saves nothing, so raw text never lands. + */ +async function redactEdit( + ctx: { readonly d: Pick }, + conversationId: string, + text: string, +): Promise { + // Each check is a model call outside the AI allowance; cap them per conversation. + await ctx.d.limiter.check(EDIT_REDACTION_LIMIT, conversationId); + const fail = () => + new StatusError(500, "verify.generation_failed", { + message: "Failed to redact the edited verification artifact", + }); + let out = regexRedactPii(text); + let spans: { text: string; kind: string }[] | null = null; + for (let attempt = 0; attempt < 2 && spans === null; attempt++) { + try { + const { text: raw } = await withPayer({ ref: "conversation", id: conversationId }, () => + generateText({ + model: ctx.d.models.model("text_fast"), + system: EDIT_PII_SYSTEM, + messages: [{ role: "user", content: [{ type: "text", text: out }] }], + providerOptions: { vertex: { thinkingConfig: { thinkingBudget: 0 } } }, + }), + ); + spans = parseSpans(raw); + } catch (err) { + ctx.d.logger.error({ error: modelErrorShape(err) }, "verify edit redaction failed"); + throw fail(); + } + } + if (spans === null) { + ctx.d.logger.error({ conversationId }, "verify edit redaction answered no JSON"); + throw fail(); + } + // A span in any casing, then each capitalised part of a name ("Jan" of "Jan de Vries") + // in any casing too, but never a joining word alone, so "van" or "los" in a sentence + // stays. Whole words only, longest first. + const swaps: { value: string; placeholder: string }[] = []; + for (const span of spans) { + const value = span.text.trim(); + if (value.length < 2 || /^$/.test(value)) continue; + const placeholder = Object.hasOwn(PLACEHOLDER, span.kind) + ? (PLACEHOLDER[span.kind] as string) + : ""; + swaps.push({ value, placeholder }); + if (span.kind === "name") + // A part written lowercase inside the name is a joining word too. + for (const part of value.split(/\s+/)) + if (part.length >= 3 && /^\p{Lu}/u.test(part) && !NAME_PARTICLES.has(part.toLowerCase())) + swaps.push({ value: part, placeholder }); + } + for (const { value, placeholder } of swaps.sort((a, b) => b.value.length - a.value.length)) { + const escaped = value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + out = out.replace( + new RegExp(`(? placeholder, + ); + } + return out; +} + export { PARTICIPANT_TOKEN_HEADER }; diff --git a/dembrane/platform/packages/verify/test/manual-edit-redaction.test.ts b/dembrane/platform/packages/verify/test/manual-edit-redaction.test.ts index 0a00d21d1..c5ba4c1f9 100644 --- a/dembrane/platform/packages/verify/test/manual-edit-redaction.test.ts +++ b/dembrane/platform/packages/verify/test/manual-edit-redaction.test.ts @@ -7,6 +7,7 @@ import { AudioUrls, ParticipantTokens } from "@dembrane/conversations"; import { createDb } from "@dembrane/db"; import { fakeModels } from "@dembrane/llm"; import { createLogger } from "@dembrane/observability"; +import { MemoryRateCounter, RateLimiter } from "@dembrane/ratelimit"; import { FilesystemStorage } from "@dembrane/storage"; import { type UpdateArtifactCtx, updateArtifact } from "../src/service"; import type { ArtifactRow } from "../src/storage"; @@ -35,7 +36,25 @@ afterAll(async () => { await database.close(); }); -function setup(anonymizeTranscripts: boolean | null) { +/** A model that names "Jan de Vries" when it is in the text, and records what it read. */ +function namingModel(seen: string[], answer?: (text: string) => string | null) { + return fakeModels({ + text: (prompt) => { + const user = prompt.find((m) => m.role === "user"); + const text = + user && Array.isArray(user.content) + ? user.content.map((c) => ("text" in c ? c.text : "")).join("") + : ""; + seen.push(text); + if (answer) return answer(text); + return JSON.stringify({ + spans: text.includes("Jan de Vries") ? [{ text: "Jan de Vries", kind: "name" }] : [], + }); + }, + }); +} + +function setup(anonymizeTranscripts: boolean | null, models = namingModel([])) { let stored: ArtifactRow = { id: ARTIFACT_ID, conversation_id: CONVERSATION_ID, @@ -56,7 +75,8 @@ function setup(anonymizeTranscripts: boolean | null) { db: database.db, audio, audioUrls: new AudioUrls("http://s3.test", "bucket"), - models: fakeModels({ text: "unused" }), + models, + limiter: new RateLimiter(new MemoryRateCounter()), tokens: new ParticipantTokens("s".repeat(48), false), logger, now: () => new Date("2026-11-30T12:00:00Z"), @@ -105,64 +125,217 @@ function setup(anonymizeTranscripts: boolean | null) { }; } +const EDIT = `Draft for you to correct. + +* Benches along the **Lindenpad**. +* My name is Jan de Vries. ${PII_INPUT} + +Is this right?`; +const EDIT_REDACTED = `Draft for you to correct. + +* Benches along the **Lindenpad**. +* My name is . ${PII_REDACTED} + +Is this right?`; + +const edit = (content: string, approvedAt: string | null = "2026-11-30T12:00:00Z") => ({ + useConversation: null, + content, + approvedAt, +}); + describe("manual Verify artifact edit PII redaction", () => { - test("redacts PII before storing and returning when anonymize_transcripts is true", async () => { - const { ctx, stored, lastWrite } = setup(true); - const result = await updateArtifact( + test("an edit on an anonymised project loses names and contact details, keeps the markdown", async () => { + const seen: string[] = []; + const { ctx, stored, lastWrite } = setup(true, namingModel(seen)); + const result = await updateArtifact(ctx, ARTIFACT_ID, edit(EDIT), undefined); + + expect(lastWrite()?.content).toBe(EDIT_REDACTED); + expect(stored().content).toBe(EDIT_REDACTED); + expect(result.content).toBe(EDIT_REDACTED); + // The model reads the text after the regex pass, never the raw contact details. + expect(seen).toHaveLength(1); + expect(seen[0]).not.toContain("jan@example.nl"); + expect(seen[0]).toContain("Jan de Vries"); + }); + + test.each([false, null])("anonymize_transcripts %p keeps the edit as typed", async (flag) => { + const seen: string[] = []; + const { ctx, stored } = setup(flag, namingModel(seen)); + const result = await updateArtifact(ctx, ARTIFACT_ID, edit(EDIT, null), undefined); + + expect(seen).toHaveLength(0); + expect(stored().content).toBe(EDIT); + expect(result.content).toBe(EDIT); + }); + + test("approving the unedited draft makes no model call", async () => { + const seen: string[] = []; + const { ctx, lastWrite } = setup(true, namingModel(seen)); + await updateArtifact(ctx, ARTIFACT_ID, edit("Initial draft"), undefined); + + expect(seen).toHaveLength(0); + expect(lastWrite()).toEqual({ content: "Initial draft", approved_at: "2026-11-30T12:00:00Z" }); + }); + + test("spans the text does not hold, and placeholders, change nothing", async () => { + const answer = () => + JSON.stringify({ + spans: [ + { text: "Piet Jansen", kind: "name" }, + { text: "", kind: "email" }, + { text: "Jan de Vries", kind: "name" }, + ], + }); + const { ctx, stored } = setup(true, namingModel([], answer)); + await updateArtifact(ctx, ARTIFACT_ID, edit(EDIT), undefined); + + expect(stored().content).toBe(EDIT_REDACTED); + }); + + test("other casings, a bare first name and a possessive go too; words that merely contain a span stay", async () => { + const text = + "Jan de Vries said so. Later JAN DE VRIES and jan de vries agreed, and Jan's dog too. vries came, jan stayed. Also Alma."; + const answer = () => + JSON.stringify({ + spans: [ + { text: "Jan de Vries", kind: "name" }, + { text: "Al", kind: "name" }, + ], + }); + const { ctx, stored } = setup(true, namingModel([], answer)); + await updateArtifact(ctx, ARTIFACT_ID, edit(text), undefined); + + expect(stored().content).toBe( + " said so. Later and agreed, and 's dog too. came, stayed. Also Alma.", + ); + }); + + test("particles of a name stay when they stand alone", async () => { + const answer = () => JSON.stringify({ spans: [{ text: "Joost van der Berg", kind: "name" }] }); + const { ctx, stored } = setup(true, namingModel([], answer)); + await updateArtifact( ctx, ARTIFACT_ID, - { - useConversation: null, - content: PII_INPUT, - approvedAt: "2026-11-30T12:00:00Z", - }, + edit( + "Joost van der Berg wants a park. Berg says the van der Pek market moved; joost agrees.", + ), undefined, ); - expect(lastWrite()?.content).toBe(PII_REDACTED); - expect(stored().content).toBe(PII_REDACTED); - expect(result.content).toBe(PII_REDACTED); - expect(result.content).not.toContain("jan@example.nl"); - expect(result.content).not.toContain("12345678"); - expect(result.content).not.toContain("87654321"); - expect(result.content).not.toContain("1234 AB"); - expect(result.content).not.toContain("NL91 ABNA"); - expect(result.content).not.toContain("123456789"); + expect(stored().content).toBe( + " wants a park. says the van der Pek market moved; agrees.", + ); }); - test("leaves manual edits unchanged when anonymize_transcripts is false", async () => { - const { ctx, stored, lastWrite } = setup(false); - const result = await updateArtifact( + test.each([ + [ + "Carlos de los Santos", + "Carlos de los Santos lo dijo. Todos los vecinos y santos estuvieron.", + " lo dijo. Todos los vecinos y estuvieron.", + ], + [ + "Pierre des Champs", + "Pierre des Champs parle des parcs. pierre aussi.", + " parle des parcs. aussi.", + ], + [ + "Giovanni dei Medici", + "Giovanni dei Medici e i parchi dei quartieri.", + " e i parchi dei quartieri.", + ], + [ + "Anna von und zu Lichtenstein", + "Anna von und zu Lichtenstein kam und blieb.", + " kam und blieb.", + ], + ])("joining words of %s stay elsewhere in the text", async (name, text, expected) => { + const answer = () => JSON.stringify({ spans: [{ text: name, kind: "name" }] }); + const { ctx, stored } = setup(true, namingModel([], answer)); + await updateArtifact(ctx, ARTIFACT_ID, edit(text), undefined); + + expect(stored().content).toBe(expected); + }); + + test("a lowercase part of a name is a joining word, wherever it comes from", async () => { + const answer = () => + JSON.stringify({ spans: [{ text: "Maria da Silva e Souza", kind: "name" }] }); + const { ctx, stored } = setup(true, namingModel([], answer)); + await updateArtifact( ctx, ARTIFACT_ID, - { - useConversation: null, - content: PII_INPUT, - approvedAt: null, - }, + edit("Maria da Silva e Souza falou. Silva concorda e souza também."), undefined, ); - expect(lastWrite()?.content).toBe(PII_INPUT); - expect(stored().content).toBe(PII_INPUT); - expect(result.content).toBe(PII_INPUT); + expect(stored().content).toBe( + " falou. concorda e também.", + ); }); - test("leaves manual edits unchanged when anonymize_transcripts is null", async () => { - const { ctx, stored, lastWrite } = setup(null); - const result = await updateArtifact( - ctx, - ARTIFACT_ID, - { - useConversation: null, - content: PII_INPUT, - approvedAt: null, - }, - undefined, + test("a kind outside the list still redacts, as a name", async () => { + const answer = () => JSON.stringify({ spans: [{ text: "Jan de Vries", kind: "constructor" }] }); + const { ctx, stored } = setup(true, namingModel([], answer)); + await updateArtifact(ctx, ARTIFACT_ID, edit(EDIT), undefined); + + expect(stored().content).toBe(EDIT_REDACTED); + }); + + test("a second answer is used when the first is not JSON", async () => { + let n = 0; + const answer = () => + ++n === 1 + ? "Sure! Here you go" + : JSON.stringify({ spans: [{ text: "Jan de Vries", kind: "name" }] }); + const { ctx, stored } = setup(true, namingModel([], answer)); + await updateArtifact(ctx, ARTIFACT_ID, edit(EDIT), undefined); + + expect(n).toBe(2); + expect(stored().content).toBe(EDIT_REDACTED); + }); + + test("edit checks are rate limited per conversation", async () => { + const seen: string[] = []; + const { ctx } = setup(true, namingModel(seen)); + for (let i = 0; i < 20; i++) + await updateArtifact(ctx, ARTIFACT_ID, edit(`${EDIT} ${i}`, null), undefined); + + await expect( + updateArtifact(ctx, ARTIFACT_ID, edit(`${EDIT} again`, null), undefined), + ).rejects.toMatchObject({ code: "rate_limit.exceeded" }); + expect(seen).toHaveLength(20); + }); + + test("a fenced JSON answer is read too", async () => { + const answer = () => '```json\n{"spans":[{"text":"Jan de Vries","kind":"name"}]}\n```'; + const { ctx, stored } = setup(true, namingModel([], answer)); + await updateArtifact(ctx, ARTIFACT_ID, edit(EDIT), undefined); + + expect(stored().content).toBe(EDIT_REDACTED); + }); + + test("a failing model saves nothing and answers verify.generation_failed", async () => { + const { ctx, stored, lastWrite } = setup(true, fakeModels({ fail: new Error("model down") })); + + await expect(updateArtifact(ctx, ARTIFACT_ID, edit(EDIT), undefined)).rejects.toMatchObject({ + status: 500, + code: "verify.generation_failed", + }); + expect(lastWrite()).toBeNull(); + expect(stored().content).toBe("Initial draft"); + }); + + test("an answer that is not the JSON asked for, twice, saves nothing", async () => { + const seen: string[] = []; + const { ctx, lastWrite } = setup( + true, + namingModel(seen, () => "Sorry, I cannot help."), ); - expect(lastWrite()?.content).toBe(PII_INPUT); - expect(stored().content).toBe(PII_INPUT); - expect(result.content).toBe(PII_INPUT); + await expect(updateArtifact(ctx, ARTIFACT_ID, edit(EDIT), undefined)).rejects.toMatchObject({ + code: "verify.generation_failed", + }); + expect(seen).toHaveLength(2); + expect(lastWrite()).toBeNull(); }); }); diff --git a/dembrane/platform/packages/verify/test/prompt-privacy.integration.test.ts b/dembrane/platform/packages/verify/test/prompt-privacy.integration.test.ts index 72896e473..0658bb5a6 100644 --- a/dembrane/platform/packages/verify/test/prompt-privacy.integration.test.ts +++ b/dembrane/platform/packages/verify/test/prompt-privacy.integration.test.ts @@ -84,7 +84,11 @@ run("verify prompt privacy", () => { ok = verifyRoutes({ ...base, models: fakeModels({ - text: "Draft for this table to correct.\n- Benches.\nIs this right?", + // The edit redaction call gets the spans it asks for; every other call a draft. + text: (prompt) => + JSON.stringify(prompt).includes("You find personal details") + ? JSON.stringify({ spans: [{ text: NAME, kind: "name" }] }) + : "Draft for this table to correct.\n- Benches.\nIs this right?", calls: calls as never, }), }); @@ -180,9 +184,9 @@ run("verify prompt privacy", () => { test("manual edits redact PII when anonymize_transcripts is true and keep text when false", async () => { const [artifact] = await sql<{ id: string }[]>` select id from conversation_artifact where conversation_id = ${conversation} limit 1`; - const input = "Mail jan@example.nl or call 06-12345678, postcode 1234 AB."; + const input = `I am ${NAME}.\n\n- Mail jan@example.nl or call 06-12345678, postcode 1234 AB.`; const redacted = - "Mail or call , postcode ."; + "I am .\n\n- Mail or call , postcode ."; await sql`update project set anonymize_transcripts = true where id = ${project}`; try { diff --git a/dembrane/platform/packages/verify/test/verify.integration.test.ts b/dembrane/platform/packages/verify/test/verify.integration.test.ts index 8487e3c97..2c7b46b37 100644 --- a/dembrane/platform/packages/verify/test/verify.integration.test.ts +++ b/dembrane/platform/packages/verify/test/verify.integration.test.ts @@ -157,6 +157,15 @@ run("verify generation against the seed", () => { }); }); + test("an edit longer than 20,000 characters is refused before anything runs", async () => { + const [artifact] = + await sql`select id from conversation_artifact where conversation_id = ${c1} limit 1`; + const asked = prompts.length; + const res = await post(`/api/verify/artifact/${artifact?.id}`, { content: "x".repeat(20_001) }); + expect(res.status).toBe(422); + expect(prompts.length).toBe(asked); + }); + test("revision uses feedback after the timestamp, only on the artifact's own conversation", async () => { const [artifact] = await sql`select id from conversation_artifact where conversation_id = ${c1} limit 1`;