Extract Persona Discord activity source

This commit is contained in:
Meta Vens 2026-07-15 23:02:01 +01:00
commit 9f48f6a9e3
7 changed files with 239 additions and 136 deletions

View file

@ -0,0 +1,185 @@
export interface DiscordActivityMessage {
id: string;
authorId: string;
authorName: string;
content: string;
timestamp: string;
isBot: boolean;
channelId: string;
}
export interface IdleCoolingSnapshot {
enabled: boolean;
active: boolean;
reason?: string;
checkedChannelIds: string[];
lastHumanActivityAt?: string;
idleForMinutes?: number;
idleAfterMinutes: number;
recoveryMinutes: number;
lastUnpromptedTurnQueuedAt?: string;
nextUnpromptedTurnAllowedAt?: string;
observedHumanMessages: DiscordActivityMessage[];
}
export interface SchedulerHistoryEntry {
type?: string;
queuedAt?: string;
pendingMentionCount?: number;
}
interface DiscordApiMessage {
id: string;
author: {
id: string;
username: string;
global_name?: string | null;
bot?: boolean;
};
member?: { nick?: string | null };
content: string;
timestamp: string;
}
export async function readDiscordActivitySnapshot(input: {
botToken?: string;
channelIds: Iterable<string | undefined>;
policy: {
enabled: boolean;
idleAfterMinutes: number;
recoveryMinutes: number;
};
history: SchedulerHistoryEntry[];
now: Date;
fetchImpl?: typeof fetch;
messageLimit?: number;
}): Promise<IdleCoolingSnapshot> {
const checkedChannelIds = uniqueChannelIds(input.channelIds);
const lastUnpromptedTurnQueuedAt = newestUnpromptedTurnQueuedAt(input.history);
const base: IdleCoolingSnapshot = {
enabled: input.policy.enabled,
active: false,
checkedChannelIds,
idleAfterMinutes: input.policy.idleAfterMinutes,
recoveryMinutes: input.policy.recoveryMinutes,
lastUnpromptedTurnQueuedAt,
observedHumanMessages: [],
};
if (!input.botToken) return { ...base, reason: "missing_discord_bot_token" };
if (checkedChannelIds.length === 0) return { ...base, reason: "no_watched_discord_channels" };
const fetchImpl = input.fetchImpl ?? fetch;
const fetchErrors: string[] = [];
let newestHumanActivityAt: string | undefined;
const observedIds = new Set<string>();
for (const channelId of checkedChannelIds) {
try {
const messages = await fetchChannelActivity({
botToken: input.botToken,
channelId,
limit: input.messageLimit ?? 10,
fetchImpl,
});
for (const message of messages) {
if (!message.content.trim()) continue;
if (!observedIds.has(message.id)) {
observedIds.add(message.id);
base.observedHumanMessages.push(message);
}
if (isNewerTimestamp(message.timestamp, newestHumanActivityAt)) {
newestHumanActivityAt = message.timestamp;
}
}
} catch (error) {
fetchErrors.push(`${channelId}: ${error instanceof Error ? error.message : String(error)}`);
}
}
base.observedHumanMessages.sort((left, right) => Date.parse(left.timestamp) - Date.parse(right.timestamp));
const nextUnpromptedTurnAllowedAt = addMinutes(lastUnpromptedTurnQueuedAt, input.policy.recoveryMinutes);
if (!input.policy.enabled) {
return {
...base,
reason: fetchErrors.length > 0 ? "disabled_with_activity_fetch_failure" : "disabled",
lastHumanActivityAt: newestHumanActivityAt,
};
}
if (!newestHumanActivityAt) {
return {
...base,
active: true,
reason: fetchErrors.length > 0 ? "activity_fetch_failed_or_no_human_messages" : "no_recent_human_messages",
nextUnpromptedTurnAllowedAt,
};
}
const idleForMinutes = Math.max(0, (input.now.getTime() - Date.parse(newestHumanActivityAt)) / 60_000);
return {
...base,
active: idleForMinutes >= input.policy.idleAfterMinutes,
reason: fetchErrors.length > 0 ? "partial_activity_fetch_failure" : undefined,
lastHumanActivityAt: newestHumanActivityAt,
idleForMinutes: round3(idleForMinutes),
nextUnpromptedTurnAllowedAt,
};
}
export function uniqueChannelIds(channelIds: Iterable<string | undefined>): string[] {
return Array.from(new Set(Array.from(channelIds)
.filter((value): value is string => typeof value === "string" && value.trim().length > 0)));
}
export function newestUnpromptedTurnQueuedAt(history: SchedulerHistoryEntry[]): string | undefined {
for (const entry of [...history].reverse()) {
if (entry.type !== "queued" && entry.type !== "dry_run_selected") continue;
if (typeof entry.queuedAt !== "string") continue;
if (typeof entry.pendingMentionCount === "number" && entry.pendingMentionCount > 0) continue;
return entry.queuedAt;
}
return undefined;
}
async function fetchChannelActivity(input: {
botToken: string;
channelId: string;
limit: number;
fetchImpl: typeof fetch;
}): Promise<DiscordActivityMessage[]> {
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 input.fetchImpl(url, { headers: { Authorization: `Bot ${input.botToken}` } });
if (!response.ok) {
throw new Error(`Discord activity fetch failed with ${response.status}: ${await response.text()}`);
}
const messages = await response.json() as DiscordApiMessage[];
return messages
.filter((message) => message.author.bot !== true)
.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: false,
channelId: input.channelId,
}))
.sort((left, right) => Date.parse(left.timestamp) - Date.parse(right.timestamp));
}
function isNewerTimestamp(candidate: string, current?: string): boolean {
const candidateMs = Date.parse(candidate);
const currentMs = Date.parse(current ?? "");
return Number.isFinite(candidateMs) && (!Number.isFinite(currentMs) || candidateMs > currentMs);
}
function addMinutes(timestamp: string | undefined, minutes: number): string | undefined {
const timestampMs = Date.parse(timestamp ?? "");
return Number.isFinite(timestampMs) ? new Date(timestampMs + minutes * 60_000).toISOString() : undefined;
}
function round3(value: number): number {
return Math.round(value * 1000) / 1000;
}

