6 Commits

Author SHA1 Message Date
muena
b630093075 feat: load available AI models from Raycast 2026-12-02 08:53:37 +01:00
muena
019f6b6d7c feat: improve Velum hit review and session creation 2026-12-02 08:53:37 +01:00
96d5f3f57d Merge pull request 'Velum Raycast: Standard-Typen alle außer IP, Datum, Referenz (agent/default-entity-types)' (#2) from paperclip-bot/velum-raycast:agent/default-entity-types into main
Reviewed-on: #2
2026-12-01 06:14:22 +00:00
e2df0cda33 feat: preselect all entity types except IP, Datum and Referenz
Forms and the project-file command now preselect the backend's
default_entity_types from /api/entity-types instead of every type. Older
backends without that field fall back to all types except IP, DATUM and
REFERENZ. Saved project selections are still loaded unchanged; the
project-file command keeps excluding ORT by default as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 06:04:40 +00:00
1eba3f5921 Merge pull request 'Velum Raycast: lokale DOCX-Verarbeitung im Hintergrund zur Freigabe (agent/velum-project-files)' (#1) from paperclip-bot/velum-raycast:agent/velum-project-files into main
Reviewed-on: #1
2026-11-30 20:15:21 +00:00
dd0ac92518 fix: propagate recognized person names across local DOCX segments
The local DOCX flow analyzes each paragraph separately, so the backend's
per-text person propagation never crosses paragraph boundaries. A name
recognized once ("Frau Jorinde Quastenberg") stayed in clear text wherever
the model missed it in context ("bei Quastenberg nachfragen").

After all segment batches of a file, add the remaining occurrences of
confidently recognized full names, their parts (3+ characters) and names
after a salutation (including a genitive s) as reviewable PERSON hits.
Whitelist, placeholder filtering and the hit review still apply.

Synthetic reproduction with de_core_news_lg: 59 unmasked name occurrences
before, 0 after; comments, insertions, deletions and anchors verified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:48:09 +00:00
29 changed files with 823 additions and 218 deletions

View File

@@ -14,18 +14,31 @@ nachverfolgten Änderungen, einschließlich gelöschter Texte und Feldcodes.
Kommentarverweise und Änderungsmarkierungen bleiben erhalten. Optionale
Microsoft-Kontoverknüpfungen in `word/people.xml` werden entfernt.
Die Erkennung bewertet jeden Absatz einzeln. Ein Name wird daher je nach Satz
erkannt oder nicht („Quastenberg prüft …“, aber nicht „bei Quastenberg
nachfragen“). Velum überträgt deshalb sicher erkannte Personennamen auf alle
weiteren Vorkommen in derselben Datei: vollständige Namen, deren Bestandteile
ab drei Zeichen und Namen nach einer Anrede wie `Frau` oder `Dr.`, auch mit
Genitiv-s. Diese Vorkommen erscheinen wie alle anderen in der Trefferprüfung und
lassen sich dort gemeinsam abwählen. Bleiben trotzdem Namen stehen, trage sie
als Projektbegriff ein, zum Beispiel `PERSON: Max Mustermann`.
Bei der Analyse und nach dem Bestätigen der Ausgabe kannst du Raycast
schließen. Öffne anschließend im selben Befehl denselben Projektordner, um
den Status oder die Trefferprüfung zu öffnen. Vor dem Anwenden prüft der
Hintergrundprozess den Datei-Hash.
Für die lokale DOCX-Verarbeitung muss `uv` installiert sein (zum Beispiel
`brew install uv`). Beim ersten Lauf verwendet es Python 3.11 und richtet
`lxml` aus seinem Paketcache ein. Das Velum-Backend muss den Segment-Endpunkt
bereitstellen. Beim Bauen der Erweiterung werden der Python-Codec und der
Hintergrundprozess mitgeliefert. Ist der Backend-Checkout an einem anderen
Ort, setze `VELUM_BACKEND_DIR` vor `npm run build` oder `npm run dev` auf
seinen `backend`-Ordner.
`brew install uv`). Beim ersten Lauf lädt es Python 3.11 und `lxml` 6.2.1 in
seinen Paketcache; dafür ist einmalig Internetzugang nötig. Dokumentinhalte
werden dabei nicht übertragen. Das Velum-Backend muss den Segment-Endpunkt
bereitstellen, also mindestens Stand `2517637` („support local DOCX segment
analysis“). Beim Bauen der Erweiterung werden der Python-Codec und der
Hintergrundprozess aus dem Backend-Checkout mitgeliefert. Der Checkout sollte
deshalb denselben Stand haben wie das produktive Backend. Ohne Angabe sucht
der Build unter `../../velum/backend`, relativ zu diesem Repository. Liegt der
Backend-Checkout an einem anderen Ort, setze `VELUM_BACKEND_DIR` vor
`npm run build` oder `npm run dev` auf seinen `backend`-Ordner.
`Projektdateien pseudonymisieren` übernimmt zuerst den geöffneten Finder-Ordner; bei Bedarf kann er im Formular erneut übernommen oder manuell gewählt werden. Im Formular werden die zu erkennenden Kategorien ausgewählt (Orte sind wegen häufiger Fehlalarme zunächst abgewählt). Danach analysiert Velum alle geeigneten Text-, DOCX-, XLSX-, PPTX- und PDF-Dateien sowie ihre Namen. Unterstriche zwischen Namensbestandteilen werden bei der Erkennung als Worttrenner behandelt; bekannte Platzhalter und wörtliche Codebegriffe bleiben erhalten. Auch Namen unveränderter Dateien werden in einem Folgelauf erneut geprüft. Ältere Word-Projektstände werden einmalig auf Kommentatoren geprüft, sofern `PERSON` ausgewählt ist. Kleine Textdateien und Namen werden in Paketen analysiert, um die Anzahl der API-Aufrufe zu verringern. Die Prüfung zeigt jede eindeutige Zuordnung einmal, nach Kategorie gruppiert, mit der Anzahl ihrer Vorkommen. Eine Zuordnung an- oder abzuwählen gilt für alle betroffenen Dateien; einzelne Vorkommen lassen sich bei Bedarf ansehen. Nach der Auswahl lassen sich erkannte Personen optional zusammenfassen, sodass ihre Erwähnungen denselben Platzhalter erhalten. `Pseudonymisierte Kopien erstellen` schreibt Dateien in den Raycast-Support-Bereich außerhalb des Projektordners. Alternativ ersetzt `Originaldateien ersetzen` die Dateien und gegebenenfalls ihre Namen vor Ort; zuvor legt Velum eine private Sicherung der Originale im Raycast-Support-Bereich an. PDF wird dabei als DOCX ausgegeben.
@@ -128,7 +141,7 @@ Alle Werte sind in den Raycast-Einstellungen pro Extension einstellbar.
- `Ausgabe der Schnellbefehle` — `In die Zwischenablage kopieren` (Default) oder `Am Cursor einfügen`
- `Eigener Name` — Default-Signatur für AI-generierte Email-Antworten, im Antwort-Befehl pro Aufruf überschreibbar
Das KI-Modell ist keine Preference: jeder AI-Befehl zeigt ein `KI-Modell`-Dropdown mit dem aktuellen Modell-Katalog aus `src/ai.ts`. Die Auswahl wird in `LocalStorage` (`velum.ai.last-model`) persistiert und ist beim nächsten Aufruf in jedem AI-Befehl vorausgewählt.
Jeder KI-Befehl bezieht die Auswahl im Feld **KI-Modell** aus `AI.Model` der installierten Raycast-Version. Mit **Raycast-Standard** verwendet Velum das Standardmodell der Raycast-API. Velum merkt sich die letzte Auswahl für alle KI-Befehle. Fehlt das gespeicherte Modell im API-Katalog, ist beim nächsten Aufruf **Raycast-Standard** ausgewählt.
- `Maximale Anzahl gespeicherter Sitzungen` — älteste werden geprunt (Default 20)
- `Raycast nach Kopieren/Einfügen schließen` — Auto-Close und Pop-To-Root nach AI-Workflow-Abschluss (Default an)

View File

@@ -15,7 +15,7 @@ import {
} from "@raycast/api";
import { marked } from "marked";
import { type ReactNode, useEffect, useRef, useState } from "react";
import type { Creativity } from "./ai";
import { resolveRaycastModel, type Creativity } from "./ai";
import { getPreferences } from "./preferences";
import type { VelumSession } from "./types";
import { markdownCodeBlock, mappingDetailTable, sessionSubtitle } from "./ui";
@@ -143,7 +143,7 @@ export function AiStreamResult(props: PseudoStageProps) {
try {
const prompt = buildPrompt(pseudonymizedText, instructions);
const stream = AI.ask(prompt, {
model: model as AI.Model,
model: resolveRaycastModel(model),
creativity,
signal: controller.signal,
});

View File

@@ -1,4 +1,4 @@
import { LocalStorage } from "@raycast/api";
import { AI, LocalStorage } from "@raycast/api";
export type Creativity = "none" | "low" | "medium" | "high";
@@ -9,86 +9,29 @@ export const CREATIVITY_OPTIONS: Creativity[] = [
"high",
];
export type ModelOption = { value: string; title: string };
export const MODEL_OPTIONS: ModelOption[] = [
{ value: "anthropic-claude-opus-4-7", title: "Claude 4.7 Opus" },
{ value: "anthropic-claude-sonnet-4-6", title: "Claude 4.6 Sonnet" },
{ value: "anthropic-claude-opus-4-6", title: "Claude 4.6 Opus" },
{ value: "anthropic-claude-sonnet-4-5", title: "Claude 4.5 Sonnet" },
{ value: "anthropic-claude-opus-4-5", title: "Claude 4.5 Opus" },
{ value: "anthropic-claude-4-5-haiku", title: "Claude 4.5 Haiku" },
{ value: "anthropic-claude-sonnet-4", title: "Claude 4 Sonnet" },
{ value: "openai-gpt-5.4", title: "OpenAI GPT-5.4" },
{ value: "openai-gpt-5.4-mini", title: "OpenAI GPT-5.4 Mini" },
{ value: "openai-gpt-5.4-nano", title: "OpenAI GPT-5.4 Nano" },
{ value: "openai-gpt-5.3-instant", title: "OpenAI GPT-5.3 Instant" },
{ value: "openai-gpt-5.3-codex", title: "OpenAI GPT-5.3 Codex" },
{ value: "openai-gpt-5.2", title: "OpenAI GPT-5.2" },
{ value: "openai-gpt-5.2-instant", title: "OpenAI GPT-5.2 Instant" },
{ value: "openai-gpt-5.1", title: "OpenAI GPT-5.1" },
{ value: "openai-gpt-5.1-instant", title: "OpenAI GPT-5.1 Instant" },
{ value: "openai-gpt-5.1-codex", title: "OpenAI GPT-5.1 Codex" },
{ value: "openai_o1-gpt-5", title: "OpenAI GPT-5" },
{ value: "openai-gpt-5-mini", title: "OpenAI GPT-5 Mini" },
{ value: "openai-gpt-5-nano", title: "OpenAI GPT-5 Nano" },
{ value: "openai-gpt-4.1", title: "OpenAI GPT-4.1" },
{ value: "openai-gpt-4.1-mini", title: "OpenAI GPT-4.1 Mini" },
{ value: "openai-gpt-4.1-nano", title: "OpenAI GPT-4.1 Nano" },
{ value: "openai-gpt-4o", title: "OpenAI GPT-4o" },
{ value: "openai-gpt-4o-mini", title: "OpenAI GPT-4o mini" },
{ value: "openai_o1-o3", title: "OpenAI o3" },
{ value: "openai_o1-o3-mini", title: "OpenAI o3-mini" },
{ value: "openai_o1-o4-mini", title: "OpenAI o4-mini" },
{ value: "openai_o1-o1", title: "OpenAI o1" },
{ value: "google-gemini-3.1-pro", title: "Google Gemini 3.1 Pro" },
{ value: "google-gemini-3-flash", title: "Google Gemini 3 Flash" },
{
value: "google-gemini-3.1-flash-lite",
title: "Google Gemini 3.1 Flash Lite",
},
{ value: "google-gemini-2.5-pro", title: "Google Gemini 2.5 Pro" },
{ value: "google-gemini-2.5-flash", title: "Google Gemini 2.5 Flash" },
{
value: "google-gemini-2.5-flash-lite",
title: "Google Gemini 2.5 Flash Lite",
},
{ value: "xai-grok-4.20", title: "xAI Grok 4.20" },
{ value: "xai-grok-4", title: "xAI Grok 4" },
{ value: "xai-grok-4-fast", title: "xAI Grok 4 Fast" },
{ value: "xai-grok-4-1-fast", title: "xAI Grok 4.1 Fast" },
{ value: "xai-grok-code-fast", title: "xAI Grok Code Fast" },
{ value: "perplexity-sonar-pro", title: "Perplexity Sonar Pro" },
{ value: "perplexity-sonar", title: "Perplexity Sonar" },
{ value: "mistral-mistral-large-latest", title: "Mistral Large" },
{ value: "mistral-mistral-medium-latest", title: "Mistral Medium" },
{ value: "mistral-mistral-small-latest", title: "Mistral Small" },
{ value: "mistral-codestral-latest", title: "Mistral Codestral" },
{ value: "mistral-open-mistral-nemo", title: "Mistral Nemo" },
{ value: "groq-llama-3.3-70b-versatile", title: "Groq Llama 3.3 70B" },
{
value: "groq-meta-llama/llama-4-scout-17b-16e-instruct",
title: "Groq Llama 4 Scout",
},
{ value: "groq-llama-3.1-8b-instant", title: "Groq Llama 3.1 8B" },
{ value: "groq-qwen/qwen3-32b", title: "Groq Qwen3 32B" },
{ value: "groq-openai/gpt-oss-120b", title: "Groq GPT-OSS 120B" },
{ value: "groq-openai/gpt-oss-20b", title: "Groq GPT-OSS 20B" },
{ value: "together-deepseek-ai/DeepSeek-R1", title: "DeepSeek R1" },
{ value: "together-deepseek-ai/DeepSeek-V3", title: "DeepSeek V3" },
{ value: "together-moonshotai/Kimi-K2.5", title: "Kimi K2.5" },
];
export const DEFAULT_MODEL = "__raycast_default__";
const LAST_MODEL_STORAGE_KEY = "velum.ai.last-model";
export const DEFAULT_MODEL: string = MODEL_OPTIONS[0].value;
// Raycast lists current names before compatibility aliases for the same model ID.
const raycastModels = new Map<string, { value: AI.Model; title: string }>();
for (const [name, value] of Object.entries(AI.Model)) {
if (!raycastModels.has(value)) {
raycastModels.set(value, { value, title: name.replaceAll("_", " ") });
}
}
export const MODEL_OPTIONS = [
{ value: DEFAULT_MODEL, title: "Raycast-Standard" },
...raycastModels.values(),
];
export function resolveRaycastModel(selection: string): AI.Model | undefined {
return raycastModels.get(selection)?.value;
}
export async function getLastUsedModel(): Promise<string> {
const stored = await LocalStorage.getItem<string>(LAST_MODEL_STORAGE_KEY);
if (stored && MODEL_OPTIONS.some((option) => option.value === stored)) {
return stored;
}
return DEFAULT_MODEL;
return stored && raycastModels.has(stored) ? stored : DEFAULT_MODEL;
}
export async function setLastUsedModel(model: string): Promise<void> {

View File

@@ -76,6 +76,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true);
@@ -99,8 +100,9 @@ export default function Command() {
try {
const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes);
setSelectedEntityTypes(loadedEntityTypes);
setEntityTypes(loadedEntityTypes.all);
setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch {
setEntityTypes([]);
} finally {
@@ -213,7 +215,8 @@ export default function Command() {
placeholder="Meeting-Notizen, Stichpunkte, Transkript …"
/>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

View File

@@ -8,7 +8,8 @@ import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID } from "./context-values";
export type { ContextFormValues } from "./context-values";
export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId?: string;
availableEntityTypes: EntityType[]; onEntityTypesChange: (types: EntityType[]) => void }) {
availableEntityTypes: EntityType[]; defaultEntityTypes: EntityType[];
onEntityTypesChange: (types: EntityType[]) => void }) {
const [projects, setProjects] = useState<Array<{ path: string; name: string }>>([]);
const [selected, setSelected] = useState(CHOOSE_CONTEXT_ID);
@@ -32,7 +33,7 @@ export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId
try {
const saved = id.startsWith("project:")
? await loadProjectEntityTypes(id.slice("project:".length)) : null;
props.onEntityTypesChange(saved ?? props.availableEntityTypes);
props.onEntityTypesChange(saved ?? props.defaultEntityTypes);
setSelected(id);
} catch (error) {
await showToast({ style: Toast.Style.Failure,
@@ -51,6 +52,8 @@ export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId
icon={session.id === props.activeSessionId ? Icon.CheckCircle : Icon.Circle} />)}
<Form.Dropdown.Item value={NEW_SESSION_ID} title="Neue Sitzung" icon={Icon.Plus} />
</Form.Dropdown>
{selected === NEW_SESSION_ID && <Form.TextField id="newSessionName" title="Sitzungsname"
placeholder="Leer lassen für einen automatisch vergebenen Namen" />}
{selected === NEW_PROJECT_ID && <Form.FilePicker id="newProjectPath" title="Projektordner"
allowMultipleSelection={false} canChooseDirectories canChooseFiles={false} />}
</>;

View File

@@ -3,5 +3,6 @@ export const NEW_PROJECT_ID = "__new_project__";
export type ContextFormValues = {
sessionId: string;
newSessionName?: string;
newProjectPath?: string[];
};

View File

@@ -81,6 +81,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true);
@@ -104,8 +105,9 @@ export default function Command() {
try {
const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes);
setSelectedEntityTypes(loadedEntityTypes);
setEntityTypes(loadedEntityTypes.all);
setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch {
setEntityTypes([]);
} finally {
@@ -218,7 +220,8 @@ export default function Command() {
placeholder="Meeting-Notizen, Email-Thread, Transkript …"
/>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

View File

@@ -102,6 +102,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true);
@@ -125,8 +126,9 @@ export default function Command() {
try {
const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes);
setSelectedEntityTypes(loadedEntityTypes);
setEntityTypes(loadedEntityTypes.all);
setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch {
setEntityTypes([]);
} finally {
@@ -278,7 +280,8 @@ export default function Command() {
))}
</Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

22
src/lib/entity-types.ts Normal file
View File

@@ -0,0 +1,22 @@
import type { EntityType } from "../types";
/** Fallback for Velum backends that do not report `default_entity_types` yet. */
export const DEFAULT_DISABLED_ENTITY_TYPES: readonly EntityType[] = [
"IP",
"DATUM",
"REFERENZ",
];
export type EntityTypeCatalog = { all: EntityType[]; defaults: EntityType[] };
/** Preselection for unconfigured contexts; the backend default wins when it is available. */
export function entityTypeCatalog(payload: {
entity_types: EntityType[];
default_entity_types?: EntityType[];
}): EntityTypeCatalog {
const all = payload.entity_types;
const defaults = payload.default_entity_types
? payload.default_entity_types.filter((type) => all.includes(type))
: all.filter((type) => !DEFAULT_DISABLED_ENTITY_TYPES.includes(type));
return { all, defaults };
}

View File

@@ -8,6 +8,7 @@ import { analyzeDocxSegments } from "../velum";
import type { EntityType, PlaceholderMapping } from "../types";
import { checkedImageReport } from "./image-policy";
import type { ImagePolicy } from "./image-policy";
import { propagateDocxPersons } from "./person-propagation";
import { MAX_BATCH_CODEPOINTS } from "./project-review";
import { projectTextAnalyzer } from "./project-text-mapping";
import type { Hit } from "./project-work";
@@ -108,7 +109,9 @@ export async function inspectDocx(
size += segment.text.length + 2;
}
await flush();
return { hits, mapping: current, segmentCount: segments.length };
const propagated = types.includes("PERSON") ? propagateDocxPersons(segments, hits, current, relative)
: { hits, mapping: current };
return { ...propagated, segmentCount: segments.length };
}
export async function writeDocx(

View File

@@ -0,0 +1,107 @@
import type { PlaceholderMapping } from "../types";
import type { Hit } from "./project-work";
// Seeds follow the backend's per-text person propagation: only confident
// PERSON hits that look like capitalized names. Unlike the backend, the parts of
// a detected full name are propagated even if the model never recognized them
// alone, because lone surnames are what it misses most in running text.
// Common words stay out of reach unless the model put them into a name.
const NAME = /^[A-ZÄÖÜ][A-Za-zÄÖÜäöüß’'-]+(?:[ \t]+[A-ZÄÖÜ][A-Za-zÄÖÜäöüß’'-]+)*$/u;
const MIN_SEED_SCORE = 0.85;
// The backend's salutation recognizer ("Frau Müller", "Dr. Schmidt") scores
// 0.7, but its structure reliably marks the following words as a name.
const SALUTATION = /^(?:Frau|Herr|Dr\.|Prof\.|Mag\.|Ing\.|DI)\s+/u;
const MIN_SALUTATION_SCORE = 0.7;
function escape(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Velum analyzes every DOCX segment separately, so a name recognized in one
* paragraph is not propagated to paragraphs where the model misses it (for
* example "bei Quastenberg nachfragen"). Add those occurrences as reviewable
* hits for the whole file.
*/
export function propagateDocxPersons(
segments: Array<{ text: string; source: string; kind: string }>, hits: Hit[], mapping: PlaceholderMapping,
relative: string,
): { hits: Hit[]; mapping: PlaceholderMapping } {
const candidates = new Map<string, number>();
const add = (name: string, score: number) => candidates.set(name, Math.max(candidates.get(name) ?? 0, score));
for (const hit of hits) {
if (hit.kind !== "content" || hit.type !== "PERSON") continue;
const salutation = hit.original.trim().match(SALUTATION);
const name = hit.original.trim().slice(salutation?.[0].length ?? 0);
if (hit.score < (salutation ? MIN_SALUTATION_SCORE : MIN_SEED_SCORE) || !NAME.test(name)) continue;
const parts = name.split(/[ \t]+/);
if (parts.length < 2 && !salutation) continue;
add(name, hit.score);
for (const part of parts) if (parts.length > 1 && Array.from(part).length >= 3) add(part, hit.score);
}
if (!candidates.size) return { hits, mapping };
const next: PlaceholderMapping = { ...mapping };
const identities = new Map<string, string>();
let counter = 0;
for (const [key, entry] of Object.entries(next)) {
if (entry.type !== "PERSON") continue;
identities.set(entry.original.trim().toLowerCase(), key);
counter = Math.max(counter, Number(key.match(/_(\d+)$/)?.[1] ?? 0));
}
const canonical = (key: string): string => {
const seen = new Set<string>();
while (next[key]?.merged_into && !seen.has(key)) {
seen.add(key);
key = next[key].merged_into!;
}
return key;
};
const placeholderFor = (name: string): string => {
let key = identities.get(name.toLowerCase());
if (!key) {
key = `PERSON_${String(++counter).padStart(2, "0")}`;
if (next[key]) throw new Error("Doppelte Platzhalternummer in der Projektzuordnung.");
next[key] = { original: name, type: "PERSON" };
identities.set(name.toLowerCase(), key);
}
return canonical(key);
};
const occupied = new Map<number, Array<[number, number]>>();
for (const hit of hits) {
if (hit.segment === undefined) continue;
const ranges = occupied.get(hit.segment) ?? [];
ranges.push([hit.start, hit.end]);
occupied.set(hit.segment, ranges);
}
// Longest names first, so a full name is masked as a unit before its parts.
// A German genitive "s" stays outside the masked span.
const patterns = [...candidates.keys()].sort((a, b) => b.length - a.length || a.localeCompare(b))
.map((name) => [name, new RegExp(`(?<![\\p{L}\\p{N}_])${escape(name)}(?=s?(?![\\p{L}\\p{N}_]))`, "gu")] as const);
const added: Hit[] = [];
for (const [index, segment] of segments.entries()) {
if (segment.kind !== "text") continue;
const ranges = occupied.get(index) ?? [];
for (const [name, pattern] of patterns) {
for (const match of segment.text.matchAll(pattern)) {
// Hit offsets count code points, matching the Python codec.
const start = Array.from(segment.text.slice(0, match.index)).length;
const end = start + Array.from(name).length;
if (ranges.some(([s, e]) => start < e && s < end)) continue;
ranges.push([start, end]);
const characters = Array.from(segment.text);
added.push({
id: `${relative}:local-docx:${index}:${start}:${end}`, file: relative, source: segment.source,
original: name, placeholder: placeholderFor(name), type: "PERSON", score: candidates.get(name)!,
context: characters.slice(Math.max(0, start - 60), end + 60).join(""),
start, end, kind: "content", segment: index,
});
}
}
occupied.set(index, ranges);
}
if (!added.length) return { hits, mapping };
const merged = [...hits, ...added].sort((a, b) => (a.segment ?? 0) - (b.segment ?? 0) || a.start - b.start);
return { hits: merged, mapping: next };
}

View File

@@ -121,6 +121,37 @@ export function groupReviewHits<T extends GroupableHit>(hits: T[]): ReviewGroup<
return [...groups.values()].sort((a, b) => a.type.localeCompare(b.type) || a.original.localeCompare(b.original));
}
/** Render source text literally, even if it contains Markdown or HTML. */
export function literalReviewContext(text: string): string {
let longestRun = 2;
for (const [run] of text.matchAll(/`+/g)) longestRun = Math.max(longestRun, run.length);
const fence = "`".repeat(longestRun + 1);
return `${fence}\n${text}\n${fence}`;
}
/** Text API positions count Unicode code points. Mark the exact occurrence in each snippet. */
export function textHitContexts(text: string, spans: Array<{ start: number; end: number }>): string[] {
const characters = Array.from(text);
const contexts: string[] = [];
let cursor = 0;
let line = 1;
for (const { span, index } of spans.map((span, index) => ({ span, index })).sort((a, b) => a.span.start - b.span.start)) {
const { start, end } = span;
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start >= end || end > characters.length) {
contexts[index] = "Ungültige Trefferposition der Velum-API.";
continue;
}
for (; cursor < start; cursor++) {
if (characters[cursor] === "\n" || (characters[cursor] === "\r" && characters[cursor + 1] !== "\n")) line++;
}
const before = characters.slice(Math.max(0, start - 90), start).join("");
const match = characters.slice(start, end).join("");
const after = characters.slice(end, end + 90).join("");
contexts[index] = `**Zeile ${line}**\n\n${literalReviewContext(`${before}⟦${match}⟧${after}`)}`;
}
return contexts;
}
export function withoutWhitelistedHits<T extends GroupableHit>(hits: T[], whitelist: ProjectWhitelistEntry[]): T[] {
const excluded = new Set(whitelist.map(whitelistKey));
return hits.filter((hit) => !excluded.has(whitelistKey(hit)));

View File

@@ -0,0 +1,76 @@
import { Action, ActionPanel, Icon, List, useNavigation } from "@raycast/api";
import { useState } from "react";
const PAGE_SIZE = 200;
export function PersonMergeTargets(props: {
people: Array<{ placeholder: string; originals: string[] }>;
onChoose: (placeholder: string) => void;
}) {
const { pop } = useNavigation();
const [query, setQuery] = useState("");
const [page, setPage] = useState(0);
const matching = props.people.filter((person) =>
`${person.originals.join(" ")} ${person.placeholder}`
.toLowerCase()
.includes(query.trim().toLowerCase()),
);
const pages = Math.ceil(matching.length / PAGE_SIZE);
return (
<List
navigationTitle="Zusammenführen mit"
filtering={false}
searchText={query}
searchBarPlaceholder="Person oder Platzhalter suchen"
onSearchTextChange={(value) => {
setQuery(value);
setPage(0);
}}
>
{pages > 1 && (
<List.Item
id="page"
title={`Seite ${page + 1}/${pages}`}
actions={
<ActionPanel>
{page + 1 < pages && (
<Action
title="Nächste Seite"
onAction={() => setPage(page + 1)}
/>
)}
{page > 0 && (
<Action
title="Vorherige Seite"
onAction={() => setPage(page - 1)}
/>
)}
</ActionPanel>
}
/>
)}
{matching
.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE)
.map((person) => (
<List.Item
key={person.placeholder}
id={person.placeholder}
title={person.originals.join(" · ")}
subtitle={person.placeholder}
actions={
<ActionPanel>
<Action
title="Personen zusammenfassen"
icon={Icon.Link}
onAction={() => {
props.onChoose(person.placeholder);
pop();
}}
/>
</ActionPanel>
}
/>
))}
</List>
);
}

View File

@@ -136,6 +136,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true);
@@ -164,8 +165,9 @@ export default function Command() {
try {
const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes);
setSelectedEntityTypes(loadedEntityTypes);
setEntityTypes(loadedEntityTypes.all);
setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch {
setEntityTypes([]);
} finally {
@@ -278,7 +280,8 @@ export default function Command() {
placeholder="Statusmeeting-Stichpunkte, Email-Auszüge, Risiken, Zahlen, Entscheidungen …"
/>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

View File

@@ -12,7 +12,7 @@ import {
saveProjectWhitelist, scanProjectFiles, whitelistKey, withoutExcludedProjectFiles,
} from "./lib/velum-project";
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, SkippedProjectFile } from "./lib/velum-project";
import { canonicalPerson, groupReviewHits, mergePeople } from "./lib/project-review";
import { canonicalPerson, groupReviewHits, literalReviewContext, mergePeople } from "./lib/project-review";
import { checkedImagePolicy, DEFAULT_IMAGE_POLICY, IMAGE_POLICY_LABELS, KEEP_IMAGE_WARNING } from "./lib/image-policy";
import type { ImagePolicy } from "./lib/image-policy";
import {
@@ -20,6 +20,7 @@ import {
} from "./lib/project-jobs";
import type { ProjectJobState } from "./lib/project-jobs";
import type { Hit, Preview } from "./lib/project-work";
import { PersonMergeTargets } from "./person-merge-targets";
const run = promisify(execFile);
const REVIEW_PAGE_SIZE = 200;
@@ -57,34 +58,13 @@ function OccurrenceReview(props: { original: string; placeholder: string; hits:
const [page, setPage] = useState(0);
const pages = Math.ceil(props.hits.length / REVIEW_PAGE_SIZE);
return <List isShowingDetail navigationTitle={`${props.original} → ${props.placeholder}`}>
{pages > 1 && <List.Item title={`Vorkommen · Seite ${page + 1}/${pages}`} actions={<ActionPanel>
{pages > 1 && <List.Item id="page" title={`Vorkommen · Seite ${page + 1}/${pages}`} actions={<ActionPanel>
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
</ActionPanel>} />}
{props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => <List.Item key={hit.id} title={hit.source}
subtitle={hit.kind === "path" ? "Datei- oder Ordnername" : "Dateiinhalt"}
detail={<List.Item.Detail markdown={hit.context.replace(/</g, "&lt;")} />} />)}
</List>;
}
function PersonMergeTargets(props: { people: Array<{ placeholder: string; originals: string[] }>;
onChoose: (placeholder: string) => void }) {
const { pop } = useNavigation();
const [query, setQuery] = useState("");
const [page, setPage] = useState(0);
const matching = props.people.filter((person) => `${person.originals.join(" ")} ${person.placeholder}`
.toLowerCase().includes(query.trim().toLowerCase()));
const pages = Math.max(1, Math.ceil(matching.length / REVIEW_PAGE_SIZE));
return <List navigationTitle="Zusammenführen mit" filtering={false} searchText={query}
onSearchTextChange={(value) => { setQuery(value); setPage(0); }}>
{pages > 1 && <List.Item title={`Seite ${page + 1}/${pages}`} actions={<ActionPanel>
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
</ActionPanel>} />}
{matching.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((person) =>
<List.Item key={person.placeholder} title={person.originals.join(" · ")} subtitle={person.placeholder}
actions={<ActionPanel><Action title="Personen zusammenfassen" icon={Icon.Link}
onAction={() => { props.onChoose(person.placeholder); pop(); }} /></ActionPanel>} />)}
{props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => <List.Item
key={hit.id} id={hit.id} title={hit.file} subtitle={hit.source === hit.file ? "Dateiinhalt" : hit.source}
detail={<List.Item.Detail markdown={literalReviewContext(hit.context)} />} />)}
</List>;
}
@@ -251,7 +231,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
</List.Section>}
{[...byType].map(([type, entries]) => <List.Section key={type}
title={`${labelForType(type)} · ${groups.filter((entry) => entry.type === type && selectedGroups.has(entry.key)).length}/${groups.filter((entry) => entry.type === type).length}`}>
{entries.map((group) => <List.Item key={group.key}
{entries.map((group) => <List.Item key={group.key} id={group.hits[0].id}
icon={{ source: selectedGroups.has(group.key) ? Icon.CheckCircle : Icon.Circle,
tintColor: selectedGroups.has(group.key) ? Color.Green : Color.SecondaryText }}
title={group.original} subtitle={`→ ${group.placeholder}`}
@@ -472,6 +452,7 @@ export default function Command() {
const [imagePolicy, setImagePolicy] = useState<ImagePolicy>(DEFAULT_IMAGE_POLICY);
const [rules, setRules] = useState("");
const [availableTypes, setAvailableTypes] = useState<EntityType[]>([]);
const [defaultTypes, setDefaultTypes] = useState<EntityType[]>([]);
const [selectedTypes, setSelectedTypes] = useState<EntityType[]>([]);
const [typesLoaded, setTypesLoaded] = useState(false);
const [typesReadyFor, setTypesReadyFor] = useState<string | null>(null);
@@ -482,14 +463,15 @@ export default function Command() {
useEffect(() => { finderFolder().then((path) => { if (path) setRoot((current) => current || path); }); }, []);
useEffect(() => {
getEntityTypes().then((types) => {
setAvailableTypes(types);
setAvailableTypes(types.all);
setDefaultTypes(types.defaults);
setTypesLoaded(true);
}).catch((error: Error) => showToast({ style: Toast.Style.Failure,
title: "Kategorien nicht verfügbar", message: error.message }));
}, []);
useEffect(() => {
if (!typesLoaded) return;
const defaults = availableTypes.filter((type) => type !== "ORT");
const defaults = defaultTypes.filter((type) => type !== "ORT");
if (!root) { setSelectedTypes(defaults); setTypesReadyFor(""); return; }
let active = true;
setTypesReadyFor(null);
@@ -500,7 +482,7 @@ export default function Command() {
}).catch((error: Error) => showToast({ style: Toast.Style.Failure,
title: "Projektkategorien nicht lesbar", message: error.message }));
return () => { active = false; };
}, [root, availableTypes, typesLoaded]);
}, [root, availableTypes, defaultTypes, typesLoaded]);
useEffect(() => {
if (!root) return;
let active = true;

View File

@@ -38,6 +38,7 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(true);
const { push } = useNavigation();
@@ -62,8 +63,9 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
try {
const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes);
setSelectedEntityTypes(loadedEntityTypes);
setEntityTypes(loadedEntityTypes.all);
setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch {
setEntityTypes([]);
} finally {
@@ -176,7 +178,8 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
placeholder="Zu pseudonymisierender Text"
/>
<ContextPicker key={contextVersion} sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

View File

@@ -20,6 +20,7 @@ import {
DEFAULT_MODEL,
getLastUsedModel,
MODEL_OPTIONS,
resolveRaycastModel,
setLastUsedModel,
} from "./ai";
import { getPreferences } from "./preferences";
@@ -62,6 +63,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [greeting, setGreeting] = useState("Lieber");
const [signOff, setSignOff] = useState("Alles Liebe,");
@@ -99,8 +101,9 @@ export default function Command() {
try {
const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes);
setSelectedEntityTypes(loadedEntityTypes);
setEntityTypes(loadedEntityTypes.all);
setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch {
setEntityTypes([]);
} finally {
@@ -299,7 +302,8 @@ export default function Command() {
/>
<Form.Separator />
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"
@@ -557,7 +561,7 @@ function ReplyResult(props: StageProps) {
instructions: props.instructions,
});
const stream = AI.ask(prompt, {
model: props.model as AI.Model,
model: resolveRaycastModel(props.model),
creativity: props.creativity,
signal: controller.signal,
});

View File

@@ -65,14 +65,17 @@ export async function setActiveSession(id: string): Promise<void> {
await LocalStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, id);
}
export async function createSession(name?: string): Promise<VelumSession> {
export async function createSession(name?: string,
initial?: Pick<VelumSession, "mapping" | "entityTypes" | "excludedTerms">): Promise<VelumSession> {
const timestamp = nowIso();
const session: VelumSession = {
id: randomUUID(),
name: name || `Sitzung ${new Date().toLocaleString()}`,
name: name?.trim() || `Sitzung ${new Date().toLocaleString()}`,
createdAt: timestamp,
updatedAt: timestamp,
mapping: {},
...initial,
...(initial && { mappingCreatedAt: mappingDates(undefined, initial.mapping, timestamp) }),
};
const sessions = await listSessions();

View File

@@ -27,6 +27,7 @@ import {
DEFAULT_MODEL,
getLastUsedModel,
MODEL_OPTIONS,
resolveRaycastModel,
setLastUsedModel,
} from "./ai";
import { buildSummaryPrompt, type Creativity } from "./summarize";
@@ -54,6 +55,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true);
@@ -77,8 +79,9 @@ export default function Command() {
try {
const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes);
setSelectedEntityTypes(loadedEntityTypes);
setEntityTypes(loadedEntityTypes.all);
setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch {
setEntityTypes([]);
} finally {
@@ -183,7 +186,8 @@ export default function Command() {
placeholder="Email-Konversation einfügen oder laden"
/>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"
@@ -351,7 +355,7 @@ function SummarizeEmailResult({
try {
const prompt = buildSummaryPrompt(pseudonymizedText, instructions);
const stream = AI.ask(prompt, {
model: model as AI.Model,
model: resolveRaycastModel(model),
creativity,
signal: controller.signal,
});

View File

@@ -107,6 +107,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true);
@@ -130,8 +131,9 @@ export default function Command() {
try {
const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes);
setSelectedEntityTypes(loadedEntityTypes);
setEntityTypes(loadedEntityTypes.all);
setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch {
setEntityTypes([]);
} finally {
@@ -244,7 +246,8 @@ export default function Command() {
placeholder="Meeting-Notizen als Fließtext einfügen — z. B. handgeschriebene Protokollnotizen, ein diktiertes Transkript oder ein zusammenhängender Bericht."
/>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

View File

@@ -1,4 +1,5 @@
import { AI } from "@raycast/api";
import { resolveRaycastModel } from "./ai";
export type Creativity = "none" | "low" | "medium" | "high";
@@ -54,7 +55,7 @@ export async function runSummaryStream(
): Promise<string> {
let buffer = "";
const stream = AI.ask(options.prompt, {
model: options.model as AI.Model,
model: resolveRaycastModel(options.model),
creativity: options.creativity,
signal: options.signal,
});

View File

@@ -1,7 +1,7 @@
import { promises as fs } from "node:fs";
import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules,
loadProjectWhitelist, replaceSpans, saveProjectWhitelist, saveRun, toUtf16Offsets, updateProjectMapping, whitelistKey } from "./lib/velum-project";
import { mappingForRestoration } from "./lib/mapping-groups";
import { mappingForRestoration, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
import type { ProjectWhitelistEntry } from "./lib/velum-project";
import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID, type ContextFormValues } from "./context-values";
import { createSession, getSession, setActiveSession, updateSessionMapping } from "./sessions";
@@ -9,7 +9,7 @@ import type { EntityType, PlaceholderMapping, PseudonymizeResponse, VelumSession
import { NEW_SESSION_ID } from "./ui";
import { normalizePseudonymizeResponse, pseudonymize } from "./velum";
function projectMapping(mapping: PlaceholderMapping): PlaceholderMapping {
export function bareMapping(mapping: PlaceholderMapping): PlaceholderMapping {
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [
key.replace(/^<|>$/g, ""),
{ ...entry, merged_into: entry.merged_into?.replace(/^<|>$/g, "") },
@@ -47,6 +47,7 @@ export type PreparedText = {
previous: PlaceholderMapping;
exclusions: ProjectWhitelistEntry[];
selected: string;
newSessionName?: string;
projectPath?: string;
projectName?: string;
};
@@ -83,30 +84,51 @@ export async function prepareTextInContext(values: ContextFormValues, text: stri
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);
const raw = applyProjectWhitelist(text, await request(text, bareMapping(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 };
return { text, raw, previous, exclusions, selected, newSessionName: values.newSessionName };
}
/** Commit only the explicitly selected hits; rejected terms become context-specific exceptions. */
export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false):
export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false,
personMerges: Record<string, string> = {}):
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 known = bareMapping(prepared.previous);
const preview = { ...known, ...bareMapping(prepared.raw.mapping) };
const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, "")));
const mapping: PlaceholderMapping = { ...known };
let 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;
if (entry.merged_into) {
const root = mappingRoot(key, preview);
mapping[key] = { ...entry, merged_into: root };
mapping[root] = preview[root];
}
}
const raw: PseudonymizeResponse = { ...prepared.raw, spans: accepted,
mapping, entity_count: active.size,
const selectedPeople = new Set(accepted.filter((span) => span.type === "PERSON")
.map((span) => mappingRoot(span.placeholder.replace(/^<|>$/g, ""), mapping)));
for (const [source, target] of Object.entries(personMerges)) {
if (!selectedPeople.has(source) || mapping[target]?.type !== "PERSON") {
throw new Error("Bitte nur ausgewählte Personen mit vorhandenen Zuordnungen zusammenfassen.");
}
mapping = mergeMappingGroups(mapping, source, target);
}
const mergedSpans = accepted.map((span) => {
if (span.type !== "PERSON") return span;
const key = span.placeholder.replace(/^<|>$/g, "");
const root = mappingRoot(key, mapping);
if (root === key) return span;
return { ...span, placeholder: span.placeholder.startsWith("<") ? `<${root}>` : root };
});
const spans = toUtf16Offsets(prepared.text, mergedSpans).map((span, index) => ({ ...span, id: String(index) }));
const raw: PseudonymizeResponse = { ...prepared.raw, spans: mergedSpans,
mapping, entity_count: new Set(mergedSpans.map((span) => span.placeholder.replace(/^<|>$/g, ""))).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 }));
@@ -120,7 +142,12 @@ export async function commitPreparedText(prepared: PreparedText, selectedHits: S
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
}
if (latest) {
await updateProjectMapping(path, () => mapping);
await updateProjectMapping(path, (current) => {
if (JSON.stringify(current) !== JSON.stringify(prepared.previous)) {
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
}
return mapping;
});
} else {
const created = await createRun(path);
created.run.mapping = mapping;
@@ -130,9 +157,16 @@ export async function commitPreparedText(prepared: PreparedText, selectedHits: S
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 (prepared.selected === NEW_SESSION_ID) {
const saved = await createSession(prepared.newSessionName, {
mapping: result.mapping, entityTypes: result.selected_entity_types, excludedTerms: exclusions,
});
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
}
const session = 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)) {
if (JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)
|| JSON.stringify(session.excludedTerms ?? []) !== JSON.stringify(prepared.exclusions)) {
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);
@@ -169,7 +203,7 @@ export async function pseudonymizeInContext(values: ContextFormValues, text: str
}))));
const raw = applyProjectWhitelist(text,
await request(text, latest?.run.mapping ?? {}, entityTypes, masks), latest?.run.mapping ?? {}, whitelist);
const mapping = projectMapping(raw.mapping);
const mapping = bareMapping(raw.mapping);
if (latest) {
await updateProjectMapping(path, (current) => {
if (JSON.stringify(current) !== JSON.stringify(latest.run.mapping)) {
@@ -188,10 +222,10 @@ export async function pseudonymizeInContext(values: ContextFormValues, text: str
mappingForRestoration(resultMapping), result.selected_entity_types) };
}
const session = selected === NEW_SESSION_ID ? await createSession() : await getSession(selected);
const session = selected === NEW_SESSION_ID ? await createSession(values.newSessionName) : await getSession(selected);
if (!session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
await setActiveSession(session.id);
const raw = await request(text, session.mapping, entityTypes);
const raw = await request(text, bareMapping(session.mapping), entityTypes);
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types);
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };

View File

@@ -1,28 +1,120 @@
import { Action, ActionPanel, Icon, List, showToast, Toast } from "@raycast/api";
import {
Action,
ActionPanel,
Icon,
List,
showToast,
Toast,
useNavigation,
} from "@raycast/api";
import { useMemo, useState } from "react";
import { groupReviewHits } from "./lib/project-review";
import { commitPreparedText, type PreparedText } from "./text-context";
import { mappingRoot } from "./lib/mapping-groups";
import {
canonicalPerson,
groupReviewHits,
mergePeople,
textHitContexts,
} from "./lib/project-review";
import { PersonMergeTargets } from "./person-merge-targets";
import {
bareMapping,
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 }) {
export function TextHitReview(props: {
prepared: PreparedText;
forAi?: boolean;
onConfirmed: (
result: PseudonymizeResponse,
session: VelumSession,
) => Promise<void> | void;
}) {
const { push } = useNavigation();
const [selected, setSelected] = useState<Set<number>>(
() => new Set(props.prepared.raw.spans.map((_, index) => index)));
() => new Set(props.prepared.raw.spans.map((_, index) => index)),
);
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
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);
}
const { byType, people, personByHit } = useMemo(() => {
const { text, raw, previous } = props.prepared;
const contexts = textHitContexts(text, raw.spans);
const hits = raw.spans.map((span, index) => ({
...span,
id: String(index),
context: contexts[index],
}));
const groups = groupReviewHits(hits);
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);
}
const known = bareMapping(previous);
const mapping = { ...known, ...bareMapping(raw.mapping) };
const names = new Map<string, Set<string>>();
for (const [key, entry] of Object.entries(mapping)) {
if (entry.type !== "PERSON") continue;
const root = mappingRoot(key, mapping);
if (!names.has(root)) names.set(root, new Set([mapping[root].original]));
names.get(root)!.add(entry.original);
}
const personByHit = new Map<number, string>();
for (const [index, hit] of hits.entries()) {
if (hit.type !== "PERSON") continue;
const key = hit.placeholder.replace(/^<|>$/g, "");
if (!mapping[key]) continue;
const root = mappingRoot(key, mapping);
personByHit.set(index, root);
names.get(root)?.add(hit.original);
}
const people = [...names]
.map(([placeholder, originals]) => ({
placeholder,
originals: [...originals],
saved: Boolean(known[placeholder]),
}))
.sort((a, b) => a.originals[0].localeCompare(b.originals[0]));
return { byType, people, personByHit };
}, [props.prepared]);
const selectedPeople = new Set(
[...personByHit]
.filter(([index]) => selected.has(index))
.map(([, person]) => person),
);
const availablePeople = people.filter(
(person) => person.saved || selectedPeople.has(person.placeholder),
);
const availablePlaceholders = new Set(
availablePeople.map((person) => person.placeholder),
);
const activeMerges = Object.fromEntries(
Object.entries(personMerges).filter(
([source, target]) =>
selectedPeople.has(source) && availablePlaceholders.has(target),
),
);
const mergeTargets = availablePeople.filter(
({ placeholder }) => !activeMerges[placeholder],
);
async function confirm() {
if (busy) return;
setBusy(true);
const toast = await showToast({ style: Toast.Style.Animated, title: "Auswahl wird übernommen" });
const toast = await showToast({
style: Toast.Style.Animated,
title: "Auswahl wird übernommen",
});
try {
const { result, session } = await commitPreparedText(props.prepared, selected, props.forAi);
const { result, session } = await commitPreparedText(
props.prepared,
selected,
props.forAi,
activeMerges,
);
toast.style = Toast.Style.Success;
toast.title = "Auswahl übernommen";
toast.message = `${selected.size} Treffer bestätigt`;
@@ -31,42 +123,125 @@ export function TextHitReview(props: { prepared: PreparedText; forAi?: boolean;
toast.style = Toast.Style.Failure;
toast.title = "Auswahl nicht übernommen";
toast.message = error instanceof Error ? error.message : String(error);
} finally { setBusy(false); }
} 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); }
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>;
return (
<List
isLoading={busy}
isShowingDetail
navigationTitle="Treffer vor Pseudonymisierung prüfen"
searchBarPlaceholder="Begriff, Kategorie oder Platzhalter suchen"
>
<List.Section title="Abschluss">
<List.Item
id="confirm"
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="Wähle einen Begriff aus, um seine Vorkommen zu sehen. Über das Aktionsmenü einer Person kannst du Namensvarianten zusammenfassen. Mit **Auswahl bestätigen** speicherst du deine Änderungen." />
}
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 person = personByHit.get(ids[0]);
const canonical = person
? canonicalPerson(person, activeMerges)
: undefined;
return (
<List.Item
key={group.key}
id={`hit-${ids[0]}`}
icon={all ? Icon.CheckCircle : Icon.Circle}
title={`${group.original} → ${canonical ?? group.placeholder}`}
subtitle={
group.hits.length > 1
? `${group.hits.length} Vorkommen`
: undefined
}
detail={
<List.Item.Detail
markdown={group.hits.map((hit) => hit.context).join("\n\n")}
/>
}
actions={
<ActionPanel>
<Action
title={all ? "Nicht maskieren" : "Maskieren"}
icon={all ? Icon.XMarkCircle : Icon.CheckCircle}
onAction={() => toggle(ids)}
/>
{person && all && mergeTargets.length > 1 && (
<Action
title="Mit Person zusammenfassen"
icon={Icon.Link}
onAction={() =>
push(
<PersonMergeTargets
people={mergeTargets.filter(
({ placeholder }) => placeholder !== canonical,
)}
onChoose={(target) =>
setPersonMerges(
mergePeople(activeMerges, person, target),
)
}
/>,
)
}
/>
)}
{person && activeMerges[person] && (
<Action
title="Zusammenführung lösen"
onAction={() => {
const next = { ...activeMerges };
delete next[person];
setPersonMerges(next);
}}
/>
)}
<Action
title="Auswahl bestätigen und fortfahren"
icon={Icon.CheckCircle}
onAction={confirm}
/>
</ActionPanel>
}
/>
);
})}
</List.Section>
))}
</List>
);
}

View File

@@ -1,6 +1,7 @@
import { fetchWithAuth } from "./auth";
import { restoreXlsxBuffer } from "./lib/xlsx-restoration";
import { checkProjectCapabilities } from "./lib/project-capabilities";
import { entityTypeCatalog, type EntityTypeCatalog } from "./lib/entity-types";
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY } from "./lib/image-policy";
import type { ImagePolicy, DocumentImageReport } from "./lib/image-policy";
import { getPreferences } from "./preferences";
@@ -103,12 +104,13 @@ async function parseJsonResponse<T>(response: Response): Promise<T> {
return (await response.json()) as T;
}
export async function getEntityTypes(): Promise<EntityType[]> {
export async function getEntityTypes(): Promise<EntityTypeCatalog> {
const response = await fetchWithAuth(apiUrl("/api/entity-types"));
const payload = await parseJsonResponse<{ entity_types: EntityType[] }>(
response,
);
return payload.entity_types;
const payload = await parseJsonResponse<{
entity_types: EntityType[];
default_entity_types?: EntityType[];
}>(response);
return entityTypeCatalog(payload);
}
export async function pseudonymize(

View File

@@ -0,0 +1,22 @@
import { expect, it } from "bun:test";
import { entityTypeCatalog } from "../src/lib/entity-types";
const all = ["PERSON", "EMAIL", "REFERENZ", "ORT", "DATUM", "URL", "IP"];
it("uses the backend default selection when Velum reports one", () => {
expect(
entityTypeCatalog({
entity_types: all,
default_entity_types: ["PERSON", "IP", "UNBEKANNT"],
}),
).toEqual({ all, defaults: ["PERSON", "IP"] });
});
it("leaves IP, Datum and Referenz off for backends without a default list", () => {
expect(entityTypeCatalog({ entity_types: all }).defaults).toEqual([
"PERSON",
"EMAIL",
"ORT",
"URL",
]);
});

View File

@@ -6,6 +6,7 @@ import ts from "typescript";
import * as xlsxRestoration from "../src/lib/xlsx-restoration";
import * as imagePolicy from "../src/lib/image-policy";
import * as projectCapabilities from "../src/lib/project-capabilities";
import * as entityTypes from "../src/lib/entity-types";
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY, KEEP_IMAGE_WARNING, sameImagePolicyCoverage, summarizeImages } from "../src/lib/image-policy";
const policies = ["placeholder", "remove", "keep"] as const;
@@ -64,6 +65,7 @@ it("übermittelt dieselbe Bildoption in Vorschau, Anwendung und erneutem Abgleic
"./lib/image-policy": imagePolicy,
"./lib/xlsx-restoration": xlsxRestoration,
"./lib/project-capabilities": projectCapabilities,
"./lib/entity-types": entityTypes,
};
const module = { exports: {} as { pseudonymizeDocument: (...args: unknown[]) => Promise<unknown>; requireProjectCapabilities: (images?: boolean) => Promise<void> } };
new Function("require", "module", "exports", code)((id: string) => mocks[id] ?? require(id), module, module.exports);
@@ -97,6 +99,7 @@ it("restores XLSX locally and keeps the API route for DOCX", async () => {
"./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }) },
"./lib/image-policy": imagePolicy,
"./lib/project-capabilities": projectCapabilities,
"./lib/entity-types": entityTypes,
"./lib/xlsx-restoration": xlsxRestoration,
};
const module = { exports: {} as { depseudonymizeDocument: (name: string, data: Buffer, mapping: Record<string, { original: string; type: string }>) => Promise<Buffer> } };

View File

@@ -0,0 +1,88 @@
import { expect, it } from "bun:test";
import { propagateDocxPersons } from "../src/lib/person-propagation";
import type { Hit } from "../src/lib/project-work";
import type { PlaceholderMapping } from "../src/types";
// Synthetic names only. The model recognizes them in the introduction, but
// not in the later paragraphs (observed with de_core_news_lg).
const segments = [
{ text: "Projektleitung: Frau Jorinde Quastenberg, Fachbereich Planung.", source: "Absatz", kind: "text" },
{ text: "Grüße Talvin", source: "Absatz", kind: "text" },
...Array.from({ length: 26 }, () => [
{ text: "bei Quastenberg nachfragen", source: "Absatz", kind: "text" },
{ text: "Feedback Jorinde Quastenberg: passt. 😀 Quastenberg", source: "Absatz", kind: "text" },
]).flat(),
{ text: "Quastenbergstraße und Talvin bleiben", source: "Absatz", kind: "text" },
{ text: "Jorinde Quastenberg", source: "Kommentar-Link", kind: "link" },
];
function hit(segment: number, start: number, original: string, placeholder: string, score = 0.85): Hit {
return { id: `a.docx:local-docx:${segment}:${start}:${start + original.length}`, file: "a.docx", source: "Absatz",
original, placeholder, type: "PERSON", score, context: "", start, end: start + original.length,
kind: "content", segment };
}
it("masks every occurrence of a recognized person name across DOCX segments", () => {
const mapping: PlaceholderMapping = {
PERSON_01: { original: "Jorinde Quastenberg", type: "PERSON" },
PERSON_02: { original: "Talvin", type: "PERSON" },
};
const detected = [hit(0, 21, "Jorinde Quastenberg", "PERSON_01"), hit(1, 6, "Talvin", "PERSON_02", 0.99)];
const result = propagateDocxPersons(segments, detected, mapping, "a.docx");
const masked = segments.map((segment, index) => {
const characters = Array.from(segment.text);
for (const found of result.hits.filter((entry) => entry.segment === index)) {
expect(characters.slice(found.start, found.end).join("")).toBe(found.original);
for (let position = found.start; position < found.end; position++) characters[position] = "#";
}
return characters.join("");
});
const remaining = masked.slice(0, -1).join("\n").match(/(?<![\p{L}])Quastenberg(?![\p{L}])/gu) ?? [];
expect(remaining).toHaveLength(0);
expect(result.hits).toHaveLength(2 + 26 * 3);
const surname = result.hits.find((entry) => entry.original === "Quastenberg")!;
expect(surname.placeholder).toBe("PERSON_03");
expect(result.mapping.PERSON_03).toEqual({ original: "Quastenberg", type: "PERSON" });
expect(result.hits.filter((entry) => entry.original === "Jorinde Quastenberg").every(
(entry) => entry.placeholder === "PERSON_01")).toBe(true);
// Unicode offsets count code points, like the Python codec.
expect(result.hits.find((entry) => entry.segment === 3 && entry.start > 30)!.start).toBe(39);
// No partial words, no lone first name without a full name, no link fields.
expect(masked[54]).toBe("Quastenbergstraße und Talvin bleiben");
expect(result.hits.some((entry) => entry.segment === 55)).toBe(false);
expect(mapping.PERSON_03).toBeUndefined();
});
it("does not seed propagation from weak or merged-away hits", () => {
const mapping: PlaceholderMapping = {
PERSON_04: { original: "Jorinde Quastenberg", type: "PERSON" },
PERSON_07: { original: "Quastenberg", type: "PERSON", merged_into: "PERSON_04" },
};
const weak = propagateDocxPersons(segments, [hit(0, 21, "Jorinde Quastenberg", "PERSON_04", 0.6)], mapping, "a.docx");
expect(weak.hits).toHaveLength(1);
const merged = propagateDocxPersons(segments, [hit(0, 21, "Jorinde Quastenberg", "PERSON_04")], mapping, "a.docx");
expect(merged.hits.find((entry) => entry.original === "Quastenberg")!.placeholder).toBe("PERSON_04");
expect(Object.keys(merged.mapping)).toEqual(["PERSON_04", "PERSON_07"]);
});
it("seeds from salutation hits without the salutation and keeps the genitive s", () => {
const texts = ["Projektleitung: Frau Jorinde Quastenberg, Planung.", "Dr. Ostermeier ist informiert.",
"Quastenbergs Bericht und Ostermeiers Notiz liegen vor.", "Frau und Herr bleiben Wörter.", "Ostermeierhof"];
const result = propagateDocxPersons(texts.map((text) => ({ text, source: "Absatz", kind: "text" })), [
hit(0, 16, "Frau Jorinde Quastenberg", "PERSON_01", 0.7),
hit(1, 0, "Dr. Ostermeier", "PERSON_02", 0.7),
], {
PERSON_01: { original: "Frau Jorinde Quastenberg", type: "PERSON" },
PERSON_02: { original: "Dr. Ostermeier", type: "PERSON" },
}, "a.docx");
const added = result.hits.filter((entry) => !["PERSON_01", "PERSON_02"].includes(entry.placeholder));
expect(added.map((entry) => [entry.segment, entry.original, texts[entry.segment!].slice(entry.start, entry.end)]))
.toEqual([[2, "Quastenberg", "Quastenberg"], [2, "Ostermeier", "Ostermeier"]]);
expect(result.hits.filter((entry) => entry.segment === 3 || entry.segment === 4)).toHaveLength(0);
expect(Object.values(result.mapping).map((entry) => entry.original)).toEqual([
"Frau Jorinde Quastenberg", "Dr. Ostermeier", "Quastenberg", "Ostermeier",
]);
});

View File

@@ -1,7 +1,8 @@
import { expect, it } from "bun:test";
import {
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, reconcileDocumentHitIds,
spansBySegment, withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
canonicalPerson, filenameScanText, groupReviewHits, literalReviewContext, makeTextBatches, mappingForSelection,
mergePeople, reconcileDocumentHitIds, spansBySegment, textHitContexts, withoutPlaceholderHits, withoutWhitelistedHits,
withoutWhitelistedRules,
} from "../src/lib/project-review";
it("liest Unterstriche in Namen als Leerzeichen und bewahrt bekannte Codebegriffe", () => {
@@ -45,6 +46,20 @@ it("zeigt gleiche Zuordnungen einmal mit der Anzahl ihrer Vorkommen", () => {
expect(groups.find((group) => group.placeholder === "PERSON_01")?.hits.map((hit) => hit.id)).toEqual(["a", "b"]);
});
it("ordnet E-Mail-Vorkommen nach Unicode-Position zu und markiert jeweils genau den ausgewählten Treffer", () => {
const [signature, sender, recipient] = textHitContexts("😀 Von: Max\nAn: Mia\nDanke, Max", [
{ start: 26, end: 29 }, { start: 7, end: 10 }, { start: 15, end: 18 },
]);
expect(signature).toContain("**Zeile 3**");
expect(signature).toContain("Danke, ⟦Max⟧");
expect(sender).toContain("**Zeile 1**");
expect(sender).toContain("😀 Von: ⟦Max⟧");
expect(recipient).toContain("**Zeile 2**");
expect(recipient).toContain("An: ⟦Mia⟧");
const source = ["**Von:** <max@example.com>", "```", "![Bild](https://example.com/image.png)"].join("\n");
expect(literalReviewContext(source)).toBe(["````", source, "````"].join("\n"));
});
it("ordnet bestätigte Dokumenttreffer nach einem 409 nur bei identischem Vorkommen neu zu", () => {
const hit = { id: "alt", source: "Absatz 1", start: 4, end: 7, type: "PERSON",
original: "Max", context: "Herr Max antwortet" };

View File

@@ -91,12 +91,14 @@ it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht er
spans: [{ start: 0, end: 11, type: "PERSON", score: 0.8,
placeholder: "PERSON_01", original: "Fachbegriff" }],
});
const prepared = await prepareTextInContext({ sessionId: "__new_session__" },
const prepared = await prepareTextInContext({ sessionId: "__new_session__", newSessionName: " Kundenmail " },
"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.name).toBe("Kundenmail");
expect(session.mapping).toEqual({});
expect(await sessions.getActiveSessionId()).toBe(session.id);
expect((await sessions.getSession(session.id))?.excludedTerms).toEqual([
{ type: "PERSON", original: "Fachbegriff" },
]);
@@ -104,6 +106,59 @@ it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht er
expect(next.raw.spans).toEqual([]);
});
it.each(["session", "project"])("fasst geprüfte Namensvarianten zusammen und speichert sie für Folgeläufe (%s)", async (context) => {
let values = { sessionId: "__new_session__", newProjectPath: [] as string[] };
if (context === "project") {
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-merge-"));
roots.push(root);
const folder = join(root, "Projekt");
await fs.mkdir(folder);
values = { sessionId: "__new_project__", newProjectPath: [folder] };
}
const source = "😀 Max Muster\nMax und Mia";
const prepared = await prepareTextInContext(values, source, ["PERSON"], async () => ({
pseudonymized_text: "😀 PERSON_01\nPERSON_02 und PERSON_03",
selected_entity_types: ["PERSON"], entity_count: 3,
mapping: {
PERSON_01: { type: "PERSON", original: "Max Muster" },
PERSON_02: { type: "PERSON", original: "Max" },
PERSON_03: { type: "PERSON", original: "Mia" },
},
spans: [
{ start: 2, end: 12, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max Muster" },
{ start: 13, end: 16, type: "PERSON", score: 1, placeholder: "PERSON_02", original: "Max" },
{ start: 21, end: 24, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Mia" },
],
}));
await expect(commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_03" }))
.rejects.toThrow("ausgewählte Personen");
const { result, session } = await commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_01" });
expect(result.pseudonymized_text).toBe("😀 <PERSON_01>\n<PERSON_01> und Mia");
expect(result.entity_count).toBe(1);
expect(result.spans.map((span) => span.placeholder)).toEqual(["PERSON_01", "PERSON_01"]);
expect(result.mapping["<PERSON_02>"]).toEqual({ type: "PERSON", original: "Max", merged_into: "<PERSON_01>" });
expect(result.mapping["<PERSON_03>"]).toBeUndefined();
expect(session.mapping["<PERSON_02>"].original).toBe("Max Muster");
const followup = await prepareTextInContext({ sessionId: session.id }, "Max und Maximilian", ["PERSON"],
async (_text, mapping) => {
expect(mapping.PERSON_02.merged_into).toBe("PERSON_01");
expect(mapping["<PERSON_02>"]).toBeUndefined();
return {
pseudonymized_text: "PERSON_01 und PERSON_03", selected_entity_types: ["PERSON"], entity_count: 2,
mapping: { ...mapping, PERSON_03: { type: "PERSON", original: "Maximilian" } },
spans: [
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
{ start: 8, end: 18, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Maximilian" },
],
};
});
const updated = await commitPreparedText(followup, new Set([0, 1]), false, { PERSON_01: "PERSON_03" });
expect(updated.result.pseudonymized_text).toBe("PERSON_03 und PERSON_03");
expect(updated.result.mapping.PERSON_02.merged_into).toBe("PERSON_03");
expect(updated.session.mapping.PERSON_02.original).toBe("Maximilian");
});
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, {