feat: review text hits and release false-positive mappings

This commit is contained in:
muena
2026-10-19 06:44:21 +02:00
parent ebf78128c4
commit 03a793ad7c
20 changed files with 536 additions and 210 deletions

View File

@@ -21,7 +21,8 @@ import {
import { PseudonymizationConfirm } from "./ai-views"; import { PseudonymizationConfirm } from "./ai-views";
import { getSelectedTextSafely } from "./selection"; import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker"; import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context"; import { prepareTextInContext } from "./text-context";
import { TextHitReview } from "./text-hit-review";
import { import {
getActiveSessionId, getActiveSessionId,
listSessions, listSessions,
@@ -151,30 +152,29 @@ export default function Command() {
}); });
try { try {
const { result: pseudoResult, session: updatedSession } = const prepared = await prepareTextInContext(values, input, values.entityTypes);
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success; toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert"; toast.title = "Treffer zur Prüfung bereit";
toast.message = `${pseudoResult.entity_count} Zuordnungen`; toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push( push(
<PseudonymizationConfirm <PseudonymizationConfirm
session={updatedSession} session={updatedSession}
pseudonymizedText={pseudoResult.pseudonymized_text} pseudonymizedText={pseudoResult.pseudonymized_text}
model={values.model} model={values.model}
creativity={values.creativity} creativity={values.creativity}
instructions={values.instructions} instructions={values.instructions}
buildPrompt={buildBriefingPrompt} buildPrompt={buildBriefingPrompt}
labels={{ labels={{
pageHeading: "Briefing", pageHeading: "Briefing",
runningLabel: "KI erstellt Briefing …", runningLabel: "KI erstellt Briefing …",
failureTitle: "Briefing fehlgeschlagen", failureTitle: "Briefing fehlgeschlagen",
copyTitle: "Briefing kopieren", copyTitle: "Briefing kopieren",
pasteTitle: "Briefing einfügen", pasteTitle: "Briefing einfügen",
}} }}
/>, />,
); );
}} />);
} catch (error) { } catch (error) {
toast.style = Toast.Style.Failure; toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen"; toast.title = "Pseudonymisierung fehlgeschlagen";

View File

@@ -21,7 +21,8 @@ import {
import { PseudonymizationConfirm } from "./ai-views"; import { PseudonymizationConfirm } from "./ai-views";
import { getSelectedTextSafely } from "./selection"; import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker"; import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context"; import { prepareTextInContext } from "./text-context";
import { TextHitReview } from "./text-hit-review";
import { import {
getActiveSessionId, getActiveSessionId,
listSessions, listSessions,
@@ -156,30 +157,29 @@ export default function Command() {
}); });
try { try {
const { result: pseudoResult, session: updatedSession } = const prepared = await prepareTextInContext(values, input, values.entityTypes);
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success; toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert"; toast.title = "Treffer zur Prüfung bereit";
toast.message = `${pseudoResult.entity_count} Zuordnungen`; toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push( push(
<PseudonymizationConfirm <PseudonymizationConfirm
session={updatedSession} session={updatedSession}
pseudonymizedText={pseudoResult.pseudonymized_text} pseudonymizedText={pseudoResult.pseudonymized_text}
model={values.model} model={values.model}
creativity={values.creativity} creativity={values.creativity}
instructions={values.instructions} instructions={values.instructions}
buildPrompt={buildActionItemsPrompt} buildPrompt={buildActionItemsPrompt}
labels={{ labels={{
pageHeading: "Action Items", pageHeading: "Action Items",
runningLabel: "KI extrahiert Action Items …", runningLabel: "KI extrahiert Action Items …",
failureTitle: "Extraktion fehlgeschlagen", failureTitle: "Extraktion fehlgeschlagen",
copyTitle: "Action Items kopieren", copyTitle: "Action Items kopieren",
pasteTitle: "Action Items einfügen", pasteTitle: "Action Items einfügen",
}} }}
/>, />,
); );
}} />);
} catch (error) { } catch (error) {
toast.style = Toast.Style.Failure; toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen"; toast.title = "Pseudonymisierung fehlgeschlagen";

View File

@@ -21,7 +21,8 @@ import {
import { PseudonymizationConfirm } from "./ai-views"; import { PseudonymizationConfirm } from "./ai-views";
import { getSelectedTextSafely } from "./selection"; import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker"; import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context"; import { prepareTextInContext } from "./text-context";
import { TextHitReview } from "./text-hit-review";
import { import {
getActiveSessionId, getActiveSessionId,
listSessions, listSessions,
@@ -184,46 +185,45 @@ export default function Command() {
}); });
try { try {
const { result: pseudoResult, session: updatedSession } = const prepared = await prepareTextInContext(values, input, values.entityTypes);
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success; toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert"; toast.title = "Treffer zur Prüfung bereit";
toast.message = `${pseudoResult.entity_count} Zuordnungen`; toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
const schema = values.schema;
const format = values.format;
const buildPrompt = (pseudonymizedText: string, instructions: string) =>
buildStructuredDataPrompt({
pseudonymizedText,
instructions,
schema,
format,
});
const schema = values.schema; push(
const format = values.format; <PseudonymizationConfirm
const buildPrompt = (pseudonymizedText: string, instructions: string) => session={updatedSession}
buildStructuredDataPrompt({ pseudonymizedText={pseudoResult.pseudonymized_text}
pseudonymizedText, model={values.model}
instructions, creativity={values.creativity}
schema, instructions={values.instructions}
format, buildPrompt={buildPrompt}
}); labels={{
pageHeading:
push( format === "json" ? "Strukturierte Daten (JSON)" : "Tabelle",
<PseudonymizationConfirm runningLabel:
session={updatedSession} format === "json"
pseudonymizedText={pseudoResult.pseudonymized_text} ? "KI extrahiert Daten (JSON) …"
model={values.model} : "KI extrahiert Tabelle …",
creativity={values.creativity} failureTitle: "Extraktion fehlgeschlagen",
instructions={values.instructions} copyTitle:
buildPrompt={buildPrompt} format === "json" ? "JSON kopieren" : "Markdown-Tabelle kopieren",
labels={{ pasteTitle:
pageHeading: format === "json" ? "JSON einfügen" : "Tabelle einfügen",
format === "json" ? "Strukturierte Daten (JSON)" : "Tabelle", }}
runningLabel: />,
format === "json" );
? "KI extrahiert Daten (JSON) …" }} />);
: "KI extrahiert Tabelle …",
failureTitle: "Extraktion fehlgeschlagen",
copyTitle:
format === "json" ? "JSON kopieren" : "Markdown-Tabelle kopieren",
pasteTitle:
format === "json" ? "JSON einfügen" : "Tabelle einfügen",
}}
/>,
);
} catch (error) { } catch (error) {
toast.style = Toast.Style.Failure; toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen"; toast.title = "Pseudonymisierung fehlgeschlagen";

View File

@@ -2,6 +2,7 @@ import { promises as fs } from "node:fs";
import { basename, dirname, join } from "node:path"; import { basename, dirname, join } from "node:path";
import type { PlaceholderMapping } from "../types"; import type { PlaceholderMapping } from "../types";
import { canonicalPerson } from "./project-review"; import { canonicalPerson } from "./project-review";
import { mappingForRestoration, mappingRoot } from "./mapping-groups";
import { import {
createRun, digest, isMarkdownFile, isRestorableDocument, listRuns, loadProjectWhitelist, publishProjectCopies, createRun, digest, isMarkdownFile, isRestorableDocument, listRuns, loadProjectWhitelist, publishProjectCopies,
replaceProjectFilesInPlace, resolveWithin, restorePath, restoreText, replaceProjectFilesInPlace, resolveWithin, restorePath, restoreText,
@@ -18,17 +19,7 @@ export type RevisionPlan = {
}; };
function existingRoot(key: string, mapping: PlaceholderMapping): string { function existingRoot(key: string, mapping: PlaceholderMapping): string {
const seen = new Set<string>(); return mappingRoot(key, mapping);
let current = key;
while (mapping[current]?.merged_into) {
if (seen.has(current)) throw new Error("Zyklische Personen-Zuordnung.");
seen.add(current);
current = mapping[current].merged_into!;
if (!mapping[current] || mapping[current].type !== "PERSON") {
throw new Error("Personen-Zuordnung verweist auf ein ungültiges Ziel.");
}
}
return current;
} }
/** Build a single direct substitution for each changed placeholder; no replacement chains. */ /** Build a single direct substitution for each changed placeholder; no replacement chains. */
@@ -61,16 +52,17 @@ export function planProjectRevision(
} }
const mapping: PlaceholderMapping = {}; const mapping: PlaceholderMapping = {};
const replacements: PlaceholderMapping = {}; const replacements: PlaceholderMapping = {};
const restoration = mappingForRestoration(previous);
const merged: string[] = []; const merged: string[] = [];
for (const [key, entry] of Object.entries(previous)) { for (const [key, entry] of Object.entries(previous)) {
const oldRoot = entry.type === "PERSON" ? existingRoot(key, previous) : key; const oldRoot = existingRoot(key, previous);
if (releaseSet.has(key)) { if (releaseSet.has(key)) {
// A canonical placeholder can stand for several spelling variants. Its // A canonical placeholder can stand for several spelling variants. Its
// visible text restores to the canonical original; every variant is excluded. // visible text restores to the canonical original; every variant is excluded.
replacements[key] = { original: entry.original, type: entry.type }; replacements[key] = { original: restoration[key].original, type: entry.type };
continue; continue;
} }
const finalRoot = entry.type === "PERSON" ? canonicalPerson(oldRoot, merges) : key; const finalRoot = entry.type === "PERSON" ? canonicalPerson(oldRoot, merges) : oldRoot;
mapping[key] = { ...entry }; mapping[key] = { ...entry };
if (entry.type === "PERSON") { if (entry.type === "PERSON") {
if (finalRoot === key) delete mapping[key].merged_into; if (finalRoot === key) delete mapping[key].merged_into;
@@ -173,8 +165,10 @@ export async function reviseProjectRun(args: {
replacementAttempted = true; replacementAttempted = true;
await replaceProjectFilesInPlace(previous.projectPath, directory, run.files); await replaceProjectFilesInPlace(previous.projectPath, directory, run.files);
} else { } else {
publishedCopyPath = await publishProjectCopies(run, directory); if (run.files.length) {
run.copyPath = publishedCopyPath; publishedCopyPath = await publishProjectCopies(run, directory);
run.copyPath = publishedCopyPath;
}
await saveRun(directory, run); await saveRun(directory, run);
} }
} catch (error) { } catch (error) {

View File

@@ -20,6 +20,7 @@ import {
deleteSession, deleteSession,
getActiveSessionId, getActiveSessionId,
listSessions, listSessions,
releaseSessionMappingGroup,
renameSession, renameSession,
setActiveSession, setActiveSession,
} from "./sessions"; } from "./sessions";
@@ -149,7 +150,13 @@ export default function Command() {
<Action.Push <Action.Push
title="Übersetzungstabelle anzeigen" title="Übersetzungstabelle anzeigen"
icon={Icon.List} icon={Icon.List}
target={<TranslationTable title={session.name} mapping={session.mapping} />} target={<TranslationTable title={session.name} mapping={session.mapping}
removeDescription="Die gesamte Gruppe wird aus der Sitzung entfernt und künftig dort nicht mehr vorgeschlagen. Bereits kopierte oder eingefügte Texte werden nicht rückwirkend geändert."
onRemove={async (root) => {
const updated = await releaseSessionMappingGroup(session.id, root);
await reload();
return updated.mapping;
}} />}
/> />
<Action <Action
title="Als Aktive Sitzung Setzen" title="Als Aktive Sitzung Setzen"

View File

@@ -0,0 +1,11 @@
import { listRuns } from "./lib/velum-project";
import { reviseProjectRun } from "./lib/project-revision";
import { depseudonymizeDocument } from "./velum";
/** Release the whole alias group and update the latest saved project files. */
export async function releaseProjectMapping(projectPath: string, placeholder: string) {
const latest = (await listRuns(projectPath))[0];
if (!latest) throw new Error("Projektstand nicht gefunden.");
return reviseProjectRun({ previous: latest.run, previousDirectory: latest.directory,
release: new Set([placeholder]), merges: {}, rewriteDocument: depseudonymizeDocument });
}

View File

@@ -22,7 +22,8 @@ import { PseudonymizationConfirm } from "./ai-views";
import { getPreferences } from "./preferences"; import { getPreferences } from "./preferences";
import { getSelectedTextSafely } from "./selection"; import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker"; import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context"; import { prepareTextInContext } from "./text-context";
import { TextHitReview } from "./text-hit-review";
import { import {
getActiveSessionId, getActiveSessionId,
listSessions, listSessions,
@@ -216,30 +217,29 @@ export default function Command() {
}); });
try { try {
const { result: pseudoResult, session: updatedSession } = const prepared = await prepareTextInContext(values, input, values.entityTypes);
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success; toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert"; toast.title = "Treffer zur Prüfung bereit";
toast.message = `${pseudoResult.entity_count} Zuordnungen`; toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push( push(
<PseudonymizationConfirm <PseudonymizationConfirm
session={updatedSession} session={updatedSession}
pseudonymizedText={pseudoResult.pseudonymized_text} pseudonymizedText={pseudoResult.pseudonymized_text}
model={values.model} model={values.model}
creativity={values.creativity} creativity={values.creativity}
instructions={values.instructions} instructions={values.instructions}
buildPrompt={buildPrompt} buildPrompt={buildPrompt}
labels={{ labels={{
pageHeading: "Steering-Update", pageHeading: "Steering-Update",
runningLabel: "KI erstellt Steering-Update …", runningLabel: "KI erstellt Steering-Update …",
failureTitle: "Steering-Update fehlgeschlagen", failureTitle: "Steering-Update fehlgeschlagen",
copyTitle: "Steering-Update kopieren", copyTitle: "Steering-Update kopieren",
pasteTitle: "Steering-Update einfügen", pasteTitle: "Steering-Update einfügen",
}} }}
/>, />,
); );
}} />);
} catch (error) { } catch (error) {
toast.style = Toast.Style.Failure; toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen"; toast.title = "Pseudonymisierung fehlgeschlagen";

View File

@@ -289,10 +289,13 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
} }
return; return;
} }
if (inPlace && !(await confirmAlert({ if (!(await confirmAlert({
title: "Originaldateien ersetzen?", title: inPlace ? "Geprüfte Auswahl anwenden und Originaldateien ersetzen?" : "Geprüfte Auswahl als Kopien erstellen?",
message: "Die gewählten Dateien und gegebenenfalls ihre Namen werden im Projektordner ersetzt. Die Originale werden vorher außerhalb des Projekts gesichert. PDF-Dateien werden als DOCX ausgegeben.", message: `${selectedGroups.size} von ${groups.length} Begriffen in ${props.preview.drafts.length} neuen oder geänderten Dateien werden maskiert. ${groups.length - selectedGroups.size} abgewählte Begriffe werden als Projektausnahmen gespeichert. ${inPlace
primaryAction: { title: "Originaldateien ersetzen", style: Alert.ActionStyle.Destructive }, ? "Die Originale und gegebenenfalls ihre Namen werden im Projektordner ersetzt und vorher außerhalb gesichert. PDF-Dateien werden als DOCX ausgegeben."
: "Die pseudonymisierten Kopien werden neben dem Projektordner gespeichert."}`,
primaryAction: { title: inPlace ? "Originaldateien ersetzen" : "Kopien erstellen",
style: inPlace ? Alert.ActionStyle.Destructive : Alert.ActionStyle.Default },
}))) return; }))) return;
setBusy(true); setBusy(true);
const toast = await showToast({ style: Toast.Style.Animated, const toast = await showToast({ style: Toast.Style.Animated,

View File

@@ -21,7 +21,8 @@ import {
} from "./ui"; } from "./ui";
import { getEntityTypes } from "./velum"; import { getEntityTypes } from "./velum";
import { ContextPicker, type ContextFormValues } from "./context-picker"; import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context"; import { prepareTextInContext } from "./text-context";
import { TextHitReview } from "./text-hit-review";
import { getPreferences } from "./preferences"; import { getPreferences } from "./preferences";
type FormValues = ContextFormValues & { type FormValues = ContextFormValues & {
@@ -109,21 +110,23 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
}); });
try { try {
const { result, session } = await pseudonymizeInContext(values, input, values.entityTypes); const prepared = await prepareTextInContext(values, input, values.entityTypes);
toast.style = Toast.Style.Success; toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert"; toast.title = "Treffer zur Prüfung bereit";
toast.message = `${result.entity_count} Zuordnungen in ${session.name}`; toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} onConfirmed={async (result, session) => {
if (props.autoOutput) { if (props.autoOutput) {
if (getPreferences().quickOutput === "paste") { if (getPreferences().quickOutput === "paste") {
await Clipboard.paste(result.pseudonymized_text); await Clipboard.paste(result.pseudonymized_text);
await showHUD(`Pseudonymisierten Text eingefügt (${session.name})`); await showHUD(`Pseudonymisierten Text eingefügt (${session.name})`);
} else {
await Clipboard.copy(result.pseudonymized_text);
await showHUD(`Pseudonymisierten Text kopiert (${session.name})`);
}
} else { } else {
await Clipboard.copy(result.pseudonymized_text); push(<PseudonymizeResult result={result} session={session} />);
await showHUD(`Pseudonymisierten Text kopiert (${session.name})`);
} }
} else push(<PseudonymizeResult result={result} session={session} />); }} />);
} catch (error) { } catch (error) {
toast.style = Toast.Style.Failure; toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen"; toast.title = "Pseudonymisierung fehlgeschlagen";

View File

@@ -12,7 +12,8 @@ import {
} from "@raycast/api"; } from "@raycast/api";
import { getSelectedTextSafely } from "./selection"; import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker"; import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context"; import { prepareTextInContext } from "./text-context";
import { TextHitReview } from "./text-hit-review";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { import {
CREATIVITY_OPTIONS, CREATIVITY_OPTIONS,
@@ -183,26 +184,25 @@ export default function Command() {
}); });
try { try {
const { result: pseudoResult, session: updatedSession } = const prepared = await prepareTextInContext(values, input, values.entityTypes);
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success; toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert"; toast.title = "Treffer zur Prüfung bereit";
toast.message = `${pseudoResult.entity_count} Zuordnungen`; toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push( push(
<ConfirmReply <ConfirmReply
session={updatedSession} session={updatedSession}
pseudonymizedText={pseudoResult.pseudonymized_text} pseudonymizedText={pseudoResult.pseudonymized_text}
model={model} model={model}
creativity={creativity} creativity={creativity}
greeting={greeting} greeting={greeting}
signOff={signOff} signOff={signOff}
userFullName={userFullName} userFullName={userFullName}
instructions={values.instructions} instructions={values.instructions}
disclosure={disclosure} disclosure={disclosure}
/>, />,
); );
}} />);
} catch (error) { } catch (error) {
toast.style = Toast.Style.Failure; toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen"; toast.title = "Pseudonymisierung fehlgeschlagen";

View File

@@ -11,6 +11,7 @@ import { canonicalPerson, mergePeople } from "./lib/project-review";
import { planProjectRevision, reviseProjectRun } from "./lib/project-revision"; import { planProjectRevision, reviseProjectRun } from "./lib/project-revision";
import { TranslationTable } from "./show-translation-tables"; import { TranslationTable } from "./show-translation-tables";
import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "./lib/mapping-groups"; import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "./lib/mapping-groups";
import { releaseProjectMapping } from "./project-mapping-actions";
type SavedRun = { run: ProjectRun; directory: string }; type SavedRun = { run: ProjectRun; directory: string };
type RestoreDecision = MappingEntry | null; type RestoreDecision = MappingEntry | null;
@@ -454,6 +455,12 @@ export default function Command() {
(current) => detachMappingGroup(current, key)); (current) => detachMappingGroup(current, key));
await refresh(); await refresh();
return updated.mapping; return updated.mapping;
}}
removeDescription="Die gesamte Gruppe wird als Projektausnahme gespeichert. Der aktuelle Projektstand und seine Dateien werden korrigiert; bei Überschreiben wird zuvor eine Sicherung erstellt."
onRemove={async (root) => {
const revised = await releaseProjectMapping(run.projectPath, root);
await refresh();
return revised.run.mapping;
}} />} /> }} />} />
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder} <Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}
onAction={() => showInFinder(runCopiesPath(run, directory))} /> onAction={() => showInFinder(runCopiesPath(run, directory))} />