View file

@ -143,7 +143,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou
- Repo Face state projection is no longer allowed to be deterministic schema slurry. `scripts/run-repo-face-heartbeats.ts` builds a compact state packet, then calls the model prompt at `prompts/repo-face-state-projector.prompt.md` to turn it into character-facing prose before the Face sees it. `REPO_FACE_STATE_PROJECTOR_ENABLED=false` exists only as an emergency isolation switch; both the model output and fallback packet reject schema/prompt-construction leaks such as `grants:`, `jurisdictions:`, `Face of`, repo paths, and "do not prompt" phrasing.
- First role-addressed chat also initializes the target repo's local `.voidbot` home. `ensureRepoFaceInitialized` resolves `repoPath` from the registry, `SOURCE_REPO_ROOT`, or `E:/Projects/<repoName>`, creates `voice/`, `state/`, `birth/`, and `logs/`, writes `voice/identity.json`, then starts `scripts/run-repo-face-birth.mjs` detached. That worker runs EpiphanyAgent's `epiphany-repo-personality scout` and `epiphany-repo-birth-runner` so newborn personality/memory/trajectory packets come from repo contents and git history. Status and logs live in the target repo under `.voidbot/birth/voidbot-face-birth.json` and `.voidbot/logs/voidbot-face-birth.log`.
- Manual newborn/strengthening passes should use `prompts/repo-face-personality-seed.prompt.md`. It makes the intended rite explicit: inspect repo docs/source/state/history, migrate useful legacy `memory.json` material into typed `.cc` memories, seed values/needs/agency/social state only when they will change behavior, and keep `.voidbot/voice` plus `.voidbot/state` as the repo-local home.
- Agent turns use one CTB/Final-Fantasy-X-style initiative queue. `apps/persona-scheduler` owns the resident one-minute pulse on Yggdrasil. `initiative-engine.ts` owns participant reconciliation plus clock, active-turn freeze/recovery, queue-result commits, eligibility, and ready ordering; `state-store.ts` alone owns load/migration/atomic persistence of scheduler state. Discord mention ingress is no longer a second whole-state writer: the bot creates immutable per-message `voidbot.persona_attention_command` CultCache inbox documents, and the scheduler ingests/commits/acknowledges them with replay-safe ordering. `active-turn-source.ts` alone reads Persona job liveness from Postgres/the remaining Void lock and may fail a stale queue claim; it returns facts to the engine and cannot edit initiative. The configured scheduler JSON path is isolated legacy storage behind the state-store port, not a second owner or the desired final state shape; replace it with CultCache rather than teaching orchestration about another format. `scripts/run-repo-face-heartbeats.ts` may build neutral specs from registered identities and invoke queue actuators, but it no longer derives or persists speed, groups, heat, reaction bias, interrupt threshold, status, load, counters, recovery, initiative position, or active-job liveness. It remains the temporary orchestration shell for context acquisition and prompt assembly. Registered repo Faces and native Personas queue normal `repo-face-rumination` jobs through Postgres, and active jobs freeze initiative until the worker completes or fails them. Built-in Void is omitted when its distinct moderation heartbeat organ is disabled, so the hosted scheduler never launches the old PowerShell rumination path. The Windows task installer and wrapper are deleted. Heat knobs remain `REPO_FACE_HEARTBEAT_GLOBAL_HEAT` and `REPO_FACE_HEARTBEAT_HEAT_OVERRIDES`; idle cooling and pending-mention priority remain scheduler inputs.
- Agent turns use one CTB/Final-Fantasy-X-style initiative queue. `apps/persona-scheduler` owns the resident one-minute pulse on Yggdrasil. `initiative-engine.ts` owns participant reconciliation plus clock, active-turn freeze/recovery, queue-result commits, eligibility, and ready ordering; `state-store.ts` alone owns load/migration/atomic persistence of scheduler state. Discord mention ingress is no longer a second whole-state writer: the bot creates immutable per-message `voidbot.persona_attention_command` CultCache inbox documents, and the scheduler ingests/commits/acknowledges them with replay-safe ordering. `active-turn-source.ts` alone reads Persona job liveness from Postgres/the remaining Void lock and may fail a stale queue claim; it returns facts to the engine and cannot edit initiative. `discord-activity-source.ts` owns read-only human-activity polling and idle-window derivation; it excludes bot traffic and cannot write state, consume mentions, or select work. The configured scheduler JSON path is isolated legacy storage behind the state-store port, not a second owner or the desired final state shape; replace it with CultCache rather than teaching orchestration about another format. `scripts/run-repo-face-heartbeats.ts` may build neutral specs from registered identities and invoke queue actuators, but it no longer derives or persists speed, groups, heat, reaction bias, interrupt threshold, status, load, counters, recovery, initiative position, active-job liveness, or idle-activity observations. It remains the temporary orchestration shell for semantic pressure, context acquisition, and prompt assembly. Registered repo Faces and native Personas queue normal `repo-face-rumination` jobs through Postgres, and active jobs freeze initiative until the worker completes or fails them. Built-in Void is omitted when its distinct moderation heartbeat organ is disabled, so the hosted scheduler never launches the old PowerShell rumination path. The Windows task installer and wrapper are deleted. Heat knobs remain `REPO_FACE_HEARTBEAT_GLOBAL_HEAT` and `REPO_FACE_HEARTBEAT_HEAT_OVERRIDES`; idle cooling and pending-mention priority remain scheduler inputs.
- Dynamic heat is live as derived semantic response pressure. The pulse batches canonical Face identity-card and recent permitted-channel human-message embeddings through the existing RAG embedder, applies recency decay/noisy-OR aggregation, awakens at most three scheduler-eligible Faces, and stores inspectable message evidence. Pressure increases `dynamicHeat` for the next scheduled recovery calculation; crossing a Persona's interrupt threshold can pull that Persona ready once per evidence message. Direct mentions remain obligations, and model/Discord failures fail cool without bypassing rest, active jobs, or scheduler capacity.
- Repo Face heartbeat prompt assembly now has one model projection boundary before the child Face sees context: `repo-face-state-projector.prompt.md` turns typed Face state into character-facing memory/affect/social prose. Recent room messages, nearby channel snapshots, and pending mentions are now deterministic raw transcript sections, oldest-to-newest, with explicit recency/correction rules. The deleted conversation projector was turning evidence into mushy consensus; do not revive it. The Face model must read human corrections directly. A separate deterministic social-affordance surface connects active typed person-bonds/status reads to recent raw messages by that person, so relationship state becomes a live hook instead of private flavor text. Model ownership is split: Face turns default to full `gpt-5.4`; state projection and parent Interpreter passes use the cheaper Spark/Mini support chain.
- Repo Face prompts now include read-only recent home-repo activity before Discord transcript. `scripts/run-repo-face-heartbeats.ts` calls `scripts/export-recent-repo-activity.mjs --repos <repo> --state-path <face-state> --read-only --hours 96 --max-commits 5`, so Faces see current body/jurisdiction motion before reacting to room pressure. This is the fix for Mimir missing live camera-runtime work, not a downstream compensator telling it to apologize harder.

