Split Persona curiosity source and projection
This commit is contained in:
parent
598dd699ad
commit
5149e35431
9 changed files with 293 additions and 551 deletions
|
|
@ -0,0 +1,97 @@
|
|||
import type { RepoDiscordIdentity, VoidSelfStateTypedProjection } from "@voidbot/core";
|
||||
import type { SourceMessage } from "@voidbot/shared";
|
||||
import type { ChannelSnapshot } from "./turn-context-source.js";
|
||||
import { collapsePersonaText, significantPersonaTopicTerms } from "./persona-curiosity-terms.js";
|
||||
|
||||
export interface PersonaCuriositySearchResult {
|
||||
chunkId: string;
|
||||
sourceId: string;
|
||||
sourceKind: "discord_message" | "source_document" | "persona_memory";
|
||||
text: string;
|
||||
score: number;
|
||||
metadata: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface PersonaCuriosityRetrievalPort {
|
||||
searchHistory(query: string, limit: number): Promise<PersonaCuriositySearchResult[]>;
|
||||
searchSources(query: string, limit: number, repoName?: string): Promise<PersonaCuriositySearchResult[]>;
|
||||
}
|
||||
|
||||
export interface PersonaCuriosityNode extends PersonaCuriositySearchResult {
|
||||
id: string;
|
||||
terms: string[];
|
||||
seedLabels: string[];
|
||||
}
|
||||
|
||||
export type PersonaCuriosityEvidenceObservation =
|
||||
| { status: "ok"; nodes: PersonaCuriosityNode[]; seedCount: number }
|
||||
| { status: "empty"; reason: string }
|
||||
| { status: "unavailable"; reason: string };
|
||||
|
||||
export async function readPersonaCuriosityEvidence(input: {
|
||||
identity: RepoDiscordIdentity;
|
||||
state: VoidSelfStateTypedProjection;
|
||||
recentMessages: SourceMessage[];
|
||||
channelSnapshots: ChannelSnapshot[];
|
||||
sourceRepoName?: string;
|
||||
retrieval: PersonaCuriosityRetrievalPort | (() => PersonaCuriosityRetrievalPort);
|
||||
}): Promise<PersonaCuriosityEvidenceObservation> {
|
||||
const seeds = buildPersonaCuriositySeedQueries(input);
|
||||
if (seeds.length === 0) return { status: "empty", reason: "No supplied context produced a viable semantic seed." };
|
||||
try {
|
||||
const retrieval = typeof input.retrieval === "function" ? input.retrieval() : input.retrieval;
|
||||
const nodesById = new Map<string, PersonaCuriosityNode>();
|
||||
for (const seed of seeds) {
|
||||
const [history, sources, homeSources] = await Promise.all([
|
||||
retrieval.searchHistory(seed.query, 8),
|
||||
retrieval.searchSources(seed.query, 8),
|
||||
input.sourceRepoName ? retrieval.searchSources(seed.query, 6, input.sourceRepoName) : Promise.resolve([]),
|
||||
]);
|
||||
for (const result of [...history, ...sources, ...homeSources]) {
|
||||
const id = `${result.sourceKind}:${result.chunkId}`;
|
||||
const terms = significantPersonaTopicTerms(result.text);
|
||||
if (terms.length < 3) continue;
|
||||
const existing = nodesById.get(id);
|
||||
if (existing) {
|
||||
existing.score = Math.max(existing.score, result.score);
|
||||
existing.seedLabels = [...new Set([...existing.seedLabels, seed.label])];
|
||||
} else {
|
||||
nodesById.set(id, { ...result, id, terms, seedLabels: [seed.label] });
|
||||
}
|
||||
}
|
||||
}
|
||||
const nodes = [...nodesById.values()].sort((left, right) => right.score - left.score).slice(0, 32);
|
||||
return nodes.length < 3
|
||||
? { status: "empty", reason: "Semantic retrieval returned fewer than three usable evidence nodes." }
|
||||
: { status: "ok", nodes, seedCount: seeds.length };
|
||||
} catch (error) {
|
||||
return { status: "unavailable", reason: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
|
||||
export function buildPersonaCuriositySeedQueries(input: {
|
||||
identity: RepoDiscordIdentity;
|
||||
state: VoidSelfStateTypedProjection;
|
||||
recentMessages: SourceMessage[];
|
||||
channelSnapshots: ChannelSnapshot[];
|
||||
}): Array<{ label: string; query: string }> {
|
||||
const room = input.recentMessages.filter(hasContent).slice(-8).map((message) => `${message.authorName}: ${collapsePersonaText(message.content, 500)}`).join("\n");
|
||||
const nearby = input.channelSnapshots.flatMap((snapshot) => snapshot.messages).filter(hasContent).slice(-8).map((message) => `${message.authorName}: ${collapsePersonaText(message.content, 320)}`).join("\n");
|
||||
const state = input.state;
|
||||
const privateState = [
|
||||
...state.selfProfile.privateNotes.slice(-8),
|
||||
...[...state.selfProfile.values].sort((left, right) => right.priority - left.priority).slice(0, 8).map((value) => `${value.label}: ${value.summary}`),
|
||||
...state.thoughtMemory.memories.filter((memory) => !memory.retiredAt).slice(-8).map(memorySeed),
|
||||
...state.thoughtMemory.shortTerm.filter((memory) => !memory.retiredAt).slice(-8).map(memorySeed),
|
||||
...state.thoughtMemory.incubation.filter((thread) => thread.status !== "retired").sort((left, right) => right.maturation - left.maturation).slice(0, 8).map((thread) => `${thread.topic}: ${thread.summary}`),
|
||||
].join("\n");
|
||||
const identity = [input.identity.displayName, input.identity.repoName, input.identity.description ?? "", ...input.identity.channelPermissions.flatMap((permission) => [permission.label ?? "", permission.topic ?? "", permission.posture ?? ""])].join("\n");
|
||||
return [{ label: "current room", query: room }, { label: "nearby rooms", query: nearby }, { label: "private state", query: privateState }, { label: "home territory", query: identity }]
|
||||
.map((seed) => ({ ...seed, query: collapsePersonaText(seed.query, 2800) }))
|
||||
.filter((seed) => significantPersonaTopicTerms(seed.query).length >= 3)
|
||||
.slice(0, 4);
|
||||
}
|
||||
|
||||
function hasContent(message: SourceMessage): boolean { return collapsePersonaText(message.content).length > 0; }
|
||||
function memorySeed(memory: VoidSelfStateTypedProjection["thoughtMemory"]["memories"][number]): string { return `${memory.kind} ${targetLabel(memory.target)} ${memory.summary} ${memory.claim ?? memory.question ?? ""}`; }
|
||||
function targetLabel(target: { label?: string; id?: string; kind?: string } | undefined): string { return target?.label ?? target?.id ?? target?.kind ?? "an unnamed target"; }
|
||||
119
apps/persona-scheduler/src/persona-curiosity-projector.ts
Normal file
119
apps/persona-scheduler/src/persona-curiosity-projector.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import type { RepoDiscordIdentity, VoidSelfStateTypedProjection } from "@voidbot/core";
|
||||
import type { SourceMessage } from "@voidbot/shared";
|
||||
import type { ChannelSnapshot } from "./turn-context-source.js";
|
||||
import type { PersonaCuriosityEvidenceObservation, PersonaCuriosityNode } from "./persona-curiosity-context-source.js";
|
||||
import { collapsePersonaText, significantPersonaTopicTerms } from "./persona-curiosity-terms.js";
|
||||
|
||||
interface PersonaCuriosityCluster {
|
||||
label: string;
|
||||
nodes: PersonaCuriosityNode[];
|
||||
prominence: number;
|
||||
saturation: number;
|
||||
novelty: number;
|
||||
clusterDensity: number;
|
||||
jurisdictionFit: number;
|
||||
evidence: string[];
|
||||
}
|
||||
|
||||
export function projectPersonaCuriosityContext(input: {
|
||||
identity: RepoDiscordIdentity;
|
||||
state: VoidSelfStateTypedProjection;
|
||||
recentMessages: SourceMessage[];
|
||||
channelSnapshots: ChannelSnapshot[];
|
||||
observation: PersonaCuriosityEvidenceObservation;
|
||||
backendDescription: string;
|
||||
}): string | undefined {
|
||||
if (input.observation.status === "empty") return undefined;
|
||||
if (input.observation.status === "unavailable") return [
|
||||
"Curiosity graph unavailable:",
|
||||
`- Semantic retrieval failed while decoding topic attractors: ${collapsePersonaText(input.observation.reason, 260)}`,
|
||||
"- Do not pretend a semantic curiosity map was available this turn. Fall back to the raw transcript, home-repo activity, and typed memory instead of inventing ranked attractors.",
|
||||
].join("\n");
|
||||
const clusters = decodePersonaCuriosityGraph(input, input.observation.nodes);
|
||||
if (clusters.length === 0) return undefined;
|
||||
return [
|
||||
"Curiosity graph attractors:",
|
||||
`- Source: semantic retrieval from ${input.backendDescription}; local graph decoding over retrieved chunks. This is curiosity weather, not orders or consensus.`,
|
||||
...clusters.map((cluster) => [
|
||||
`- ${cluster.label || "unnamed cluster"}: prominence ${formatSignal(cluster.prominence)}, saturation ${formatSignal(cluster.saturation)}, novelty ${formatSignal(cluster.novelty)}, cluster density ${formatSignal(cluster.clusterDensity)}, jurisdiction fit ${formatSignal(cluster.jurisdictionFit)}.`,
|
||||
` Suggested motion: ${suggestMotion(input.identity, cluster)}`,
|
||||
` Evidence: ${cluster.evidence.join("; ")}.`,
|
||||
].join("\n")),
|
||||
"- The living use is intelligent curiosity: follow underexplored neighboring clusters, deepen home-territory clusters only with fresh anchors, and let saturated clusters create boredom, fatigue, or a deliberate closing move instead of another repetition.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function decodePersonaCuriosityGraph(input: {
|
||||
identity: RepoDiscordIdentity;
|
||||
state: VoidSelfStateTypedProjection;
|
||||
recentMessages: SourceMessage[];
|
||||
channelSnapshots: ChannelSnapshot[];
|
||||
}, nodes: PersonaCuriosityNode[]): PersonaCuriosityCluster[] {
|
||||
const edgeWeights = new Map<string, number>();
|
||||
const adjacency = new Map(nodes.map((node) => [node.id, new Set<string>()]));
|
||||
for (let leftIndex = 0; leftIndex < nodes.length; leftIndex += 1) for (let rightIndex = leftIndex + 1; rightIndex < nodes.length; rightIndex += 1) {
|
||||
const left = nodes[leftIndex];
|
||||
const right = nodes[rightIndex];
|
||||
const weight = edgeWeight(left, right);
|
||||
if (weight < 0.16) continue;
|
||||
edgeWeights.set(edgeKey(left.id, right.id), weight);
|
||||
adjacency.get(left.id)?.add(right.id);
|
||||
adjacency.get(right.id)?.add(left.id);
|
||||
}
|
||||
const visited = new Set<string>();
|
||||
const nodesById = new Map(nodes.map((node) => [node.id, node]));
|
||||
const connected: PersonaCuriosityNode[][] = [];
|
||||
for (const node of nodes) {
|
||||
if (visited.has(node.id)) continue;
|
||||
const stack = [node.id];
|
||||
const cluster: PersonaCuriosityNode[] = [];
|
||||
visited.add(node.id);
|
||||
while (stack.length > 0) {
|
||||
const id = stack.pop();
|
||||
if (!id) continue;
|
||||
const current = nodesById.get(id);
|
||||
if (current) cluster.push(current);
|
||||
for (const neighbor of adjacency.get(id) ?? []) if (!visited.has(neighbor)) { visited.add(neighbor); stack.push(neighbor); }
|
||||
}
|
||||
connected.push(cluster);
|
||||
}
|
||||
const recentTerms = termCounts([...input.recentMessages, ...input.channelSnapshots.flatMap((snapshot) => snapshot.messages)].slice(-36).map((message) => message.content));
|
||||
const stateTerms = termCounts([
|
||||
...input.state.selfProfile.privateNotes,
|
||||
...input.state.selfProfile.values.map((value) => `${value.label} ${value.summary}`),
|
||||
...input.state.thoughtMemory.memories.map(memorySurface),
|
||||
...input.state.thoughtMemory.shortTerm.map(memorySurface),
|
||||
...input.state.thoughtMemory.incubation.map((thread) => `${thread.topic} ${thread.summary}`),
|
||||
...input.state.agencyPressure.pressures.map((pressure) => `${pressure.summary} ${pressure.claim ?? ""} ${pressure.question ?? ""} ${pressure.tension ?? ""}`),
|
||||
].slice(-64));
|
||||
const identityTerms = new Set(significantPersonaTopicTerms([input.identity.id, input.identity.displayName, input.identity.repoName, input.identity.description ?? "", ...input.identity.channelPermissions.flatMap((permission) => [permission.label ?? "", permission.topic ?? "", permission.posture ?? ""])].join(" ")));
|
||||
return connected.filter((cluster) => cluster.length >= 2).map((cluster): PersonaCuriosityCluster => {
|
||||
const terms = rankedTerms(cluster).slice(0, 7);
|
||||
const density = clusterDensity(cluster, edgeWeights);
|
||||
const stateOverlap = weightedOverlap(terms, stateTerms);
|
||||
const saturation = clamp((weightedOverlap(terms, recentTerms) * 0.72) + (stateOverlap * 0.42));
|
||||
const jurisdictionFit = clamp(terms.filter((term) => identityTerms.has(term)).length / Math.max(1, Math.min(terms.length, 4)) + cluster.filter((node) => normalize(node.metadata.repoName ?? "") === normalize(input.identity.repoName)).length / Math.max(1, cluster.length) * 0.55);
|
||||
return {
|
||||
label: terms.slice(0, 4).join(" / "), nodes: cluster, saturation, jurisdictionFit, clusterDensity: density,
|
||||
novelty: clamp(1 - saturation + Math.max(0, 0.4 - stateOverlap)),
|
||||
prominence: clamp((average(cluster.map((node) => node.score)) * 0.58) + (density * 0.28) + (Math.min(cluster.length, 8) / 8 * 0.18)),
|
||||
evidence: [...cluster].sort((left, right) => right.score - left.score).slice(0, 3).map(evidenceLabel),
|
||||
};
|
||||
}).sort((left, right) => attractorRank(right) - attractorRank(left) || right.prominence - left.prominence).slice(0, 5);
|
||||
}
|
||||
|
||||
function edgeWeight(left: PersonaCuriosityNode, right: PersonaCuriosityNode): number { const sameRepo = left.metadata.repoName && right.metadata.repoName && normalize(left.metadata.repoName) === normalize(right.metadata.repoName) ? 1 : 0; const sameCorpus = left.sourceKind === right.sourceKind ? 1 : 0; const sharedSeed = left.seedLabels.some((label) => right.seedLabels.includes(label)) ? 1 : 0; return clamp(jaccard(left.terms, right.terms) * 0.58 + sameRepo * 0.16 + sameCorpus * 0.1 + sharedSeed * 0.08 + (1 - Math.min(1, Math.abs(left.score - right.score))) * 0.08); }
|
||||
function rankedTerms(cluster: PersonaCuriosityNode[]): string[] { const counts = new Map<string, number>(); for (const node of cluster) for (const term of node.terms) counts.set(term, (counts.get(term) ?? 0) + 1); return [...counts].sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0])).map(([term]) => term); }
|
||||
function termCounts(surfaces: string[]): Map<string, number> { const counts = new Map<string, number>(); for (const surface of surfaces) for (const term of significantPersonaTopicTerms(surface)) counts.set(term, (counts.get(term) ?? 0) + 1); return counts; }
|
||||
function weightedOverlap(terms: string[], counts: Map<string, number>): number { if (terms.length === 0 || counts.size === 0) return 0; const max = Math.max(...counts.values(), 1); return clamp(terms.reduce((sum, term) => sum + (counts.get(term) ?? 0) / max, 0) / Math.min(terms.length, 6)); }
|
||||
function clusterDensity(cluster: PersonaCuriosityNode[], weights: Map<string, number>): number { let sum = 0; let pairs = 0; for (let left = 0; left < cluster.length; left += 1) for (let right = left + 1; right < cluster.length; right += 1) { sum += weights.get(edgeKey(cluster[left].id, cluster[right].id)) ?? 0; pairs += 1; } return pairs > 0 ? clamp(sum / pairs) : 0; }
|
||||
function attractorRank(cluster: PersonaCuriosityCluster): number { return clamp(cluster.prominence * 0.42 + cluster.novelty * 0.28 + cluster.clusterDensity * 0.16 + cluster.jurisdictionFit * 0.18 - cluster.saturation * 0.2); }
|
||||
function suggestMotion(identity: RepoDiscordIdentity, cluster: PersonaCuriosityCluster): string { if (cluster.saturation >= 0.68 && cluster.novelty <= 0.42) return `treat this as over-chewed; ${identity.displayName} should close, defer, or pivot to a neighboring question unless a new concrete anchor appears.`; if (cluster.jurisdictionFit >= 0.55 && cluster.novelty >= 0.45) return "this is home-territory curiosity with room to grow; read, ask, draft, or make a fresh anchored distinction."; if (cluster.novelty >= 0.62) return `this is an underexplored neighboring trail; curiosity may pull ${identity.displayName} sideways instead of repeating the room's dominant topic.`; if (cluster.jurisdictionFit < 0.3) return "this likely belongs to another steward; use it as social weather, consultation, or rivalry pressure rather than absorbing the work."; return "stay interested only if the turn adds a new anchor, concrete question, or relationship move."; }
|
||||
function evidenceLabel(node: PersonaCuriosityNode): string { const source = node.sourceKind === "source_document" ? [node.metadata.repoName, node.metadata.path].filter(Boolean).join(":") || node.sourceId : [node.metadata.channelId ? `channel ${node.metadata.channelId}` : undefined, node.sourceId].filter(Boolean).join(":") || node.sourceId; return `${source} (${node.score.toFixed(2)}, ${node.seedLabels.join("/")})`; }
|
||||
function memorySurface(memory: VoidSelfStateTypedProjection["thoughtMemory"]["memories"][number]): string { return `${memory.summary} ${memory.claim ?? ""} ${memory.question ?? ""} ${memory.tension ?? ""}`; }
|
||||
function edgeKey(left: string, right: string): string { return left < right ? `${left}::${right}` : `${right}::${left}`; }
|
||||
function jaccard(left: string[], right: string[]): number { const a = new Set(left); const b = new Set(right); const union = new Set([...a, ...b]).size; return union === 0 ? 0 : [...a].filter((term) => b.has(term)).length / union; }
|
||||
function average(values: number[]): number { return values.length > 0 ? values.reduce((sum, value) => sum + value, 0) / values.length : 0; }
|
||||
function formatSignal(value: number): string { return `${value >= 0.68 ? "high" : value >= 0.38 ? "medium" : "low"} ${value.toFixed(2)}`; }
|
||||
function normalize(value: string): string { return value.trim().toLowerCase(); }
|
||||
function clamp(value: number): number { return Math.min(1, Math.max(0, Number(value.toFixed(3)))); }
|
||||
20
apps/persona-scheduler/src/persona-curiosity-terms.ts
Normal file
20
apps/persona-scheduler/src/persona-curiosity-terms.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
const STOP_WORDS = new Set([
|
||||
"about", "actually", "after", "again", "agent", "agents", "already", "another", "around", "because", "before", "being", "between", "channel", "could", "does", "doing", "don", "even", "every", "exactly", "face", "faces", "first", "from", "give", "going", "good", "have", "here", "into", "just", "kind", "know", "latest", "like", "line", "little", "made", "make", "maybe", "more", "need", "needs", "only", "other", "point", "post", "really", "recent", "right", "rights", "room", "same", "should", "something", "still", "take", "talk", "than", "that", "their", "them", "there", "these", "they", "thing", "things", "think", "this", "those", "through", "turn", "want", "what", "when", "where", "which", "while", "with", "work", "would", "write", "you", "your",
|
||||
]);
|
||||
|
||||
export function significantPersonaTopicTerms(content: string): string[] {
|
||||
const normalized = collapsePersonaText(content)
|
||||
.toLowerCase()
|
||||
.replace(/[`*_~]/g, "")
|
||||
.replace(/<:[^>]+>/g, "")
|
||||
.replace(/https?:\/\/\S+/g, "url")
|
||||
.replace(/[^\p{L}\p{N}\s.'-]/gu, " ")
|
||||
.replace(/\b\d{5,}\b/g, " ")
|
||||
.replace(/\b[a-z]*\d+[a-z0-9]*\b/g, " ");
|
||||
return [...new Set(normalized.split(/\s+/).map((term) => term.replace(/^['.-]+|['.-]+$/g, "")).filter((term) => term.length >= 4 && !STOP_WORDS.has(term)))];
|
||||
}
|
||||
|
||||
export function collapsePersonaText(value: string, maxLength?: number): string {
|
||||
const normalized = value.replace(/\s+/g, " ").trim();
|
||||
return maxLength && normalized.length > maxLength ? `${normalized.slice(0, maxLength - 3)}...` : normalized;
|
||||
}
|
||||
Loading…
Reference in a new issue