View File

@@ -2,6 +2,8 @@ import { LocalStorage } from "@raycast/api";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { getPreferences } from "./preferences"; import { getPreferences } from "./preferences";
import type { PlaceholderMapping, VelumSession } from "./types"; import type { PlaceholderMapping, VelumSession } from "./types";
import { mappingRoot } from "./lib/mapping-groups";
import { whitelistKey } from "./lib/project-whitelist";
const SESSIONS_STORAGE_KEY = "velum.sessions.v1"; const SESSIONS_STORAGE_KEY = "velum.sessions.v1";
const ACTIVE_SESSION_STORAGE_KEY = "velum.sessions.active.v1"; const ACTIVE_SESSION_STORAGE_KEY = "velum.sessions.active.v1";
@@ -85,6 +87,7 @@ export async function updateSessionMapping(
id: string, id: string,
mapping: PlaceholderMapping, mapping: PlaceholderMapping,
entityTypes?: string[], entityTypes?: string[],
excludedTerms?: VelumSession["excludedTerms"],
): Promise<VelumSession> { ): Promise<VelumSession> {
const sessions = await listSessions(); const sessions = await listSessions();
const timestamp = nowIso(); const timestamp = nowIso();
@@ -98,6 +101,7 @@ export async function updateSessionMapping(
updatedAt: timestamp, updatedAt: timestamp,
mapping, mapping,
entityTypes, entityTypes,
excludedTerms,
}; };
await saveSessions([created, ...sessions]); await saveSessions([created, ...sessions]);
return created; return created;
@@ -107,6 +111,7 @@ export async function updateSessionMapping(
...sessions[index], ...sessions[index],
mapping, mapping,
entityTypes, entityTypes,
excludedTerms: excludedTerms ?? sessions[index].excludedTerms,
updatedAt: timestamp, updatedAt: timestamp,
}; };
const next = [...sessions]; const next = [...sessions];
@@ -115,6 +120,18 @@ export async function updateSessionMapping(
return updated; return updated;
} }
export async function releaseSessionMappingGroup(id: string, root: string): Promise<VelumSession> {
const session = await getSession(id);
if (!session) throw new Error("Sitzung nicht gefunden.");
if (!session.mapping[root]) throw new Error("Zuordnung nicht gefunden. Bitte die Ansicht aktualisieren.");
const removed = Object.keys(session.mapping).filter((key) => mappingRoot(key, session.mapping) === root);
const mapping = Object.fromEntries(Object.entries(session.mapping).filter(([key]) => !removed.includes(key)));
const excludedTerms = [...new Map([...(session.excludedTerms ?? []),
...removed.map((key) => ({ type: session.mapping[key].type, original: session.mapping[key].original }))]
.map((entry) => [whitelistKey(entry), entry])).values()];
return updateSessionMapping(id, mapping, session.entityTypes, excludedTerms);
}
export async function renameSession(id: string, name: string): Promise<void> { export async function renameSession(id: string, name: string): Promise<void> {
const sessions = await listSessions(); const sessions = await listSessions();
await saveSessions( await saveSessions(

View File

@@ -1,6 +1,8 @@
import { import {
Action, Action,
ActionPanel, ActionPanel,
Alert,
confirmAlert,
Form, Form,
Icon, Icon,
List, List,
@@ -11,8 +13,9 @@ import {
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry, updateProjectMapping } from "./lib/velum-project"; import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry, updateProjectMapping } from "./lib/velum-project";
import { detachMappingGroup, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups"; import { detachMappingGroup, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
import { getSession, listSessions, updateSessionMapping } from "./sessions"; import { getSession, listSessions, releaseSessionMappingGroup, updateSessionMapping } from "./sessions";
import type { PlaceholderMapping } from "./types"; import type { PlaceholderMapping } from "./types";
import { releaseProjectMapping } from "./project-mapping-actions";
type TableSource = { type TableSource = {
id: string; id: string;
@@ -55,12 +58,16 @@ export function TranslationTable({
onAdd, onAdd,
onMerge, onMerge,
onDetach, onDetach,
onRemove,
removeDescription,
}: { }: {
title: string; title: string;
mapping: PlaceholderMapping; mapping: PlaceholderMapping;
onAdd?: (input: ManualEntry) => Promise<PlaceholderMapping>; onAdd?: (input: ManualEntry) => Promise<PlaceholderMapping>;
onMerge?: (source: string, target: string) => Promise<PlaceholderMapping>; onMerge?: (source: string, target: string) => Promise<PlaceholderMapping>;
onDetach?: (key: string) => Promise<PlaceholderMapping>; onDetach?: (key: string) => Promise<PlaceholderMapping>;
onRemove?: (root: string) => Promise<PlaceholderMapping>;
removeDescription?: string;
}) { }) {
const { push, pop } = useNavigation(); const { push, pop } = useNavigation();
const [visibleMapping, setVisibleMapping] = useState(mapping); const [visibleMapping, setVisibleMapping] = useState(mapping);
@@ -88,6 +95,14 @@ export function TranslationTable({
return false; return false;
} finally { setBusy(false); } } finally { setBusy(false); }
} }
async function remove(root: string, members: string[]) {
if (!onRemove || !(await confirmAlert({
title: `${members.length} Zuordnung${members.length === 1 ? "" : "en"} als False Positive freigeben?`,
message: removeDescription ?? "Diese Zuordnungen werden entfernt und als Ausnahmen gespeichert.",
primaryAction: { title: "Freigeben", style: Alert.ActionStyle.Destructive },
}))) return;
await change(() => onRemove(root), "False Positive freigegeben");
}
return ( return (
<List <List
@@ -141,6 +156,8 @@ export function TranslationTable({
<Action key={target} title={`${visibleMapping[target].original} · ${target}`} <Action key={target} title={`${visibleMapping[target].original} · ${target}`}
onAction={() => change(() => onMerge(placeholder, target), "Zuordnungen zusammengefasst")} />)} onAction={() => change(() => onMerge(placeholder, target), "Zuordnungen zusammengefasst")} />)}
</ActionPanel.Submenu>} </ActionPanel.Submenu>}
{onRemove && <Action title="False Positive freigeben" icon={Icon.XMarkCircle}
onAction={() => remove(placeholder, members)} />}
<Action.CopyToClipboard <Action.CopyToClipboard
title="Platzhalter kopieren" title="Platzhalter kopieren"
content={placeholder} content={placeholder}
@@ -243,6 +260,12 @@ export default function Command() {
await refresh(); await refresh();
return run.mapping; return run.mapping;
}} }}
removeDescription="Die gesamte Gruppe wird als Projektausnahme gespeichert. Der aktuelle Projektstand und seine Dateien werden korrigiert; bei Überschreiben wird zuvor eine Sicherung erstellt."
onRemove={async (root) => {
const revised = await releaseProjectMapping(source.id, root);
await refresh();
return revised.run.mapping;
}}
/> />
} }
/> />
@@ -296,6 +319,12 @@ export default function Command() {
await refresh(); await refresh();
return updated.mapping; return updated.mapping;
}} }}
removeDescription="Die gesamte Gruppe wird aus der Sitzung entfernt und künftig dort nicht mehr vorgeschlagen. Bereits kopierte oder eingefügte Texte werden nicht rückwirkend geändert."
onRemove={async (root) => {
const updated = await releaseSessionMappingGroup(source.id, root);
await refresh();
return updated.mapping;
}}
/> />
} }
/> />