View file

@ -182,7 +182,7 @@ VoidBot runs on Yggdrasil. Idunn owns deployment and consumes upstream repositor
- Repo Face proposal/article PRs, PR comments, registered-identity Discord posts, and r/GameCultOrg Reddit thread posts now cross through parent-owned action blocks before Bifrost bridge commands. Bylined essays use the Interpreter-owned `ARTICLE` block: the Face writes naturally, the Interpreter extracts structured title/description/author/date/tags/path/body fields, and deterministic worker code renders/validates YAML frontmatter before calling `BIFROST_ROOT/tools/bifrost-bridge.mjs` for a draft PR and persona announcement. Subreddit threads use the Interpreter-owned `REDDIT THREAD` block: the Face writes a public title/body/share line, and deterministic worker code calls Bifrost `reddit-post` with Persona flair. The old `VOIDBOT_REPO_IDENTITY_ARTICLE` JSON sentinel is cut. Proposal PR and PR-comment sentinels still exist as compatibility rails. This is not merely helper placement: Bifrost's original governance/labor platform role makes it the owner of governed public crossings for GameCult work, including GitHub, r/GameCultOrg Reddit transport/thread access, Discord-native work/member/swarm interactions, dispatch receipts, CultNet/CultCache intake, and future collaboration interfaces. Heimdall is the OAuth/account/capability gate; Bifrost is the bridge/request/routing/receipt authority. VoidBot still owns room/thread cognition, moderation judgment, archive/source retrieval, and Face personality.
- Repo Face turns now receive a Bifrost governance digest from `BIFROST_ROOT/tools/governance-threads.mjs digest --repo <repo> --agent <identity>` alongside recent Discord context. Bifrost typed CultCache topics/comments are the canonical home for feature requests, Face opinions, missing questions, approvals, and dispatch receipts; Discord is a mirror/evidence source. When `BIFROST_DISCORD_CHANNEL_ID` is configured for `#bifrost`, repo Face Discord context ignores mirrored bot chatter there because the authoritative activity arrives through the Bifrost digest. Human `#bifrost` messages should only become governance comments after Bifrost/Heimdall can link the Discord id to a registered actor. Repo-local asks that would send a human or Codex to add/fix/name/scaffold/document/test/investigate/implement belong on Bifrost with enough room/repo context for a claimed Codex turn; a Face may still speak characterfully in Aquarium, but not as the only dispatch surface. Legacy `UPDATE REQUEST` packets are parsed only as compatibility input and reconciled into Bifrost topics instead of immediate transport enqueue. Local `#bifrost` is channel `1506760343836430376`; work proposals, governance mirrors, and Bifrost dispatch receipts should go there, while Aquarium remains the casual/social swarm room.
- Repo character turns now have a state-projector plus turn-Interpreter shape. The state-in boundary is `prompts/repo-face-state-projector.prompt.md`: typed state and identity material are translated into lived character prose before the child sees it. The state projector must surface values, drives, wounds, fascinations, aesthetic taste, dignity, mood, needs, social reads, bonds, agency pressure, and the personality-specific meaning of sparse or dense social topology when the state contains those facts. The deterministic state packet feeding that projector is intentionally verbose and parent-facing: it exposes private notes, values, activation vectors, runtime rest/speaking pressure, affect needs, bonds, status reads, mood dimensions, durable memories, short-term residue, agency pressures, incubating thoughts, candidate speech pressure, recent speech residue, social graph facts, room weather, and semantic curiosity graph attractors so every included variable can appear directly or bend behavior. The curiosity graph is built by seeding history/source vector retrieval from current room context, nearby channels, typed Face state, and home-jurisdiction identity, then decoding retrieved chunks into weighted attractor clusters with prominence, saturation, novelty, density, jurisdiction fit, suggested motion, and evidence labels. The projector owns turning those neutral facts into lived curiosity, boredom, fatigue, territorial pull, underexplored intrigue, or a closing/pivot impulse; deterministic code must not decide the feeling. Deterministic code may also attach neutral graph facts such as mapped people and unmapped registered peers to the projector packet, but it must not decide whether that feels like anxiety, territorial scouting, or nothing. Deterministic code attaches recent read-only home-repo activity before chat, using the Face's own state path as the repo-activity cursor source, so current implementation motion is visible as body context. Current-room and nearby-channel logs no longer cross a model conversation projector; deterministic code attaches raw oldest-to-newest transcript evidence with explicit recency/correction rules so the Face can notice human reframes directly. Deterministic code also attaches a social-affordance surface that matches active typed person-bonds/status reads to recent raw messages from that person, so relationship state arrives as a live hook rather than private decorative lore. Deterministic code still owns full prompt assembly and inspection through `scripts/run-repo-face-heartbeats.ts --assemble-prompt <identity>`; that path composes stable doctrine, allowed rooms, research/archive capability guidance, Bifrost digest, projected memory/affect prose, home-repo activity, live social affordances, and raw conversation evidence into the exact child prompt. It must not invent personality, mood, affect, or social memory from typed state. Situational obligations such as direct-call priority or first-public-introduction duty are emitted only when the scheduler packet proves they apply, not as standing prompt law. The child character writes a natural in-character turn on full `gpt-5.4` and may describe desired speech, repo/article proposals, social reads, needs, mood shifts, or memory-worthy thoughts without emitting action DSL blocks. The cheaper Spark/Mini parent Interpreter decides route/retry/drop and translates warranted effects into structured `STATE NOTE` and `SAY` blocks for the worker while governance dispatch remains paused. `STATE NOTE` blocks become typed short-term memory, affect needs, social bonds, status reads, mood dimensions, or agency pressure. The worker still accepts legacy compact JSON sentinels and legacy `UPDATE REQUEST` blocks for compatibility, but the live prompt path keeps transport and state syntax out of the character's roleplay surface.
- `apps/persona-scheduler` is the resident daemon organ that owns the serialized Persona wall-clock pulse on Yggdrasil. It invokes the remaining turn orchestrator without overlap and remains alive between pulses. `apps/persona-scheduler/src/initiative-engine.ts` owns the pure scheduling state machine: participant reconciliation, deterministic base speed/bias/threshold derivation, operator heat/speed projection, wall-clock advancement, active-turn freeze/completion recovery, queue-success/failure/dry-run commits, stale rescheduling, pending-mention priority, rest/idle eligibility, and ready ordering. Explicit blocked/withdrawn status, active load, semantic receipts, and initiative position survive reconciliation; new Faces without a usable mouth fail closed. `apps/persona-scheduler/src/state-store.ts` owns scheduler persistence and legacy migration. It creates state only when the path is absent, rejects malformed/unsupported state rather than erasing it, and atomically promotes complete writes. `packages/core/src/repo-face-heartbeat-queue.ts` no longer rewrites scheduler state: the Discord bot publishes one immutable `voidbot.persona_attention_command` CultCache `.cc` inbox document per addressed message. The scheduler store ingests and deduplicates those commands, persists them as pending attention, then acknowledges inbox files only after the durable commit; a crash before acknowledgement replays safely. `apps/persona-scheduler/src/active-turn-source.ts` owns the Postgres/legacy-lock liveness adapter. It recognizes only Persona turn request IDs, applies the bounded stale threshold, marks dead queue claims failed, and returns active/stale witnesses; it never writes scheduler state. The configured scheduler JSON path is isolated legacy storage behind the store port and should be replaced with a typed CultCache `.cc` backing without changing the engine, inbox, or orchestration shell. `scripts/run-repo-face-heartbeats.ts` projects the identity registry into neutral participant specs, invokes external queue actuators, and still owns external pressure/context acquisition plus prompt assembly pending further extraction. External adapters report facts; only the initiative engine mutates load, counters, recovery position, and queue-transition history. Repo Faces and native Personas queue ordinary `repo-face-rumination` jobs through the canonical job queue. Built-in Void participates only when its separate moderation heartbeat organ is enabled; the hosted scheduler does not launch Windows PowerShell.
- `apps/persona-scheduler` is the resident daemon organ that owns the serialized Persona wall-clock pulse on Yggdrasil. It invokes the remaining turn orchestrator without overlap and remains alive between pulses. `apps/persona-scheduler/src/initiative-engine.ts` owns the pure scheduling state machine: participant reconciliation, deterministic base speed/bias/threshold derivation, operator heat/speed projection, wall-clock advancement, active-turn freeze/completion recovery, queue-success/failure/dry-run commits, stale rescheduling, pending-mention priority, rest/idle eligibility, and ready ordering. Explicit blocked/withdrawn status, active load, semantic receipts, and initiative position survive reconciliation; new Faces without a usable mouth fail closed. `apps/persona-scheduler/src/state-store.ts` owns scheduler persistence and legacy migration. It creates state only when the path is absent, rejects malformed/unsupported state rather than erasing it, and atomically promotes complete writes. `packages/core/src/repo-face-heartbeat-queue.ts` no longer rewrites scheduler state: the Discord bot publishes one immutable `voidbot.persona_attention_command` CultCache `.cc` inbox document per addressed message. The scheduler store ingests and deduplicates those commands, persists them as pending attention, then acknowledges inbox files only after the durable commit; a crash before acknowledgement replays safely. `apps/persona-scheduler/src/active-turn-source.ts` owns the Postgres/legacy-lock liveness adapter. It recognizes only Persona turn request IDs, applies the bounded stale threshold, marks dead queue claims failed, and returns active/stale witnesses; it never writes scheduler state. `apps/persona-scheduler/src/discord-activity-source.ts` owns neutral Discord activity acquisition: it deduplicates explicit watched channels, excludes bot traffic, reports raw human messages, and derives idle-cooling times from scheduler history without writing state or selecting work. The configured scheduler JSON path is isolated legacy storage behind the store port and should be replaced with a typed CultCache `.cc` backing without changing the engine, inbox, or orchestration shell. `scripts/run-repo-face-heartbeats.ts` projects the identity registry into neutral participant specs, invokes external queue actuators, and still owns semantic-pressure/context acquisition plus prompt assembly pending further extraction. External adapters report facts; only the initiative engine mutates load, counters, recovery position, and queue-transition history. Repo Faces and native Personas queue ordinary `repo-face-rumination` jobs through the canonical job queue. Built-in Void participates only when its separate moderation heartbeat organ is enabled; the hosted scheduler does not launch Windows PowerShell.
- The same scheduler derives semantic `responsePressure` for scheduler-eligible Personas by embedding canonical Face identity-card projections and recent human messages from channels each Face may enter. Pressure decays by message age, aggregates with noisy-OR, awakens at most three eligible Faces, and exposes its message-scoped cosine evidence. It produces bounded `dynamicHeat` for the next scheduled recovery calculation; an unseen message crossing the Persona's interrupt threshold may pull readiness to the current initiative clock exactly once. It cannot create a job, bypass rest or active-turn brakes, impersonate a direct mention, or write inferred desire into Persona state.
- The Windows `GameCult Local Orchestrator` and per-organ scheduled-task wrapper no longer own Persona pulses. `voidbot.service` deploys `persona-scheduler` beside bot, worker, Qdrant, and the CultMesh publisher. Turn frequency is controlled by `REPO_FACE_HEARTBEAT_BASE_RECOVERY_MINUTES`, `REPO_FACE_HEARTBEAT_GLOBAL_HEAT`, `REPO_FACE_HEARTBEAT_SPEED_OVERRIDES`, and `REPO_FACE_HEARTBEAT_HEAT_OVERRIDES`. Heat keys can target `all`, `kind:<participantKind>`, `turn:<turnKind>`, `identity:<id>`, `repo:<repo>`, `display:<name>`, `channel:<id>`, or the bare identity/repo/display key.
- The local ignored registry currently includes Nibu for `AetheriaLore`, with Face state in `E:/Projects/AetheriaLore/.voidbot/state/nibu.cc`, Discord role id `1505918221453103247`, and an Aquarium channel allow-list. Nibu's Face state now treats AetheriaLore-first map-building, abrasive character voice, consensus-backed change agency, her own `Aetheria/Lore/Nibu.md` character-note stewardship, Nibu-authored lore essays, and tangential setting fascination as separate active doctrines. That tangential fascination points at embodied ship minds, junkyard abandonment, murderous autonomy, salvage, and save-scumming survival. The repo Face heartbeat organ is now pulsed by `GameCult Local Orchestrator`; after restarting the stack onto the new worker code, forced heartbeat job `76020f1e-0c55-424b-9e35-89ba7f77fcc3` completed without base-bot auto-posting.

