Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dembrane/frontend/src/lib/errors/catalog/verify.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 3 additions & 3 deletions dembrane/platform/PACKAGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Most namespaces use core, observability, db, http, access, queue, ratelimit, leg
- **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.
- **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.
- **account** (in 5, out 16): The signed-in user's own account: profile, onboarding, settings, invites, transactional email. Used by support, accounts, reports, api and 1 more. Uses tenancy, notifications, samples, billing, auth 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, 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.
- **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.
- **support** (in 3, out 10): Support tickets: lifecycle rules, visibility and notices. Used by accounts, api, worker. Uses account, i18n, storage.
Expand All @@ -34,7 +34,7 @@ Most namespaces use core, observability, db, http, access, queue, ratelimit, leg
- **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.
- **feedback** (in 1, out 7): Ratings on model output, and the staff link to the old issue reports' images. Used by api. Uses storage.
- **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.
Expand All @@ -60,9 +60,9 @@ Most namespaces use core, observability, db, http, access, queue, ratelimit, leg
- **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.
- **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.
- **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.
- **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, observability and 1 more.

**Allowed imports between namespaces**
Expand Down
1 change: 1 addition & 0 deletions dembrane/platform/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dembrane/platform/packages/core/src/catalog/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions dembrane/platform/packages/verify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion dembrane/platform/packages/verify/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
});

Expand Down
184 changes: 177 additions & 7 deletions dembrane/platform/packages/verify/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ 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";
import { type ArtifactRow, type VerifyStorage, verifyStorage } from "./storage";
Expand Down Expand Up @@ -251,7 +253,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<VerifyDeps, "tokens"> },
header: string | undefined,
conversationId: string,
) {
ctx.d.tokens.check(header, conversationId);
}

Expand Down Expand Up @@ -291,7 +297,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<VerifyDeps, "tokens">;
readonly store: Pick<UpdateArtifactCtx["store"], "conversation">;
},
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");
Expand Down Expand Up @@ -330,7 +343,10 @@ function audioChunks(chunks: Chunk[], after: number | null): Chunk[] {
});
}

async function audioParts(ctx: Ctx, chunks: Chunk[]) {
async function audioParts(
ctx: { readonly d: Pick<VerifyDeps, "audio" | "audioUrls" | "logger"> },
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)}` });
Expand All @@ -352,7 +368,7 @@ async function audioParts(ctx: Ctx, chunks: Chunk[]) {
}

async function complete(
ctx: Ctx,
ctx: { readonly d: Pick<VerifyDeps, "models" | "logger"> },
system: string,
content: (TextPart | FilePart)[],
failure: string,
Expand Down Expand Up @@ -580,8 +596,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" | "limiter" | "logger" | "now"
>;
readonly store: {
artifact(id: string): Promise<ArtifactRow | null>;
conversation(id: string): Promise<{
conversation: { readonly id: string; readonly deleted_at: string | null };
project: VerifiableProject | null;
} | null>;
chunks(conversationId: string): ReturnType<VerifyStorage["chunks"]>;
updateArtifact(
id: string,
fields: { content?: string; approved_at?: string },
): Promise<ArtifactRow | null>;
};
}

export async function updateArtifact(
ctx: Ctx,
ctx: UpdateArtifactCtx,
artifactId: string,
body: {
useConversation: { conversationId: string; timestamp: Date } | null;
Expand All @@ -600,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<typeof row.project>;
// 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;
Expand Down Expand Up @@ -644,7 +684,15 @@ 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) {
// 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 =
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", {
message: "No valid fields to update",
Expand All @@ -658,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 <redacted_email> 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<string, string> = {
name: "<redacted_name>",
email: "<redacted_email>",
phone: "<redacted_phone>",
address: "<redacted_address>",
username: "<redacted_username>",
id: "<redacted_id>",
iban: "<redacted_iban>",
card: "<redacted_card>",
license_plate: "<redacted_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<VerifyDeps, "models" | "limiter" | "logger"> },
conversationId: string,
text: string,
): Promise<string> {
// 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 || /^<redacted_\w+>$/.test(value)) continue;
const placeholder = Object.hasOwn(PLACEHOLDER, span.kind)
? (PLACEHOLDER[span.kind] as string)
: "<redacted_name>";
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(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "giu"),
() => placeholder,
);
}
return out;
}

export { PARTICIPANT_TOKEN_HEADER };
Loading
Loading