View File

@@ -15,7 +15,8 @@ import { markdownToHtml, maybeCloseRaycast } from "./ai-views";
import { copyRichText } from "./rich-clipboard"; import { copyRichText } from "./rich-clipboard";
import { getSelectedTextSafely } from "./selection"; import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker"; import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context"; import { prepareTextInContext } from "./text-context";
import { TextHitReview } from "./text-hit-review";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { import {
getActiveSessionId, getActiveSessionId,
@@ -129,22 +130,21 @@ export default function Command() {
}); });
try { try {
const { result: pseudoResult, session: updatedSession } = const prepared = await prepareTextInContext(values, input, values.entityTypes);
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success; toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert"; toast.title = "Treffer zur Prüfung bereit";
toast.message = `${pseudoResult.entity_count} Zuordnungen`; toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push( push(
<ConfirmPseudonymized <ConfirmPseudonymized
session={updatedSession} session={updatedSession}
pseudonymizedText={pseudoResult.pseudonymized_text} pseudonymizedText={pseudoResult.pseudonymized_text}
model={values.model} model={values.model}
creativity={values.creativity} creativity={values.creativity}
instructions={values.instructions} instructions={values.instructions}
/>, />,
); );
}} />);
} catch (error) { } catch (error) {
toast.style = Toast.Style.Failure; toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen"; toast.title = "Pseudonymisierung fehlgeschlagen";

View File

@@ -21,7 +21,8 @@ import {
import { PseudonymizationConfirm } from "./ai-views"; import { PseudonymizationConfirm } from "./ai-views";
import { getSelectedTextSafely } from "./selection"; import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker"; import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context"; import { prepareTextInContext } from "./text-context";
import { TextHitReview } from "./text-hit-review";
import { import {
getActiveSessionId, getActiveSessionId,
listSessions, listSessions,
@@ -182,30 +183,29 @@ export default function Command() {
}); });
try { try {
const { result: pseudoResult, session: updatedSession } = const prepared = await prepareTextInContext(values, input, values.entityTypes);
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success; toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert"; toast.title = "Treffer zur Prüfung bereit";
toast.message = `${pseudoResult.entity_count} Zuordnungen`; toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push( push(
<PseudonymizationConfirm <PseudonymizationConfirm
session={updatedSession} session={updatedSession}
pseudonymizedText={pseudoResult.pseudonymized_text} pseudonymizedText={pseudoResult.pseudonymized_text}
model={values.model} model={values.model}
creativity={values.creativity} creativity={values.creativity}
instructions={values.instructions} instructions={values.instructions}
buildPrompt={buildMeetingNotesPrompt} buildPrompt={buildMeetingNotesPrompt}
labels={{ labels={{
pageHeading: "Meeting-Zusammenfassung", pageHeading: "Meeting-Zusammenfassung",
runningLabel: "KI strukturiert Meeting-Notizen …", runningLabel: "KI strukturiert Meeting-Notizen …",
failureTitle: "Zusammenfassung fehlgeschlagen", failureTitle: "Zusammenfassung fehlgeschlagen",
copyTitle: "Zusammenfassung kopieren", copyTitle: "Zusammenfassung kopieren",
pasteTitle: "Zusammenfassung einfügen", pasteTitle: "Zusammenfassung einfügen",
}} }}
/>, />,
); );
}} />);
} catch (error) { } catch (error) {
toast.style = Toast.Style.Failure; toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen"; toast.title = "Pseudonymisierung fehlgeschlagen";

View File

@@ -1,6 +1,6 @@
import { promises as fs } from "node:fs"; import { promises as fs } from "node:fs";
import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules, import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules,
loadProjectWhitelist, replaceSpans, saveRun, toUtf16Offsets, updateProjectMapping, whitelistKey } from "./lib/velum-project"; loadProjectWhitelist, replaceSpans, saveProjectWhitelist, saveRun, toUtf16Offsets, updateProjectMapping, whitelistKey } from "./lib/velum-project";
import { mappingForRestoration } from "./lib/mapping-groups"; import { mappingForRestoration } from "./lib/mapping-groups";
import type { ProjectWhitelistEntry } from "./lib/velum-project"; import type { ProjectWhitelistEntry } from "./lib/velum-project";
import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID, type ContextFormValues } from "./context-values"; import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID, type ContextFormValues } from "./context-values";
@@ -41,6 +41,104 @@ export function applyProjectWhitelist(text: string, response: PseudonymizeRespon
}; };
} }
export type PreparedText = {
text: string;
raw: PseudonymizeResponse;
previous: PlaceholderMapping;
exclusions: ProjectWhitelistEntry[];
selected: string;
projectPath?: string;
projectName?: string;
};
/** The local API may propose hits, but this step never stores mappings or starts a cloud request. */
export async function prepareTextInContext(values: ContextFormValues, text: string,
entityTypes: EntityType[], request: typeof pseudonymize = pseudonymize): Promise<PreparedText> {
const selected = values.sessionId;
if (!selected || selected === CHOOSE_CONTEXT_ID) throw new Error("Bitte ein Projekt oder eine Sitzung wählen.");
if (selected === NEW_PROJECT_ID || selected.startsWith("project:")) {
const folder = selected === NEW_PROJECT_ID ? values.newProjectPath?.[0] : selected.slice("project:".length);
if (!folder || !(await fs.stat(folder).catch(() => undefined))?.isDirectory()) {
throw new Error("Bitte einen vorhandenen Projektordner wählen.");
}
const path = canonicalProjectPath(folder);
const latest = (await listRuns(path))[0];
if (selected === NEW_PROJECT_ID && latest) {
throw new Error("Für diesen Ordner besteht bereits ein Projekt. Bitte es in der Liste wählen.");
}
if (selected !== NEW_PROJECT_ID && !latest) throw new Error("Projektstand nicht gefunden. Bitte die Liste aktualisieren.");
const [rules, exclusions] = await Promise.all([loadProjectRules(path), loadProjectWhitelist(path)]);
const excluded = new Set(exclusions.map(whitelistKey));
const masks = forceMasks(rules.filter((rule) => !excluded.has(whitelistKey({ type: rule.type, original: rule.value }))));
const previous = latest?.run.mapping ?? {};
const raw = applyProjectWhitelist(text, await request(text, previous, entityTypes, masks), previous, exclusions);
if (!raw.spans.length && raw.pseudonymized_text !== text) {
throw new Error("Die Analyse lieferte Maskierungen ohne überprüfbare Treffer. Es wurde nichts gespeichert.");
}
return { text, raw, previous, exclusions, selected, projectPath: path,
projectName: latest?.run.projectName ?? path.split("/").filter(Boolean).at(-1) ?? path };
}
const session = selected === NEW_SESSION_ID ? undefined : await getSession(selected);
if (selected !== NEW_SESSION_ID && !session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
const previous = session?.mapping ?? {};
const exclusions = session?.excludedTerms ?? [];
const raw = applyProjectWhitelist(text, await request(text, previous, entityTypes), previous, exclusions);
if (!raw.spans.length && raw.pseudonymized_text !== text) {
throw new Error("Die Analyse lieferte Maskierungen ohne überprüfbare Treffer. Es wurde nichts gespeichert.");
}
return { text, raw, previous, exclusions, selected };
}
/** Commit only the explicitly selected hits; rejected terms become context-specific exceptions. */
export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false):
Promise<{ result: PseudonymizeResponse; session: VelumSession }> {
const accepted = prepared.raw.spans.filter((_, index) => selectedHits.has(index));
const rejected = prepared.raw.spans.filter((_, index) => !selectedHits.has(index));
const spans = toUtf16Offsets(prepared.text, accepted).map((span, index) => ({ ...span, id: String(index) }));
const known = projectMapping(prepared.previous);
const preview = projectMapping(prepared.raw.mapping);
const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, "")));
const mapping: PlaceholderMapping = { ...known };
for (const key of active) {
const entry = preview[key];
if (!entry) throw new Error(`Zuordnung für ${key} fehlt. Es wurde nichts gespeichert.`);
mapping[key] = entry;
}
const raw: PseudonymizeResponse = { ...prepared.raw, spans: accepted,
mapping, entity_count: active.size,
pseudonymized_text: replaceSpans(prepared.text, spans, new Set(spans.map((span) => span.id))) };
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
const additions = rejected.map(({ type, original }) => ({ type, original }));
const exclusions = [...new Map([...prepared.exclusions, ...additions]
.map((item) => [whitelistKey(item), item])).values()];
if (prepared.projectPath) {
const path = prepared.projectPath;
const latest = (await listRuns(path))[0];
if (prepared.selected === NEW_PROJECT_ID ? Boolean(latest)
: !latest || JSON.stringify(latest.run.mapping) !== JSON.stringify(prepared.previous)) {
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
}
if (latest) {
await updateProjectMapping(path, () => mapping);
} else {
const created = await createRun(path);
created.run.mapping = mapping;
await saveRun(created.directory, created.run);
}
if (additions.length) await saveProjectWhitelist(path, exclusions);
return { result, session: resultSession(path, prepared.projectName ?? path,
mappingForRestoration(result.mapping), result.selected_entity_types) };
}
const session = prepared.selected === NEW_SESSION_ID ? await createSession() : await getSession(prepared.selected);
if (!session) throw new Error("Sitzung nicht gefunden. Bitte erneut analysieren.");
if (prepared.selected !== NEW_SESSION_ID && JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)) {
throw new Error("Die Sitzung wurde inzwischen geändert. Bitte erneut analysieren.");
}
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types, exclusions);
await setActiveSession(saved.id);
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
}
/** A text command must use the context explicitly selected in its form. */ /** A text command must use the context explicitly selected in its form. */
export async function pseudonymizeInContext(values: ContextFormValues, text: string, export async function pseudonymizeInContext(values: ContextFormValues, text: string,
entityTypes: EntityType[], forAi = false, entityTypes: EntityType[], forAi = false,

72
src/text-hit-review.tsx Normal file
View File

@@ -0,0 +1,72 @@
import { Action, ActionPanel, Icon, List, showToast, Toast } from "@raycast/api";
import { useMemo, useState } from "react";
import { groupReviewHits } from "./lib/project-review";
import { commitPreparedText, type PreparedText } from "./text-context";
import type { PseudonymizeResponse, VelumSession } from "./types";
export function TextHitReview(props: { prepared: PreparedText; forAi?: boolean;
onConfirmed: (result: PseudonymizeResponse, session: VelumSession) => Promise<void> | void }) {
const [selected, setSelected] = useState<Set<number>>(
() => new Set(props.prepared.raw.spans.map((_, index) => index)));
const [busy, setBusy] = useState(false);
const groups = useMemo(() => groupReviewHits(props.prepared.raw.spans.map((span, index) => ({
...span, id: String(index),
}))), [props.prepared]);
const byType = new Map<string, typeof groups>();
for (const group of groups) {
if (!byType.has(group.type)) byType.set(group.type, []);
byType.get(group.type)!.push(group);
}
async function confirm() {
if (busy) return;
setBusy(true);
const toast = await showToast({ style: Toast.Style.Animated, title: "Auswahl wird übernommen" });
try {
const { result, session } = await commitPreparedText(props.prepared, selected, props.forAi);
toast.style = Toast.Style.Success;
toast.title = "Auswahl übernommen";
toast.message = `${selected.size} Treffer bestätigt`;
await props.onConfirmed(result, session);
} catch (error) {
toast.style = Toast.Style.Failure;
toast.title = "Auswahl nicht übernommen";
toast.message = error instanceof Error ? error.message : String(error);
} finally { setBusy(false); }
}
function toggle(ids: number[]) {
setSelected((current) => {
const next = new Set(current);
const all = ids.every((id) => next.has(id));
for (const id of ids) { if (all) next.delete(id); else next.add(id); }
return next;
});
}
return <List isLoading={busy} isShowingDetail navigationTitle="Treffer vor Pseudonymisierung prüfen"
searchBarPlaceholder="Begriff, Kategorie oder Platzhalter suchen">
<List.Section title="Abschluss">
<List.Item icon={Icon.CheckCircle} title="Auswahl bestätigen"
subtitle={`${selected.size} von ${props.prepared.raw.spans.length} Treffern werden maskiert · Abgewählte werden als Ausnahme gespeichert`}
detail={<List.Item.Detail markdown="Prüfe die erkannten Begriffe unten. Klicke auf einen Treffer, um ihn ab- oder wieder anzuwählen. Erst mit **Auswahl bestätigen** werden die Zuordnungen gespeichert und der nächste Schritt gestartet." />}
actions={<ActionPanel><Action title="Auswahl bestätigen und fortfahren" icon={Icon.CheckCircle} onAction={confirm} /></ActionPanel>} />
</List.Section>
{[...byType].map(([type, typeGroups]) => <List.Section key={type} title={`${type} · ${typeGroups.length} Begriffe`}>
{typeGroups.map((group) => {
const ids = group.hits.map((hit) => Number(hit.id));
const all = ids.every((id) => selected.has(id));
const first = group.hits[0];
const start = Math.max(0, first.start - 90);
const end = Math.min([...props.prepared.text].length, first.end + 90);
const context = [...props.prepared.text].slice(start, end).join("");
return <List.Item key={group.key} icon={all ? Icon.CheckCircle : Icon.Circle}
title={`${group.original} → ${group.placeholder}`}
subtitle={group.hits.length > 1 ? `${group.hits.length} Vorkommen` : undefined}
detail={<List.Item.Detail markdown={`**Kontext**\n\n${context.replace(/`/g, "'")}`} />}
actions={<ActionPanel>
<Action title={all ? "Nicht maskieren" : "Maskieren"} icon={all ? Icon.XMarkCircle : Icon.CheckCircle}
onAction={() => toggle(ids)} />
<Action title="Auswahl bestätigen und fortfahren" icon={Icon.CheckCircle} onAction={confirm} />
</ActionPanel>} />;
})}
</List.Section>)}
</List>;
}

View File

@@ -35,6 +35,7 @@ export type VelumSession = {
updatedAt: string; updatedAt: string;
mapping: PlaceholderMapping; mapping: PlaceholderMapping;
entityTypes?: EntityType[]; entityTypes?: EntityType[];
excludedTerms?: Array<{ type: string; original: string }>;
}; };
export type QuickOutput = "copy" | "paste"; export type QuickOutput = "copy" | "paste";

View File

@@ -60,6 +60,16 @@ describe("Nachbearbeitung von Projektständen", () => {
expect(plan.mapping).toEqual({}); expect(plan.mapping).toEqual({});
}); });
it("gibt auch gruppierte Begriffe samt Verweisen frei und verwendet den Hauptbegriff", () => {
const plan = revision.planProjectRevision({
BEGRIFF_01: { type: "BEGRIFF", original: "Kundensoftware" },
BEGRIFF_02: { type: "BEGRIFF", original: "Kunden-App", merged_into: "BEGRIFF_01" },
}, new Set(["BEGRIFF_02"]), {});
expect(plan.released).toEqual(["BEGRIFF_01", "BEGRIFF_02"]);
expect(plan.replacements.BEGRIFF_02.original).toBe("Kundensoftware");
expect(plan.mapping).toEqual({});
});
it("repariert bereits gespeicherte Personen-Zusammenführungen in Inhalt und Dateiname", async () => { it("repariert bereits gespeicherte Personen-Zusammenführungen in Inhalt und Dateiname", async () => {
const root = await fs.mkdtemp(join(tmpdir(), "velum-merge-repair-")); const root = await fs.mkdtemp(join(tmpdir(), "velum-merge-repair-"));
roots.push(root); roots.push(root);

View File

@@ -4,16 +4,27 @@ import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import type { PlaceholderMapping, PseudonymizeResponse } from "../src/types"; import type { PlaceholderMapping, PseudonymizeResponse } from "../src/types";
const storage = new Map<string, string>();
mock.module("@raycast/api", () => ({ mock.module("@raycast/api", () => ({
environment: { supportPath: tmpdir() }, environment: { supportPath: tmpdir() },
Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined, Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined,
LocalStorage: {}, getPreferenceValues: () => ({}), LocalStorage: {
getItem: async (key: string) => storage.get(key),
setItem: async (key: string, value: string) => { storage.set(key, value); },
removeItem: async (key: string) => { storage.delete(key); },
},
getPreferenceValues: () => ({ velumBaseUrl: "", authentikTokenUrl: "", clientId: "",
serviceAccountUsername: "", serviceAccountPassword: "", maxSessions: "20" }),
})); }));
const { applyProjectWhitelist, pseudonymizeInContext } = await import("../src/text-context"); const { applyProjectWhitelist, pseudonymizeInContext, prepareTextInContext, commitPreparedText } = await import("../src/text-context");
const project = await import("../src/lib/velum-project"); const project = await import("../src/lib/velum-project");
const sessions = await import("../src/sessions");
const { normalizePseudonymizeResponse } = await import("../src/velum"); const { normalizePseudonymizeResponse } = await import("../src/velum");
const roots: string[] = []; const roots: string[] = [];
afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); }); afterEach(async () => {
storage.clear();
await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
});
it("behält Verweise beim Umstellen auf KI-Platzhalter konsistent", () => { it("behält Verweise beim Umstellen auf KI-Platzhalter konsistent", () => {
const result = normalizePseudonymizeResponse({ const result = normalizePseudonymizeResponse({
@@ -44,6 +55,69 @@ it("übernimmt eine Projekt-Ausnahme auch bei Textbefehlen", () => {
expect(result.entity_count).toBe(1); expect(result.entity_count).toBe(1);
}); });
it("speichert vor der Trefferbestätigung nichts und übernimmt nur ausgewählte Treffer", async () => {
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-review-"));
roots.push(root);
const folder = join(root, "Projekt");
await fs.mkdir(folder);
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => ({
pseudonymized_text: "PERSON_01 und ORT_01", selected_entity_types: ["PERSON", "ORT"],
spans: [
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
{ start: 8, end: 14, type: "ORT", score: 1, placeholder: "ORT_01", original: "Montag" },
], entity_count: 2,
mapping: { ...mapping, PERSON_01: { type: "PERSON", original: "Max" },
ORT_01: { type: "ORT", original: "Montag" } },
});
const prepared = await prepareTextInContext({ sessionId: "__new_project__", newProjectPath: [folder] },
"Max und Montag", ["PERSON", "ORT"], request);
expect(await project.listRuns(folder)).toHaveLength(0);
expect(await project.loadProjectWhitelist(folder)).toEqual([]);
const { result } = await commitPreparedText(prepared, new Set([0]), true);
expect(result.pseudonymized_text).toBe("<PERSON_01> und Montag");
expect(result.mapping["<ORT_01>"]).toBeUndefined();
expect((await project.listRuns(folder))[0].run.mapping.ORT_01).toBeUndefined();
expect(await project.loadProjectWhitelist(folder)).toEqual([{ type: "ORT", original: "Montag" }]);
const next = await prepareTextInContext({ sessionId: `project:${folder}` },
"Max und Montag", ["PERSON", "ORT"], request);
expect(next.raw.spans.map((span) => span.original)).toEqual(["Max"]);
});
it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht erneut vor", async () => {
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => ({
pseudonymized_text: "PERSON_01", selected_entity_types: ["PERSON"], entity_count: 1,
mapping: { ...mapping, PERSON_01: { type: "PERSON", original: "Fachbegriff" } },
spans: [{ start: 0, end: 11, type: "PERSON", score: 0.8,
placeholder: "PERSON_01", original: "Fachbegriff" }],
});
const prepared = await prepareTextInContext({ sessionId: "__new_session__" },
"Fachbegriff", ["PERSON"], request);
expect(await sessions.listSessions()).toHaveLength(0);
const { result, session } = await commitPreparedText(prepared, new Set());
expect(result.pseudonymized_text).toBe("Fachbegriff");
expect(session.mapping).toEqual({});
expect((await sessions.getSession(session.id))?.excludedTerms).toEqual([
{ type: "PERSON", original: "Fachbegriff" },
]);
const next = await prepareTextInContext({ sessionId: session.id }, "Fachbegriff", ["PERSON"], request);
expect(next.raw.spans).toEqual([]);
});
it("entfernt eine False-Positive-Gruppe aus der Sitzung und merkt alle Varianten", async () => {
const session = await sessions.createSession("Test");
await sessions.updateSessionMapping(session.id, {
"<PERSON_01>": { type: "PERSON", original: "Fachbegriff" },
"<PERSON_02>": { type: "PERSON", original: "Fachbegriff kurz", merged_into: "<PERSON_01>" },
"<ORG_01>": { type: "ORG", original: "Beispiel GmbH" },
});
const revised = await sessions.releaseSessionMappingGroup(session.id, "<PERSON_01>");
expect(Object.keys(revised.mapping)).toEqual(["<ORG_01>"]);
expect(revised.excludedTerms).toEqual([
{ type: "PERSON", original: "Fachbegriff" },
{ type: "PERSON", original: "Fachbegriff kurz" },
]);
});
it("verlangt eine ausdrückliche Kontextwahl und legt ein Textprojekt nur einmal an", async () => { it("verlangt eine ausdrückliche Kontextwahl und legt ein Textprojekt nur einmal an", async () => {
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-context-")); const root = await fs.mkdtemp(join(tmpdir(), "velum-text-context-"));
roots.push(root); roots.push(root);