Add semantic Persona response pressure
This commit is contained in:
parent
7202a41d9e
commit
b0dbb2d8bd
12 changed files with 483 additions and 6 deletions
|
|
@ -8,6 +8,7 @@ export * from "./job-queue";
|
|||
export * from "./permission-engine";
|
||||
export * from "./repo-discord-identities";
|
||||
export * from "./repo-face-heartbeat-queue";
|
||||
export * from "./repo-face-response-pressure";
|
||||
export * from "./repo-face-initializer";
|
||||
export * from "./repo-face-rest";
|
||||
export * from "./repo-face-voice-presence";
|
||||
|
|
|
|||
89
packages/core/src/repo-face-response-pressure.ts
Normal file
89
packages/core/src/repo-face-response-pressure.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
export interface ResponsePressureEvidence {
|
||||
messageId: string;
|
||||
observedAt: string;
|
||||
similarity: number;
|
||||
}
|
||||
|
||||
export interface ResponsePressureProjection {
|
||||
identityId: string;
|
||||
pressure: number;
|
||||
interrupt: boolean;
|
||||
evidence: Array<ResponsePressureEvidence & { contribution: number }>;
|
||||
}
|
||||
|
||||
export interface ResponsePressureParticipant {
|
||||
identityId: string;
|
||||
interruptThreshold: number;
|
||||
}
|
||||
|
||||
export function projectRepoFaceResponsePressure(input: {
|
||||
participants: ResponsePressureParticipant[];
|
||||
evidence: Array<ResponsePressureEvidence & { identityId: string }>;
|
||||
now: Date;
|
||||
halfLifeMinutes?: number;
|
||||
ttlMinutes?: number;
|
||||
similarityFloor?: number;
|
||||
maxAwakened?: number;
|
||||
}): ResponsePressureProjection[] {
|
||||
const halfLifeMinutes = positive(input.halfLifeMinutes, 30);
|
||||
const ttlMinutes = positive(input.ttlMinutes, 180);
|
||||
const similarityFloor = bounded(input.similarityFloor ?? 0.32, 0, 0.99);
|
||||
const byIdentity = new Map<string, Array<ResponsePressureEvidence & { contribution: number }>>();
|
||||
|
||||
for (const item of input.evidence) {
|
||||
const ageMinutes = Math.max(0, (input.now.getTime() - Date.parse(item.observedAt)) / 60_000);
|
||||
if (!Number.isFinite(ageMinutes) || ageMinutes > ttlMinutes || item.similarity < similarityFloor) {
|
||||
continue;
|
||||
}
|
||||
const normalized = (item.similarity - similarityFloor) / (1 - similarityFloor);
|
||||
const contribution = bounded(normalized * 2 ** (-ageMinutes / halfLifeMinutes), 0, 1);
|
||||
if (contribution <= 0) {
|
||||
continue;
|
||||
}
|
||||
const entries = byIdentity.get(item.identityId) ?? [];
|
||||
const priorIndex = entries.findIndex((entry) => entry.messageId === item.messageId);
|
||||
const projected = { ...item, contribution };
|
||||
if (priorIndex >= 0) {
|
||||
entries[priorIndex] = projected;
|
||||
} else {
|
||||
entries.push(projected);
|
||||
}
|
||||
byIdentity.set(item.identityId, entries);
|
||||
}
|
||||
|
||||
const projections = input.participants.map((participant) => {
|
||||
const evidence = (byIdentity.get(participant.identityId) ?? [])
|
||||
.sort((left, right) => right.contribution - left.contribution || left.messageId.localeCompare(right.messageId));
|
||||
const pressure = bounded(noisyOr(evidence.map((entry) => entry.contribution)), 0, 1);
|
||||
return {
|
||||
identityId: participant.identityId,
|
||||
pressure,
|
||||
interrupt: pressure >= bounded(participant.interruptThreshold, 0, 1),
|
||||
evidence: evidence.slice(0, 6),
|
||||
};
|
||||
}).sort((left, right) => right.pressure - left.pressure || left.identityId.localeCompare(right.identityId));
|
||||
|
||||
const awakened = new Set(
|
||||
projections.filter((projection) => projection.pressure > 0).slice(0, positiveInteger(input.maxAwakened, 3))
|
||||
.map((projection) => projection.identityId),
|
||||
);
|
||||
return projections.map((projection) => awakened.has(projection.identityId)
|
||||
? projection
|
||||
: { ...projection, pressure: 0, interrupt: false, evidence: [] });
|
||||
}
|
||||
|
||||
function noisyOr(values: number[]): number {
|
||||
return 1 - values.reduce((remainder, value) => remainder * (1 - bounded(value, 0, 1)), 1);
|
||||
}
|
||||
|
||||
function bounded(value: number, minimum: number, maximum: number): number {
|
||||
return Number.isFinite(value) ? Math.max(minimum, Math.min(maximum, value)) : minimum;
|
||||
}
|
||||
|
||||
function positive(value: number | undefined, fallback: number): number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
function positiveInteger(value: number | undefined, fallback: number): number {
|
||||
return Math.max(1, Math.floor(positive(value, fallback)));
|
||||
}
|
||||
73
packages/rag/src/affinity-projection.ts
Normal file
73
packages/rag/src/affinity-projection.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { createHash } from "node:crypto";
|
||||
|
||||
import { cosineSimilarity, type TextEmbedder } from "./hash-embedder";
|
||||
|
||||
export interface AffinityCard {
|
||||
id: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface EmbeddedAffinityCard extends AffinityCard {
|
||||
contentHash: string;
|
||||
embedderId: string;
|
||||
embedding: number[];
|
||||
}
|
||||
|
||||
export interface AffinityMessage {
|
||||
id: string;
|
||||
text: string;
|
||||
observedAt: string;
|
||||
}
|
||||
|
||||
export interface AffinityScore {
|
||||
cardId: string;
|
||||
messageId: string;
|
||||
observedAt: string;
|
||||
similarity: number;
|
||||
}
|
||||
|
||||
export async function embedAffinityCards(
|
||||
embedder: TextEmbedder,
|
||||
cards: AffinityCard[],
|
||||
): Promise<EmbeddedAffinityCard[]> {
|
||||
const usable = cards.filter((card) => card.id.trim() && card.text.trim());
|
||||
const embeddings = await embedder.embedDocuments(usable.map((card) => card.text));
|
||||
if (embeddings.length !== usable.length) {
|
||||
throw new Error(`Affinity embedder returned ${embeddings.length} card vectors for ${usable.length} cards.`);
|
||||
}
|
||||
|
||||
return usable.map((card, index) => ({
|
||||
...card,
|
||||
contentHash: createHash("sha256").update(card.text).digest("hex"),
|
||||
embedderId: embedder.id,
|
||||
embedding: embeddings[index] ?? [],
|
||||
}));
|
||||
}
|
||||
|
||||
export async function scoreAffinityMessages(
|
||||
embedder: TextEmbedder,
|
||||
cards: EmbeddedAffinityCard[],
|
||||
messages: AffinityMessage[],
|
||||
): Promise<AffinityScore[]> {
|
||||
const mismatched = cards.find((card) => card.embedderId !== embedder.id);
|
||||
if (mismatched) {
|
||||
throw new Error(`Affinity card ${mismatched.id} uses ${mismatched.embedderId}, not ${embedder.id}.`);
|
||||
}
|
||||
|
||||
const usable = messages.filter((message) => message.id.trim() && message.text.trim());
|
||||
const embeddings = await embedder.embedDocuments(usable.map((message) => message.text));
|
||||
if (embeddings.length !== usable.length) {
|
||||
throw new Error(`Affinity embedder returned ${embeddings.length} message vectors for ${usable.length} messages.`);
|
||||
}
|
||||
|
||||
return cards.flatMap((card) => usable.map((message, index) => ({
|
||||
cardId: card.id,
|
||||
messageId: message.id,
|
||||
observedAt: message.observedAt,
|
||||
similarity: clampSimilarity(cosineSimilarity(card.embedding, embeddings[index] ?? [])),
|
||||
})));
|
||||
}
|
||||
|
||||
function clampSimilarity(value: number): number {
|
||||
return Number.isFinite(value) ? Math.max(-1, Math.min(1, value)) : 0;
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
export * from "./embedder-factory";
|
||||
export * from "./affinity-projection";
|
||||
export * from "./history-ingester";
|
||||
export * from "./history-retrieval";
|
||||
export * from "./discord-log-importer";
|
||||
|
|
|
|||
Loading…
Reference in a new issue