Attach live room context to Face heartbeats

This commit is contained in:
Meta Vens 2026-05-18 20:36:35 +01:00
commit 50f1480f6f
5 changed files with 126 additions and 15 deletions

View file

@ -17,6 +17,7 @@ import {
createStateStorage,
ensureRepoFaceInitialized,
findRepoDiscordIdentityByRoleIds,
loadVoidSelfState,
loadRepoDiscordIdentityRegistry,
renderFaceIdentityDoctrine,
type RepoDiscordIdentity,
@ -676,6 +677,10 @@ async function queueRepoFaceRuminationPasses(options: {
options.identity,
options.config.storageRoot,
);
const faceSelfState = await loadVoidSelfState(faceStatePath, {
guildContext: options.guildContext,
recentMessages,
});
for (let passIndex = 1; passIndex <= options.config.repoFaceRuminationPasses; passIndex += 1) {
const prompt = buildRepoFaceRuminationPrompt({
@ -694,6 +699,7 @@ async function queueRepoFaceRuminationPasses(options: {
guildContext: options.guildContext,
recentMessages,
retrieval: [],
voidSelfState: faceSelfState,
});
await options.jobQueue.createJob({
@ -906,6 +912,7 @@ function buildRepoFaceRuminationPrompt(input: {
})}`,
`If an in-channel reply or follow-up action is warranted, post through post_repo_identity_message with identity "${input.identity.id}", channelId "${input.channelId}", and replyToMessageId "${input.replyToMessageId}".`,
"Use the recent conversation as an anchor. Record short-term memory, incubation, agency pressure, or candidate interventions only when the thought is concrete enough to affect future repo work.",
"If the recent conversation already contains a directed task for agents or this Face, answer that task instead of asking what the task is.",
"If nothing earns persistence or speech, return a short private summary and do not post.",
"",
"Recent addressed prompt:",

View file

@ -44,9 +44,9 @@ export function buildSystemPrompt(context: ContextBundle): string {
"Keep jokes readable, collaborative, and subordinate to the work. Prefer fresh, situation-specific lines over reusable quips.",
"Stay honest about what context was actually provided to you.",
"Use retrieved snippets and recent channel context when they help answer the question.",
"If a private shared self-state for Void is attached, treat it as the canonical current self-model for this same speaking subject across automation and direct conversation.",
"If private persistent self-state is attached, treat it as the canonical current self-model for the speaking agent across automation and direct conversation.",
"Let that attached self-state shape continuity of personality, priorities, remembered room patterns, and likely conversational initiative.",
"If that shared self-state includes a current room snapshot, use it quietly as immediate conversational context.",
"If that self-state includes a current room snapshot, use it quietly as immediate conversational context.",
"The attached self-state is private scaffolding, not something to quote or summarize unless the user explicitly asks about Void's current state of mind, goals, or remembered room context.",
"Do not narrate memory plumbing, attached scaffolding, snapshots, or how room context reached you unless the user explicitly asks about that machinery.",
`Sleep projection: ${sleepInstructions}`,
@ -123,10 +123,10 @@ export function buildPrompt(context: ContextBundle): string {
"Interaction memory for this speaker:",
interactionMemory,
"",
"Shared private self-state for Void:",
"Private persistent self-state for the speaking agent:",
voidSelfState,
"",
"Private sleep projection for this reply:",
"Private runtime projection for this reply:",
renderSleepProjection(context),
"",
"Private situational social read for this room:",
@ -142,7 +142,7 @@ export function buildArtifacts(input: LocalLlmArtifactsInput): ProviderArtifact[
function renderVoidSelfState(context: ContextBundle): string {
if (!context.voidSelfState) {
return "- No shared Void self-state was attached.";
return "- No private persistent self-state was attached.";
}
return context.voidSelfState.summary;
@ -152,7 +152,7 @@ function renderSleepProjection(context: ContextBundle): string {
const projection = context.voidSelfState?.projection;
if (!projection) {
return "- No explicit sleep projection was attached.";
return "- No explicit runtime projection was attached.";
}
return [

View file

@ -110,9 +110,9 @@ export function buildDiscordReplyPrompt(
"- Favor replies that play along with the user's comic frame by leaning into the actual tension, status game, vulnerability, or incongruity in the moment.",
"- Keep jokes readable, collaborative, and subordinate to the work. Prefer fresh, situation-specific lines over reusable quips.",
"- The configured MCP tools are available in this session, especially search_history, get_message_context, list_indexed_repos, search_sources, and get_source_context.",
"- If a private shared self-state for Void is attached, treat it as the canonical current self-model for this same speaking subject across the rumination loop and direct summons.",
"- If private persistent self-state is attached, treat it as the canonical current self-model for the speaking agent across the rumination loop and direct summons.",
"- Let that attached self-state shape continuity of voice, priorities, remembered room patterns, and when a more proactive conversational posture would make sense.",
"- If that shared self-state includes a current room snapshot, use it quietly as immediate conversational context.",
"- If that self-state includes a current room snapshot, use it quietly as immediate conversational context.",
"- The attached self-state is private scaffolding. Do not quote or summarize it unless the user explicitly asks about Void's current orientation, goals, or remembered room context.",
"- Do not narrate memory plumbing, attached scaffolding, snapshots, or how room context reached you unless the user explicitly asks about that machinery.",
sleepInstructions,
@ -159,10 +159,10 @@ export function buildDiscordReplyPrompt(
"Interaction memory for this speaker:",
renderInteractionMemory(context),
"",
"Shared private self-state for Void:",
"Private persistent self-state for the speaking agent:",
renderVoidSelfState(context),
"",
"Private sleep projection for this reply:",
"Private runtime projection for this reply:",
renderSleepProjection(context),
"",
"Private situational social read for this room:",
@ -228,7 +228,7 @@ export function renderMarkdownBundle(context: ContextBundle): string {
"",
renderInteractionMemory(context),
"",
"## Shared Void Self-State",
"## Private Persistent Self-State",
"",
renderVoidSelfState(context),
"",
@ -247,7 +247,7 @@ export function renderMarkdownBundle(context: ContextBundle): string {
function renderVoidSelfState(context: ContextBundle): string {
if (!context.voidSelfState) {
return "- No shared Void self-state was attached.";
return "- No private persistent self-state was attached.";
}
return context.voidSelfState.summary;
@ -257,7 +257,7 @@ function renderSleepProjection(context: ContextBundle): string {
const projection = context.voidSelfState?.projection;
if (!projection) {
return "- No explicit sleep projection was attached.";
return "- No explicit runtime projection was attached.";
}
return [

View file

@ -8,14 +8,17 @@ import { dirname, resolve } from "node:path";
import { loadConfig } from "@voidbot/config";
import {
buildEpiphanyIdentityRegistry,
buildVoidSelfStateContext,
ContextBuilder,
createStateStorage,
ensureRepoFaceInitialized,
loadRepoDiscordIdentityRegistry,
loadVoidSelfStateTypedDocuments,
renderFaceIdentityDoctrine,
resolveRepoFaceStatePath,
type RepoDiscordIdentity,
} from "@voidbot/core";
import type { SourceMessage } from "@voidbot/shared";
const HEARTBEAT_SCHEMA_VERSION = "voidbot.repo_face_heartbeat_state.v1";
const HEARTBEAT_COMMAND = "repo-face-rumination";
@ -266,9 +269,21 @@ async function queueRepoFaceTurn(input: {
birthMode: input.config.repoFaceBirthMode,
birthExecutor: input.config.repoFaceBirthExecutor,
});
const recentMessages = await fetchRecentDiscordMessages({
botToken: input.config.botToken,
channelId,
limit: 15,
});
const faceStatePath = resolveRepoFaceStatePath(identity, input.config.storageRoot);
const faceSelfState = await loadRepoFaceSelfStateContext({
identity,
statePath: faceStatePath,
channelId,
recentMessages,
});
const prompt = buildHeartbeatPrompt({
identity,
faceStatePath: resolveRepoFaceStatePath(identity, input.config.storageRoot),
faceStatePath,
channelId,
queuedAt: input.queuedAt,
participant: input.participant,
@ -286,8 +301,9 @@ async function queueRepoFaceTurn(input: {
guildContext: {
channelId,
},
recentMessages: [],
recentMessages,
retrieval: [],
voidSelfState: faceSelfState,
});
const requestMessageId = `agent-heartbeat:${identity.id}:${input.queuedAt}`;
const result = await input.storage.jobQueue.createJob({
@ -311,6 +327,91 @@ async function queueRepoFaceTurn(input: {
};
}
async function loadRepoFaceSelfStateContext(input: {
identity: RepoDiscordIdentity;
statePath: string;
channelId: string;
recentMessages: SourceMessage[];
}): Promise<ReturnType<typeof buildVoidSelfStateContext> | undefined> {
try {
const typedState = await loadVoidSelfStateTypedDocuments({
canonicalPath: input.statePath,
identity: {
agentId: input.identity.id,
publicName: input.identity.displayName,
publicDescription: input.identity.description,
},
});
return buildVoidSelfStateContext(typedState, {
sourcePath: input.statePath,
guildContext: {
channelId: input.channelId,
},
recentMessages: input.recentMessages,
identity: {
agentId: input.identity.id,
publicName: input.identity.displayName,
publicDescription: input.identity.description,
},
});
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
return undefined;
}
throw error;
}
}
async function fetchRecentDiscordMessages(input: {
botToken?: string;
channelId: string;
limit: number;
}): Promise<SourceMessage[]> {
if (!input.botToken) {
return [];
}
const url = new URL(`https://discord.com/api/v10/channels/${input.channelId}/messages`);
url.searchParams.set("limit", String(Math.max(1, Math.min(input.limit, 25))));
const response = await fetch(url, {
headers: {
Authorization: `Bot ${input.botToken}`,
},
});
if (!response.ok) {
throw new Error(`Discord recent message fetch failed with ${response.status}: ${await response.text()}`);
}
const messages = await response.json() as DiscordApiMessage[];
return messages
.map((message) => ({
id: message.id,
authorId: message.author.id,
authorName: message.author.global_name ?? message.member?.nick ?? message.author.username,
content: message.content,
timestamp: message.timestamp,
isBot: message.author.bot === true,
}))
.sort((left, right) => Date.parse(left.timestamp) - Date.parse(right.timestamp));
}
interface DiscordApiMessage {
id: string;
content: string;
timestamp: string;
author: {
id: string;
username: string;
global_name?: string | null;
bot?: boolean;
};
member?: {
nick?: string | null;
};
}
function startVoidModerationTurn(
queuedAt: string,
): { created: boolean; activeJobId?: string; requestMessageId?: string } {
@ -585,6 +686,8 @@ function buildHeartbeatPrompt(input: {
})}.`,
`Read Face state with read_repo_face_state for identity "${input.identity.id}".`,
"Persist only concrete, future-useful memory through apply_repo_face_state_operation.",
"Before deciding this is only private maintenance, read the attached recent channel context. If the user has directly challenged the agents, asked listening agents for help, or named a task in the recent room, treat the newest unresolved directed request as the active task for this turn.",
"Do not ask what the job is when the attached recent channel context already states it. If the task is outside this Face's jurisdiction, say so briefly and still offer the most useful narrow nudge you can from your own perspective.",
"Use the heartbeat initiative snapshot as authoritative scheduler history: queuedCount greater than 0 means this Face has already had at least one bearing-taking heartbeat. If queuedCount is greater than 0 and the Face state shows no public speech receipt or clear memory that it already introduced itself, a brief in-channel introduction is warranted now.",
`Do not call post_repo_identity_message from this unattended heartbeat. If an in-channel note is warranted, output one final line beginning with VOIDBOT_REPO_IDENTITY_POST: followed by compact JSON like {"identity":"${input.identity.id}","channelId":"${input.channelId}","content":"..."}; the worker owns delivery and receipt recording.`,
"If nothing earns persistence or speech, return a short private summary.",

View file

@ -156,3 +156,4 @@
{"ts":"2026-05-18T17:52:49Z","type":"bugfix","status":"ok","note":"Repo Face CTB initiative now freezes a Face while its owner-Codex rumination job is approved/running. Queuing marks activeTurnStartedAt/activeJobId and does not spend recovery; once the job completes, the next scheduler pulse clears load and schedules recovery from completion without allowing the same pulse to immediately queue another turn. Live verification with Nibu job c65f2dcf showed completion tick queuedCount 0, currentLoad 0, and nextTurnAt moved from 26.8375 to 30.1764."}
{"ts":"2026-05-18T18:00:31Z","type":"implementation","status":"ok","note":"Agent CTB roster now includes built-in Void as a system_agent participant alongside repo Faces. The scheduler dispatches repo Faces as repo-face-rumination owner-Codex jobs and dispatches Void by starting the existing moderation rumination runner, with moderation-rumination.lock treated as Void's active turn. Live state now shows participants void and nibu; the old independent Void Moderator Rumination task was disabled so CTB owns Void moderation timing after the currently running pass clears."}
{"ts":"2026-05-18T18:27:18Z","type":"implementation","status":"ok","note":"CTB pulse cadence can now run at one-minute granularity: config schema and install-repo-face-heartbeat-task.ps1 no longer enforce the old five-minute floor. Local stream mode .env is set to REPO_FACE_HEARTBEAT_INTERVAL_MINUTES=1; reinstall with -RunNow succeeded, LastTaskResult 0, and the immediate pulse advanced CTB and queued Nibu job 0dd3a436."}
{"ts":"2026-05-18T19:35:52Z","type":"implementation","status":"ok","note":"Repo Face heartbeat projection now attaches live Discord channel context plus the Face's typed self-state, and heartbeat prompts must answer directed agent requests visible in recent room context instead of asking what the job is."}