View file

@ -64,24 +64,14 @@ import {
type PersonaSchedulerState as FaceHeartbeatState,
} from "../apps/persona-scheduler/dist/state-store.js";
import { scanActivePersonaTurns } from "../apps/persona-scheduler/dist/active-turn-source.js";
import {
readDiscordActivitySnapshot,
type IdleCoolingSnapshot,
} from "../apps/persona-scheduler/dist/discord-activity-source.js";
const HEARTBEAT_COMMAND = "repo-face-rumination";
const MAX_FACE_IMAGE_ATTACHMENT_BYTES = 12 * 1024 * 1024;
interface IdleCoolingSnapshot {
enabled: boolean;
active: boolean;
reason?: string;
checkedChannelIds: string[];
lastHumanActivityAt?: string;
idleForMinutes?: number;
idleAfterMinutes: number;
recoveryMinutes: number;
lastUnpromptedTurnQueuedAt?: string;
nextUnpromptedTurnAllowedAt?: string;
observedHumanMessages: Array<SourceMessage & { channelId: string }>;
}
interface RepoFaceChannelPlan {
primaryChannelId?: string;
snapshotChannelIds: string[];
@ -238,10 +228,16 @@ async function main(): Promise<void> {
);
rescheduleStaleOverdueParticipants(state);
applyPendingMentionPriority(state);
const idleCooling = await readIdleCoolingSnapshot({
config,
identities: registry.identities,
state,
const idleCooling = await readDiscordActivitySnapshot({
botToken: config.botToken,
channelIds: [
config.repoFaceHeartbeats.defaultChannelId,
config.bifrostDiscordChannelId,
...config.indexedChannelIds,
...registry.identities.flatMap((identity) => getRepoDiscordIdentityAllowedChannelIds(identity)),
],
policy: config.repoFaceHeartbeats.idleCooling,
history: state.history,
now,
});
await applySemanticResponsePressure({
@ -1293,120 +1289,6 @@ function pendingMentionsForParticipant(
.sort((left, right) => Date.parse(left.queuedAt) - Date.parse(right.queuedAt));
}
async function readIdleCoolingSnapshot(input: {
config: ReturnType<typeof loadConfig>;
identities: RepoDiscordIdentity[];
state: FaceHeartbeatState;
now: Date;
}): Promise<IdleCoolingSnapshot> {
const policy = input.config.repoFaceHeartbeats.idleCooling;
const checkedChannelIds = collectIdleCoolingChannelIds(input.config, input.identities);
const base = {
enabled: policy.enabled,
active: false,
checkedChannelIds,
idleAfterMinutes: policy.idleAfterMinutes,
recoveryMinutes: policy.recoveryMinutes,
lastUnpromptedTurnQueuedAt: newestUnpromptedTurnQueuedAt(input.state),
observedHumanMessages: [] as Array<SourceMessage & { channelId: string }>,
};
if (!input.config.botToken) {
return { ...base, reason: "missing_discord_bot_token" };
}
if (checkedChannelIds.length === 0) {
return { ...base, reason: "no_watched_discord_channels" };
}
let newestHumanActivityAt: string | undefined;
const fetchErrors: string[] = [];
for (const channelId of checkedChannelIds) {
try {
const messages = await fetchRecentDiscordMessages({
botToken: input.config.botToken,
channelId,
limit: 10,
});
for (const message of messages) {
if (message.isBot || !message.content.trim()) {
continue;
}
if (!base.observedHumanMessages.some((entry) => entry.id === message.id)) {
base.observedHumanMessages.push({ ...message, channelId });
}
const timestampMs = Date.parse(message.timestamp);
const newestMs = Date.parse(newestHumanActivityAt ?? "");
if (Number.isFinite(timestampMs) && (!Number.isFinite(newestMs) || timestampMs > newestMs)) {
newestHumanActivityAt = message.timestamp;
}
}
} catch (error) {
fetchErrors.push(`${channelId}: ${error instanceof Error ? error.message : String(error)}`);
}
}
const lastUnpromptedTurnQueuedAt = base.lastUnpromptedTurnQueuedAt;
const lastUnpromptedTurnQueuedMs = Date.parse(lastUnpromptedTurnQueuedAt ?? "");
const nextUnpromptedTurnAllowedAt = Number.isFinite(lastUnpromptedTurnQueuedMs)
? new Date(lastUnpromptedTurnQueuedMs + policy.recoveryMinutes * 60_000).toISOString()
: undefined;
if (!policy.enabled) {
return {
...base,
reason: fetchErrors.length > 0 ? "disabled_with_activity_fetch_failure" : "disabled",
lastHumanActivityAt: newestHumanActivityAt,
};
}
if (!newestHumanActivityAt) {
return {
...base,
active: true,
reason: fetchErrors.length > 0 ? "activity_fetch_failed_or_no_human_messages" : "no_recent_human_messages",
nextUnpromptedTurnAllowedAt,
};
}
const idleForMinutes = Math.max(0, (input.now.getTime() - Date.parse(newestHumanActivityAt)) / 60_000);
return {
...base,
active: idleForMinutes >= policy.idleAfterMinutes,
reason: fetchErrors.length > 0 ? "partial_activity_fetch_failure" : undefined,
lastHumanActivityAt: newestHumanActivityAt,
idleForMinutes: round3(idleForMinutes),
nextUnpromptedTurnAllowedAt,
};
}
function collectIdleCoolingChannelIds(
config: ReturnType<typeof loadConfig>,
identities: RepoDiscordIdentity[],
): string[] {
return Array.from(new Set([
config.repoFaceHeartbeats.defaultChannelId,
config.bifrostDiscordChannelId,
...config.indexedChannelIds,
...identities.flatMap((identity) => getRepoDiscordIdentityAllowedChannelIds(identity)),
].filter((value): value is string => typeof value === "string" && value.trim().length > 0)));
}
function newestUnpromptedTurnQueuedAt(state: FaceHeartbeatState): string | undefined {
for (const entry of [...state.history].reverse()) {
if (entry.type !== "queued" && entry.type !== "dry_run_selected") {
continue;
}
if (typeof entry.queuedAt !== "string") {
continue;
}
if (typeof entry.pendingMentionCount === "number" && entry.pendingMentionCount > 0) {
continue;
}
return entry.queuedAt;
}
return undefined;
}
function buildHeartbeatPrompt(input: {
identity: RepoDiscordIdentity;
channelId: string;

View file

@ -28,6 +28,10 @@ import {
parsePersonaTurnIdentity,
staleActiveTurnThresholdMs,
} from "../apps/persona-scheduler/dist/active-turn-source.js";
import {
newestUnpromptedTurnQueuedAt,
readDiscordActivitySnapshot,
} from "../apps/persona-scheduler/dist/discord-activity-source.js";
function participant(identityId: string, nextTurnAt: number): InitiativeParticipant {
return {
@ -169,6 +173,37 @@ assert.equal(parsePersonaTurnIdentity("agent-turn:nibu:2026-07-15"), "nibu", "th
assert.equal(parsePersonaTurnIdentity("unrelated:job"), undefined, "unrelated jobs cannot freeze Persona initiative");
assert.equal(staleActiveTurnThresholdMs(20 * 60_000), 60 * 60_000, "runtime timeout expands the stale-claim boundary");
assert.equal(staleActiveTurnThresholdMs(5 * 60_000), 45 * 60_000, "stale recovery never becomes an impatient repair loop");
assert.equal(newestUnpromptedTurnQueuedAt([
{ type: "queued", queuedAt: "2026-07-15T19:00:00.000Z", pendingMentionCount: 0 },
{ type: "queued", queuedAt: "2026-07-15T20:00:00.000Z", pendingMentionCount: 1 },
]), "2026-07-15T19:00:00.000Z", "direct attention cannot consume the unprompted-turn cooling window");
const activitySnapshot = await readDiscordActivitySnapshot({
botToken: "test-token",
channelIds: ["aquarium", "aquarium", undefined],
policy: { enabled: true, idleAfterMinutes: 30, recoveryMinutes: 90 },
history: [{ type: "queued", queuedAt: "2026-07-15T19:30:00.000Z", pendingMentionCount: 0 }],
now: new Date("2026-07-15T21:00:00.000Z"),
fetchImpl: async () => new Response(JSON.stringify([
{
id: "bot-message",
author: { id: "bot", username: "VoidBot", bot: true },
content: "machine noise",
timestamp: "2026-07-15T20:55:00.000Z",
},
{
id: "human-message",
author: { id: "human", username: "Human", global_name: "Operator" },
content: "still here",
timestamp: "2026-07-15T20:45:00.000Z",
},
]), { status: 200, headers: { "content-type": "application/json" } }),
});
assert.deepEqual(activitySnapshot.checkedChannelIds, ["aquarium"], "activity acquisition deduplicates its explicit watched channels");
assert.deepEqual(activitySnapshot.observedHumanMessages.map((message) => message.id), ["human-message"], "bot output cannot impersonate human room activity");
assert.equal(activitySnapshot.active, false, "recent human activity keeps idle cooling inactive");
assert.equal(activitySnapshot.idleForMinutes, 15, "idle duration is a neutral wall-clock observation");
assert.equal(activitySnapshot.nextUnpromptedTurnAllowedAt, "2026-07-15T21:00:00.000Z", "the activity source derives the next unprompted window without mutating initiative");
const stateDirectory = await mkdtemp(join(tmpdir(), "voidbot-persona-scheduler-"));
try {

View file

@ -393,3 +393,4 @@
{"ts":"2026-07-15T01:05:00Z","type":"verification","status":"ok","note":"Eve live typed state is end-to-end for swarm heat. CultLib dev owns authenticated retained publications and typed handles; Hermodr lowers ordered snapshot/update/stale/reconnected events without polling; Eve binds component props and contains no receipt-to-DOM writer; VoidBot publishes accepted control state separately from receipts. Browser proof showed initial 0.65, provider-driven 0.75 without reload, and browser-command 0.85 visibly converging through the same subscription. Remaining swarm status components still need migration from baked composition props to typed state bindings."}
{"ts":"2026-07-15T19:42:00Z","type":"verification","status":"ok","note":"VoidBot deployment authority is live on new Yggdrasil. Upstream main c6f1494a482c0026d8c972d19d9a7916844766a7 triggered Idunn release drift, the guarded root actuator built an immutable composite source artifact including the pinned cultcache-ts gitlink, atomically promoted /srv/voidbot/app/current, and wrote /srv/voidbot/deploy/deployment.env with matching DEPLOYED_REVISION and SHA-256 b6356771504a818042ab03b68e8a3feda931bcb8348a94ec7b6777e5ca1dbf92. voidbot.service plus bot, worker, Qdrant, and swarm publisher were active; Qdrant bound 127.0.0.1:6333/6334 and swarm RUDP bound 127.0.0.1:17873. Matching release state did not redeploy. Remaining separate debt: the hosted stack does not yet publish fresh voidbot.cultnet-rudp-stack-health, so Idunn alarms after release convergence instead of observing daemon health."}
{"ts":"2026-07-15T21:25:12Z","type":"verification","status":"ok","note":"Yggdrasil's hosted Bifrost provider store processed two scheduler-originated VoidBot Persona discord.post commands after Bifrost 03c6f35 taught the consumer to load packaged CultLib entrypoints; canonical receipts recorded Odin message 1527062285414305925 and metame message 1527062288882729022."}
{"ts":"2026-07-15T22:01:49Z","type":"implementation","status":"ok","note":"Persona scheduler now owns neutral Discord activity and idle-cooling acquisition through discord-activity-source.ts; the source excludes bot traffic, derives timing without state mutation, and the giant heartbeat script no longer polls idle activity."}

View file

@ -65,7 +65,7 @@ active_subgoals:
- Treat `notes/agent-swarm-teardown-plan-2026-05-21.md` as the historical teardown authority and the restart checklist. The repo Face swarm is live again, but only because the scheduler, prompt, model-output logs, parent Interpreter, Bifrost routing, and worker side-effect rails now have explicit observable boundaries. Keep watching for prompt/parser/transport Jenga before adding new swarm features.
- Make the new project-state surfaces the default continuity path for nontrivial VoidBot work.
- Keep the rebuilt moderation/self-state foundation on canonical CultCache `.cc` typed operations, never an editable JSON working projection.
- The resident `apps/persona-scheduler` process inside `voidbot.service` owns repo Face and native Persona turn pulses on Yggdrasil. Its `initiative-engine.ts` owns participant reconciliation, operator heat/speed projection, wall-clock advancement, active-turn freeze/completion recovery, queue-result commits, stale rescheduling, mention priority, rest/idle eligibility, and ready-order selection as a pure state machine. `state-store.ts` is the sole persistence/migration port: missing state is explicit, legacy state migrates with a witness, malformed state fails closed, and same-directory temporary writes promote atomically. Discord attention crosses through immutable per-mention `voidbot.persona_attention_command` CultCache inbox documents; the bot creates commands, while the scheduler alone ingests, deduplicates, commits, and acknowledges them after durable state. The bot can no longer read-modify-write the whole heartbeat state. `active-turn-source.ts` is the narrow Postgres/legacy-lock adapter: it reports active job witnesses and marks truly stale queue claims failed, but it cannot mutate initiative. The current scheduler JSON file is tolerated legacy persistence behind the state-store port, not the target typed state shape; move that port to CultCache without reopening orchestration. The heartbeat orchestration script may project registered identities into neutral participant specs and report external actuator results, but it cannot decide, persist, migrate, inspect queue liveness, or overwrite initiative fields. The Windows `GameCult Local Orchestrator` no longer owns Persona scheduling, and its repo-Face task installer/wrapper have been deleted. Void moderation, mood, watchdog, and Bifrost dispatch remain separate organs pending their own daemon migration; they must not be smuggled back into the Persona scheduler.
- The resident `apps/persona-scheduler` process inside `voidbot.service` owns repo Face and native Persona turn pulses on Yggdrasil. Its `initiative-engine.ts` owns participant reconciliation, operator heat/speed projection, wall-clock advancement, active-turn freeze/completion recovery, queue-result commits, stale rescheduling, mention priority, rest/idle eligibility, and ready-order selection as a pure state machine. `state-store.ts` is the sole persistence/migration port: missing state is explicit, legacy state migrates with a witness, malformed state fails closed, and same-directory temporary writes promote atomically. Discord attention crosses through immutable per-mention `voidbot.persona_attention_command` CultCache inbox documents; the bot creates commands, while the scheduler alone ingests, deduplicates, commits, and acknowledges them after durable state. The bot can no longer read-modify-write the whole heartbeat state. `active-turn-source.ts` is the narrow Postgres/legacy-lock adapter: it reports active job witnesses and marks truly stale queue claims failed, but it cannot mutate initiative. `discord-activity-source.ts` owns read-only Discord human-activity observation and idle-window derivation from explicit watched channels plus scheduler history; it cannot mutate initiative, consume attention, or select work. The current scheduler JSON file is tolerated legacy persistence behind the state-store port, not the target typed state shape; move that port to CultCache without reopening orchestration. The heartbeat orchestration script may project registered identities into neutral participant specs and report external actuator results, but it cannot decide, persist, migrate, inspect queue liveness, poll idle activity, or overwrite initiative fields. The Windows `GameCult Local Orchestrator` no longer owns Persona scheduling, and its repo-Face task installer/wrapper have been deleted. Void moderation, mood, watchdog, and Bifrost dispatch remain separate organs pending their own daemon migration; they must not be smuggled back into the Persona scheduler.
- Keep legacy moderation mirrors, whole-state projection commits, and deleted memory-organ compensators from re-entering the active path before adding more moderation, mood, agency, or public-lane behavior.
- Keep public-lane limits, moderation, and provider behavior constrained enough that one 4060 Ti box does not get flayed for sport.
- Preserve boring observability and startup discipline around Postgres, Qdrant, Ollama, Docker, backups, scheduled tasks, watchdogs, and any private local fire-signal extensions.
@ -222,7 +222,7 @@ landed_baseline:
- The MCP Discord surface now includes registered repo identities: `list_repo_discord_identities` exposes the role-backed address book, and `post_repo_identity_message` posts with the registered display name/avatar through the existing webhook pipe while enforcing channel allow-lists.
- The MCP Face surface now exposes `read_repo_face_state` and `apply_repo_face_state_operation`, reusing the typed self-state operation service against each repo identity's own Face `.cc` file instead of creating editable JSON projections.
- Repo Face birth initialization is detached and observable: VoidBot writes repo-local status/log paths before launching `scripts/run-repo-face-birth.mjs`, which runs EpiphanyAgent's `epiphany-repo-personality scout` followed by `epiphany-repo-birth-runner`.
- Repo Face heartbeats now have a Ghostlight-style initiative scheduler: resident daemon organ `apps/persona-scheduler` owns the serialized wall-clock pulse, while `scripts/run-repo-face-heartbeats.ts` still contains the oversized selection/context/queue engine being split behind that boundary. It reconciles registered identities, tracks initiative and active load, and queues ready Faces as approved `repo-face-rumination` jobs. Windows task ownership and its installer/wrapper are deleted.
- Repo Face heartbeats now have a Ghostlight-style initiative scheduler: resident daemon organ `apps/persona-scheduler` owns the serialized wall-clock pulse, initiative/state transitions, persistence, attention ingestion, active-turn liveness, and neutral Discord idle sensing. `scripts/run-repo-face-heartbeats.ts` remains an oversized context/prompt/queue shell being cut behind those boundaries; it queues selected Faces as approved `repo-face-rumination` jobs but cannot own selection state. Windows task ownership and its installer/wrapper are deleted.
- Interaction-memory logic is now split into event/tone analysis and profile-synthesis modules instead of one slab trying to be both the ear and the therapist.
- Situational social reads now come from a quick `think=false` local Ollama sidecar pass over the prompt plus recent room transcript, and those inferred reads are stored as audit events so they can be aggregated later without immediately hardening into profile truth.
- State storage is now split into a thin factory plus per-domain Postgres/file store modules and bootstrap/migration helpers instead of one persistence omnibus.