forked from r.muellner/velum-raycast
feat: review text hits and release false-positive mappings
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
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 type { ProjectWhitelistEntry } from "./lib/velum-project";
|
||||
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. */
|
||||
export async function pseudonymizeInContext(values: ContextFormValues, text: string,
|
||||
entityTypes: EntityType[], forAi = false,
|
||||
|
||||
Reference in New Issue
Block a user