Require source grounding for project and lore answers
This commit is contained in:
parent
75052f198a
commit
b4693f5609
6 changed files with 236 additions and 3 deletions
|
|
@ -223,6 +223,8 @@ The `local_llm` provider uses Ollama chat completion plus a bounded host-managed
|
|||
|
||||
Unlike the owner Codex lane, this is not MCP. It is a tighter host-controlled loop and deliberately excludes side-effecting tools.
|
||||
|
||||
Project, repo, and lore questions are now source-grounded by policy: if the prompt matches indexed repo/project cues, Void must touch the source-side lookup tools before answering confidently.
|
||||
|
||||
## Discord, Repo, And Lore Indexing
|
||||
|
||||
### Discord history
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ import {
|
|||
type GuildContext,
|
||||
type JobRecord,
|
||||
type ProviderName,
|
||||
type SourceGroundingHint,
|
||||
type SourceMessage,
|
||||
type StylePack,
|
||||
isProviderName,
|
||||
|
|
@ -340,6 +341,7 @@ export async function startBot(): Promise<void> {
|
|||
permissionEngine,
|
||||
contextBuilder,
|
||||
retrievalService,
|
||||
sourceArchiveRepository,
|
||||
jobQueue,
|
||||
auditLog,
|
||||
interactionMemory,
|
||||
|
|
@ -417,6 +419,7 @@ export async function startBot(): Promise<void> {
|
|||
permissionEngine,
|
||||
contextBuilder,
|
||||
retrievalService,
|
||||
sourceArchiveRepository,
|
||||
jobQueue,
|
||||
auditLog,
|
||||
interactionMemory,
|
||||
|
|
@ -442,6 +445,7 @@ export async function startBot(): Promise<void> {
|
|||
permissionEngine,
|
||||
contextBuilder,
|
||||
retrievalService,
|
||||
sourceArchiveRepository,
|
||||
jobQueue,
|
||||
auditLog,
|
||||
interactionMemory,
|
||||
|
|
@ -558,6 +562,7 @@ interface PromptHandlerOptions {
|
|||
permissionEngine: PermissionEngine;
|
||||
contextBuilder: ContextBuilder;
|
||||
retrievalService: RetrievalService;
|
||||
sourceArchiveRepository: FileSourceDocumentArchiveRepository;
|
||||
jobQueue: FileBackedJobQueue;
|
||||
auditLog: FileAuditLog;
|
||||
interactionMemory: FileInteractionMemoryBank;
|
||||
|
|
@ -613,6 +618,10 @@ async function handlePrompt(options: PromptHandlerOptions): Promise<void> {
|
|||
}
|
||||
|
||||
const recentMessages = await getRecentMessages(options.channel, 10);
|
||||
const sourceGrounding = inferSourceGroundingHint(
|
||||
options.prompt,
|
||||
await options.sourceArchiveRepository.listRepoSummaries(),
|
||||
);
|
||||
const shouldAttachInitialRetrieval =
|
||||
!provider.getCapabilities().includes("tool_driven_retrieval") &&
|
||||
(shouldIndexChannel(options.config.channelIndexing, buildChannelIndexingTarget(options.channel)) ||
|
||||
|
|
@ -630,6 +639,7 @@ async function handlePrompt(options: PromptHandlerOptions): Promise<void> {
|
|||
recentMessages,
|
||||
retrieval,
|
||||
interactionMemory,
|
||||
sourceGrounding,
|
||||
stylePack: options.stylePack,
|
||||
});
|
||||
|
||||
|
|
@ -1171,6 +1181,95 @@ function stripBotMention(content: string): string {
|
|||
return content.replace(/<@!?(\d+)>/g, "").trim();
|
||||
}
|
||||
|
||||
function inferSourceGroundingHint(
|
||||
prompt: string,
|
||||
repoSummaries: Array<{ repoName: string }>,
|
||||
): SourceGroundingHint {
|
||||
const normalized = ` ${normalizeForMatching(prompt)} `;
|
||||
const reasons = new Set<string>();
|
||||
const matchedRepoNames = new Set<string>();
|
||||
|
||||
for (const repo of repoSummaries) {
|
||||
for (const alias of buildRepoAliases(repo.repoName)) {
|
||||
if (alias.length < 4) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (normalized.includes(` ${alias} `)) {
|
||||
matchedRepoNames.add(repo.repoName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (matchedRepoNames.size > 0) {
|
||||
reasons.add("matched indexed repo/project name");
|
||||
}
|
||||
|
||||
const genericSourceCues = [
|
||||
" repo ",
|
||||
" repository ",
|
||||
" repositories ",
|
||||
" codebase ",
|
||||
" source ",
|
||||
" sources ",
|
||||
" lore ",
|
||||
" vault ",
|
||||
" canon ",
|
||||
" file ",
|
||||
" files ",
|
||||
" docs ",
|
||||
" documentation ",
|
||||
" module ",
|
||||
" implementation ",
|
||||
" project ",
|
||||
" projects ",
|
||||
];
|
||||
|
||||
if (genericSourceCues.some((cue) => normalized.includes(cue))) {
|
||||
reasons.add("contains source/lore cue");
|
||||
}
|
||||
|
||||
return {
|
||||
required: reasons.size > 0,
|
||||
reasons: [...reasons],
|
||||
matchedRepoNames: [...matchedRepoNames].sort(),
|
||||
};
|
||||
}
|
||||
|
||||
function buildRepoAliases(repoName: string): string[] {
|
||||
const normalizedRepo = repoName.replace(/[_-]+/g, " ").trim();
|
||||
const lower = normalizeForMatching(normalizedRepo);
|
||||
const compact = normalizeForMatching(repoName);
|
||||
const words = splitPascalCase(normalizedRepo)
|
||||
.flatMap((part) => part.split(/\s+/))
|
||||
.map((part) => normalizeForMatching(part))
|
||||
.filter((part) => part.length > 0);
|
||||
const aliases = new Set<string>([lower, compact, words.join(" ")]);
|
||||
|
||||
for (const word of words) {
|
||||
if (word.length >= 4) {
|
||||
aliases.add(word);
|
||||
}
|
||||
}
|
||||
|
||||
return [...aliases].filter((alias) => alias.length > 0);
|
||||
}
|
||||
|
||||
function splitPascalCase(value: string): string[] {
|
||||
return value
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.split(/\s+/)
|
||||
.filter((part) => part.length > 0);
|
||||
}
|
||||
|
||||
function normalizeForMatching(value: string): string {
|
||||
return value
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function isAmbientVoidReference(
|
||||
message: Message,
|
||||
botUserId: string | undefined,
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {
|
|||
type GuildContext,
|
||||
type InteractionMemoryProfile,
|
||||
type RetrievalResult,
|
||||
type SourceGroundingHint,
|
||||
type SourceMessage,
|
||||
type StylePack,
|
||||
} from "@voidbot/shared";
|
||||
|
|
@ -15,6 +16,7 @@ export interface BuildContextInput {
|
|||
recentMessages?: SourceMessage[];
|
||||
retrieval?: RetrievalResult[];
|
||||
interactionMemory?: InteractionMemoryProfile;
|
||||
sourceGrounding?: SourceGroundingHint;
|
||||
stylePack?: StylePack;
|
||||
}
|
||||
|
||||
|
|
@ -27,6 +29,7 @@ export class ContextBuilder {
|
|||
recentMessages: input.recentMessages ?? [],
|
||||
retrieval: input.retrieval ?? [],
|
||||
interactionMemory: input.interactionMemory,
|
||||
sourceGrounding: input.sourceGrounding,
|
||||
stylePack: input.stylePack,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
|
||||
type OllamaThinkMode = boolean | "low" | "medium" | "high";
|
||||
const MAX_TOOL_TURNS = 4;
|
||||
const MAX_SOURCE_GROUNDING_RETRIES = 1;
|
||||
const MAX_TOOL_RESULTS = MAX_RETRIEVAL_RESULT_LIMIT;
|
||||
const MAX_CONTEXT_WINDOW = 20;
|
||||
|
||||
|
|
@ -183,6 +184,8 @@ export class LocalLlmProvider implements ProviderAdapter {
|
|||
const tools = this.options.toolbox ? buildToolDefinitions() : undefined;
|
||||
const toolTrace: ToolTraceRecord[] = [];
|
||||
const thinkingTrace: string[] = [];
|
||||
const sourceGroundingRequired = Boolean(request.contextBundle.sourceGrounding?.required);
|
||||
let sourceGroundingReminderCount = 0;
|
||||
|
||||
try {
|
||||
let finalPayload: OllamaChatResponse | undefined;
|
||||
|
|
@ -230,7 +233,28 @@ export class LocalLlmProvider implements ProviderAdapter {
|
|||
messages.push(assistantMessage);
|
||||
|
||||
if (toolCalls.length === 0) {
|
||||
finalOutputText = normalizeModelText(assistantMessage.content);
|
||||
const candidateOutput = normalizeModelText(assistantMessage.content);
|
||||
|
||||
if (
|
||||
sourceGroundingRequired &&
|
||||
!didUseSourceGrounding(toolTrace) &&
|
||||
this.options.toolbox
|
||||
) {
|
||||
if (sourceGroundingReminderCount < MAX_SOURCE_GROUNDING_RETRIES) {
|
||||
sourceGroundingReminderCount += 1;
|
||||
messages.push({
|
||||
role: "user",
|
||||
content: buildSourceGroundingReminder(request.contextBundle),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
finalOutputText =
|
||||
"Void: This one needs actual source grounding before I answer it cleanly. Ask again after I pull from the indexed repos, or use the deeper Codex lane.";
|
||||
break;
|
||||
}
|
||||
|
||||
finalOutputText = candidateOutput;
|
||||
break;
|
||||
}
|
||||
|
||||
|
|
@ -339,6 +363,7 @@ function buildSystemPrompt(context: ContextBundle): string {
|
|||
"If explicit interaction memory for the current speaker is attached, you may let it gently color the tone and reference it when relevant, but do not invent history beyond what was provided.",
|
||||
"When the answer depends on archived Discord history or indexed repo/lore context, use the available read-only tools instead of guessing.",
|
||||
"If you need to target a specific indexed repo and do not know the valid repo names yet, call list_indexed_repos before search_sources.",
|
||||
renderSourceGroundingInstructions(context, false),
|
||||
"Do not claim to have performed searches or tool calls beyond the material actually executed in this run.",
|
||||
"If the supplied context looks incomplete, say so plainly instead of bluffing.",
|
||||
"Keep the final answer concise and readable in Discord.",
|
||||
|
|
@ -416,6 +441,42 @@ function renderInteractionMemory(context: ContextBundle): string {
|
|||
].join("\n");
|
||||
}
|
||||
|
||||
function renderSourceGroundingInstructions(
|
||||
context: ContextBundle,
|
||||
reminder: boolean,
|
||||
): string {
|
||||
if (!context.sourceGrounding?.required) {
|
||||
return "Source-side grounding is optional here; use it when it clearly helps.";
|
||||
}
|
||||
|
||||
const matchedRepos =
|
||||
context.sourceGrounding.matchedRepoNames.length > 0
|
||||
? ` Matched repos/projects: ${context.sourceGrounding.matchedRepoNames.join(", ")}.`
|
||||
: "";
|
||||
const reasons =
|
||||
context.sourceGrounding.reasons.length > 0
|
||||
? ` Reasons: ${context.sourceGrounding.reasons.join(", ")}.`
|
||||
: "";
|
||||
const retry =
|
||||
reminder
|
||||
? " The previous answer attempt was discarded because it did not touch the source-side tools."
|
||||
: "";
|
||||
|
||||
return `This prompt requires source-grounded evidence before you answer. Use list_indexed_repos, search_sources, or get_source_context first.${matchedRepos}${reasons}${retry}`;
|
||||
}
|
||||
|
||||
function buildSourceGroundingReminder(context: ContextBundle): string {
|
||||
return `${renderSourceGroundingInstructions(context, true)} Answer again only after using the source-side tools.`;
|
||||
}
|
||||
|
||||
function didUseSourceGrounding(toolTrace: ToolTraceRecord[]): boolean {
|
||||
return toolTrace.some((trace) =>
|
||||
trace.tool === "list_indexed_repos" ||
|
||||
trace.tool === "search_sources" ||
|
||||
trace.tool === "get_source_context",
|
||||
);
|
||||
}
|
||||
|
||||
function buildArtifacts(
|
||||
requestBody: Record<string, unknown>,
|
||||
payload: OllamaChatResponse,
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ const HANDOFF_SENTINEL = "VOIDBOT_HANDOFF_REQUIRED:";
|
|||
const OWNER_NOTIFY_SENTINEL = "VOIDBOT_OWNER_NOTIFY:";
|
||||
const TOOL_REQUEST_SENTINEL = "VOIDBOT_TOOL_REQUEST:";
|
||||
const MAX_HISTORY_TOOL_CALLS = 4;
|
||||
const MAX_SOURCE_GROUNDING_RETRIES = 1;
|
||||
const DEFAULT_HISTORY_LIMIT = DEFAULT_RETRIEVAL_RESULT_LIMIT;
|
||||
const MAX_HISTORY_LIMIT = MAX_RETRIEVAL_RESULT_LIMIT;
|
||||
const MAX_NOTIFICATION_MESSAGE_LENGTH = 400;
|
||||
|
|
@ -245,9 +246,15 @@ export class OwnerCodexProvider implements ProviderAdapter {
|
|||
const artifacts: ProviderArtifact[] = [...baseArtifacts];
|
||||
const turnResults: CodexRunResult[] = [];
|
||||
let result: CodexRunResult | undefined;
|
||||
let sourceGroundingReminderCount = 0;
|
||||
const sourceGroundingRequired = Boolean(request.contextBundle.sourceGrounding?.required);
|
||||
|
||||
for (let turn = 0; turn <= MAX_HISTORY_TOOL_CALLS; turn += 1) {
|
||||
const codexPrompt = buildDiscordReplyPrompt(request.contextBundle, toolCalls);
|
||||
for (let turn = 0; turn <= MAX_HISTORY_TOOL_CALLS + MAX_SOURCE_GROUNDING_RETRIES; turn += 1) {
|
||||
const codexPrompt = buildDiscordReplyPrompt(
|
||||
request.contextBundle,
|
||||
toolCalls,
|
||||
sourceGroundingReminderCount > 0,
|
||||
);
|
||||
|
||||
result = await runCodexExec({
|
||||
executable: this.options.executable,
|
||||
|
|
@ -303,6 +310,19 @@ export class OwnerCodexProvider implements ProviderAdapter {
|
|||
}
|
||||
|
||||
if (!result.toolRequest) {
|
||||
if (
|
||||
sourceGroundingRequired &&
|
||||
!didUseSourceGrounding(result.traceEvents)
|
||||
) {
|
||||
if (sourceGroundingReminderCount < MAX_SOURCE_GROUNDING_RETRIES) {
|
||||
sourceGroundingReminderCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
result.handoffReason =
|
||||
"This question needed source-grounded evidence, but the reply lane never used the source tools.";
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
|
@ -947,6 +967,7 @@ function normalizeDiscordReply(stdout: string): NormalizedDiscordReply {
|
|||
function buildDiscordReplyPrompt(
|
||||
context: ContextBundle,
|
||||
toolCalls: ToolCallRecord[],
|
||||
sourceGroundingReminder: boolean,
|
||||
): string {
|
||||
const recentMessages = context.recentMessages.length
|
||||
? context.recentMessages
|
||||
|
|
@ -966,6 +987,10 @@ function buildDiscordReplyPrompt(
|
|||
context.stylePack && context.stylePack.enabled
|
||||
? context.stylePack.instructions
|
||||
: "No style pack is active.";
|
||||
const sourceGroundingInstructions = renderSourceGroundingInstructions(
|
||||
context,
|
||||
sourceGroundingReminder,
|
||||
);
|
||||
|
||||
return [
|
||||
"# VoidBot Owner Discord Reply",
|
||||
|
|
@ -987,6 +1012,7 @@ function buildDiscordReplyPrompt(
|
|||
"- For questions about Discord history, prior discussion, or user preferences, use search_history and get_message_context instead of filesystem inspection.",
|
||||
"- For questions about GameCult repos, source trees, repo-local docs, or AetheriaLore, use search_sources and get_source_context before broad workspace scans.",
|
||||
"- If you want to narrow source search to a specific repo but do not know the valid repo names yet, call list_indexed_repos first.",
|
||||
sourceGroundingInstructions,
|
||||
"- Do not inspect .voidbot/rag/messages.json, .voidbot/rag/source-documents.json, .voidbot/history-vector-store.json, or .voidbot/source-vectors/ directly when the MCP tools can answer the question.",
|
||||
"- Avoid broad workspace scans for archived Discord history or indexed source repos unless the MCP tools are clearly insufficient.",
|
||||
"- Do not modify files, install packages, or require network access.",
|
||||
|
|
@ -1028,6 +1054,7 @@ function buildRequestPayload(request: ProviderRequest): Record<string, unknown>
|
|||
actor: request.contextBundle.actor,
|
||||
guildContext: request.contextBundle.guildContext,
|
||||
interactionMemory: request.contextBundle.interactionMemory,
|
||||
sourceGrounding: request.contextBundle.sourceGrounding,
|
||||
stylePack: request.contextBundle.stylePack,
|
||||
recentMessages: request.contextBundle.recentMessages,
|
||||
retrieval: request.contextBundle.retrieval,
|
||||
|
|
@ -1133,6 +1160,40 @@ function renderInteractionMemory(context: ContextBundle): string {
|
|||
].join("\n");
|
||||
}
|
||||
|
||||
function renderSourceGroundingInstructions(
|
||||
context: ContextBundle,
|
||||
reminder: boolean,
|
||||
): string {
|
||||
if (!context.sourceGrounding?.required) {
|
||||
return "- Source-side grounding is optional here; use it when it clearly helps.";
|
||||
}
|
||||
|
||||
const matchedRepos =
|
||||
context.sourceGrounding.matchedRepoNames.length > 0
|
||||
? ` Matched repos/projects: ${context.sourceGrounding.matchedRepoNames.join(", ")}.`
|
||||
: "";
|
||||
const reasons =
|
||||
context.sourceGrounding.reasons.length > 0
|
||||
? ` Reasons: ${context.sourceGrounding.reasons.join(", ")}.`
|
||||
: "";
|
||||
const retry =
|
||||
reminder
|
||||
? " The previous answer attempt was discarded because it did not touch the source-side tools."
|
||||
: "";
|
||||
|
||||
return `- This prompt requires source-grounded evidence before you answer. Use list_indexed_repos, search_sources, or get_source_context first.${matchedRepos}${reasons}${retry}`;
|
||||
}
|
||||
|
||||
function didUseSourceGrounding(events: CodexTraceEvent[]): boolean {
|
||||
return events.some(
|
||||
(event) =>
|
||||
event.kind === "mcp_tool_completed" &&
|
||||
(event.tool === "list_indexed_repos" ||
|
||||
event.tool === "search_sources" ||
|
||||
event.tool === "get_source_context"),
|
||||
);
|
||||
}
|
||||
|
||||
function renderToolTranscript(toolCalls: ToolCallRecord[], turnResults: CodexRunResult[]): string {
|
||||
const legacyTranscript =
|
||||
toolCalls.length > 0
|
||||
|
|
|
|||
|
|
@ -166,6 +166,12 @@ export interface InteractionMemoryProfile {
|
|||
recentEvents: InteractionMemoryEvent[];
|
||||
}
|
||||
|
||||
export interface SourceGroundingHint {
|
||||
required: boolean;
|
||||
reasons: string[];
|
||||
matchedRepoNames: string[];
|
||||
}
|
||||
|
||||
export interface ContextBundle {
|
||||
prompt: string;
|
||||
actor: Actor;
|
||||
|
|
@ -173,6 +179,7 @@ export interface ContextBundle {
|
|||
recentMessages: SourceMessage[];
|
||||
retrieval: RetrievalResult[];
|
||||
interactionMemory?: InteractionMemoryProfile;
|
||||
sourceGrounding?: SourceGroundingHint;
|
||||
stylePack?: StylePack;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue