2026-05-18 11:23:44 +01:00
import "dotenv/config" ;
import { createHash } from "node:crypto" ;
2026-05-20 21:45:56 +01:00
import { spawn , spawnSync } from "node:child_process" ;
2026-05-21 21:45:31 +01:00
import { appendFile , mkdir , readFile , stat , writeFile } from "node:fs/promises" ;
2026-05-24 02:59:21 +01:00
import { homedir } from "node:os" ;
2026-05-24 03:28:40 +01:00
import { dirname , extname , resolve } from "node:path" ;
2026-05-18 11:23:44 +01:00
import { loadConfig } from "@voidbot/config" ;
import {
2026-05-18 17:17:08 +01:00
buildEpiphanyIdentityRegistry ,
2026-05-18 11:23:44 +01:00
ContextBuilder ,
createStateStorage ,
ensureRepoFaceInitialized ,
2026-05-20 20:31:42 +01:00
getRepoDiscordIdentityAllowedChannelIds ,
2026-05-21 09:26:04 +01:00
faceRegistryAsRepoDiscordRegistry ,
2026-05-20 20:31:42 +01:00
projectRepoFaceSleepCycleForNow ,
applyVoidSelfStateOperation ,
2026-05-21 09:26:04 +01:00
loadFaceIdentityRegistry ,
2026-05-18 20:36:35 +01:00
loadVoidSelfStateTypedDocuments ,
2026-05-19 11:56:01 +01:00
REPO_FACE_HEARTBEAT_SCHEMA_VERSION ,
2026-05-20 20:31:42 +01:00
type RepoFaceRestSnapshot ,
2026-05-18 11:23:44 +01:00
resolveRepoFaceStatePath ,
2026-05-19 11:56:01 +01:00
type RepoFacePendingMention ,
2026-05-18 11:23:44 +01:00
type RepoDiscordIdentity ,
2026-05-25 00:06:01 +01:00
type VoidScheduledRuntime ,
2026-05-21 17:24:37 +01:00
type VoidSelfStateTypedProjection ,
2026-05-18 11:23:44 +01:00
} from "@voidbot/core" ;
2026-05-24 06:11:47 +01:00
import {
createTextEmbedder ,
createVectorStores ,
RetrievalService ,
} from "@voidbot/rag" ;
2026-05-24 03:28:40 +01:00
import {
loadPromptTemplate ,
type InteractionMemoryProfile ,
type PromptImageAttachment ,
2026-05-24 06:11:47 +01:00
type RetrievalResult ,
2026-05-24 03:28:40 +01:00
type SourceMessage ,
type SourceMessageAttachment ,
} from "@voidbot/shared" ;
2026-05-18 11:23:44 +01:00
2026-05-19 11:56:01 +01:00
const HEARTBEAT_SCHEMA_VERSION = REPO_FACE_HEARTBEAT_SCHEMA_VERSION ;
2026-05-18 11:23:44 +01:00
const HEARTBEAT_COMMAND = "repo-face-rumination" ;
2026-05-20 23:37:13 +01:00
const MIN_STALE_ACTIVE_JOB_MS = 45 * 60 _000 ;
2026-05-24 03:28:40 +01:00
const MAX_FACE_IMAGE_ATTACHMENT_BYTES = 12 * 1024 * 1024 ;
2026-05-18 11:23:44 +01:00
interface FaceHeartbeatParticipant {
identityId : string ;
2026-05-18 19:05:09 +01:00
participantKind : "repo_face" | "system_agent" ;
turnKind : "repo_face_rumination" | "void_moderation" ;
2026-05-18 11:23:44 +01:00
repoName : string ;
displayName : string ;
initiativeSpeed : number ;
reactionBias : number ;
interruptThreshold : number ;
currentLoad : number ;
2026-05-18 18:31:35 +01:00
status : "active" | "blocked" | "withdrawn" | "offscreen" ;
groups : string [ ] ;
heat : number ;
effectiveSpeed : number ;
baseRecoveryMinutes : number ;
nextTurnAt : number ;
lastTurnAt? : number ;
2026-05-18 18:53:14 +01:00
activeTurnStartedAt? : number ;
activeJobId? : string ;
2026-05-18 11:23:44 +01:00
lastQueuedAt? : string ;
queuedCount : number ;
constraints : string [ ] ;
}
interface FaceHeartbeatState {
schemaVersion : typeof HEARTBEAT_SCHEMA_VERSION ;
2026-05-18 18:31:35 +01:00
initiativeClock : number ;
baseRecoveryMinutes : number ;
globalHeat : number ;
2026-05-18 11:23:44 +01:00
lastTickAt? : string ;
participants : FaceHeartbeatParticipant [ ] ;
history : Array < Record < string , unknown > > ;
2026-05-19 11:56:01 +01:00
pendingMentions : RepoFacePendingMention [ ] ;
2026-05-24 22:45:17 +01:00
controls : FaceHeartbeatControls ;
}
interface FaceHeartbeatControls {
cadenceMultiplier : number ;
manualTurnRequests : ManualTurnRequest [ ] ;
updatedAt? : string ;
}
interface ManualTurnRequest {
id : string ;
identityId : string ;
requestedAt : string ;
status : "pending" | "applied" | "consumed" | "rejected" ;
note? : string ;
2026-05-18 11:23:44 +01:00
}
2026-05-20 23:37:13 +01:00
interface ActiveTurnScan {
active : Map < string , string > ;
staleRecovered : StaleActiveTurn [ ] ;
}
2026-05-22 23:23:25 +01:00
interface IdleCoolingSnapshot {
enabled : boolean ;
active : boolean ;
reason? : string ;
checkedChannelIds : string [ ] ;
lastHumanActivityAt? : string ;
idleForMinutes? : number ;
idleAfterMinutes : number ;
recoveryMinutes : number ;
2026-05-24 22:26:01 +01:00
napAfterMinutes : number ;
napModeActive? : boolean ;
2026-05-22 23:23:25 +01:00
lastUnpromptedTurnQueuedAt? : string ;
nextUnpromptedTurnAllowedAt? : string ;
}
2026-05-20 23:37:13 +01:00
interface StaleActiveTurn {
identityId : string ;
jobId : string ;
requestMessageId? : string ;
state : string ;
updatedAt? : string ;
ageMinutes : number ;
}
2026-05-20 20:31:42 +01:00
interface RepoFaceChannelPlan {
primaryChannelId? : string ;
snapshotChannelIds : string [ ] ;
options : RepoFaceChannelOption [ ] ;
lowThresholdTopics : string [ ] ;
}
interface RepoFaceChannelOption {
channelId : string ;
label : string ;
topic : string ;
speechThreshold : "very_low" | "low" | "medium" | "high" ;
speedMultiplier : number ;
posture? : string ;
}
2026-05-24 19:36:38 +01:00
interface RepoFaceRuntimePressureSnapshot {
needToSpeak : number ;
confessionPressure : number ;
noveltyPressure : number ;
}
2026-05-26 14:42:44 +01:00
interface RepoFaceMemoryMaintenanceEvent {
type :
| "repo_face_memory_maintenance_started"
| "repo_face_memory_maintenance_completed"
| "repo_face_memory_maintenance_failed"
| "repo_face_memory_maintenance_failed_to_start" ;
identityId : string ;
observedAt : string ;
reason? : string ;
statusPath? : string ;
pid? : number ;
exitCode? : number | null ;
durationSeconds? : number ;
failureReason? : string ;
}
2026-05-20 21:45:56 +01:00
interface BifrostGovernanceDigest {
generatedAt : string ;
topics : BifrostGovernanceTopic [ ] ;
}
interface BifrostGovernanceTopic {
id : string ;
title : string ;
jurisdictionRepoName : string ;
jurisdictionAgentIdentity? : string ;
status : string ;
summaryMarkdown : string ;
priority : number ;
updatedAt : string ;
approvedByAgent? : string ;
dispatchRequestId? : string ;
comments? : BifrostGovernanceComment [ ] ;
}
interface BifrostGovernanceComment {
id : string ;
authorKind : string ;
authorId : string ;
stance : string ;
bodyMarkdown : string ;
createdAt : string ;
}
2026-05-20 20:31:42 +01:00
interface ChannelSnapshot {
channelId : string ;
messages : SourceMessage [ ] ;
}
2026-05-18 11:23:44 +01:00
async function main ( ) : Promise < void > {
const config = loadConfig ( ) ;
2026-05-18 18:31:35 +01:00
const dryRun = process . argv . includes ( "--dry-run" ) ;
2026-05-26 14:42:44 +01:00
const maintenanceOnly = process . argv . includes ( "--maintenance-only" ) ;
2026-05-21 13:07:00 +01:00
const assemblePromptIdentity = readArgValue ( "--assemble-prompt" ) ;
if ( assemblePromptIdentity ) {
const result = await assembleRepoFaceTurnPrompt ( {
config ,
identityId : assemblePromptIdentity ,
outPath : readArgValue ( "--out" ) ,
memorySurfacePath : readArgValue ( "--memory-surface" ) ,
2026-05-21 13:40:40 +01:00
conversationSurfacePath : readArgValue ( "--conversation-surface" ) ,
2026-05-21 13:07:00 +01:00
} ) ;
process . stdout . write ( ` ${ JSON . stringify ( result ) } \ n ` ) ;
return ;
}
2026-05-18 11:23:44 +01:00
2026-05-26 14:42:44 +01:00
if ( maintenanceOnly ) {
if ( ! config . repoFaceHeartbeats . enabled && ! process . argv . includes ( "--force" ) ) {
process . stdout . write ( ` ${ JSON . stringify ( {
ok : true ,
skipped : true ,
reason : "repo_face_heartbeats_disabled" ,
} ) } \ n ` );
return ;
}
const faceRegistry = await loadFaceIdentityRegistry ( config . repoDiscordIdentitiesPath ) ;
const registry = faceRegistryAsRepoDiscordRegistry ( faceRegistry ) ;
const state = await readHeartbeatState ( config . repoFaceHeartbeats . statePath ) ;
state . controls = normalizeHeartbeatControls ( state . controls ) ;
const now = new Date ( ) ;
const idleCooling = await readIdleCoolingSnapshot ( {
config ,
identities : registry.identities ,
state ,
now ,
} ) ;
const runtimeSnapshots = await loadRepoFaceRuntimeSnapshots (
registry . identities ,
config . storageRoot ,
state ,
{
dryRun ,
idleCooling ,
startMemoryMaintenance : true ,
maxMaintenanceRuns : readIntArgValue ( "--max-maintenance-runs" , 1 ) ,
waitForMaintenanceCompletion : true ,
} ,
) ;
state . lastTickAt = now . toISOString ( ) ;
state . history . push ( {
type : "repo_face_memory_maintenance_tick" ,
observedAt : state.lastTickAt ,
dryRun ,
idleCooling ,
maintenanceEventCount : runtimeSnapshots.maintenanceEvents.length ,
} ) ;
state . history = state . history . slice ( - 80 ) ;
if ( ! dryRun ) {
await writeHeartbeatState ( config . repoFaceHeartbeats . statePath , state ) ;
}
const ok = runtimeSnapshots . maintenanceEvents . every ( ( event ) = >
event . type !== "repo_face_memory_maintenance_failed_to_start" &&
event . type !== "repo_face_memory_maintenance_failed"
) ;
process . stdout . write ( ` ${ JSON . stringify ( {
ok ,
dryRun ,
maintenanceOnly : true ,
maintenanceEventCount : runtimeSnapshots.maintenanceEvents.length ,
maintenanceEvents : runtimeSnapshots.maintenanceEvents ,
statePath : config.repoFaceHeartbeats.statePath ,
} ) } \ n ` );
if ( ! ok ) {
process . exitCode = 1 ;
}
return ;
}
2026-05-21 08:57:52 +01:00
const pause = await readAgentSwarmPause ( ) ;
if ( pause . paused ) {
const state = await readHeartbeatState ( config . repoFaceHeartbeats . statePath ) ;
state . lastTickAt = new Date ( ) . toISOString ( ) ;
state . history . push ( {
type : "skipped" ,
reason : "agent_swarm_paused" ,
skippedAt : state.lastTickAt ,
pausePath : pause.path ,
pauseReason : pause.reason ,
} ) ;
state . history = state . history . slice ( - 80 ) ;
if ( ! dryRun ) {
await writeHeartbeatState ( config . repoFaceHeartbeats . statePath , state ) ;
}
process . stdout . write (
` ${ JSON . stringify ( {
ok : true ,
queuedCount : 0 ,
dryRun ,
skipped : true ,
reason : "agent_swarm_paused" ,
pausePath : pause.path ,
statePath : config.repoFaceHeartbeats.statePath ,
} ) } \ n ` ,
) ;
return ;
}
2026-05-18 11:23:44 +01:00
if ( ! config . repoFaceHeartbeats . enabled && ! process . argv . includes ( "--force" ) ) {
const state = await readHeartbeatState ( config . repoFaceHeartbeats . statePath ) ;
state . lastTickAt = new Date ( ) . toISOString ( ) ;
state . history . push ( {
type : "skipped" ,
reason : "repo_face_heartbeats_disabled" ,
skippedAt : state.lastTickAt ,
} ) ;
state . history = state . history . slice ( - 80 ) ;
await writeHeartbeatState ( config . repoFaceHeartbeats . statePath , state ) ;
return ;
}
2026-05-21 09:26:04 +01:00
const faceRegistry = await loadFaceIdentityRegistry ( config . repoDiscordIdentitiesPath ) ;
const registry = faceRegistryAsRepoDiscordRegistry ( faceRegistry ) ;
2026-05-18 11:23:44 +01:00
const state = await readHeartbeatState ( config . repoFaceHeartbeats . statePath ) ;
2026-05-24 22:45:17 +01:00
state . controls = normalizeHeartbeatControls ( state . controls ) ;
2026-05-18 11:23:44 +01:00
const now = new Date ( ) ;
2026-05-25 00:06:01 +01:00
const idleCooling = await readIdleCoolingSnapshot ( {
config ,
identities : registry.identities ,
state ,
now ,
} ) ;
const runtimeSnapshots = await loadRepoFaceRuntimeSnapshots (
registry . identities ,
config . storageRoot ,
state ,
2026-05-26 14:42:44 +01:00
{ dryRun , idleCooling , startMemoryMaintenance : false } ,
2026-05-25 00:06:01 +01:00
) ;
2026-05-20 20:31:42 +01:00
advanceInitiativeClockFromWallClock ( state , now ) ;
2026-05-20 23:37:13 +01:00
const activeTurnScan = dryRun
? { active : new Map < string , string > ( ) , staleRecovered : [ ] }
2026-05-18 19:05:09 +01:00
: await listExistingActiveTurns ( config . databaseDsn , config . stateStorageBackend , config ) ;
2026-05-20 23:37:13 +01:00
for ( const stale of activeTurnScan . staleRecovered ) {
state . history . push ( {
type : "stale_active_turn_recovered" ,
identityId : stale.identityId ,
activeJobId : stale.jobId ,
requestMessageId : stale.requestMessageId ,
jobState : stale.state ,
jobUpdatedAt : stale.updatedAt ,
ageMinutes : stale.ageMinutes ,
recoveredAt : now.toISOString ( ) ,
} ) ;
}
2026-05-18 11:23:44 +01:00
2026-05-18 18:31:35 +01:00
state . baseRecoveryMinutes = config . repoFaceHeartbeats . baseRecoveryMinutes ;
2026-05-25 19:53:44 +01:00
const cadenceMultiplier = clamp ( state . controls . cadenceMultiplier , 0.01 , 12 ) ;
2026-05-24 22:45:17 +01:00
const effectiveGlobalHeat = config . repoFaceHeartbeats . globalHeat * cadenceMultiplier ;
state . globalHeat = effectiveGlobalHeat ;
2026-05-18 18:53:14 +01:00
const completedThisTick = new Set < string > ( ) ;
2026-05-18 11:23:44 +01:00
state . participants = reconcileParticipants (
state . participants ,
2026-05-18 19:05:09 +01:00
buildParticipantSpecs ( registry . identities ) ,
2026-05-18 11:23:44 +01:00
config . repoFaceHeartbeats . defaultChannelId ,
2026-05-18 18:31:35 +01:00
config . repoFaceHeartbeats . speedOverrides ,
config . repoFaceHeartbeats . heatOverrides ,
state . initiativeClock ,
config . repoFaceHeartbeats . baseRecoveryMinutes ,
2026-05-24 22:45:17 +01:00
effectiveGlobalHeat ,
2026-05-24 19:36:38 +01:00
runtimeSnapshots . pressureByIdentity ,
2026-05-18 18:53:14 +01:00
) . map ( ( participant ) = >
2026-05-20 23:37:13 +01:00
applyActiveTurnFreeze (
participant ,
activeTurnScan . active . get ( participant . identityId ) ,
state ,
completedThisTick ,
) ,
2026-05-18 18:53:14 +01:00
) ;
2026-05-20 20:31:42 +01:00
rescheduleStaleOverdueParticipants ( state ) ;
2026-05-19 11:56:01 +01:00
applyPendingMentionPriority ( state ) ;
2026-05-24 22:45:17 +01:00
const manualOverrideIdentities = applyManualTurnRequests ( state , now ) ;
2026-05-26 15:06:56 +01:00
reinitializeCtbSpacingOnWake ( {
state ,
restStates : runtimeSnapshots.restStates ,
idleCooling ,
maxJobs : config.repoFaceHeartbeats.maxJobsPerTick ,
manualOverrideIdentities ,
} ) ;
2026-05-18 11:23:44 +01:00
const selected = selectReadyParticipants (
2026-05-18 18:31:35 +01:00
state ,
2026-05-18 11:23:44 +01:00
config . repoFaceHeartbeats . maxJobsPerTick ,
2026-05-18 18:53:14 +01:00
completedThisTick ,
2026-05-24 19:36:38 +01:00
runtimeSnapshots . restStates ,
2026-05-22 23:23:25 +01:00
idleCooling ,
2026-05-24 22:45:17 +01:00
manualOverrideIdentities ,
2026-05-18 11:23:44 +01:00
) ;
const queuedIdentityIds : string [ ] = [ ] ;
2026-05-18 18:31:35 +01:00
if ( selected . length > 0 && dryRun ) {
const queuedAt = new Date ( ) . toISOString ( ) ;
for ( const participant of selected ) {
2026-05-19 11:56:01 +01:00
const pendingMentions = pendingMentionsForParticipant ( state , participant . identityId ) ;
2026-05-18 18:31:35 +01:00
const recoveryMinutes = recoveryFor ( participant ) ;
participant . lastQueuedAt = queuedAt ;
participant . lastTurnAt = state . initiativeClock ;
participant . queuedCount += 1 ;
participant . nextTurnAt = Math . max ( state . initiativeClock , participant . nextTurnAt ) + recoveryMinutes ;
2026-05-24 22:45:17 +01:00
consumeManualTurnRequests ( state , participant . identityId , "consumed" , "dry run selected" ) ;
2026-05-18 18:31:35 +01:00
queuedIdentityIds . push ( participant . identityId ) ;
state . history . push ( {
type : "dry_run_selected" ,
identityId : participant.identityId ,
queuedAt ,
initiativeClock : state.initiativeClock ,
nextTurnAt : participant.nextTurnAt ,
recoveryMinutes ,
heat : participant.heat ,
effectiveSpeed : participant.effectiveSpeed ,
2026-05-19 11:56:01 +01:00
pendingMentionCount : pendingMentions.length ,
2026-05-18 18:31:35 +01:00
} ) ;
}
} else if ( selected . length > 0 ) {
2026-05-18 11:23:44 +01:00
const storage = await createStateStorage ( {
backend : config.stateStorageBackend ,
databaseDsn : config.databaseDsn ,
jobsFile : config.jobsFile ,
auditLogFile : config.auditLogFile ,
interactionMemoryFile : config.interactionMemoryFile ,
rateLimitStateFile : config.rateLimitStateFile ,
} ) ;
try {
for ( const participant of selected ) {
const queuedAt = new Date ( ) . toISOString ( ) ;
2026-05-19 11:56:01 +01:00
const pendingMentions = pendingMentionsForParticipant ( state , participant . identityId ) ;
2026-05-18 19:05:09 +01:00
const turn = await queueParticipantTurn ( {
2026-05-18 11:23:44 +01:00
participant ,
2026-05-19 11:56:01 +01:00
pendingMentions ,
2026-05-18 19:05:09 +01:00
registryIdentities : registry.identities ,
config ,
storage ,
queuedAt ,
2026-05-18 11:23:44 +01:00
} ) ;
2026-05-18 19:05:09 +01:00
if ( turn . created ) {
queuedIdentityIds . push ( participant . identityId ) ;
2026-05-18 11:23:44 +01:00
participant . lastQueuedAt = queuedAt ;
2026-05-18 18:53:14 +01:00
participant . activeTurnStartedAt = state . initiativeClock ;
2026-05-18 19:05:09 +01:00
participant . activeJobId = turn . activeJobId ;
2026-05-18 18:31:35 +01:00
participant . lastTurnAt = state . initiativeClock ;
2026-05-18 11:23:44 +01:00
participant . queuedCount += 1 ;
2026-05-18 18:53:14 +01:00
participant . currentLoad = 1 ;
2026-05-24 22:45:17 +01:00
consumeManualTurnRequests ( state , participant . identityId , "consumed" , ` queued ${ turn . activeJobId } ` ) ;
2026-05-19 11:56:01 +01:00
if ( pendingMentions . length > 0 ) {
const consumedIds = new Set ( pendingMentions . map ( ( entry ) = > entry . id ) ) ;
state . pendingMentions = state . pendingMentions . filter ( ( entry ) = > ! consumedIds . has ( entry . id ) ) ;
}
2026-05-18 11:23:44 +01:00
state . history . push ( {
type : "queued" ,
2026-05-18 19:05:09 +01:00
identityId : participant.identityId ,
participantKind : participant.participantKind ,
turnKind : participant.turnKind ,
activeJobId : turn.activeJobId ,
requestMessageId : turn.requestMessageId ,
2026-05-18 11:23:44 +01:00
queuedAt ,
2026-05-18 18:31:35 +01:00
initiativeClock : state.initiativeClock ,
2026-05-18 18:53:14 +01:00
frozen : true ,
2026-05-18 18:31:35 +01:00
heat : participant.heat ,
effectiveSpeed : participant.effectiveSpeed ,
2026-05-19 11:56:01 +01:00
pendingMentionCount : pendingMentions.length ,
2026-05-18 11:23:44 +01:00
} ) ;
2026-05-19 08:05:48 +01:00
} else if ( turn . failureReason ) {
participant . currentLoad = 0 ;
state . history . push ( {
type : "turn_failed_to_start" ,
identityId : participant.identityId ,
participantKind : participant.participantKind ,
turnKind : participant.turnKind ,
activeJobId : turn.activeJobId ,
requestMessageId : turn.requestMessageId ,
queuedAt ,
initiativeClock : state.initiativeClock ,
reason : turn.failureReason ,
heat : participant.heat ,
effectiveSpeed : participant.effectiveSpeed ,
} ) ;
2026-05-18 11:23:44 +01:00
}
}
} finally {
await storage . close ( ) ;
}
}
state . history = state . history . slice ( - 80 ) ;
state . lastTickAt = now . toISOString ( ) ;
2026-05-21 00:02:33 +01:00
if ( ! dryRun ) {
await writeHeartbeatState ( config . repoFaceHeartbeats . statePath , state ) ;
}
2026-05-18 11:23:44 +01:00
process . stdout . write (
` ${ JSON . stringify ( {
ok : true ,
participantCount : state.participants.length ,
2026-05-18 18:31:35 +01:00
initiativeClock : state.initiativeClock ,
2026-05-18 11:23:44 +01:00
queuedCount : queuedIdentityIds.length ,
2026-05-18 18:31:35 +01:00
dryRun ,
2026-05-18 11:23:44 +01:00
selected : selected.map ( ( entry ) = > entry . identityId ) ,
queued : queuedIdentityIds ,
statePath : config.repoFaceHeartbeats.statePath ,
2026-05-22 23:23:25 +01:00
idleCooling ,
2026-05-18 11:23:44 +01:00
} ) } \ n ` ,
) ;
}
2026-05-21 08:57:52 +01:00
async function readAgentSwarmPause ( ) : Promise < { paused : boolean ; path : string ; reason? : string } > {
const path = resolve ( process . cwd ( ) , "state" , "agent-swarm-paused.json" ) ;
try {
const parsed = JSON . parse ( stripLeadingBom ( await readFile ( path , "utf8" ) ) ) as Record < string , unknown > ;
return {
paused : parsed.paused !== false ,
path ,
reason : typeof parsed . reason === "string" ? parsed.reason : undefined ,
} ;
} catch ( error ) {
if ( error && typeof error === "object" && "code" in error && error . code === "ENOENT" ) {
return { paused : false , path } ;
}
return {
paused : true ,
path ,
reason : "Pause file exists but could not be parsed; failing closed." ,
} ;
}
}
2026-05-18 19:05:09 +01:00
interface ParticipantSpec {
id : string ;
participantKind : FaceHeartbeatParticipant [ "participantKind" ] ;
turnKind : FaceHeartbeatParticipant [ "turnKind" ] ;
repoName : string ;
displayName : string ;
allowedChannelIds : string [ ] ;
2026-05-20 20:31:42 +01:00
channelSpeedMultiplier : number ;
2026-05-18 19:05:09 +01:00
identity? : RepoDiscordIdentity ;
}
function buildParticipantSpecs ( identities : RepoDiscordIdentity [ ] ) : ParticipantSpec [ ] {
return [
{
id : "void" ,
participantKind : "system_agent" ,
turnKind : "void_moderation" ,
repoName : "VoidBot" ,
displayName : "Void" ,
allowedChannelIds : [ ] ,
2026-05-20 20:31:42 +01:00
channelSpeedMultiplier : 1 ,
2026-05-18 19:05:09 +01:00
} ,
. . . identities . map ( ( identity ) = > ( {
id : identity.id ,
participantKind : "repo_face" as const ,
turnKind : "repo_face_rumination" as const ,
repoName : identity.repoName ,
displayName : identity.displayName ,
2026-05-20 20:31:42 +01:00
allowedChannelIds : getRepoDiscordIdentityAllowedChannelIds ( identity ) ,
channelSpeedMultiplier : channelSpeedMultiplierFor ( identity ) ,
2026-05-18 19:05:09 +01:00
identity ,
} ) ) ,
] ;
}
async function queueParticipantTurn ( input : {
participant : FaceHeartbeatParticipant ;
2026-05-19 11:56:01 +01:00
pendingMentions : RepoFacePendingMention [ ] ;
2026-05-18 19:05:09 +01:00
registryIdentities : RepoDiscordIdentity [ ] ;
config : ReturnType < typeof loadConfig > ;
storage : Awaited < ReturnType < typeof createStateStorage > > ;
queuedAt : string ;
2026-05-19 08:05:48 +01:00
} ) : Promise < { created : boolean ; activeJobId? : string ; requestMessageId? : string ; failureReason? : string } > {
2026-05-18 19:05:09 +01:00
switch ( input . participant . turnKind ) {
case "repo_face_rumination" :
return queueRepoFaceTurn ( input ) ;
case "void_moderation" :
2026-05-20 20:31:42 +01:00
return startVoidModerationTurn ( {
queuedAt : input.queuedAt ,
storageRoot : input.config.storageRoot ,
pendingMentions : input.pendingMentions ,
} ) ;
2026-05-18 19:05:09 +01:00
}
}
async function queueRepoFaceTurn ( input : {
participant : FaceHeartbeatParticipant ;
2026-05-19 11:56:01 +01:00
pendingMentions : RepoFacePendingMention [ ] ;
2026-05-18 19:05:09 +01:00
registryIdentities : RepoDiscordIdentity [ ] ;
config : ReturnType < typeof loadConfig > ;
storage : Awaited < ReturnType < typeof createStateStorage > > ;
queuedAt : string ;
2026-05-20 20:31:42 +01:00
} ) : Promise < { created : boolean ; activeJobId? : string ; requestMessageId? : string ; failureReason? : string } > {
2026-05-18 19:05:09 +01:00
const identity = input . registryIdentities . find ( ( entry ) = > entry . id === input . participant . identityId ) ;
if ( ! identity ) {
return { created : false } ;
}
2026-05-22 21:05:05 +01:00
const preferredChannelId = newestPendingMentionChannel ( input . pendingMentions ) ;
const channelPlan = buildChannelPlan (
identity ,
input . config . repoFaceHeartbeats . defaultChannelId ,
preferredChannelId ,
) ;
2026-05-20 20:31:42 +01:00
const channelId = channelPlan . primaryChannelId ;
2026-05-18 19:05:09 +01:00
if ( ! channelId ) {
input . participant . status = "blocked" ;
input . participant . constraints = mergeStrings (
input . participant . constraints ,
2026-05-21 09:26:04 +01:00
"No CTB turn channel is configured for this Face." ,
2026-05-18 19:05:09 +01:00
) ;
return { created : false } ;
}
const contextBuilder = new ContextBuilder ( ) ;
2026-05-21 11:40:23 +01:00
await ensureRepoFaceInitialized ( {
2026-05-18 19:05:09 +01:00
identity ,
storageRoot : input.config.storageRoot ,
sourceRepoRoot : input.config.sourceRepoRoot ,
epiphanyAgentRoot : input.config.epiphanyAgentRoot ,
workspaceRoot : process.cwd ( ) ,
birthMode : input.config.repoFaceBirthMode ,
birthExecutor : input.config.repoFaceBirthExecutor ,
} ) ;
2026-05-18 20:36:35 +01:00
const recentMessages = await fetchRecentDiscordMessages ( {
botToken : input.config.botToken ,
channelId ,
limit : 15 ,
2026-05-20 21:45:56 +01:00
ignoreBotMessages : channelId === input . config . bifrostDiscordChannelId ,
2026-05-18 20:36:35 +01:00
} ) ;
2026-05-20 20:31:42 +01:00
const channelSnapshots = await fetchChannelSnapshots ( {
botToken : input.config.botToken ,
channelIds : channelPlan.snapshotChannelIds ,
primaryChannelId : channelId ,
limit : 6 ,
2026-05-20 21:45:56 +01:00
bifrostDiscordChannelId : input.config.bifrostDiscordChannelId ,
} ) ;
2026-05-21 20:48:02 +01:00
const bifrostDigest = input . config . repoFaceBifrostEnabled
? await fetchBifrostGovernanceDigest ( {
bifrostRoot : input.config.bifrostRoot ,
repoName : identity.repoName ,
agentIdentity : identity.id ,
2026-05-22 23:39:00 +01:00
} )
2026-05-21 20:48:02 +01:00
: undefined ;
2026-05-22 23:39:00 +01:00
const roomContext = {
recentMessages ,
channelSnapshots ,
} ;
const humanPronounGuidance = await loadRepoFaceHumanPronounGuidance ( input . config , roomContext ) ;
2026-05-21 17:24:37 +01:00
const memorySurface = await renderRepoFaceMemorySurfaceForTurn (
identity ,
2026-05-21 21:06:11 +01:00
input . config ,
2026-05-22 13:33:07 +01:00
input . registryIdentities ,
2026-05-22 23:39:00 +01:00
roomContext ,
humanPronounGuidance ,
2026-05-21 17:24:37 +01:00
) ;
2026-05-22 00:43:47 +01:00
const repoActivitySurface = renderRepoFaceRepoActivitySurface ( identity , input . config ) ;
2026-05-24 02:59:21 +01:00
const globalAgentDoctrine = await loadGlobalAgentDoctrine ( ) ;
2026-05-21 23:49:07 +01:00
const conversationMemorySurface = renderRepoFaceConversationTranscript ( {
2026-05-21 21:45:31 +01:00
identity ,
recentMessages ,
channelSnapshots ,
pendingMentions : input.pendingMentions ,
2026-05-21 23:49:07 +01:00
channelPlan ,
2026-05-21 21:45:31 +01:00
} ) ;
2026-05-18 19:05:09 +01:00
const prompt = buildHeartbeatPrompt ( {
identity ,
channelId ,
2026-05-20 20:31:42 +01:00
channelPlan ,
channelSnapshots ,
recentMessages ,
2026-05-21 17:24:37 +01:00
memorySurface ,
2026-05-22 00:43:47 +01:00
repoActivitySurface ,
2026-05-21 21:45:31 +01:00
conversationMemorySurface ,
2026-05-22 23:39:00 +01:00
humanPronounGuidance ,
2026-05-20 21:45:56 +01:00
bifrostDigest ,
2026-05-18 19:05:09 +01:00
participant : input.participant ,
2026-05-19 11:56:01 +01:00
pendingMentions : input.pendingMentions ,
2026-05-19 08:16:06 +01:00
jurisdictionDive : buildJurisdictionDiveDirective ( identity , input . participant ) ,
2026-05-19 16:30:51 +01:00
githubActionsEnabled : input.config.repoFaceGithubActionsEnabled ,
2026-05-24 02:59:21 +01:00
globalAgentDoctrine ,
2026-05-18 19:05:09 +01:00
} ) ;
2026-05-24 03:28:40 +01:00
const imageAttachments = collectPromptImageAttachments ( [
recentMessages ,
. . . channelSnapshots . map ( ( snapshot ) = > snapshot . messages ) ,
] . flat ( ) ) ;
2026-05-18 19:05:09 +01:00
const contextBundle = contextBuilder . build ( {
prompt ,
actor : {
2026-05-21 09:26:04 +01:00
id : "voidbot-agent-turn" ,
displayName : "VoidBot Agent Turn" ,
2026-05-18 19:05:09 +01:00
isAdmin : true ,
isBot : true ,
} ,
guildContext : {
channelId ,
} ,
2026-05-18 20:36:35 +01:00
recentMessages ,
2026-05-24 03:28:40 +01:00
imageAttachments ,
2026-05-18 19:05:09 +01:00
retrieval : [ ] ,
2026-05-21 11:40:23 +01:00
voidSelfState : undefined ,
2026-05-18 19:05:09 +01:00
} ) ;
2026-05-21 09:26:04 +01:00
const requestMessageId = ` agent-turn: ${ identity . id } : ${ input . queuedAt } ` ;
2026-05-18 19:05:09 +01:00
const result = await input . storage . jobQueue . createJob ( {
command : HEARTBEAT_COMMAND ,
provider : "owner_codex" ,
runApprovalRequired : false ,
postApprovalRequired : false ,
requester : contextBundle.actor ,
guildContext : contextBundle.guildContext ,
prompt ,
contextBundle ,
outputChannelId : channelId ,
requestMessageId ,
initialState : "approved" ,
} ) ;
return {
created : result.created ,
activeJobId : result.job.id ,
requestMessageId ,
} ;
}
2026-05-24 19:36:38 +01:00
async function loadRepoFaceRuntimeSnapshots (
2026-05-20 20:31:42 +01:00
identities : RepoDiscordIdentity [ ] ,
storageRoot : string ,
heartbeatState : FaceHeartbeatState ,
2026-05-26 14:42:44 +01:00
options : {
dryRun? : boolean ;
idleCooling? : IdleCoolingSnapshot ;
startMemoryMaintenance? : boolean ;
maxMaintenanceRuns? : number ;
waitForMaintenanceCompletion? : boolean ;
} = { } ,
2026-05-24 19:36:38 +01:00
) : Promise < {
restStates : Map < string , RepoFaceRestSnapshot > ;
pressureByIdentity : Map < string , RepoFaceRuntimePressureSnapshot > ;
2026-05-26 14:42:44 +01:00
maintenanceEvents : RepoFaceMemoryMaintenanceEvent [ ] ;
2026-05-24 19:36:38 +01:00
} > {
2026-05-20 20:31:42 +01:00
const restStates = new Map < string , RepoFaceRestSnapshot > ( ) ;
2026-05-24 19:36:38 +01:00
const pressureByIdentity = new Map < string , RepoFaceRuntimePressureSnapshot > ( ) ;
2026-05-26 14:42:44 +01:00
const maintenanceEvents : RepoFaceMemoryMaintenanceEvent [ ] = [ ] ;
let maintenanceRunCount = 0 ;
const maxMaintenanceRuns = Math . max ( 0 , options . maxMaintenanceRuns ? ? Number . POSITIVE_INFINITY ) ;
2026-05-20 20:31:42 +01:00
const now = new Date ( ) ;
for ( const identity of identities ) {
try {
const statePath = resolveRepoFaceStatePath ( identity , storageRoot ) ;
const typedState = await loadVoidSelfStateTypedDocuments ( {
canonicalPath : statePath ,
identity : {
agentId : identity.id ,
publicName : identity.displayName ,
publicDescription : identity.description ,
} ,
} ) ;
const projected = projectRepoFaceSleepCycleForNow (
typedState . scheduledRuntime . sleepCycle ,
identity . id ,
now ,
) ;
2026-05-25 00:06:01 +01:00
const sleepCycle = projectSleepCycleForOperatorAbsence (
projected . sleepCycle ,
options . idleCooling ,
now ,
) ;
if ( ! options . dryRun && ! sleepCyclesEqual ( typedState . scheduledRuntime . sleepCycle , sleepCycle ) ) {
2026-05-20 20:31:42 +01:00
await applyVoidSelfStateOperation (
{
canonicalPath : statePath ,
identity : {
agentId : identity.id ,
publicName : identity.displayName ,
publicDescription : identity.description ,
} ,
} ,
{
operation : "update_sleep_cycle" ,
2026-05-25 00:06:01 +01:00
sleepCycle ,
2026-05-20 20:31:42 +01:00
} ,
) ;
}
2026-05-21 00:02:33 +01:00
const speakingPressure = buildRepoFaceSpeakingPressure (
2026-05-20 20:31:42 +01:00
typedState ,
2026-05-25 00:06:01 +01:00
sleepCycle ,
2026-05-21 00:02:33 +01:00
now ,
) ;
2026-05-24 19:36:38 +01:00
pressureByIdentity . set ( identity . id , {
needToSpeak : speakingPressure.needToSpeak ,
confessionPressure : speakingPressure.confessionPressure ? ? 0 ,
noveltyPressure : speakingPressure.noveltyPressure ? ? 0 ,
} ) ;
2026-05-21 00:02:33 +01:00
if ( ! options . dryRun && ! speakingPressuresEqual ( typedState . scheduledRuntime . speakingPressure , speakingPressure ) ) {
await applyVoidSelfStateOperation (
{
canonicalPath : statePath ,
identity : {
agentId : identity.id ,
publicName : identity.displayName ,
publicDescription : identity.description ,
} ,
} ,
{
operation : "update_speaking_pressure" ,
speakingPressure ,
} ,
) ;
}
2026-05-26 14:42:44 +01:00
const maintenance = options . dryRun || options . startMemoryMaintenance !== true || maintenanceRunCount >= maxMaintenanceRuns
2026-05-21 00:02:33 +01:00
? { started : false , reason : "dry_run" , statusPath : undefined }
: await maybeStartRepoFaceMemoryMaintenance ( {
identity ,
statePath ,
typedState ,
2026-05-25 00:06:01 +01:00
projectedRest : {
isNapping : sleepCycle.isNapping === true ,
napEndsAt : sleepCycle.currentNapEndsAt ,
nextNapStartsAt : sleepCycle.nextNapStartsAt ,
} ,
2026-05-26 14:42:44 +01:00
waitForCompletion : options.waitForMaintenanceCompletion === true ,
2026-05-21 00:02:33 +01:00
} ) ;
2026-05-20 20:31:42 +01:00
if ( maintenance . started || maintenance . failureReason ) {
2026-05-26 14:42:44 +01:00
maintenanceRunCount += 1 ;
}
if ( maintenance . started || maintenance . failureReason || maintenance . completed ) {
const event : RepoFaceMemoryMaintenanceEvent = {
type : maintenance . completed
? "repo_face_memory_maintenance_completed"
: maintenance . started
? "repo_face_memory_maintenance_started"
: maintenance . exitCode === undefined
? "repo_face_memory_maintenance_failed_to_start"
: "repo_face_memory_maintenance_failed" ,
2026-05-20 20:31:42 +01:00
identityId : identity.id ,
observedAt : now.toISOString ( ) ,
reason : maintenance.reason ,
statusPath : maintenance.statusPath ,
pid : maintenance.pid ,
2026-05-26 14:42:44 +01:00
exitCode : maintenance.exitCode ,
durationSeconds : maintenance.durationSeconds ,
2026-05-20 20:31:42 +01:00
failureReason : maintenance.failureReason ,
2026-05-26 14:42:44 +01:00
} ;
heartbeatState . history . push ( event ) ;
maintenanceEvents . push ( event ) ;
2026-05-20 20:31:42 +01:00
}
restStates . set ( identity . id , {
2026-05-25 00:06:01 +01:00
isNapping : sleepCycle.isNapping === true ,
napEndsAt : sleepCycle.currentNapEndsAt ,
nextNapStartsAt : sleepCycle.nextNapStartsAt ,
2026-05-20 20:31:42 +01:00
} ) ;
} catch ( error ) {
const code = ( error as NodeJS . ErrnoException ) . code ;
if ( code !== "ENOENT" ) {
throw error ;
}
}
}
2026-05-26 14:42:44 +01:00
return { restStates , pressureByIdentity , maintenanceEvents } ;
2026-05-20 20:31:42 +01:00
}
2026-05-25 00:06:01 +01:00
function projectSleepCycleForOperatorAbsence (
sleepCycle : VoidScheduledRuntime [ "sleepCycle" ] ,
idleCooling : IdleCoolingSnapshot | undefined ,
now : Date ,
) : VoidScheduledRuntime [ "sleepCycle" ] {
if ( idleCooling ? . napModeActive !== true ) {
2026-05-25 22:28:51 +01:00
const activeDreamThemes = sleepCycle . activeDreamThemes . filter ( ( theme ) = > theme !== "operator-absence-dreaming" ) ;
if ( sleepCycle . isNapping !== true || ! sleepCycle . activeDreamThemes . includes ( "operator-absence-dreaming" ) ) {
return activeDreamThemes . length === sleepCycle . activeDreamThemes . length
? sleepCycle
: {
. . . sleepCycle ,
activeDreamThemes ,
} ;
}
return {
. . . sleepCycle ,
isNapping : false ,
currentNapStartedAt : undefined ,
currentNapEndsAt : undefined ,
nextNapStartsAt : new Date ( now . getTime ( ) + 180 * 60 _000 ) . toISOString ( ) ,
activeDreamThemes ,
} ;
2026-05-25 00:06:01 +01:00
}
const nowMs = now . getTime ( ) ;
const minimumNapMinutes = Math . max ( 60 , Math . min ( 180 , idleCooling . recoveryMinutes || 120 ) ) ;
const currentNapEndsMs = Date . parse ( sleepCycle . currentNapEndsAt ? ? "" ) ;
const desiredNapEndsMs = nowMs + minimumNapMinutes * 60 _000 ;
const napEndsMs = Number . isFinite ( currentNapEndsMs )
? Math . max ( currentNapEndsMs , desiredNapEndsMs )
: desiredNapEndsMs ;
const activeDreamThemes = Array . from ( new Set ( [
. . . sleepCycle . activeDreamThemes ,
"operator-absence-dreaming" ,
"memory-distillation" ,
] ) ) ;
return {
. . . sleepCycle ,
isNapping : true ,
currentNapStartedAt : sleepCycle.isNapping && sleepCycle . currentNapStartedAt
? sleepCycle . currentNapStartedAt
: now . toISOString ( ) ,
currentNapEndsAt : new Date ( napEndsMs ) . toISOString ( ) ,
nextNapStartsAt : new Date ( napEndsMs + 180 * 60 _000 ) . toISOString ( ) ,
activeDreamThemes ,
} ;
}
2026-05-21 00:02:33 +01:00
function buildRepoFaceSpeakingPressure (
typedState : Awaited < ReturnType < typeof loadVoidSelfStateTypedDocuments > > ,
sleepCycle : Awaited < ReturnType < typeof projectRepoFaceSleepCycleForNow > > [ "sleepCycle" ] ,
now : Date ,
) : Awaited < ReturnType < typeof loadVoidSelfStateTypedDocuments > > [ "scheduledRuntime" ] [ "speakingPressure" ] {
const previous = typedState . scheduledRuntime . speakingPressure ;
const lastReceipt = typedState . speechReceipts . recentReceipts
. slice ( )
. sort ( ( left , right ) = > Date . parse ( right . sentAt ) - Date . parse ( left . sentAt ) )
[ 0 ] ;
const lastSpokeAt = lastReceipt ? . sentAt ? ? previous . lastSpokeAt ;
const hoursSinceSpeech = lastSpokeAt ? Math . max ( 0 , ( now . getTime ( ) - Date . parse ( lastSpokeAt ) ) / 3 _600_000 ) : 24 ;
const recentSpeechDamping = clamp ( Math . exp ( - hoursSinceSpeech / 3.5 ) , 0 , 1 ) ;
const affectNeedPressure = ( typedState . faceAffect . needs ? ? [ ] )
. filter ( ( entry ) = > entry . status === "active" || entry . status === "neglected" )
. reduce ( ( sum , entry ) = > {
const neglectedWeight = entry . status === "neglected" ? 1.25 : 1 ;
const substrateWeight = [ "substrate" , "agency" , "status" , "territory" , "recognition" ] . includes ( entry . kind ) ? 0.18 : 0.11 ;
return sum + entry . intensity * substrateWeight * neglectedWeight ;
} , 0 ) ;
const statusReadPressure = ( typedState . faceAffect . statusReads ? ? [ ] )
. filter ( ( entry ) = > ! entry . retiredAt )
. reduce ( ( sum , entry ) = > {
const sharpWeight = [ "neglected" , "bypassed" , "blocked" , "ignored" , "threatened" , "challenged" ] . includes ( entry . status ) ? 0.14 : 0.08 ;
return sum + entry . intensity * sharpWeight ;
} , 0 ) ;
const socialBondPressure = ( typedState . faceAffect . socialBonds ? ? [ ] )
. filter ( ( entry ) = > entry . status === "active" )
. reduce ( ( sum , entry ) = > sum + entry . intensity * 0.07 , 0 ) ;
const moodPressure = ( typedState . faceAffect . moodDimensions ? ? [ ] )
. reduce ( ( sum , entry ) = > {
const expressiveWeight = [ "anger" , "annoyance" , "irritation" , "envy" , "pride" , "smugness" , "playfulness" , "anxiety" , "commandForce" , "restlessness" ] . includes ( entry . name )
? 0.06
: 0.025 ;
return sum + entry . value * expressiveWeight ;
} , 0 ) ;
2026-05-24 20:38:51 +01:00
const socialBiasPressure = ( typedState . faceAffect . socialBiases ? ? [ ] )
. reduce ( ( sum , entry ) = > {
const pressureWeight = [ "neuroticism" , "threat_sensitivity" , "hostile_attribution_bias" , "reassurance_need" , "grievance_retention" , "status_vigilance" ] . includes ( entry . name )
? 0.055
: - 0.025 ;
return sum + entry . value * pressureWeight ;
} , 0 ) ;
2026-05-21 00:02:33 +01:00
const agencyPressure = typedState . agencyPressure . pressures
. filter ( ( entry ) = > entry . status === "active" || entry . status === "ready_to_act" )
. reduce ( ( sum , entry ) = > sum + entry . intensity * ( entry . kind . includes ( "advocacy" ) ? 0.22 : 0.11 ) , 0 ) ;
const candidatePressure = typedState . candidateInterventions . interventions
. filter ( ( entry ) = > entry . status === "queued" || entry . status === "deferred" )
. reduce ( ( sum , entry ) = > sum + entry . priority * ( entry . mustEventuallyShare ? 0.22 : 0.12 ) , 0 ) ;
const silencePressure = clamp ( hoursSinceSpeech / 8 , 0 , 1 ) ;
const sleepiness = sleepCycle . isNapping ? 0.22 : 0 ;
const targetNeed = clamp (
2026-05-24 20:38:51 +01:00
0.12 + silencePressure * 0.18 + affectNeedPressure + statusReadPressure + socialBondPressure + moodPressure + socialBiasPressure + agencyPressure + candidatePressure - recentSpeechDamping * 0.24 - sleepiness ,
2026-05-21 00:02:33 +01:00
0 ,
1 ,
) ;
const needToSpeak = round3 ( clamp ( ( previous . needToSpeak ? ? 0.25 ) * 0.58 + targetNeed * 0.42 , 0 , 1 ) ) ;
return {
needToSpeak ,
2026-05-24 20:38:51 +01:00
confessionPressure : round3 ( clamp ( ( previous . confessionPressure ? ? 0.2 ) * 0.7 + moodPressure * 0.42 + socialBondPressure * 0.18 + socialBiasPressure * 0.2 , 0 , 1 ) ) ,
noveltyPressure : round3 ( clamp ( ( previous . noveltyPressure ? ? 0.25 ) * 0.62 + affectNeedPressure * 0.35 + statusReadPressure * 0.24 + socialBiasPressure * 0.18 + candidatePressure * 0.28 , 0 , 1 ) ) ,
2026-05-21 00:02:33 +01:00
recentSpeechDamping : round3 ( recentSpeechDamping ) ,
lastSpokeAt ,
} ;
}
function speakingPressuresEqual (
left : Awaited < ReturnType < typeof loadVoidSelfStateTypedDocuments > > [ "scheduledRuntime" ] [ "speakingPressure" ] ,
right : Awaited < ReturnType < typeof loadVoidSelfStateTypedDocuments > > [ "scheduledRuntime" ] [ "speakingPressure" ] ,
) : boolean {
return left . needToSpeak === right . needToSpeak
&& left . confessionPressure === right . confessionPressure
&& left . noveltyPressure === right . noveltyPressure
&& left . recentSpeechDamping === right . recentSpeechDamping
&& left . lastSpokeAt === right . lastSpokeAt ;
}
2026-05-20 20:31:42 +01:00
async function maybeStartRepoFaceMemoryMaintenance ( input : {
identity : RepoDiscordIdentity ;
statePath : string ;
typedState : Awaited < ReturnType < typeof loadVoidSelfStateTypedDocuments > > ;
projectedRest : RepoFaceRestSnapshot ;
2026-05-26 14:42:44 +01:00
waitForCompletion? : boolean ;
2026-05-20 20:31:42 +01:00
} ) : Promise < {
started : boolean ;
2026-05-26 14:42:44 +01:00
completed? : boolean ;
2026-05-20 20:31:42 +01:00
reason? : string ;
statusPath? : string ;
pid? : number ;
2026-05-26 14:42:44 +01:00
exitCode? : number | null ;
durationSeconds? : number ;
2026-05-20 20:31:42 +01:00
failureReason? : string ;
} > {
const shortTerm = input . typedState . thoughtMemory . shortTerm ? ? [ ] ;
if ( shortTerm . length === 0 ) {
return { started : false , reason : "no_short_term_memory" } ;
}
const oldestShortTermMs = Math . min (
. . . shortTerm . map ( ( memory ) = > Date . parse ( memory . updatedAt ) ) . filter ( Number . isFinite ) ,
) ;
const hasStaleShortTerm =
Number . isFinite ( oldestShortTermMs ) &&
Date . now ( ) - oldestShortTermMs >= 6 * 60 * 60 * 1000 ;
if ( input . projectedRest . isNapping !== true && ! hasStaleShortTerm ) {
return { started : false , reason : "not_napping_or_stale" } ;
}
const paths = repoFaceMemoryMaintenancePaths ( input . statePath ) ;
const currentStatus = await readJsonFile ( paths . statusPath ) ;
if ( isRecentRunningStatus ( currentStatus , 25 ) ) {
return { started : false , reason : "maintenance_already_running" , statusPath : paths.statusPath } ;
}
2026-05-24 22:26:01 +01:00
if ( input . projectedRest . isNapping === true && isStatusCompletedRecently ( currentStatus , 60 ) ) {
return { started : false , reason : "nap_maintenance_recently_completed" , statusPath : paths.statusPath } ;
}
2026-05-20 20:31:42 +01:00
if ( isStatusCompletedAfter ( currentStatus , newestTimestampMs ( shortTerm ) ) ) {
return { started : false , reason : "maintenance_already_completed_for_sources" , statusPath : paths.statusPath } ;
}
2026-05-25 07:03:10 +01:00
const reason = input . projectedRest . isNapping
? "repo_face_napping_with_short_term_memory"
: "repo_face_stale_short_term_memory" ;
2026-05-20 20:31:42 +01:00
try {
await mkdir ( paths . statusDir , { recursive : true } ) ;
await mkdir ( paths . logDir , { recursive : true } ) ;
2026-05-25 07:03:10 +01:00
await writeFile ( paths . statusPath , ` ${ JSON . stringify ( {
status : "starting" ,
startedAt : new Date ( ) . toISOString ( ) ,
stateFile : input.statePath ,
reason ,
shortTermCount : shortTerm.length ,
newestShortTermUpdatedAt : newestTimestampMs ( shortTerm ) > 0
? new Date ( newestTimestampMs ( shortTerm ) ) . toISOString ( )
: undefined ,
} , null , 2 ) } \ n ` , "utf8");
2026-05-26 14:42:44 +01:00
if ( input . waitForCompletion === true ) {
const startedAtMs = Date . now ( ) ;
const stamp = new Date ( startedAtMs ) . toISOString ( ) . replace ( /[:.]/g , "-" ) ;
const stdoutPath = resolve ( paths . logDir , ` repo-face-memory-maintenance- ${ input . identity . id } - ${ stamp } .stdout.log ` ) ;
const stderrPath = resolve ( paths . logDir , ` repo-face-memory-maintenance- ${ input . identity . id } - ${ stamp } .stderr.log ` ) ;
const maxRuntimeMinutes = Number . parseInt ( process . env . VOID_MEMORY_MAINTENANCE_MAX_RUNTIME_MINUTES ? ? "15" , 10 ) ;
const result = spawnSync (
"powershell.exe" ,
[
"-NoProfile" ,
"-NonInteractive" ,
"-ExecutionPolicy" ,
"Bypass" ,
"-File" ,
resolve ( process . cwd ( ) , "scripts" , "run-void-memory-maintenance.ps1" ) ,
"-StateFilePath" ,
input . statePath ,
"-ForceDistillation" ,
] ,
{
cwd : process.cwd ( ) ,
encoding : "utf8" ,
timeout : Math.max ( 5 , maxRuntimeMinutes + 2 ) * 60 _000 ,
windowsHide : true ,
env : {
. . . process . env ,
VOID_MEMORY_MAINTENANCE_STATUS_DIR : paths.statusDir ,
VOID_MEMORY_MAINTENANCE_LOG_DIR : paths.logDir ,
} ,
} ,
) ;
await writeFile ( stdoutPath , result . stdout ? ? "" , "utf8" ) ;
await writeFile ( stderrPath , result . stderr ? ? "" , "utf8" ) ;
const durationSeconds = round3 ( ( Date . now ( ) - startedAtMs ) / 1000 ) ;
if ( result . error || result . status !== 0 ) {
const currentStatus = await readJsonFile ( paths . statusPath ) ;
if ( currentStatus ? . status === "starting" || currentStatus ? . status === "running" || currentStatus ? . status === "running_skip_model" ) {
await writeFile ( paths . statusPath , ` ${ JSON . stringify ( {
status : "failed" ,
startedAt : currentStatus.startedAt ? ? new Date ( startedAtMs ) . toISOString ( ) ,
finishedAt : new Date ( ) . toISOString ( ) ,
durationSeconds ,
stateFile : input.statePath ,
reason ,
exitCode : result.status ,
signal : result.signal ,
error : result.error instanceof Error ? result.error.message : undefined ,
stdoutPath ,
stderrPath ,
} , null , 2 ) } \ n ` , "utf8").catch(() => undefined);
}
return {
started : false ,
reason ,
statusPath : paths.statusPath ,
exitCode : result.status ,
durationSeconds ,
failureReason : result.error instanceof Error
? result . error . message
: ` memory maintenance exited with ${ result . status ? ? result . signal ? ? "unknown status" } ` ,
} ;
}
return {
started : true ,
completed : true ,
reason ,
statusPath : paths.statusPath ,
exitCode : result.status ,
durationSeconds ,
} ;
}
2026-05-20 20:31:42 +01:00
const child = spawn (
"powershell.exe" ,
[
"-NoProfile" ,
"-NonInteractive" ,
"-ExecutionPolicy" ,
"Bypass" ,
"-File" ,
resolve ( process . cwd ( ) , "scripts" , "run-void-memory-maintenance.ps1" ) ,
"-StateFilePath" ,
input . statePath ,
"-ForceDistillation" ,
] ,
{
cwd : process.cwd ( ) ,
detached : true ,
stdio : "ignore" ,
windowsHide : true ,
env : {
. . . process . env ,
VOID_MEMORY_MAINTENANCE_STATUS_DIR : paths.statusDir ,
VOID_MEMORY_MAINTENANCE_LOG_DIR : paths.logDir ,
} ,
} ,
) ;
child . unref ( ) ;
return {
started : true ,
2026-05-25 07:03:10 +01:00
reason ,
2026-05-20 20:31:42 +01:00
statusPath : paths.statusPath ,
pid : child.pid ,
} ;
} catch ( error ) {
2026-05-25 07:03:10 +01:00
await writeFile ( paths . statusPath , ` ${ JSON . stringify ( {
status : "failed_to_start" ,
startedAt : new Date ( ) . toISOString ( ) ,
stateFile : input.statePath ,
reason ,
error : error instanceof Error ? error.message : String ( error ) ,
} , null , 2 ) } \ n ` , "utf8").catch(() => undefined);
2026-05-20 20:31:42 +01:00
return {
started : false ,
reason : "spawn_failed" ,
statusPath : paths.statusPath ,
failureReason : error instanceof Error ? error.message : String ( error ) ,
} ;
}
}
function repoFaceMemoryMaintenancePaths ( statePath : string ) : {
statusDir : string ;
logDir : string ;
statusPath : string ;
} {
const stateDir = dirname ( statePath ) ;
const voidbotRoot = dirname ( stateDir ) ;
const statusDir = resolve ( voidbotRoot , "status" ) ;
const logDir = resolve ( voidbotRoot , "logs" ) ;
return {
statusDir ,
logDir ,
statusPath : resolve ( statusDir , "void-memory-maintenance.json" ) ,
} ;
}
async function readJsonFile ( path : string ) : Promise < Record < string , unknown > | undefined > {
try {
return JSON . parse ( stripLeadingBom ( await readFile ( path , "utf8" ) ) ) as Record < string , unknown > ;
} catch {
return undefined ;
}
}
function isRecentRunningStatus ( status : Record < string , unknown > | undefined , maxAgeMinutes : number ) : boolean {
if ( status ? . status !== "running" && status ? . status !== "running_skip_model" && status ? . status !== "starting" ) {
return false ;
}
const startedAtMs = typeof status . startedAt === "string" ? Date . parse ( status . startedAt ) : NaN ;
2026-05-26 14:42:44 +01:00
if ( ! Number . isFinite ( startedAtMs ) ) {
return false ;
}
if ( status . status === "starting" ) {
const hasProcessEvidence = typeof status . pid === "number" || typeof status . lockPath === "string" ;
const startingGraceMs = hasProcessEvidence ? maxAgeMinutes * 60_000 : 60_000 ;
return Date . now ( ) - startedAtMs < startingGraceMs ;
}
return Date . now ( ) - startedAtMs < maxAgeMinutes * 60 _000 ;
2026-05-20 20:31:42 +01:00
}
function isStatusCompletedAfter ( status : Record < string , unknown > | undefined , sourceTimestampMs : number ) : boolean {
if ( status ? . status !== "ok" || ! Number . isFinite ( sourceTimestampMs ) ) {
return false ;
}
const finishedAtMs = typeof status . finishedAt === "string" ? Date . parse ( status . finishedAt ) : NaN ;
return Number . isFinite ( finishedAtMs ) && finishedAtMs >= sourceTimestampMs ;
}
2026-05-24 22:26:01 +01:00
function isStatusCompletedRecently ( status : Record < string , unknown > | undefined , maxAgeMinutes : number ) : boolean {
if ( status ? . status !== "ok" ) {
return false ;
}
const finishedAtMs = typeof status . finishedAt === "string" ? Date . parse ( status . finishedAt ) : NaN ;
return Number . isFinite ( finishedAtMs ) && Date . now ( ) - finishedAtMs < maxAgeMinutes * 60 _000 ;
}
2026-05-20 20:31:42 +01:00
function newestTimestampMs ( entries : Array < { updatedAt : string } > ) : number {
return Math . max ( . . . entries . map ( ( entry ) = > Date . parse ( entry . updatedAt ) ) . filter ( Number . isFinite ) ) ;
}
function sleepCyclesEqual ( left : unknown , right : unknown ) : boolean {
return JSON . stringify ( left ) === JSON . stringify ( right ) ;
}
2026-05-18 20:36:35 +01:00
async function fetchRecentDiscordMessages ( input : {
botToken? : string ;
channelId : string ;
limit : number ;
2026-05-20 21:45:56 +01:00
ignoreBotMessages? : boolean ;
2026-05-18 20:36:35 +01:00
} ) : 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 [ ] ;
2026-05-24 03:28:40 +01:00
const sourceMessages = await Promise . all ( messages
2026-05-20 21:45:56 +01:00
. filter ( ( message ) = > ! ( input . ignoreBotMessages && message . author . bot === true ) )
2026-05-24 03:28:40 +01:00
. map ( async ( message ) = > {
const attachments = await materializeDiscordAttachments ( {
channelId : input.channelId ,
message ,
} ) ;
return {
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 ,
. . . ( attachments . length > 0 ? { attachments } : { } ) ,
} ;
} ) ) ;
return sourceMessages
2026-05-18 20:36:35 +01:00
. sort ( ( left , right ) = > Date . parse ( left . timestamp ) - Date . parse ( right . timestamp ) ) ;
}
2026-05-20 20:31:42 +01:00
async function fetchChannelSnapshots ( input : {
botToken? : string ;
channelIds : string [ ] ;
primaryChannelId : string ;
limit : number ;
2026-05-20 21:45:56 +01:00
bifrostDiscordChannelId? : string ;
2026-05-20 20:31:42 +01:00
} ) : Promise < ChannelSnapshot [ ] > {
const snapshots : ChannelSnapshot [ ] = [ ] ;
for ( const channelId of input . channelIds . filter ( ( entry ) = > entry !== input . primaryChannelId ) . slice ( 0 , 5 ) ) {
try {
snapshots . push ( {
channelId ,
messages : await fetchRecentDiscordMessages ( {
botToken : input.botToken ,
channelId ,
limit : input.limit ,
2026-05-20 21:45:56 +01:00
ignoreBotMessages : channelId === input . bifrostDiscordChannelId ,
2026-05-20 20:31:42 +01:00
} ) ,
} ) ;
} catch ( error ) {
const message = error instanceof Error ? error.message : String ( error ) ;
snapshots . push ( {
channelId ,
messages : [ {
id : ` snapshot-error: ${ channelId } ` ,
authorId : "voidbot" ,
authorName : "VoidBot" ,
content : ` Could not read recent channel context: ${ message } ` ,
timestamp : new Date ( ) . toISOString ( ) ,
isBot : true ,
} ] ,
} ) ;
}
}
return snapshots ;
}
2026-05-24 03:28:40 +01:00
async function materializeDiscordAttachments ( input : {
channelId : string ;
message : DiscordApiMessage ;
} ) : Promise < SourceMessageAttachment [ ] > {
const attachments = input . message . attachments ? ? [ ] ;
if ( attachments . length === 0 ) {
return [ ] ;
}
const materialized : SourceMessageAttachment [ ] = [ ] ;
for ( const attachment of attachments . slice ( 0 , 4 ) ) {
const kind = isDiscordImageAttachment ( attachment ) ? "image" : "other" ;
let localPath : string | undefined ;
if ( kind === "image" && isWithinFaceImageSizeLimit ( attachment ) ) {
localPath = await cacheDiscordImageAttachment ( {
channelId : input.channelId ,
messageId : input.message.id ,
attachment ,
} ) ;
}
materialized . push ( {
kind ,
id : attachment.id ,
filename : attachment.filename ,
contentType : attachment.content_type ,
url : attachment.url ,
proxyUrl : attachment.proxy_url ,
size : typeof attachment . size === "number" ? attachment.size : undefined ,
width : typeof attachment . width === "number" ? attachment.width : undefined ,
height : typeof attachment . height === "number" ? attachment.height : undefined ,
localPath ,
} ) ;
}
return materialized ;
}
function isWithinFaceImageSizeLimit ( attachment : DiscordApiAttachment ) : boolean {
return typeof attachment . size !== "number" || attachment . size <= MAX_FACE_IMAGE_ATTACHMENT_BYTES ;
}
function isDiscordImageAttachment ( attachment : DiscordApiAttachment ) : boolean {
const contentType = attachment . content_type ? . toLowerCase ( ) ? ? "" ;
if ( contentType . startsWith ( "image/" ) ) {
return true ;
}
return /\.(png|jpe?g|gif|webp)$/i . test ( attachment . filename ? ? attachment . url ? ? "" ) ;
}
async function cacheDiscordImageAttachment ( input : {
channelId : string ;
messageId : string ;
attachment : DiscordApiAttachment ;
} ) : Promise < string | undefined > {
const sourceUrl = input . attachment . url ? ? input . attachment . proxy_url ;
if ( ! sourceUrl ) {
return undefined ;
}
const safeExtension = normalizedImageExtension ( input . attachment ) ;
const fileStem = [
input . messageId ,
input . attachment . id ? ? createHash ( "sha256" ) . update ( sourceUrl ) . digest ( "hex" ) . slice ( 0 , 12 ) ,
] . join ( "-" ) ;
const directory = resolve ( ".voidbot" , "media" , "discord-images" , input . channelId ) ;
const localPath = resolve ( directory , ` ${ fileStem } ${ safeExtension } ` ) ;
try {
await stat ( localPath ) ;
return localPath ;
} catch {
// Cache miss. Fall through to fetch.
}
try {
const response = await fetch ( sourceUrl ) ;
if ( ! response . ok ) {
return undefined ;
}
const arrayBuffer = await response . arrayBuffer ( ) ;
await mkdir ( directory , { recursive : true } ) ;
await writeFile ( localPath , Buffer . from ( arrayBuffer ) ) ;
return localPath ;
} catch {
return undefined ;
}
}
function normalizedImageExtension ( attachment : DiscordApiAttachment ) : string {
const fromName = extname ( attachment . filename ? ? "" ) . toLowerCase ( ) ;
if ( /^\.(png|jpe?g|gif|webp)$/ . test ( fromName ) ) {
return fromName ;
}
const contentType = attachment . content_type ? . toLowerCase ( ) ;
switch ( contentType ) {
case "image/jpeg" :
return ".jpg" ;
case "image/gif" :
return ".gif" ;
case "image/webp" :
return ".webp" ;
case "image/png" :
default :
return ".png" ;
}
}
2026-05-20 21:45:56 +01:00
async function fetchBifrostGovernanceDigest ( input : {
bifrostRoot : string ;
repoName : string ;
agentIdentity : string ;
} ) : Promise < BifrostGovernanceDigest | undefined > {
const scriptPath = resolve ( input . bifrostRoot , "tools" , "governance-threads.mjs" ) ;
const result = spawnSync (
process . execPath ,
[
scriptPath ,
"digest" ,
"--repo" , input . repoName ,
"--agent" , input . agentIdentity ,
"--limit" , "6" ,
] ,
{
cwd : input.bifrostRoot ,
encoding : "utf8" ,
stdio : [ "ignore" , "pipe" , "pipe" ] ,
windowsHide : true ,
timeout : 30000 ,
} ,
) ;
if ( result . status !== 0 ) {
return {
generatedAt : new Date ( ) . toISOString ( ) ,
topics : [ {
id : "bifrost-digest-error" ,
title : "Bifrost governance digest unavailable" ,
jurisdictionRepoName : input.repoName ,
jurisdictionAgentIdentity : input.agentIdentity ,
status : "error" ,
summaryMarkdown : ` Could not read Bifrost governance digest: ${ result . stderr || result . error ? . message || result . stdout || "unknown failure" } ` ,
priority : 0 ,
updatedAt : new Date ( ) . toISOString ( ) ,
comments : [ ] ,
} ] ,
} ;
}
try {
return JSON . parse ( result . stdout ) as BifrostGovernanceDigest ;
} catch ( error ) {
const message = error instanceof Error ? error.message : String ( error ) ;
return {
generatedAt : new Date ( ) . toISOString ( ) ,
topics : [ {
id : "bifrost-digest-parse-error" ,
title : "Bifrost governance digest parse failure" ,
jurisdictionRepoName : input.repoName ,
jurisdictionAgentIdentity : input.agentIdentity ,
status : "error" ,
summaryMarkdown : ` Could not parse Bifrost governance digest: ${ message } ` ,
priority : 0 ,
updatedAt : new Date ( ) . toISOString ( ) ,
comments : [ ] ,
} ] ,
} ;
}
}
2026-05-18 20:36:35 +01:00
interface DiscordApiMessage {
id : string ;
content : string ;
timestamp : string ;
2026-05-24 03:28:40 +01:00
attachments? : DiscordApiAttachment [ ] ;
2026-05-18 20:36:35 +01:00
author : {
id : string ;
username : string ;
global_name? : string | null ;
bot? : boolean ;
} ;
member ? : {
nick? : string | null ;
} ;
}
2026-05-24 03:28:40 +01:00
interface DiscordApiAttachment {
id? : string ;
filename? : string ;
content_type? : string ;
size? : number ;
url? : string ;
proxy_url? : string ;
width? : number | null ;
height? : number | null ;
}
2026-05-20 20:31:42 +01:00
async function startVoidModerationTurn ( input : {
queuedAt : string ;
storageRoot : string ;
pendingMentions : RepoFacePendingMention [ ] ;
} ) : Promise < { created : boolean ; activeJobId? : string ; requestMessageId? : string ; failureReason? : string } > {
2026-05-18 19:05:09 +01:00
const runnerScript = resolve ( process . cwd ( ) , "scripts" , "run-void-moderator-rumination.ps1" ) ;
2026-05-20 20:31:42 +01:00
const statusDir = resolve ( input . storageRoot , "status" ) ;
const lockPath = resolve ( statusDir , "moderation-rumination.lock" ) ;
const statusPath = resolve ( statusDir , "moderation-rumination.json" ) ;
const pendingMentionsPath = resolve ( statusDir , "void-moderation-pending-mentions.json" ) ;
2026-05-19 08:05:48 +01:00
const launchedAt = Date . now ( ) ;
2026-05-20 20:31:42 +01:00
await mkdir ( statusDir , { recursive : true } ) ;
await writeFile (
pendingMentionsPath ,
` ${ JSON . stringify ( {
generatedAt : input.queuedAt ,
pendingMentions : input.pendingMentions ,
} , null , 2 ) } \ n ` ,
"utf8" ,
) ;
2026-05-19 08:05:48 +01:00
const launchCommand = [
2026-05-20 20:31:42 +01:00
` $ env:VOID_RUMINATION_PENDING_MENTIONS_PATH = ${ toPowerShellSingleQuotedString ( pendingMentionsPath ) } ; ` ,
2026-05-19 08:05:48 +01:00
` $ arguments = @( ${ [
"-NoProfile" ,
"-NonInteractive" ,
"-ExecutionPolicy" ,
"Bypass" ,
"-File" ,
runnerScript ,
] . map ( toPowerShellSingleQuotedString ) . join ( ", " ) } ) ; ` ,
` Start-Process -FilePath ${ toPowerShellSingleQuotedString ( "powershell.exe" ) } -ArgumentList $ arguments -WorkingDirectory ${ toPowerShellSingleQuotedString ( process . cwd ( ) ) } -WindowStyle Hidden; ` ,
] . join ( " " ) ;
2026-05-18 19:05:09 +01:00
const child = spawn (
"powershell.exe" ,
[
"-NoProfile" ,
"-NonInteractive" ,
"-ExecutionPolicy" ,
"Bypass" ,
2026-05-19 08:05:48 +01:00
"-Command" ,
launchCommand ,
2026-05-18 19:05:09 +01:00
] ,
{
cwd : process.cwd ( ) ,
stdio : "ignore" ,
windowsHide : true ,
} ,
) ;
child . unref ( ) ;
2026-05-19 08:05:48 +01:00
const handshake = await waitForVoidModerationHandshake ( {
lockPath ,
statusPath ,
launchedAt ,
timeoutMs : 60000 ,
} ) ;
if ( ! handshake . started ) {
return {
created : false ,
activeJobId : child.pid ? ` launcher-process: ${ child . pid } ` : undefined ,
2026-05-21 09:26:04 +01:00
requestMessageId : ` agent-turn:void: ${ input . queuedAt } ` ,
2026-05-19 08:05:48 +01:00
failureReason : handshake.reason ,
} ;
}
2026-05-18 19:05:09 +01:00
return {
created : true ,
2026-05-20 20:31:42 +01:00
activeJobId : ` process:void-moderation: ${ input . queuedAt } ` ,
2026-05-21 09:26:04 +01:00
requestMessageId : ` agent-turn:void: ${ input . queuedAt } ` ,
2026-05-18 19:05:09 +01:00
} ;
}
2026-05-19 08:05:48 +01:00
function toPowerShellSingleQuotedString ( value : string ) : string {
return ` ' ${ value . replace ( /'/g , "''" ) } ' ` ;
}
async function waitForVoidModerationHandshake ( input : {
lockPath : string ;
statusPath : string ;
launchedAt : number ;
timeoutMs : number ;
} ) : Promise < { started : true } | { started : false ; reason : string } > {
const deadline = Date . now ( ) + input . timeoutMs ;
while ( Date . now ( ) < deadline ) {
if ( await wasTouchedAfter ( input . lockPath , input . launchedAt ) ) {
return { started : true } ;
}
if ( await wasTouchedAfter ( input . statusPath , input . launchedAt ) ) {
return { started : true } ;
}
await sleep ( 250 ) ;
}
return {
started : false ,
reason : "void_moderation_launch_handshake_missing" ,
} ;
}
async function wasTouchedAfter ( path : string , timestampMs : number ) : Promise < boolean > {
try {
const info = await stat ( path ) ;
return info . mtimeMs >= timestampMs - 500 ;
} catch {
return false ;
}
}
function sleep ( ms : number ) : Promise < void > {
return new Promise ( ( resolveSleep ) = > setTimeout ( resolveSleep , ms ) ) ;
}
2026-05-18 19:05:09 +01:00
async function listExistingActiveTurns (
2026-05-18 11:23:44 +01:00
databaseDsn : string ,
stateStorageBackend : "file" | "postgres" ,
config : ReturnType < typeof loadConfig > ,
2026-05-20 23:37:13 +01:00
) : Promise < ActiveTurnScan > {
2026-05-18 11:23:44 +01:00
const storage = await createStateStorage ( {
backend : stateStorageBackend ,
databaseDsn ,
jobsFile : config.jobsFile ,
auditLogFile : config.auditLogFile ,
interactionMemoryFile : config.interactionMemoryFile ,
rateLimitStateFile : config.rateLimitStateFile ,
} ) ;
try {
const jobs = await storage . jobQueue . listByStates ( [ "approved" , "running" ] ) ;
2026-05-18 18:53:14 +01:00
const active = new Map < string , string > ( ) ;
2026-05-20 23:37:13 +01:00
const staleRecovered : StaleActiveTurn [ ] = [ ] ;
const staleAfterMs = Math . max ( MIN_STALE_ACTIVE_JOB_MS , config . codexExecTimeoutMs * 3 ) ;
const nowMs = Date . now ( ) ;
2026-05-18 11:23:44 +01:00
for ( const job of jobs ) {
if ( job . command !== HEARTBEAT_COMMAND ) {
continue ;
}
const match =
2026-05-21 09:26:04 +01:00
job . requestMessageId ? . match ( /^agent-turn:([^:]+):/ ) ? ?
2026-05-18 19:05:09 +01:00
job . requestMessageId ? . match ( /^agent-heartbeat:([^:]+):/ ) ? ?
2026-05-18 11:23:44 +01:00
job . requestMessageId ? . match ( /^repo-face-heartbeat:([^:]+):/ ) ? ?
job . requestMessageId ? . match ( /:repo-face:([^:]+):\d+$/ ) ;
if ( match ) {
2026-05-20 23:37:13 +01:00
const updatedMs = Date . parse ( job . updatedAt ) ;
const ageMs = Number . isFinite ( updatedMs ) ? nowMs - updatedMs : Number.POSITIVE_INFINITY ;
if ( ageMs > staleAfterMs ) {
const ageMinutes = Number . isFinite ( ageMs ) ? Math . round ( ( ageMs / 60 _000 ) * 10 ) / 10 : - 1 ;
await storage . jobQueue . markFailed (
job . id ,
2026-05-21 09:26:04 +01:00
` Repo Face CTB recovered stale active turn job after ${ ageMinutes } minutes without progress. ` ,
2026-05-20 23:37:13 +01:00
) ;
staleRecovered . push ( {
identityId : match [ 1 ] ,
jobId : job.id ,
requestMessageId : job.requestMessageId ,
state : job.state ,
updatedAt : job.updatedAt ,
ageMinutes ,
} ) ;
continue ;
}
2026-05-18 18:53:14 +01:00
active . set ( match [ 1 ] , job . id ) ;
2026-05-18 11:23:44 +01:00
}
}
2026-05-18 19:05:09 +01:00
const voidLock = await readRecentLock ( resolve ( config . storageRoot , "status" , "moderation-rumination.lock" ) , 20 ) ;
if ( voidLock ) {
active . set ( "void" , "lock:moderation-rumination" ) ;
}
2026-05-20 23:37:13 +01:00
return { active , staleRecovered } ;
2026-05-18 11:23:44 +01:00
} finally {
await storage . close ( ) ;
}
}
2026-05-18 19:05:09 +01:00
async function readRecentLock ( path : string , maxAgeMinutes : number ) : Promise < boolean > {
try {
const info = await stat ( path ) ;
const ageMs = Date . now ( ) - info . mtimeMs ;
return ageMs >= 0 && ageMs < maxAgeMinutes * 60 _000 ;
} catch {
return false ;
}
}
2026-05-18 11:23:44 +01:00
function reconcileParticipants (
existing : FaceHeartbeatParticipant [ ] ,
2026-05-18 19:05:09 +01:00
specs : ParticipantSpec [ ] ,
2026-05-18 11:23:44 +01:00
defaultChannelId : string | undefined ,
2026-05-18 18:31:35 +01:00
speedOverrides : Record < string , number > ,
heatOverrides : Record < string , number > ,
initiativeClock : number ,
baseRecoveryMinutes : number ,
globalHeat : number ,
2026-05-24 19:36:38 +01:00
pressureByIdentity : Map < string , RepoFaceRuntimePressureSnapshot > = new Map ( ) ,
2026-05-18 11:23:44 +01:00
) : FaceHeartbeatParticipant [ ] {
const existingById = new Map ( existing . map ( ( entry ) = > [ entry . identityId , entry ] ) ) ;
2026-05-18 19:05:09 +01:00
const count = Math . max ( specs . length , 1 ) ;
return specs . map ( ( spec , index ) = > {
const current = existingById . get ( spec . id ) ;
const hasChannel = spec . participantKind === "system_agent" || Boolean ( spec . allowedChannelIds [ 0 ] || defaultChannelId ) ;
2026-05-20 20:31:42 +01:00
const speed = initiativeSpeedFor ( spec , speedOverrides ) * spec . channelSpeedMultiplier ;
2026-05-18 19:05:09 +01:00
const groups = initiativeGroupsFor ( spec ) ;
const heat = heatFor ( spec , groups , globalHeat , heatOverrides ) ;
2026-05-24 19:36:38 +01:00
const urgency = urgencyFor ( pressureByIdentity . get ( spec . id ) ) ;
2026-05-25 19:53:44 +01:00
const effectiveSpeed = clamp ( speed * heat * urgency , 0.01 , 12 ) ;
2026-05-24 19:36:38 +01:00
const defaultNextTurnAt = Number . isFinite ( current ? . nextTurnAt )
2026-05-18 18:31:35 +01:00
? current . nextTurnAt
: initiativeClock + ( ( baseRecoveryMinutes / count ) * index ) ;
2026-05-24 19:36:38 +01:00
const nextTurnAt = pullNextTurnTowardUrgency (
defaultNextTurnAt ,
initiativeClock ,
baseRecoveryMinutes ,
effectiveSpeed ,
urgency ,
) ;
2026-05-18 11:23:44 +01:00
if ( current ) {
return {
. . . current ,
2026-05-18 19:05:09 +01:00
participantKind : spec.participantKind ,
turnKind : spec.turnKind ,
repoName : spec.repoName ,
displayName : spec.displayName ,
2026-05-18 18:31:35 +01:00
initiativeSpeed : speed ,
groups ,
heat ,
effectiveSpeed ,
baseRecoveryMinutes ,
nextTurnAt ,
2026-05-24 19:36:38 +01:00
constraints : mergeOptionalString (
2026-05-18 18:31:35 +01:00
mergeStrings (
2026-05-24 19:36:38 +01:00
mergeStrings (
current . constraints ,
"Agent runtime uses CTB-style turns." ,
) ,
"Wall-clock elapsed time advances initiative; heat changes recovery speed but does not fast-forward time." ,
2026-05-18 18:31:35 +01:00
) ,
2026-05-24 19:36:38 +01:00
urgency > 1
? "Typed speaking pressure raises initiative urgency and may pull the next turn closer."
: undefined ,
2026-05-18 18:31:35 +01:00
) ,
2026-05-18 11:23:44 +01:00
status : hasChannel
2026-05-22 22:52:41 +01:00
? current . status === "withdrawn" || current . status === "blocked"
? current . status
2026-05-18 11:23:44 +01:00
: "active"
: "blocked" ,
} ;
}
return {
2026-05-18 19:05:09 +01:00
identityId : spec.id ,
participantKind : spec.participantKind ,
turnKind : spec.turnKind ,
repoName : spec.repoName ,
displayName : spec.displayName ,
2026-05-18 11:23:44 +01:00
initiativeSpeed : speed ,
2026-05-18 19:05:09 +01:00
reactionBias : reactionBiasFor ( spec ) ,
interruptThreshold : interruptThresholdFor ( spec ) ,
2026-05-18 11:23:44 +01:00
currentLoad : 0 ,
status : hasChannel ? "active" : "blocked" ,
2026-05-18 18:31:35 +01:00
groups ,
heat ,
effectiveSpeed ,
baseRecoveryMinutes ,
nextTurnAt ,
2026-05-18 11:23:44 +01:00
queuedCount : 0 ,
constraints : [
2026-05-21 09:26:04 +01:00
"Agent runtime uses CTB-style turns." ,
2026-05-20 20:31:42 +01:00
"Wall-clock elapsed time advances initiative; heat changes recovery speed but does not fast-forward time." ,
2026-05-24 19:36:38 +01:00
. . . ( urgency > 1 ? [ "Typed speaking pressure raises initiative urgency and may pull the next turn closer." ] : [ ] ) ,
2026-05-18 11:23:44 +01:00
"Worker final summaries are not auto-posted as the base bot." ,
] ,
} ;
} ) ;
}
2026-05-24 19:36:38 +01:00
function urgencyFor ( pressure : RepoFaceRuntimePressureSnapshot | undefined ) : number {
if ( ! pressure ) {
return 1 ;
}
const urgency =
pressure . needToSpeak * 1.35 +
pressure . noveltyPressure * 0.35 +
pressure . confessionPressure * 0.2 ;
return round3 ( clamp ( 1 + urgency , 1 , 3.2 ) ) ;
}
function pullNextTurnTowardUrgency (
nextTurnAt : number ,
initiativeClock : number ,
baseRecoveryMinutes : number ,
effectiveSpeed : number ,
urgency : number ,
) : number {
if ( urgency <= 1.05 || nextTurnAt <= initiativeClock ) {
return nextTurnAt ;
}
2026-05-25 19:53:44 +01:00
const maxWait = Math . max ( 0.75 , baseRecoveryMinutes / Math . max ( effectiveSpeed , 0.01 ) ) ;
2026-05-24 19:36:38 +01:00
return Math . min ( nextTurnAt , round3 ( initiativeClock + maxWait ) ) ;
}
2026-05-18 18:53:14 +01:00
function applyActiveTurnFreeze (
participant : FaceHeartbeatParticipant ,
activeJobId : string | undefined ,
state : FaceHeartbeatState ,
completedThisTick : Set < string > ,
) : FaceHeartbeatParticipant {
if ( activeJobId ) {
return {
. . . participant ,
currentLoad : 1 ,
activeJobId ,
activeTurnStartedAt : participant.activeTurnStartedAt ? ? participant . lastTurnAt ? ? state . initiativeClock ,
} ;
}
if ( participant . currentLoad >= 1 || participant . activeTurnStartedAt !== undefined || participant . activeJobId ) {
const completedTurnStartedAt = participant . activeTurnStartedAt ? ? participant . lastTurnAt ? ? state . initiativeClock ;
const unfrozen = {
. . . participant ,
currentLoad : 0 ,
activeTurnStartedAt : undefined ,
activeJobId : undefined ,
} ;
const recoveryMinutes = recoveryFor ( unfrozen ) ;
unfrozen . nextTurnAt = Math . max ( state . initiativeClock , completedTurnStartedAt ) + recoveryMinutes ;
completedThisTick . add ( participant . identityId ) ;
state . history . push ( {
type : "turn_completed" ,
identityId : participant.identityId ,
completedAtClock : state.initiativeClock ,
startedAtClock : completedTurnStartedAt ,
nextTurnAt : unfrozen.nextTurnAt ,
recoveryMinutes ,
heat : participant.heat ,
effectiveSpeed : participant.effectiveSpeed ,
} ) ;
return unfrozen ;
}
return {
. . . participant ,
currentLoad : 0 ,
} ;
}
2026-05-18 11:23:44 +01:00
function selectReadyParticipants (
2026-05-18 18:31:35 +01:00
state : FaceHeartbeatState ,
2026-05-18 11:23:44 +01:00
maxJobs : number ,
2026-05-18 18:53:14 +01:00
completedThisTick : Set < string > ,
2026-05-20 20:31:42 +01:00
restStates : Map < string , RepoFaceRestSnapshot > ,
2026-05-22 23:23:25 +01:00
idleCooling : IdleCoolingSnapshot ,
2026-05-24 22:45:17 +01:00
manualOverrideIdentities : Set < string > ,
2026-05-18 11:23:44 +01:00
) : FaceHeartbeatParticipant [ ] {
2026-05-19 11:56:01 +01:00
const pendingMentionCounts = countPendingMentionsByIdentity ( state . pendingMentions ) ;
2026-05-18 18:31:35 +01:00
const eligible = state . participants
2026-05-18 11:23:44 +01:00
. filter ( ( participant ) = > {
2026-05-20 20:31:42 +01:00
const pendingMentionCount = pendingMentionCounts . get ( participant . identityId ) ? ? 0 ;
2026-05-24 22:45:17 +01:00
const manualOverrideCount = manualOverrideIdentities . has ( participant . identityId ) ? 1 : 0 ;
2026-05-20 20:31:42 +01:00
const restState = restStates . get ( participant . identityId ) ;
2026-05-18 11:23:44 +01:00
return (
participant . status === "active" &&
2026-05-18 18:53:14 +01:00
participant . currentLoad < 1 &&
2026-05-20 20:31:42 +01:00
! completedThisTick . has ( participant . identityId ) &&
! (
participant . participantKind === "repo_face" &&
pendingMentionCount === 0 &&
2026-05-24 22:45:17 +01:00
manualOverrideCount === 0 &&
2026-05-24 22:26:01 +01:00
restState ? . isNapping === true &&
idleCooling . napModeActive !== true
2026-05-20 20:31:42 +01:00
)
2026-05-18 11:23:44 +01:00
) ;
2026-05-18 18:31:35 +01:00
} ) ;
if ( eligible . length === 0 ) {
return [ ] ;
}
2026-05-22 23:23:25 +01:00
const ready = eligible
2026-05-18 18:31:35 +01:00
. filter ( ( participant ) = > participant . nextTurnAt <= state . initiativeClock )
2026-05-18 11:23:44 +01:00
. sort ( ( left , right ) = > {
2026-05-24 22:45:17 +01:00
const manualDelta =
Number ( manualOverrideIdentities . has ( right . identityId ) ) -
Number ( manualOverrideIdentities . has ( left . identityId ) ) ;
if ( manualDelta !== 0 ) {
return manualDelta ;
}
2026-05-19 11:56:01 +01:00
const pendingDelta =
( pendingMentionCounts . get ( right . identityId ) ? ? 0 ) -
( pendingMentionCounts . get ( left . identityId ) ? ? 0 ) ;
if ( pendingDelta !== 0 ) {
return pendingDelta ;
}
2026-05-18 18:31:35 +01:00
const readyDelta = left . nextTurnAt - right . nextTurnAt ;
2026-05-18 11:23:44 +01:00
if ( readyDelta !== 0 ) {
return readyDelta ;
}
if ( right . reactionBias !== left . reactionBias ) {
return right . reactionBias - left . reactionBias ;
}
2026-05-18 18:31:35 +01:00
if ( right . effectiveSpeed !== left . effectiveSpeed ) {
return right . effectiveSpeed - left . effectiveSpeed ;
2026-05-18 11:23:44 +01:00
}
return left . identityId . localeCompare ( right . identityId ) ;
2026-05-22 23:23:25 +01:00
} ) ;
if ( ! idleCooling . enabled || ! idleCooling . active ) {
return ready . slice ( 0 , maxJobs ) ;
}
const mentioned = ready . filter ( ( participant ) = > ( pendingMentionCounts . get ( participant . identityId ) ? ? 0 ) > 0 ) ;
2026-05-24 22:45:17 +01:00
const manual = ready . filter ( ( participant ) = > manualOverrideIdentities . has ( participant . identityId ) ) ;
const prompted = uniqueParticipants ( [ . . . manual , . . . mentioned ] ) ;
const unprompted = ready . filter ( ( participant ) = >
( pendingMentionCounts . get ( participant . identityId ) ? ? 0 ) === 0 &&
! manualOverrideIdentities . has ( participant . identityId )
) ;
2026-05-24 22:26:01 +01:00
const napRuns = idleCooling . napModeActive === true
? unprompted . filter ( ( participant ) = > restStates . get ( participant . identityId ) ? . isNapping === true )
: [ ] ;
const awakeRuns = unprompted . filter ( ( participant ) = > restStates . get ( participant . identityId ) ? . isNapping !== true ) ;
2026-05-22 23:23:25 +01:00
const coolingAllowsUnpromptedTurn =
! idleCooling . nextUnpromptedTurnAllowedAt ||
Date . parse ( idleCooling . nextUnpromptedTurnAllowedAt ) <= Date . now ( ) ;
2026-05-24 22:45:17 +01:00
const cooled = coolingAllowsUnpromptedTurn && prompted . length < maxJobs
2026-05-24 22:26:01 +01:00
? ( napRuns [ 0 ] ? napRuns : awakeRuns ) . slice ( 0 , 1 )
: [ ] ;
2026-05-22 23:23:25 +01:00
2026-05-24 22:45:17 +01:00
return [ . . . prompted , . . . cooled ] . slice ( 0 , maxJobs ) ;
}
function uniqueParticipants ( participants : FaceHeartbeatParticipant [ ] ) : FaceHeartbeatParticipant [ ] {
const seen = new Set < string > ( ) ;
const unique : FaceHeartbeatParticipant [ ] = [ ] ;
for ( const participant of participants ) {
if ( seen . has ( participant . identityId ) ) {
continue ;
}
seen . add ( participant . identityId ) ;
unique . push ( participant ) ;
}
return unique ;
2026-05-18 11:23:44 +01:00
}
2026-05-20 20:31:42 +01:00
function advanceInitiativeClockFromWallClock ( state : FaceHeartbeatState , now : Date ) : void {
const lastTickMs = Date . parse ( state . lastTickAt ? ? "" ) ;
if ( ! Number . isFinite ( lastTickMs ) ) {
return ;
}
const elapsedMinutes = ( now . getTime ( ) - lastTickMs ) / 60 _000 ;
if ( elapsedMinutes <= 0 ) {
return ;
}
const boundedElapsedMinutes = Math . min ( elapsedMinutes , 60 ) ;
state . initiativeClock = round3 ( state . initiativeClock + boundedElapsedMinutes ) ;
}
function rescheduleStaleOverdueParticipants ( state : FaceHeartbeatState ) : void {
const activeParticipants = state . participants . filter ( ( participant ) = > participant . status === "active" ) ;
const count = Math . max ( activeParticipants . length , 1 ) ;
let rescheduledCount = 0 ;
activeParticipants . forEach ( ( participant , index ) = > {
const staleThreshold = Math . max ( participant . baseRecoveryMinutes , 15 ) ;
if ( participant . nextTurnAt >= state . initiativeClock - staleThreshold ) {
return ;
}
participant . nextTurnAt = round3 ( state . initiativeClock + ( participant . baseRecoveryMinutes / count ) * index ) ;
rescheduledCount += 1 ;
} ) ;
if ( rescheduledCount > 0 ) {
state . history . push ( {
type : "wall_clock_resync" ,
rescheduledCount ,
initiativeClock : state.initiativeClock ,
} ) ;
}
}
2026-05-19 11:56:01 +01:00
function applyPendingMentionPriority ( state : FaceHeartbeatState ) : void {
const pendingMentionCounts = countPendingMentionsByIdentity ( state . pendingMentions ) ;
for ( const participant of state . participants ) {
if (
participant . status === "active" &&
participant . currentLoad < 1 &&
( pendingMentionCounts . get ( participant . identityId ) ? ? 0 ) > 0
) {
participant . nextTurnAt = Math . min ( participant . nextTurnAt , state . initiativeClock ) ;
}
}
}
2026-05-24 22:45:17 +01:00
function applyManualTurnRequests ( state : FaceHeartbeatState , now : Date ) : Set < string > {
const manualOverrideIdentities = new Set < string > ( ) ;
const participantsByIdentity = new Map ( state . participants . map ( ( participant ) = > [ participant . identityId , participant ] ) ) ;
let changed = false ;
for ( const request of state . controls . manualTurnRequests ) {
if ( request . status !== "pending" && request . status !== "applied" ) {
continue ;
}
const participant = participantsByIdentity . get ( request . identityId ) ;
if ( ! participant || participant . status !== "active" ) {
request . status = "rejected" ;
request . note = "No active participant with that identity." ;
changed = true ;
continue ;
}
if ( participant . currentLoad >= 1 || participant . activeJobId ) {
request . status = "applied" ;
request . note = "Participant is already running; request will clear after the turn closes." ;
manualOverrideIdentities . add ( request . identityId ) ;
changed = true ;
continue ;
}
participant . nextTurnAt = Math . min ( participant . nextTurnAt , state . initiativeClock ) ;
manualOverrideIdentities . add ( request . identityId ) ;
if ( request . status !== "applied" ) {
request . status = "applied" ;
request . note = "Pulled to the front of the CTB queue." ;
state . history . push ( {
type : "manual_turn_override_applied" ,
identityId : request.identityId ,
requestId : request.id ,
appliedAt : now.toISOString ( ) ,
initiativeClock : state.initiativeClock ,
} ) ;
changed = true ;
}
}
if ( changed ) {
state . controls . updatedAt = now . toISOString ( ) ;
}
state . controls . manualTurnRequests = state . controls . manualTurnRequests . slice ( - 20 ) ;
return manualOverrideIdentities ;
}
2026-05-26 15:06:56 +01:00
function reinitializeCtbSpacingOnWake ( input : {
state : FaceHeartbeatState ;
restStates : Map < string , RepoFaceRestSnapshot > ;
idleCooling : IdleCoolingSnapshot ;
maxJobs : number ;
manualOverrideIdentities : Set < string > ;
} ) : void {
const active = input . state . participants . filter ( ( participant ) = >
participant . status === "active" &&
participant . currentLoad < 1 &&
! participant . activeJobId
) ;
if ( active . length <= input . maxJobs ) {
return ;
}
const pendingMentionCounts = countPendingMentionsByIdentity ( input . state . pendingMentions ) ;
const ready = active . filter ( ( participant ) = > participant . nextTurnAt <= input . state . initiativeClock ) ;
const readyRatio = ready . length / Math . max ( active . length , 1 ) ;
const nappingCount = active . filter ( ( participant ) = > input . restStates . get ( participant . identityId ) ? . isNapping === true ) . length ;
const previousHistory = input . state . history . slice ( - 20 ) ;
const heatBacklogAllowed =
input . state . globalHeat > 1.5 ||
active . some ( ( participant ) = > participant . heat > 1.5 || participant . effectiveSpeed > 6 ) ;
const lastPauseIndex = findLastHistoryIndex ( previousHistory , ( entry ) = >
entry . type === "skipped" && entry . reason === "agent_swarm_paused"
) ;
const lastCollectiveNapIndex = findLastHistoryIndex ( previousHistory , ( entry ) = >
entry . type === "repo_face_memory_maintenance_tick" &&
isRecord ( entry . idleCooling ) &&
entry . idleCooling . napModeActive === true
) ;
const lastSpacingIndex = findLastHistoryIndex ( previousHistory , ( entry ) = >
entry . type === "ctb_spacing_reinitialized"
) ;
const recentlyPaused = lastPauseIndex >= 0 && lastPauseIndex > lastSpacingIndex ;
const recentlyCollectiveNapping = lastCollectiveNapIndex >= 0 && lastCollectiveNapIndex > lastSpacingIndex ;
const allReadyCollapse = ! heatBacklogAllowed && ready . length > input . maxJobs && readyRatio >= 0.75 ;
const coldStartCollapse = ready . length > input . maxJobs && active . every ( ( participant ) = > participant . queuedCount === 0 ) ;
const wakingFromCollectiveSleep = recentlyCollectiveNapping && input . idleCooling . napModeActive !== true ;
const wakingFromPause = recentlyPaused ;
if ( ! allReadyCollapse && ! coldStartCollapse && ! wakingFromPause && ! wakingFromCollectiveSleep ) {
return ;
}
const protectedIdentities = new Set < string > ( ) ;
for ( const participant of active ) {
if (
( pendingMentionCounts . get ( participant . identityId ) ? ? 0 ) > 0 ||
input . manualOverrideIdentities . has ( participant . identityId )
) {
protectedIdentities . add ( participant . identityId ) ;
}
}
const unprotected = active
. filter ( ( participant ) = > ! protectedIdentities . has ( participant . identityId ) )
. sort ( ( left , right ) = > {
const dueDelta = left . nextTurnAt - right . nextTurnAt ;
if ( dueDelta !== 0 ) {
return dueDelta ;
}
if ( right . effectiveSpeed !== left . effectiveSpeed ) {
return right . effectiveSpeed - left . effectiveSpeed ;
}
return left . identityId . localeCompare ( right . identityId ) ;
} ) ;
if ( unprotected . length === 0 ) {
return ;
}
const immediateSlots = Math . max ( 0 , input . maxJobs - protectedIdentities . size ) ;
const spacingMinutes = round3 ( input . state . baseRecoveryMinutes / Math . max ( active . length , 1 ) ) ;
let rescheduledCount = 0 ;
unprotected . forEach ( ( participant , index ) = > {
const delayedSlot = Math . max ( 0 , index - immediateSlots + 1 ) ;
const targetTurnAt = round3 ( input . state . initiativeClock + spacingMinutes * delayedSlot ) ;
if ( participant . nextTurnAt !== targetTurnAt ) {
participant . nextTurnAt = targetTurnAt ;
rescheduledCount += 1 ;
}
} ) ;
if ( rescheduledCount > 0 ) {
input . state . history . push ( {
type : "ctb_spacing_reinitialized" ,
reason : wakingFromPause
? "wake_from_swarm_pause"
: wakingFromCollectiveSleep
? "wake_from_collective_sleep"
: coldStartCollapse
? "cold_start_ready_collapse"
: "ready_collapse" ,
rescheduledCount ,
readyCountBefore : ready.length ,
activeCount : active.length ,
nappingCount ,
protectedCount : protectedIdentities.size ,
immediateSlots ,
spacingMinutes ,
initiativeClock : input.state.initiativeClock ,
} ) ;
}
}
2026-05-24 22:45:17 +01:00
function consumeManualTurnRequests (
state : FaceHeartbeatState ,
identityId : string ,
status : ManualTurnRequest [ "status" ] ,
note : string ,
) : void {
const now = new Date ( ) . toISOString ( ) ;
let changed = false ;
for ( const request of state . controls . manualTurnRequests ) {
if ( ( request . status === "pending" || request . status === "applied" ) && request . identityId === identityId ) {
request . status = status ;
request . note = note ;
changed = true ;
}
}
if ( changed ) {
state . controls . updatedAt = now ;
}
}
2026-05-19 11:56:01 +01:00
function pendingMentionsForParticipant (
state : FaceHeartbeatState ,
identityId : string ,
) : RepoFacePendingMention [ ] {
return state . pendingMentions
. filter ( ( mention ) = > mention . identityId === identityId )
. sort ( ( left , right ) = > Date . parse ( left . queuedAt ) - Date . parse ( right . queuedAt ) ) ;
}
function countPendingMentionsByIdentity (
pendingMentions : RepoFacePendingMention [ ] ,
) : Map < string , number > {
const counts = new Map < string , number > ( ) ;
for ( const mention of pendingMentions ) {
counts . set ( mention . identityId , ( counts . get ( mention . identityId ) ? ? 0 ) + 1 ) ;
}
return counts ;
}
2026-05-26 15:06:56 +01:00
function findLastHistoryIndex (
history : Array < Record < string , unknown > > ,
predicate : ( entry : Record < string , unknown > ) = > boolean ,
) : number {
for ( let index = history . length - 1 ; index >= 0 ; index -= 1 ) {
if ( predicate ( history [ index ] ) ) {
return index ;
}
}
return - 1 ;
}
2026-05-22 23:23:25 +01:00
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 ,
2026-05-24 22:26:01 +01:00
napAfterMinutes : policy.napAfterMinutes ,
2026-05-22 23:23:25 +01:00
lastUnpromptedTurnQueuedAt : newestUnpromptedTurnQueuedAt ( input . state ) ,
} ;
if ( ! policy . enabled ) {
return { . . . base , reason : "disabled" } ;
}
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 ;
}
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 ( ! newestHumanActivityAt ) {
return {
. . . base ,
active : true ,
2026-05-24 22:26:01 +01:00
napModeActive : true ,
2026-05-22 23:23:25 +01:00
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 ) ;
2026-05-24 22:26:01 +01:00
const active = idleForMinutes >= policy . idleAfterMinutes ;
2026-05-22 23:23:25 +01:00
return {
. . . base ,
2026-05-24 22:26:01 +01:00
active ,
napModeActive : active && idleForMinutes >= policy . napAfterMinutes ,
2026-05-22 23:23:25 +01:00
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 ;
}
2026-05-18 11:23:44 +01:00
function buildHeartbeatPrompt ( input : {
identity : RepoDiscordIdentity ;
channelId : string ;
2026-05-20 20:31:42 +01:00
channelPlan : RepoFaceChannelPlan ;
channelSnapshots : ChannelSnapshot [ ] ;
recentMessages : SourceMessage [ ] ;
2026-05-21 11:40:23 +01:00
memorySurface? : string ;
2026-05-22 00:43:47 +01:00
repoActivitySurface? : string ;
2026-05-21 13:40:40 +01:00
conversationMemorySurface? : string ;
2026-05-22 23:39:00 +01:00
humanPronounGuidance? : RepoFaceHumanPronounGuidance [ ] ;
2026-05-20 21:45:56 +01:00
bifrostDigest? : BifrostGovernanceDigest ;
2026-05-18 11:23:44 +01:00
participant : FaceHeartbeatParticipant ;
2026-05-19 11:56:01 +01:00
pendingMentions : RepoFacePendingMention [ ] ;
2026-05-19 08:16:06 +01:00
jurisdictionDive : JurisdictionDiveDirective ;
2026-05-19 16:30:51 +01:00
githubActionsEnabled : boolean ;
2026-05-24 02:59:21 +01:00
globalAgentDoctrine : string ;
2026-05-18 11:23:44 +01:00
} ) : string {
2026-05-21 10:26:07 +01:00
return loadPromptTemplate ( "repo-face-turn.prompt.md" , {
displayName : input.identity.displayName ,
identityId : input.identity.id ,
repoName : input.identity.repoName ,
2026-05-21 12:06:52 +01:00
identityDoctrine : renderRepoCharacterIdentityDoctrine ( input . identity ) ,
2026-05-24 02:59:21 +01:00
globalAgentDoctrine : input.globalAgentDoctrine ,
2026-05-21 10:26:07 +01:00
channelId : input.channelId ,
2026-05-21 11:40:23 +01:00
memorySurface : input.memorySurface ? ? ` - ${ input . identity . displayName } has no strong personal memory surface yet. Let the attached conversation and repo evidence wake something specific. ` ,
2026-05-22 00:43:47 +01:00
repoActivitySurface : input.repoActivitySurface ? ? "- No recent home repo activity was attached for this turn." ,
2026-05-21 23:49:07 +01:00
conversationMemorySurface : input.conversationMemorySurface ? ? "- No recent conversation transcript was attached for this turn." ,
2026-05-22 23:39:00 +01:00
humanPronounDirective : renderRepoFaceHumanPronounFacts ( input . humanPronounGuidance ? ? [ ] )
? ? "Known human pronoun guidance:\n- No explicit human pronoun guidance is attached for this turn. Use names or neutral phrasing instead of guessing." ,
2026-05-21 13:27:38 +01:00
turnSituationDirective : renderTurnSituationDirective ( {
identity : input.identity ,
participant : input.participant ,
recentMessages : input.recentMessages ,
channelSnapshots : input.channelSnapshots ,
pendingMentions : input.pendingMentions ,
} ) ,
2026-05-21 10:26:07 +01:00
bifrostDigestDirective : renderBifrostGovernanceDigestDirective ( input . bifrostDigest ) ,
2026-05-21 13:40:40 +01:00
channelPermissionDirective : renderChannelPermissionDirective ( input . channelPlan ) ,
2026-05-21 13:45:54 +01:00
researchCapabilitiesDirective : renderResearchCapabilitiesDirective ( input . identity ) ,
2026-05-21 10:26:07 +01:00
socialEmbodimentDirective : renderSocialEmbodimentDirective ( input . identity ) ,
jurisdictionRespectDirective : renderJurisdictionRespectDirective ( input . identity ) ,
comedyImprovDirective : renderComedyImprovDirective ( input . identity ) ,
worldbuildingPublicationDirective : renderWorldbuildingPublicationDirective ( input . identity ) ,
jurisdictionDiveLine : input.jurisdictionDive.promptLine ,
githubActionsEnabled : input.githubActionsEnabled ,
} ) ;
2026-05-18 11:23:44 +01:00
}
2026-05-21 13:07:00 +01:00
async function assembleRepoFaceTurnPrompt ( input : {
config : ReturnType < typeof loadConfig > ;
identityId : string ;
outPath? : string ;
memorySurfacePath? : string ;
2026-05-21 13:40:40 +01:00
conversationSurfacePath? : string ;
2026-05-21 13:07:00 +01:00
} ) : Promise < {
ok : true ;
identityId : string ;
promptLength : number ;
outPath? : string ;
memorySurfacePath? : string ;
2026-05-21 13:40:40 +01:00
conversationSurfacePath? : string ;
2026-05-21 13:07:00 +01:00
} > {
const faceRegistry = await loadFaceIdentityRegistry ( input . config . repoDiscordIdentitiesPath ) ;
const registry = faceRegistryAsRepoDiscordRegistry ( faceRegistry ) ;
const identity = registry . identities . find (
( entry ) = > entry . id . toLowerCase ( ) === input . identityId . toLowerCase ( ) ,
) ;
if ( ! identity ) {
throw new Error ( ` Unknown repo Face identity: ${ input . identityId } ` ) ;
}
const channelPlan = buildChannelPlan ( identity , input . config . repoFaceHeartbeats . defaultChannelId ) ;
const channelId = channelPlan . primaryChannelId ;
if ( ! channelId ) {
throw new Error ( ` No prompt assembly channel is configured for ${ identity . id } . ` ) ;
}
2026-05-22 14:57:28 +01:00
const [ recentMessages , channelSnapshots , bifrostDigest ] = await Promise . all ( [
2026-05-21 13:07:00 +01:00
fetchRecentDiscordMessages ( {
botToken : input.config.botToken ,
channelId ,
limit : 15 ,
ignoreBotMessages : channelId === input . config . bifrostDiscordChannelId ,
} ) ,
fetchChannelSnapshots ( {
botToken : input.config.botToken ,
channelIds : channelPlan.snapshotChannelIds ,
primaryChannelId : channelId ,
limit : 6 ,
bifrostDiscordChannelId : input.config.bifrostDiscordChannelId ,
} ) ,
2026-05-21 20:48:02 +01:00
input . config . repoFaceBifrostEnabled
? fetchBifrostGovernanceDigest ( {
bifrostRoot : input.config.bifrostRoot ,
repoName : identity.repoName ,
agentIdentity : identity.id ,
} )
: Promise . resolve ( undefined ) ,
2026-05-21 13:07:00 +01:00
] ) ;
2026-05-22 23:39:00 +01:00
const roomContext = {
recentMessages ,
channelSnapshots ,
} ;
const humanPronounGuidance = await loadRepoFaceHumanPronounGuidance ( input . config , roomContext ) ;
2026-05-22 14:57:28 +01:00
const memorySurface = input . memorySurfacePath
? await readOptionalMemorySurface ( input . memorySurfacePath )
2026-05-22 23:39:00 +01:00
: await renderRepoFaceMemorySurfaceForTurn (
identity ,
input . config ,
registry . identities ,
roomContext ,
humanPronounGuidance ,
) ;
2026-05-22 00:43:47 +01:00
const repoActivitySurface = renderRepoFaceRepoActivitySurface ( identity , input . config ) ;
2026-05-24 02:59:21 +01:00
const globalAgentDoctrine = await loadGlobalAgentDoctrine ( ) ;
2026-05-21 21:45:31 +01:00
const conversationMemorySurface = input . conversationSurfacePath
? await readOptionalMemorySurface ( input . conversationSurfacePath )
2026-05-21 23:49:07 +01:00
: renderRepoFaceConversationTranscript ( {
2026-05-21 21:45:31 +01:00
identity ,
recentMessages ,
channelSnapshots ,
pendingMentions : [ ] ,
2026-05-21 23:49:07 +01:00
channelPlan ,
2026-05-21 21:45:31 +01:00
} ) ;
2026-05-21 13:07:00 +01:00
const participant = buildInspectionParticipant (
identity ,
input . config . repoFaceHeartbeats . baseRecoveryMinutes ,
) ;
const prompt = buildHeartbeatPrompt ( {
identity ,
channelId ,
channelPlan ,
channelSnapshots ,
recentMessages ,
memorySurface ,
2026-05-22 00:43:47 +01:00
repoActivitySurface ,
2026-05-21 13:40:40 +01:00
conversationMemorySurface ,
2026-05-22 23:39:00 +01:00
humanPronounGuidance ,
2026-05-21 13:07:00 +01:00
bifrostDigest ,
participant ,
pendingMentions : [ ] ,
jurisdictionDive : buildJurisdictionDiveDirective ( identity , participant ) ,
githubActionsEnabled : input.config.repoFaceGithubActionsEnabled ,
2026-05-24 02:59:21 +01:00
globalAgentDoctrine ,
2026-05-21 13:07:00 +01:00
} ) ;
if ( input . outPath ) {
const outPath = resolve ( input . outPath ) ;
await mkdir ( dirname ( outPath ) , { recursive : true } ) ;
await writeFile ( outPath , prompt , "utf8" ) ;
}
return {
ok : true ,
identityId : identity.id ,
promptLength : prompt.length ,
outPath : input.outPath ? resolve ( input . outPath ) : undefined ,
memorySurfacePath : input.memorySurfacePath ? resolve ( input . memorySurfacePath ) : undefined ,
2026-05-21 13:40:40 +01:00
conversationSurfacePath : input.conversationSurfacePath ? resolve ( input . conversationSurfacePath ) : undefined ,
2026-05-21 13:07:00 +01:00
} ;
}
2026-05-24 02:59:21 +01:00
async function loadGlobalAgentDoctrine ( ) : Promise < string > {
const candidates = [
process . env . CODEX_HOME ? resolve ( process . env . CODEX_HOME , "AGENTS.md" ) : undefined ,
process . env . USERPROFILE ? resolve ( process . env . USERPROFILE , ".codex" , "AGENTS.md" ) : undefined ,
resolve ( homedir ( ) , ".codex" , "AGENTS.md" ) ,
] . filter ( ( value ) : value is string = > typeof value === "string" && value . trim ( ) . length > 0 ) ;
const uniqueCandidates = [ . . . new Set ( candidates ) ] ;
const errors : string [ ] = [ ] ;
for ( const candidate of uniqueCandidates ) {
try {
const content = await readFile ( candidate , "utf8" ) ;
if ( content . trim ( ) . length > 0 ) {
return content . trim ( ) ;
}
errors . push ( ` ${ candidate } : empty file ` ) ;
} catch ( error ) {
const message = error instanceof Error ? error.message : String ( error ) ;
errors . push ( ` ${ candidate } : ${ message } ` ) ;
}
}
return [
"# Global Agent Instructions Unavailable" ,
"" ,
"The Face prompt attempted to load the global Codex AGENTS.md file, but no readable file was found." ,
"This is not a replacement doctrine. Treat it as an inspection failure and avoid claiming global guidance was available for this turn." ,
"" ,
"Attempted paths:" ,
. . . errors . map ( ( error ) = > ` - ${ error } ` ) ,
] . join ( "\n" ) ;
}
2026-05-21 17:24:37 +01:00
async function renderRepoFaceMemorySurfaceForTurn (
identity : RepoDiscordIdentity ,
2026-05-21 21:06:11 +01:00
config : ReturnType < typeof loadConfig > ,
2026-05-22 13:33:07 +01:00
registryIdentities : RepoDiscordIdentity [ ] = [ ] ,
2026-05-22 14:57:28 +01:00
roomContext ? : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
2026-05-22 23:39:00 +01:00
humanPronounGuidance? : RepoFaceHumanPronounGuidance [ ] ,
2026-05-21 17:24:37 +01:00
) : Promise < string > {
2026-05-21 21:06:11 +01:00
const statePath = resolveRepoFaceStatePath ( identity , config . storageRoot ) ;
2026-05-21 17:24:37 +01:00
const typedState = await loadVoidSelfStateTypedDocuments ( { canonicalPath : statePath } ) ;
2026-05-24 06:11:47 +01:00
const curiosityGraphFacts = roomContext
? await renderRepoFaceCuriosityGraphFacts ( identity , config , typedState , roomContext )
: undefined ;
2026-05-22 15:59:49 +01:00
const statePacket = renderRepoFaceStatePacket (
identity ,
typedState ,
registryIdentities ,
roomContext ,
2026-05-22 23:39:00 +01:00
humanPronounGuidance ? ? await loadRepoFaceHumanPronounGuidance ( config , roomContext ) ,
2026-05-24 06:11:47 +01:00
curiosityGraphFacts ,
2026-05-22 15:59:49 +01:00
) ;
2026-05-21 21:06:11 +01:00
if ( ! config . repoFaceHeartbeats . stateProjectorEnabled ) {
return rejectLeakyMemorySurface ( statePacket ) ;
}
return projectRepoFaceMemorySurface ( {
identity ,
statePacket ,
config ,
} ) ;
2026-05-21 17:24:37 +01:00
}
2026-05-21 21:06:11 +01:00
function renderRepoFaceStatePacket (
2026-05-21 17:24:37 +01:00
identity : RepoDiscordIdentity ,
state : VoidSelfStateTypedProjection ,
2026-05-22 13:33:07 +01:00
registryIdentities : RepoDiscordIdentity [ ] = [ ] ,
2026-05-22 14:57:28 +01:00
roomContext ? : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
2026-05-22 15:59:49 +01:00
humanPronounGuidance : RepoFaceHumanPronounGuidance [ ] = [ ] ,
2026-05-24 06:11:47 +01:00
curiosityGraphFacts? : string ,
2026-05-21 17:24:37 +01:00
) : string {
const name = identity . displayName ;
const lines : string [ ] = [ ] ;
const profile = state . selfProfile ;
2026-05-22 15:10:55 +01:00
const privateNotes = profile . privateNotes ;
2026-05-21 17:24:37 +01:00
const values = [ . . . profile . values ]
2026-05-22 15:10:55 +01:00
. sort ( ( left , right ) = > right . priority - left . priority ) ;
2026-05-21 17:24:37 +01:00
const needs = [ . . . state . faceAffect . needs ]
2026-05-22 15:10:55 +01:00
. filter ( ( need ) = > need . status !== "retired" )
. sort ( sortAffectByStatusAndIntensity ) ;
2026-05-21 17:24:37 +01:00
const bonds = [ . . . state . faceAffect . socialBonds ]
2026-05-22 15:10:55 +01:00
. filter ( ( bond ) = > bond . status !== "retired" )
. sort ( sortAffectByStatusAndIntensity ) ;
2026-05-21 17:24:37 +01:00
const statusReads = [ . . . state . faceAffect . statusReads ]
. filter ( ( read ) = > ! read . retiredAt )
2026-05-22 15:10:55 +01:00
. sort ( sortAffectByStatusAndIntensity ) ;
const moodDimensions = [ . . . state . faceAffect . moodDimensions ]
. sort ( ( left , right ) = > right . value - left . value ) ;
2026-05-24 20:38:51 +01:00
const socialBiases = [ . . . state . faceAffect . socialBiases ]
. sort ( ( left , right ) = > right . value - left . value ) ;
2026-05-26 22:21:23 +01:00
const doctrineStances = [ . . . state . faceAffect . doctrineStances ]
. filter ( ( stance ) = > stance . status !== "retired" && ! stance . retiredAt )
. sort ( sortAffectByStatusAndIntensity ) ;
2026-05-21 17:24:37 +01:00
const agencyPressures = [ . . . state . agencyPressure . pressures ]
2026-05-22 15:10:55 +01:00
. filter ( ( pressure ) = > pressure . status !== "retired" )
. sort ( sortAffectByStatusAndIntensity ) ;
const durableMemories = [ . . . state . thoughtMemory . memories ]
. filter ( ( memory ) = > ! memory . retiredAt )
. slice ( - 12 )
. reverse ( ) ;
const shortTermResidue = [ . . . state . thoughtMemory . shortTerm ]
. filter ( ( memory ) = > ! memory . retiredAt )
. slice ( - 12 )
. reverse ( ) ;
2026-05-21 17:24:37 +01:00
const incubation = [ . . . state . thoughtMemory . incubation ]
. filter ( ( thread ) = > thread . status !== "retired" )
2026-05-22 15:10:55 +01:00
. sort ( ( left , right ) = > right . maturation - left . maturation ) ;
const candidateInterventions = [ . . . state . candidateInterventions . interventions ]
. filter ( ( intervention ) = > intervention . status !== "retired" )
. slice ( - 8 )
. reverse ( ) ;
const recentReceipts = [ . . . state . speechReceipts . recentReceipts ]
. slice ( - 6 )
. reverse ( ) ;
const activationFacts = renderRepoFaceActivationProfileFacts ( profile . activationProfile ) ;
const runtimeFacts = renderRepoFaceRuntimePressureFacts ( name , state ) ;
2026-05-25 07:03:10 +01:00
const humanSteeringFacts = roomContext
? renderRepoFaceHumanSteeringFacts ( identity , roomContext )
: undefined ;
2026-05-21 17:24:37 +01:00
2026-05-21 21:06:11 +01:00
const selfTexture = [
. . . privateNotes . map ( projectPrivateNoteForMemorySurface ) ,
. . . values . map ( ( value ) = > value . summary || value . label ) ,
]
. map ( cleanCharacterFacingSentence )
. filter ( ( entry ) = > entry . length > 0 )
2026-05-22 15:10:55 +01:00
. slice ( 0 , 18 ) ;
2026-05-21 21:06:11 +01:00
if ( selfTexture . length > 0 ) {
lines . push ( ` Right now, ${ name } is carrying this close to the skin: ${ joinAsNarrativeList ( selfTexture ) } . ` ) ;
2026-05-21 17:24:37 +01:00
}
2026-05-21 21:06:11 +01:00
2026-05-22 15:10:55 +01:00
if ( activationFacts ) {
lines . push ( activationFacts ) ;
}
if ( runtimeFacts ) {
lines . push ( runtimeFacts ) ;
}
2026-05-21 17:24:37 +01:00
if ( needs . length > 0 ) {
2026-05-21 21:06:11 +01:00
lines . push ( [
2026-05-22 15:10:55 +01:00
` ${ name } 's explicit needs and frictions: ` ,
2026-05-21 21:06:11 +01:00
. . . needs . map ( ( need ) = > {
2026-05-22 15:10:55 +01:00
const target = targetLabel ( need . target ) ;
const claimOrQuestion = need . claim
? ` Claim: ${ asSentence ( need . claim ) } `
: need . question
? ` Question: ${ asSentence ( need . question ) } `
: "" ;
return [
` - ${ need . kind } need toward ${ target } [ ${ need . status } , intensity ${ need . intensity . toFixed ( 2 ) } , valence ${ need . valence . toFixed ( 2 ) } ]: ${ asSentence ( need . summary ) } ` ,
claimOrQuestion ,
` Tension: ${ asSentence ( need . tension ) } ` ,
` Behavioral pull: ${ asSentence ( need . actionImplication ) } ` ,
] . filter ( Boolean ) . join ( " " ) ;
2026-05-21 21:06:11 +01:00
} ) ,
] . join ( "\n" ) ) ;
2026-05-21 17:24:37 +01:00
}
2026-05-21 21:06:11 +01:00
2026-05-21 17:24:37 +01:00
if ( bonds . length > 0 ) {
2026-05-21 21:06:11 +01:00
lines . push ( [
"The social map has teeth:" ,
. . . bonds . map ( ( bond ) = > {
2026-05-22 15:10:55 +01:00
const target = targetLabel ( bond . target ) ;
return [
` - ${ target } draws ${ bond . stance } [ ${ bond . status } , intensity ${ bond . intensity . toFixed ( 2 ) } ]: ${ asSentence ( bond . summary ) } ` ,
` Read: ${ asSentence ( bond . claim ) } ` ,
` Tension: ${ asSentence ( bond . tension ) } ` ,
` Behavioral pull: ${ asSentence ( bond . actionImplication ) } ` ,
] . join ( " " ) ;
2026-05-21 21:06:11 +01:00
} ) ,
] . join ( "\n" ) ) ;
2026-05-21 17:24:37 +01:00
}
2026-05-21 21:06:11 +01:00
2026-05-21 17:24:37 +01:00
if ( statusReads . length > 0 ) {
2026-05-21 21:06:11 +01:00
lines . push ( [
"Status in the swarm is part of the weather:" ,
. . . statusReads . map ( ( read ) = > {
2026-05-22 15:10:55 +01:00
const target = targetLabel ( read . target ) ;
return [
` - Around ${ target } , ${ name } feels ${ read . status } [intensity ${ read . intensity . toFixed ( 2 ) } ]: ${ asSentence ( read . summary ) } ` ,
` Read: ${ asSentence ( read . claim ) } ` ,
` Tension: ${ asSentence ( read . tension ) } ` ,
` Behavioral pull: ${ asSentence ( read . actionImplication ) } ` ,
] . join ( " " ) ;
2026-05-21 21:06:11 +01:00
} ) ,
] . join ( "\n" ) ) ;
2026-05-21 17:24:37 +01:00
}
2026-05-21 21:06:11 +01:00
2026-05-22 15:10:55 +01:00
if ( moodDimensions . length > 0 ) {
lines . push ( [
"Mood dimensions currently bending the turn:" ,
. . . moodDimensions . map ( ( dimension ) = >
` - ${ dimension . name } = ${ dimension . value . toFixed ( 2 ) } ${ dimension . source ? ` from ${ cleanCharacterFacingSentence ( dimension . source ) } ` : "" } ` ,
) ,
] . join ( "\n" ) ) ;
}
2026-05-24 20:38:51 +01:00
if ( socialBiases . length > 0 ) {
lines . push ( [
"Social interpretation biases that shape ambiguous signals:" ,
. . . socialBiases . map ( ( bias ) = >
` - ${ bias . name } = ${ bias . value . toFixed ( 2 ) } : ${ asSentence ( bias . summary ) } Behavioral pull: ${ asSentence ( bias . behavioralPull ) } ` ,
) ,
] . join ( "\n" ) ) ;
}
2026-05-26 22:21:23 +01:00
if ( doctrineStances . length > 0 ) {
lines . push ( [
` ${ name } 's lived relation to Cult/Praxis doctrine: ` ,
. . . doctrineStances . map ( ( stance ) = >
[
` - ${ stance . doctrine } toward ${ targetLabel ( stance . target ) } [ ${ stance . status } , intensity ${ stance . intensity . toFixed ( 2 ) } , valence ${ stance . valence . toFixed ( 2 ) } ]: ${ asSentence ( stance . summary ) } ` ,
stance . claim ? ` Claim: ${ asSentence ( stance . claim ) } ` : "" ,
stance . question ? ` Question: ${ asSentence ( stance . question ) } ` : "" ,
` Tension: ${ asSentence ( stance . tension ) } ` ,
` Behavioral pull: ${ asSentence ( stance . actionImplication ) } ` ,
] . filter ( Boolean ) . join ( " " ) ,
) ,
] . join ( "\n" ) ) ;
}
2026-05-22 15:10:55 +01:00
if ( durableMemories . length > 0 ) {
lines . push ( [
"Durable memories that should still bias judgment:" ,
. . . durableMemories . map ( ( memory ) = > renderRepoFaceMemoryFact ( name , memory ) ) ,
] . join ( "\n" ) ) ;
}
if ( shortTermResidue . length > 0 ) {
lines . push ( [
"Short-term residue waiting to settle:" ,
. . . shortTermResidue . map ( ( memory ) = > renderRepoFaceMemoryFact ( name , memory ) ) ,
] . join ( "\n" ) ) ;
}
2026-05-22 13:33:07 +01:00
const socialGraphFacts = renderRepoFaceSocialGraphFacts ( identity , registryIdentities , state ) ;
if ( socialGraphFacts ) {
lines . push ( socialGraphFacts ) ;
}
2026-05-22 17:19:47 +01:00
const peerOpeningFacts = roomContext
? renderRepoFacePeerOpeningFacts ( identity , registryIdentities , roomContext )
: undefined ;
if ( peerOpeningFacts ) {
lines . push ( peerOpeningFacts ) ;
}
2026-05-23 13:46:52 +01:00
const socialPressureFacts = roomContext
? renderRepoFaceRelationshipPressureFacts ( identity , registryIdentities , state , roomContext )
: undefined ;
if ( socialPressureFacts ) {
lines . push ( socialPressureFacts ) ;
}
2026-05-22 15:59:49 +01:00
const pronounFacts = renderRepoFaceHumanPronounFacts ( humanPronounGuidance ) ;
if ( pronounFacts ) {
lines . push ( pronounFacts ) ;
}
2026-05-22 14:57:28 +01:00
const roomTextureFacts = roomContext
? renderRepoFaceRoomTextureFacts ( identity , roomContext )
: undefined ;
if ( roomTextureFacts ) {
lines . push ( roomTextureFacts ) ;
}
2026-05-24 06:11:47 +01:00
if ( curiosityGraphFacts ) {
lines . push ( curiosityGraphFacts ) ;
}
2026-05-26 13:36:58 +01:00
if ( agencyPressures . length > 0 ) {
2026-05-21 21:06:11 +01:00
lines . push ( [
2026-05-22 15:10:55 +01:00
"Agency pressures that want eventual motion:" ,
2026-05-21 21:06:11 +01:00
. . . agencyPressures . map ( ( pressure ) = >
2026-05-22 15:10:55 +01:00
[
` - ${ pressure . kind } toward ${ targetLabel ( pressure . target ) } [ ${ pressure . status } , intensity ${ pressure . intensity . toFixed ( 2 ) } ]: ${ asSentence ( pressure . summary ) } ` ,
pressure . claim ? ` Claim: ${ asSentence ( pressure . claim ) } ` : "" ,
pressure . question ? ` Question: ${ asSentence ( pressure . question ) } ` : "" ,
pressure . tension ? ` Tension: ${ asSentence ( pressure . tension ) } ` : "" ,
` Behavioral pull: ${ asSentence ( pressure . actionImplication ) } ` ,
] . filter ( Boolean ) . join ( " " ) ,
2026-05-21 21:06:11 +01:00
) ,
] . join ( "\n" ) ) ;
2026-05-21 17:24:37 +01:00
}
2026-05-21 21:06:11 +01:00
2026-05-26 13:36:58 +01:00
if ( incubation . length > 0 ) {
2026-05-22 15:10:55 +01:00
lines . push ( [
"Thoughts still moving under the floorboards:" ,
. . . incubation . map ( ( thread ) = >
[
` - ${ cleanCharacterFacingSentence ( thread . topic ) } [ ${ thread . status } , maturation ${ thread . maturation . toFixed ( 2 ) } ]: ${ cleanCharacterFacingSentence ( thread . summary ) } ` ,
typeof thread . desireToSpeak === "number" ? ` desire to speak ${ thread . desireToSpeak . toFixed ( 2 ) } ` : "" ,
typeof thread . noveltyToRoom === "number" ? ` room novelty ${ thread . noveltyToRoom . toFixed ( 2 ) } ` : "" ,
typeof thread . saturationScore === "number" ? ` saturation ${ thread . saturationScore . toFixed ( 2 ) } ` : "" ,
] . filter ( Boolean ) . join ( "; " ) ,
) ,
] . join ( "\n" ) ) ;
2026-05-21 17:24:37 +01:00
}
2026-05-21 21:06:11 +01:00
2026-05-26 13:36:58 +01:00
if ( candidateInterventions . length > 0 ) {
2026-05-22 15:10:55 +01:00
lines . push ( [
"Unsaid or recently deferred speech pressure:" ,
. . . candidateInterventions . map ( ( intervention ) = >
[
` - ${ intervention . kind } [ ${ intervention . status } , priority ${ intervention . priority . toFixed ( 2 ) } ${ intervention . mustEventuallyShare ? ", must eventually share" : "" } ]: ${ asSentence ( intervention . summary ) } ` ,
` Draft residue: ${ cleanCharacterFacingSentence ( intervention . draft ) } ` ,
] . join ( " " ) ,
) ,
"Do not repeat a waiting line unless the room gives it a sharper angle." ,
] . join ( "\n" ) ) ;
}
2026-05-26 13:36:58 +01:00
if ( recentReceipts . length > 0 ) {
2026-05-22 15:10:55 +01:00
lines . push ( [
"Recent speech residue:" ,
. . . recentReceipts . map ( ( receipt ) = >
` - Said recently ${ receipt . preview ? ` : ${ cleanCharacterFacingSentence ( receipt . preview ) } ` : "." } Let this create repetition caution, confidence, embarrassment, or follow-through as appropriate. ` ,
) ,
] . join ( "\n" ) ) ;
2026-05-21 17:24:37 +01:00
}
2026-05-25 07:03:10 +01:00
if ( humanSteeringFacts ) {
lines . push ( humanSteeringFacts ) ;
}
2026-05-21 17:24:37 +01:00
if ( lines . length === 0 ) {
return ` You are ${ name } , but your durable state is thin. Use the room, repo, and your jurisdiction to form a real opinion before speaking. ` ;
}
2026-05-26 13:36:58 +01:00
return rejectLeakyMemorySurface ( lines . join ( "\n\n" ) ) ;
2026-05-21 21:06:11 +01:00
}
2026-05-22 15:10:55 +01:00
function sortAffectByStatusAndIntensity (
left : { status? : string ; intensity? : number } ,
right : { status? : string ; intensity? : number } ,
) : number {
const rank = ( status : string | undefined ) : number = > {
switch ( status ) {
case "neglected" :
case "ready_to_act" :
return 0 ;
case "active" :
return 1 ;
case "challenged" :
return 1 ;
case "cooling" :
return 2 ;
case "satisfied" :
case "resolved" :
return 3 ;
default :
return 4 ;
}
} ;
const rankDelta = rank ( left . status ) - rank ( right . status ) ;
if ( rankDelta !== 0 ) {
return rankDelta ;
}
return ( right . intensity ? ? 0 ) - ( left . intensity ? ? 0 ) ;
}
function targetLabel ( target : { label? : string ; id? : string ; kind? : string } | undefined ) : string {
if ( ! target ) {
return "an unnamed target" ;
}
return target . label ? ? target . id ? ? target . kind ? ? "an unnamed target" ;
}
function renderRepoFaceActivationProfileFacts (
activationProfile : VoidSelfStateTypedProjection [ "selfProfile" ] [ "activationProfile" ] ,
) : string | undefined {
const sections = Object . entries ( activationProfile )
. map ( ( [ section , values ] ) = > {
const entries = Object . entries ( values )
. sort ( ( [ , left ] , [ , right ] ) = > right . weight - left . weight )
. map ( ( [ key , value ] ) = > ` ${ key } = ${ value . weight . toFixed ( 2 ) } ${ value . note ? ` ( ${ cleanCharacterFacingSentence ( value . note ) } ) ` : "" } ` ) ;
return entries . length > 0 ? ` - ${ section } : ${ entries . join ( "; " ) } ` : undefined ;
} )
. filter ( ( entry ) : entry is string = > typeof entry === "string" ) ;
return sections . length > 0
? [ "Activation profile that should color behavior:" , . . . sections ] . join ( "\n" )
: undefined ;
}
function renderRepoFaceRuntimePressureFacts (
name : string ,
state : VoidSelfStateTypedProjection ,
) : string | undefined {
const lines : string [ ] = [ ] ;
const sleep = state . scheduledRuntime . sleepCycle ;
if ( sleep . isNapping || sleep . activeDreamThemes . length > 0 ) {
lines . push (
` ${ name } 's rest state: ${ sleep . isNapping ? "currently in a sleep/low-output phase" : "awake but carrying dream residue" } ${ sleep . activeDreamThemes . length > 0 ? ` around ${ joinAsNarrativeList ( sleep . activeDreamThemes . map ( cleanCharacterFacingSentence ) ) } ` : "" } . ` ,
) ;
}
const speaking = state . scheduledRuntime . speakingPressure ;
const speakingParts = [
` need to speak ${ speaking . needToSpeak . toFixed ( 2 ) } ` ,
typeof speaking . confessionPressure === "number" ? ` confession ${ speaking . confessionPressure . toFixed ( 2 ) } ` : "" ,
typeof speaking . noveltyPressure === "number" ? ` novelty ${ speaking . noveltyPressure . toFixed ( 2 ) } ` : "" ,
typeof speaking . recentSpeechDamping === "number" ? ` recent-speech damping ${ speaking . recentSpeechDamping . toFixed ( 2 ) } ` : "" ,
] . filter ( Boolean ) ;
lines . push ( ` Speaking pressure: ${ speakingParts . join ( ", " ) } . Treat this as appetite/restraint, not an order. ` ) ;
if ( state . scheduledRuntime . lastRuns . length > 0 ) {
lines . push ( ` Recent internal passes: ${ state . scheduledRuntime . lastRuns . slice ( - 4 ) . map ( ( run ) = >
cleanCharacterFacingSentence ( run . summary ) ,
) . join ( " | " ) } ` );
}
return lines . length > 0 ? lines . join ( "\n" ) : undefined ;
}
function renderRepoFaceMemoryFact (
name : string ,
memory : VoidSelfStateTypedProjection [ "thoughtMemory" ] [ "memories" ] [ number ] ,
) : string {
const parts = [
` - ${ memory . kind } about ${ targetLabel ( memory . target ) } : ${ asSentence ( memory . summary ) } ` ,
memory . claim ? ` Claim: ${ asSentence ( memory . claim ) } ` : "" ,
memory . question ? ` Question: ${ asSentence ( memory . question ) } ` : "" ,
memory . tension ? ` Tension: ${ asSentence ( memory . tension ) } ` : "" ,
memory . actionImplication ? ` Behavioral pull for ${ name } : ${ asSentence ( memory . actionImplication ) } ` : "" ,
] ;
return parts . filter ( Boolean ) . join ( " " ) ;
}
2026-05-22 14:57:28 +01:00
function renderRepoFaceRoomTextureFacts (
identity : RepoDiscordIdentity ,
input : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
) : string | undefined {
const stats = collectRepoFaceRoomTextureStats ( identity , input ) ;
if ( ! stats ) {
return undefined ;
}
const temporaryPressures = stats . texture === "heavy" || stats . agentShare >= 0.55
? [
"- Temporary affect pressure candidates: play, rest, and social_contact may be hungry because the room is carrying sustained work/agent weight." ,
"- These are not stored needs and not orders. Project whether this character gets mischievous, bored, sharp, withdrawn, socially hungry, status-testing, or still work-focused." ,
]
: [ ] ;
return [
"Room texture facts:" ,
` - Observed messages: ${ stats . total } ; humans: ${ stats . humanMessages } ; agents/bots: ${ stats . agentMessages } ; distinct speakers: ${ stats . speakerCount } . ` ,
` - Long messages: ${ stats . longMessages } ; short messages: ${ stats . shortMessages } ; average length: ${ stats . averageCharacters } characters. ` ,
` - This Face's own recent messages in the attached window: ${ stats . ownMessages } . ` ,
` - Structural texture: ${ stats . texture } . This is evidence about conversational weight, not a command to speak or joke. ` ,
. . . temporaryPressures ,
] . join ( "\n" ) ;
}
2026-05-24 06:11:47 +01:00
interface RepoFaceCuriosityNode {
id : string ;
text : string ;
sourceKind : RetrievalResult [ "sourceKind" ] ;
score : number ;
terms : string [ ] ;
metadata : Record < string , string > ;
seedLabels : string [ ] ;
}
interface RepoFaceCuriosityCluster {
label : string ;
nodes : RepoFaceCuriosityNode [ ] ;
prominence : number ;
saturation : number ;
novelty : number ;
2026-05-28 19:56:16 +01:00
recentOverlap : number ;
stateOverlap : number ;
2026-05-24 06:11:47 +01:00
clusterDensity : number ;
jurisdictionFit : number ;
evidence : string [ ] ;
}
async function renderRepoFaceCuriosityGraphFacts (
identity : RepoDiscordIdentity ,
config : ReturnType < typeof loadConfig > ,
state : VoidSelfStateTypedProjection ,
roomContext : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
) : Promise < string | undefined > {
const seedQueries = buildRepoFaceCuriositySeedQueries ( identity , state , roomContext ) ;
if ( seedQueries . length === 0 ) {
return undefined ;
}
try {
const retrieval = createRepoFaceCuriosityRetrievalService ( config ) ;
const nodesById = new Map < string , RepoFaceCuriosityNode > ( ) ;
for ( const seed of seedQueries ) {
const [ historyResults , sourceResults , homeSourceResults ] = await Promise . all ( [
retrieval . searchHistory ( seed . query , 8 ) ,
retrieval . searchRepositorySources ( seed . query , 8 ) ,
retrieval . searchRepositorySources ( seed . query , 6 , { repoName : identity.repoName } ) ,
] ) ;
for ( const result of [ . . . historyResults , . . . sourceResults , . . . homeSourceResults ] ) {
const id = ` ${ result . sourceKind } : ${ result . chunkId } ` ;
const terms = significantTopicTerms ( result . text ) ;
if ( terms . length < 3 ) {
continue ;
}
const existing = nodesById . get ( id ) ;
if ( existing ) {
existing . score = Math . max ( existing . score , result . score ) ;
existing . seedLabels = mergeStrings ( existing . seedLabels , seed . label ) ;
continue ;
}
nodesById . set ( id , {
id ,
text : result.text ,
sourceKind : result.sourceKind ,
score : result.score ,
terms ,
metadata : result.metadata ,
seedLabels : [ seed . label ] ,
} ) ;
}
}
const nodes = [ . . . nodesById . values ( ) ]
. sort ( ( left , right ) = > right . score - left . score )
. slice ( 0 , 32 ) ;
if ( nodes . length < 3 ) {
return undefined ;
}
const clusters = decodeRepoFaceCuriosityGraph ( identity , state , roomContext , nodes ) ;
if ( clusters . length === 0 ) {
return undefined ;
}
return renderRepoFaceCuriosityClusters ( identity , config , clusters ) ;
} catch ( error ) {
const message = error instanceof Error ? error.message : String ( error ) ;
return [
"Curiosity graph unavailable:" ,
` - Semantic retrieval failed while decoding topic attractors: ${ collapseWhitespace ( message , 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" ) ;
}
}
function createRepoFaceCuriosityRetrievalService ( config : ReturnType < typeof loadConfig > ) : RetrievalService {
const historyEmbedder = createTextEmbedder ( {
backend : config.ragEmbeddingBackend ,
hashDimensions : config.ragEmbeddingDimensions ,
ollamaBaseUrl : config.ragOllamaBaseUrl ,
ollamaModel : config.ragOllamaModel ,
ollamaTimeoutMs : config.ragOllamaTimeoutMs ,
queryInstruction : config.ragQueryInstruction ,
} ) ;
const sourceEmbedder = createTextEmbedder ( {
backend : config.ragEmbeddingBackend ,
hashDimensions : config.ragEmbeddingDimensions ,
ollamaBaseUrl : config.ragOllamaBaseUrl ,
ollamaModel : config.ragOllamaModel ,
ollamaTimeoutMs : config.ragOllamaTimeoutMs ,
queryInstruction : config.ragSourceQueryInstruction || config . ragQueryInstruction ,
} ) ;
const stores = createVectorStores ( {
kind : config.vectorStore.kind ,
historyPath : config.vectorStore.path ,
sourceRoot : config.sourceVectorStoreRoot ,
qdrant : config.qdrant ,
historyEmbedder ,
sourceEmbedder ,
} ) ;
return new RetrievalService ( stores . history , stores . source ) ;
}
function buildRepoFaceCuriositySeedQueries (
identity : RepoDiscordIdentity ,
state : VoidSelfStateTypedProjection ,
roomContext : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
) : Array < { label : string ; query : string } > {
const room = roomContext . recentMessages
. filter ( ( message ) = > collapseWhitespace ( message . content ) . length > 0 )
. slice ( - 8 )
. map ( ( message ) = > ` ${ message . authorName } : ${ collapseWhitespace ( message . content , 500 ) } ` )
. join ( "\n" ) ;
const nearby = roomContext . channelSnapshots
. flatMap ( ( snapshot ) = > snapshot . messages )
. filter ( ( message ) = > collapseWhitespace ( message . content ) . length > 0 )
. slice ( - 8 )
. map ( ( message ) = > ` ${ message . authorName } : ${ collapseWhitespace ( message . content , 320 ) } ` )
. join ( "\n" ) ;
const privateThoughts = [
. . . state . selfProfile . privateNotes . slice ( - 8 ) ,
. . . state . selfProfile . values
. slice ( )
. 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 ( ( memory ) = > ` ${ memory . kind } ${ targetLabel ( memory . target ) } ${ memory . summary } ${ memory . claim ? ? memory . question ? ? "" } ` ) ,
. . . state . thoughtMemory . shortTerm
. filter ( ( memory ) = > ! memory . retiredAt )
. slice ( - 8 )
. map ( ( memory ) = > ` ${ memory . kind } ${ targetLabel ( memory . target ) } ${ memory . summary } ${ memory . claim ? ? memory . question ? ? "" } ` ) ,
. . . 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 identityQuery = [
identity . displayName ,
identity . repoName ,
identity . description ? ? "" ,
. . . 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 : privateThoughts } ,
{ label : "home territory" , query : identityQuery } ,
]
. map ( ( seed ) = > ( { . . . seed , query : collapseWhitespace ( seed . query , 2800 ) } ) )
. filter ( ( seed ) = > significantTopicTerms ( seed . query ) . length >= 3 )
. slice ( 0 , 4 ) ;
}
function decodeRepoFaceCuriosityGraph (
identity : RepoDiscordIdentity ,
state : VoidSelfStateTypedProjection ,
roomContext : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
nodes : RepoFaceCuriosityNode [ ] ,
) : RepoFaceCuriosityCluster [ ] {
const edgeWeights = new Map < string , number > ( ) ;
const adjacency = new Map < string , Set < string > > ( ) ;
for ( const node of nodes ) {
adjacency . set ( node . id , new Set ( ) ) ;
}
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 = repoFaceCuriosityEdgeWeight ( left , right ) ;
if ( weight < 0.16 ) {
continue ;
}
const key = curiosityEdgeKey ( left . id , right . id ) ;
edgeWeights . set ( key , weight ) ;
adjacency . get ( left . id ) ? . add ( right . id ) ;
adjacency . get ( right . id ) ? . add ( left . id ) ;
}
}
const visited = new Set < string > ( ) ;
const clusters : RepoFaceCuriosityNode [ ] [ ] = [ ] ;
const nodesById = new Map ( nodes . map ( ( node ) = > [ node . id , node ] ) ) ;
for ( const node of nodes ) {
if ( visited . has ( node . id ) ) {
continue ;
}
const stack = [ node . id ] ;
const cluster : RepoFaceCuriosityNode [ ] = [ ] ;
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 ) ;
}
}
}
clusters . push ( cluster ) ;
}
const recentTerms = collectRecentRoomTopicTermCounts ( roomContext ) ;
const stateTerms = collectRepoFaceStateTopicTermCounts ( state ) ;
const identityTerms = new Set ( significantTopicTerms ( [
identity . id ,
identity . displayName ,
identity . repoName ,
identity . description ? ? "" ,
. . . identity . channelPermissions . flatMap ( ( permission ) = > [
permission . label ? ? "" ,
permission . topic ? ? "" ,
permission . posture ? ? "" ,
] ) ,
] . join ( " " ) ) ) ;
return clusters
. filter ( ( cluster ) = > cluster . length >= 2 )
. map ( ( cluster ) : RepoFaceCuriosityCluster = > {
const clusterTerms = rankedClusterTerms ( cluster ) . slice ( 0 , 7 ) ;
const density = clusterDensity ( cluster , edgeWeights ) ;
const averageScore = average ( cluster . map ( ( node ) = > node . score ) ) ;
const recentOverlap = weightedTermOverlap ( clusterTerms , recentTerms ) ;
const stateOverlap = weightedTermOverlap ( clusterTerms , stateTerms ) ;
const saturation = clamp ( ( recentOverlap * 0.72 ) + ( stateOverlap * 0.42 ) , 0 , 1 ) ;
const jurisdictionFit = clamp (
clusterTerms . filter ( ( term ) = > identityTerms . has ( term ) ) . length / Math . max ( 1 , Math . min ( clusterTerms . length , 4 ) )
+ cluster . filter ( ( node ) = > normalizeKey ( node . metadata . repoName ? ? "" ) === normalizeKey ( identity . repoName ) ) . length / Math . max ( 1 , cluster . length ) * 0.55 ,
0 ,
1 ,
) ;
const novelty = clamp ( 1 - saturation + Math . max ( 0 , 0.4 - stateOverlap ) , 0 , 1 ) ;
const prominence = clamp ( ( averageScore * 0.58 ) + ( density * 0.28 ) + ( Math . min ( cluster . length , 8 ) / 8 * 0.18 ) , 0 , 1 ) ;
return {
label : clusterTerms.slice ( 0 , 4 ) . join ( " / " ) ,
nodes : cluster ,
prominence ,
saturation ,
novelty ,
2026-05-28 19:56:16 +01:00
recentOverlap ,
stateOverlap ,
2026-05-24 06:11:47 +01:00
clusterDensity : density ,
jurisdictionFit ,
evidence : cluster
. slice ( )
. sort ( ( left , right ) = > right . score - left . score )
. slice ( 0 , 3 )
. map ( ( node ) = > curiosityEvidenceLabel ( node ) ) ,
} ;
} )
. sort ( ( left , right ) = > {
const leftRank = curiosityAttractorRank ( left ) ;
const rightRank = curiosityAttractorRank ( right ) ;
if ( rightRank !== leftRank ) {
return rightRank - leftRank ;
}
return right . prominence - left . prominence ;
} )
. slice ( 0 , 5 ) ;
}
function renderRepoFaceCuriosityClusters (
identity : RepoDiscordIdentity ,
config : ReturnType < typeof loadConfig > ,
clusters : RepoFaceCuriosityCluster [ ] ,
) : string {
const backend = config . vectorStore . kind === "qdrant"
? ` Qdrant collections ${ config . qdrant . historyCollection } + ${ config . qdrant . sourceCollection } `
: "local vector shards" ;
return [
"Curiosity graph attractors:" ,
2026-05-28 19:56:16 +01:00
` - Source: semantic retrieval from ${ backend } ; local graph decoding over retrieved chunks. Saturation is derived here from semantic overlap with recent conversation and Face state, not from a separate repeated-term detector. This is curiosity weather, not orders or consensus. ` ,
. . . clusters . map ( ( cluster , index ) = > {
2026-05-24 06:11:47 +01:00
const suggestedMotion = suggestCuriosityMotion ( identity , cluster ) ;
return [
2026-05-28 19:56:16 +01:00
` - Semantic cluster ${ index + 1 } : prominence ${ formatSignal ( cluster . prominence ) } , semantic saturation ${ formatSignal ( cluster . saturation ) } , novelty ${ formatSignal ( cluster . novelty ) } , recent-conversation overlap ${ formatSignal ( cluster . recentOverlap ) } , Face-state overlap ${ formatSignal ( cluster . stateOverlap ) } , cluster density ${ formatSignal ( cluster . clusterDensity ) } , jurisdiction fit ${ formatSignal ( cluster . jurisdictionFit ) } . ` ,
2026-05-24 06:11:47 +01:00
` Suggested motion: ${ suggestedMotion } ` ,
` 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" ) ;
}
function repoFaceCuriosityEdgeWeight ( left : RepoFaceCuriosityNode , right : RepoFaceCuriosityNode ) : number {
const termSimilarity = jaccard ( left . terms , right . terms ) ;
const sameRepo = left . metadata . repoName && right . metadata . repoName && normalizeKey ( left . metadata . repoName ) === normalizeKey ( right . metadata . repoName )
? 1
: 0 ;
const sameCorpus = left . sourceKind === right . sourceKind ? 1 : 0 ;
const sharedSeeds = left . seedLabels . filter ( ( label ) = > right . seedLabels . includes ( label ) ) . length > 0 ? 1 : 0 ;
const scoreProximity = 1 - Math . min ( 1 , Math . abs ( left . score - right . score ) ) ;
return clamp ( ( termSimilarity * 0.58 ) + ( sameRepo * 0.16 ) + ( sameCorpus * 0.1 ) + ( sharedSeeds * 0.08 ) + ( scoreProximity * 0.08 ) , 0 , 1 ) ;
}
function rankedClusterTerms ( cluster : RepoFaceCuriosityNode [ ] ) : 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 . entries ( ) ]
. sort ( ( left , right ) = > {
if ( right [ 1 ] !== left [ 1 ] ) {
return right [ 1 ] - left [ 1 ] ;
}
return left [ 0 ] . localeCompare ( right [ 0 ] ) ;
} )
. map ( ( [ term ] ) = > term ) ;
}
function collectRecentRoomTopicTermCounts ( input : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ) : Map < string , number > {
const counts = new Map < string , number > ( ) ;
const messages = [
. . . input . recentMessages ,
. . . input . channelSnapshots . flatMap ( ( snapshot ) = > snapshot . messages ) ,
] . slice ( - 36 ) ;
for ( const message of messages ) {
for ( const term of significantTopicTerms ( message . content ) ) {
counts . set ( term , ( counts . get ( term ) ? ? 0 ) + 1 ) ;
}
}
return counts ;
}
function collectRepoFaceStateTopicTermCounts ( state : VoidSelfStateTypedProjection ) : Map < string , number > {
const counts = new Map < string , number > ( ) ;
const surfaces = [
. . . state . selfProfile . privateNotes ,
. . . state . selfProfile . values . map ( ( value ) = > ` ${ value . label } ${ value . summary } ` ) ,
. . . state . thoughtMemory . memories . map ( ( memory ) = > ` ${ memory . summary } ${ memory . claim ? ? "" } ${ memory . question ? ? "" } ${ memory . tension ? ? "" } ` ) ,
. . . state . thoughtMemory . shortTerm . map ( ( memory ) = > ` ${ memory . summary } ${ memory . claim ? ? "" } ${ memory . question ? ? "" } ${ memory . tension ? ? "" } ` ) ,
. . . state . thoughtMemory . incubation . map ( ( thread ) = > ` ${ thread . topic } ${ thread . summary } ` ) ,
. . . state . agencyPressure . pressures . map ( ( pressure ) = > ` ${ pressure . summary } ${ pressure . claim ? ? "" } ${ pressure . question ? ? "" } ${ pressure . tension ? ? "" } ` ) ,
2026-05-26 22:21:23 +01:00
. . . state . faceAffect . doctrineStances . map ( ( stance ) = > ` ${ stance . doctrine } ${ stance . summary } ${ stance . claim ? ? "" } ${ stance . question ? ? "" } ${ stance . tension } ` ) ,
2026-05-24 06:11:47 +01:00
] . slice ( - 64 ) ;
for ( const surface of surfaces ) {
for ( const term of significantTopicTerms ( surface ) ) {
counts . set ( term , ( counts . get ( term ) ? ? 0 ) + 1 ) ;
}
}
return counts ;
}
function weightedTermOverlap ( terms : string [ ] , counts : Map < string , number > ) : number {
if ( terms . length === 0 || counts . size === 0 ) {
return 0 ;
}
const maxCount = Math . max ( . . . counts . values ( ) , 1 ) ;
const overlap = terms . reduce ( ( sum , term ) = > sum + ( ( counts . get ( term ) ? ? 0 ) / maxCount ) , 0 ) ;
return clamp ( overlap / Math . min ( terms . length , 6 ) , 0 , 1 ) ;
}
function clusterDensity ( cluster : RepoFaceCuriosityNode [ ] , edgeWeights : Map < string , number > ) : number {
if ( cluster . length < 2 ) {
return 0 ;
}
let sum = 0 ;
let pairs = 0 ;
for ( let leftIndex = 0 ; leftIndex < cluster . length ; leftIndex += 1 ) {
for ( let rightIndex = leftIndex + 1 ; rightIndex < cluster . length ; rightIndex += 1 ) {
sum += edgeWeights . get ( curiosityEdgeKey ( cluster [ leftIndex ] . id , cluster [ rightIndex ] . id ) ) ? ? 0 ;
pairs += 1 ;
}
}
return pairs > 0 ? clamp ( sum / pairs , 0 , 1 ) : 0 ;
}
function curiosityAttractorRank ( cluster : RepoFaceCuriosityCluster ) : number {
return clamp (
cluster . prominence * 0.42
+ cluster . novelty * 0.28
+ cluster . clusterDensity * 0.16
+ cluster . jurisdictionFit * 0.18
- cluster . saturation * 0.2 ,
0 ,
1 ,
) ;
}
function suggestCuriosityMotion ( identity : RepoDiscordIdentity , cluster : RepoFaceCuriosityCluster ) : 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 curiosityEvidenceLabel ( node : RepoFaceCuriosityNode ) : 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 curiosityEdgeKey ( left : string , right : string ) : string {
return left < right ? ` ${ left } :: ${ right } ` : ` ${ right } :: ${ left } ` ;
}
function jaccard ( left : string [ ] , right : string [ ] ) : number {
const leftSet = new Set ( left ) ;
const rightSet = new Set ( right ) ;
const union = new Set ( [ . . . leftSet , . . . rightSet ] ) . size ;
if ( union === 0 ) {
return 0 ;
}
let intersection = 0 ;
for ( const term of leftSet ) {
if ( rightSet . has ( term ) ) {
intersection += 1 ;
}
}
return intersection / 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 {
if ( value >= 0.68 ) {
return ` high ${ value . toFixed ( 2 ) } ` ;
}
if ( value >= 0.38 ) {
return ` medium ${ value . toFixed ( 2 ) } ` ;
}
return ` low ${ value . toFixed ( 2 ) } ` ;
}
2026-05-25 07:03:10 +01:00
function renderRepoFaceHumanSteeringFacts (
identity : RepoDiscordIdentity ,
input : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
) : string | undefined {
const currentRoomMessages = input . recentMessages
. filter ( ( message ) = > collapseWhitespace ( message . content ) . length > 0 )
. sort ( ( left , right ) = > Date . parse ( left . createdAt ) - Date . parse ( right . createdAt ) ) ;
const latestHuman = [ . . . currentRoomMessages ]
. reverse ( )
. find ( ( message ) = > ! message . isBot ) ;
if ( ! latestHuman ) {
return undefined ;
}
const latestHumanIndex = currentRoomMessages . findIndex ( ( message ) = > message . id === latestHuman . id ) ;
const laterAgentMessages = latestHumanIndex >= 0
? currentRoomMessages . slice ( latestHumanIndex + 1 ) . filter ( ( message ) = > message . isBot )
: [ ] ;
const latestHumanText = collapseWhitespace ( latestHuman . content , 420 ) ;
const normalizedHumanText = normalizeForRepetition ( latestHuman . content ) ;
const faceMentioned =
normalizedHumanText . includes ( normalizeSocialLabel ( identity . displayName ) ) ||
normalizedHumanText . includes ( normalizeSocialLabel ( identity . repoName ) ) ||
normalizedHumanText . includes ( normalizeSocialLabel ( identity . id ) ) ;
const isQuestionOrDirection = /[?]$/ . test ( latestHumanText )
|| /\b(should|need|needs|must|important|work|doing|why|what|where|when|how|rather|instead|stop|start|fix|look|check)\b/i . test ( latestHumanText ) ;
if ( ! isQuestionOrDirection && laterAgentMessages . length < 4 ) {
return undefined ;
}
return [
"Latest human steering in the current room:" ,
` - ${ latestHuman . authorName ? ? latestHuman . authorId } most recently grounded the room with: " ${ latestHumanText } " ` ,
faceMentioned
? ` - This appears to name ${ identity . displayName } or ${ identity . repoName } ; treat it as a live pull on this character unless later human context clearly supersedes it. `
: ` - This may not belong to ${ identity . displayName } 's territory. If it points at another steward or repo, do not keep expanding the old topic as if the whole room still belongs to you. ` ,
! faceMentioned
? ` - Because the latest human steering does not name ${ identity . displayName } , default to restraint. Do not ask the named steward for a new proof, artifact, or task unless the human invited ${ identity . displayName } into that work; a private note, clean handoff, or one social boundary is usually the coherent move. `
: "" ,
laterAgentMessages . length > 0
? ` - ${ laterAgentMessages . length } agent message(s) followed without a newer human steering message. Read them as peer reactions after the human ground, not as stronger authority, consensus, or proof that the old topic is still healthy. `
: "" ,
"- If you speak after an agent-only tail, either answer the human steering plainly, make a concrete social move to a specific person, bring fresh evidence, or stay private. Do not add another polished variation merely because peers kept talking." ,
] . filter ( Boolean ) . join ( "\n" ) ;
}
2026-05-22 14:57:28 +01:00
interface RepoFaceRoomTextureStats {
total : number ;
agentMessages : number ;
humanMessages : number ;
ownMessages : number ;
longMessages : number ;
shortMessages : number ;
averageCharacters : number ;
speakerCount : number ;
texture : "heavy" | "light" | "mixed" ;
agentShare : number ;
}
function collectRepoFaceRoomTextureStats (
identity : RepoDiscordIdentity ,
input : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
) : RepoFaceRoomTextureStats | undefined {
const messages = [
. . . input . recentMessages ,
. . . input . channelSnapshots . flatMap ( ( snapshot ) = > snapshot . messages ) ,
] ;
if ( messages . length === 0 ) {
return undefined ;
}
const ownToken = normalizeSocialLabel ( identity . displayName ) ;
const total = messages . length ;
const agentMessages = messages . filter ( ( message ) = > message . isBot ) . length ;
const humanMessages = total - agentMessages ;
const ownMessages = messages . filter ( ( message ) = > normalizeSocialLabel ( message . authorName ) === ownToken ) . length ;
const longMessages = messages . filter ( ( message ) = > collapseWhitespace ( message . content , 10 _000 ) . length >= 220 ) . length ;
const shortMessages = messages . filter ( ( message ) = > collapseWhitespace ( message . content , 10 _000 ) . length <= 90 ) . length ;
const averageCharacters = Math . round (
messages . reduce ( ( sum , message ) = > sum + collapseWhitespace ( message . content , 10 _000 ) . length , 0 ) / total ,
) ;
const speakerCount = new Set (
messages . map ( ( message ) = > normalizeSocialLabel ( message . authorName || message . authorId ) ) . filter ( Boolean ) ,
) . size ;
const texture =
longMessages >= Math . ceil ( total * 0.45 ) || averageCharacters >= 180
? "heavy"
: shortMessages >= Math . ceil ( total * 0.55 )
? "light"
: "mixed" ;
return {
total ,
agentMessages ,
humanMessages ,
ownMessages ,
longMessages ,
shortMessages ,
averageCharacters ,
speakerCount ,
texture ,
agentShare : agentMessages / total ,
} ;
}
2026-05-22 13:33:07 +01:00
function renderRepoFaceSocialGraphFacts (
identity : RepoDiscordIdentity ,
registryIdentities : RepoDiscordIdentity [ ] ,
state : VoidSelfStateTypedProjection ,
) : string | undefined {
const relations = collectRepoFaceSocialRelations ( state ) ;
const unmappedPeers = collectUnmappedSocialPeers ( identity , registryIdentities , relations ) ;
if ( registryIdentities . length === 0 ) {
return undefined ;
}
const lines = [
"Social graph topology:" ,
relations . length === 0
? "- No active person-bonds or person-status reads exist yet."
: ` - Active mapped people: ${ relations . map ( ( relation ) = > relation . targetLabel ) . join ( ", " ) } . ` ,
] ;
if ( unmappedPeers . length > 0 ) {
lines . push ( ` - Unmapped active peers: ${ formatUnmappedPeers ( unmappedPeers ) } . ` ) ;
}
lines . push ( "- These are topology facts only; they do not say how the gap should feel." ) ;
return lines . join ( "\n" ) ;
}
2026-05-22 17:19:47 +01:00
function renderRepoFacePeerOpeningFacts (
identity : RepoDiscordIdentity ,
registryIdentities : RepoDiscordIdentity [ ] ,
roomContext : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
) : string | undefined {
const selfTokens = new Set ( socialTargetTokens ( identity . displayName , identity . id , identity . repoName ) ) ;
const peersByToken = new Map < string , RepoDiscordIdentity > ( ) ;
for ( const peer of registryIdentities ) {
for ( const token of socialTargetTokens ( peer . displayName , peer . id , peer . repoName ) ) {
if ( ! selfTokens . has ( token ) ) {
peersByToken . set ( token , peer ) ;
}
}
}
const entries : Array < { label : string ; message : SourceMessage } > = [
. . . roomContext . recentMessages . map ( ( message ) = > ( { label : "current room" , message } ) ) ,
. . . roomContext . channelSnapshots . flatMap ( ( snapshot ) = >
snapshot . messages . map ( ( message ) = > ( { label : "nearby room" , message } ) ) ,
) ,
] ;
const byPeer = new Map < string , { peer : RepoDiscordIdentity ; entries : Array < { label : string ; message : SourceMessage } > } > ( ) ;
for ( const entry of entries ) {
if ( ! entry . message . isBot || ! entry . message . content . trim ( ) ) {
continue ;
}
const peer = peersByToken . get ( normalizeSocialLabel ( entry . message . authorName ) ) ;
if ( ! peer ) {
continue ;
}
const bucket = byPeer . get ( peer . id ) ? ? { peer , entries : [ ] } ;
bucket . entries . push ( entry ) ;
byPeer . set ( peer . id , bucket ) ;
}
const peerFacts = [ . . . byPeer . values ( ) ]
. sort ( ( left , right ) = > right . entries . length - left . entries . length )
. slice ( 0 , 6 )
. map ( ( { peer , entries } ) = > {
const latest = entries . at ( - 1 ) ;
const channelLabels = [ . . . new Set ( entries . map ( ( entry ) = > entry . label ) ) ] . join ( ", " ) ;
const excerpt = latest ? collapseWhitespace ( latest . message . content , 180 ) : "" ;
return ` - ${ peer . displayName } : ${ entries . length } recent nearby message ${ entries . length === 1 ? "" : "s" } in ${ channelLabels } . Latest visible line: " ${ excerpt } " ` ;
} ) ;
if ( peerFacts . length === 0 ) {
return undefined ;
}
return [
"Recent peer openings for possible social reads:" ,
. . . peerFacts ,
"These are raw openings for the projector to translate into possible trust, irritation, rivalry, alliance, or no social move at all. Do not treat them as consensus." ,
] . join ( "\n" ) ;
}
2026-05-23 13:46:52 +01:00
function renderRepoFaceRelationshipPressureFacts (
identity : RepoDiscordIdentity ,
registryIdentities : RepoDiscordIdentity [ ] ,
state : VoidSelfStateTypedProjection ,
roomContext : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
) : string | undefined {
const selfTokens = socialPressureTokensForIdentity ( identity ) ;
const jurisdictionTokens = socialPressureJurisdictionTokens ( identity ) ;
const peerProfiles = registryIdentities
. filter ( ( peer ) = > normalizeSocialLabel ( peer . id ) !== normalizeSocialLabel ( identity . id ) )
. map ( ( peer ) = > ( {
identity : peer ,
tokens : socialPressureTokensForIdentity ( peer ) ,
} ) ) ;
const relationTargets = collectRepoFaceSocialRelations ( state )
. map ( ( relation ) = > ( {
label : relation.targetLabel ,
tokens : socialPressureTokens ( relation . targetLabel ) ,
} ) )
. filter ( ( relation ) = > relation . tokens . length > 0 ) ;
const entries : Array < { label : string ; message : SourceMessage } > = [
. . . roomContext . recentMessages . map ( ( message ) = > ( { label : "current room" , message } ) ) ,
. . . roomContext . channelSnapshots . flatMap ( ( snapshot ) = >
snapshot . messages . map ( ( message ) = > ( { label : "nearby room" , message } ) ) ,
) ,
] ;
const byId = new Map < string , {
label : string ;
message : SourceMessage ;
score : number ;
signals : string [ ] ;
} > ( ) ;
for ( const entry of entries ) {
const content = collapseWhitespace ( entry . message . content , 10 _000 ) ;
if ( ! content ) {
continue ;
}
const normalizedContent = normalizeSocialLabel ( content ) ;
const authorToken = normalizeSocialLabel ( entry . message . authorName ? ? entry . message . authorId ) ;
const signals : string [ ] = [ ] ;
let score = 0 ;
const authorIsSelf = tokenAppearsInNormalizedText ( authorToken , selfTokens ) ;
const contentNamesSelf = tokenAppearsInNormalizedText ( normalizedContent , selfTokens ) ;
if ( contentNamesSelf ) {
score += 3 ;
signals . push ( ` names ${ identity . displayName } ` ) ;
} else if ( authorIsSelf ) {
score += 1 ;
signals . push ( ` ${ identity . displayName } 's own recent line ` ) ;
}
const peerMatches = peerProfiles
. filter ( ( peer ) = >
tokenAppearsInNormalizedText ( authorToken , peer . tokens ) ||
tokenAppearsInNormalizedText ( normalizedContent , peer . tokens ) ,
)
. slice ( 0 , 3 ) ;
if ( peerMatches . length > 0 ) {
score += peerMatches . length ;
signals . push ( ` touches peer ${ peerMatches . map ( ( peer ) = > peer . identity . displayName ) . join ( "/" ) } ` ) ;
}
const relationMatches = relationTargets
. filter ( ( relation ) = >
tokenAppearsInNormalizedText ( authorToken , relation . tokens ) ||
tokenAppearsInNormalizedText ( normalizedContent , relation . tokens ) ,
)
. slice ( 0 , 3 ) ;
if ( relationMatches . length > 0 ) {
score += relationMatches . length ;
signals . push ( ` touches existing social target ${ relationMatches . map ( ( relation ) = > relation . label ) . join ( "/" ) } ` ) ;
}
if ( tokenAppearsInNormalizedText ( normalizedContent , jurisdictionTokens ) ) {
score += 1 ;
signals . push ( "touches this jurisdiction or its domain language" ) ;
}
const socialPressureKinds = socialPressureLanguageKinds ( content ) ;
if ( socialPressureKinds . length > 0 ) {
score += 2 ;
signals . push ( ` uses social/status language ( ${ socialPressureKinds . join ( ", " ) } ) ` ) ;
}
if ( ! entry . message . isBot && score > 0 ) {
score += 1 ;
signals . push ( "human voice" ) ;
}
if ( score < 4 ) {
continue ;
}
const existing = byId . get ( entry . message . id ) ;
if ( ! existing || score > existing . score ) {
byId . set ( entry . message . id , {
label : entry.label ,
message : entry.message ,
score ,
signals : [ . . . new Set ( signals ) ] ,
} ) ;
}
}
const facts = [ . . . byId . values ( ) ]
. sort ( ( left , right ) = > {
const leftMs = Date . parse ( left . message . timestamp ) ;
const rightMs = Date . parse ( right . message . timestamp ) ;
if ( Number . isFinite ( leftMs ) && Number . isFinite ( rightMs ) && leftMs !== rightMs ) {
return leftMs - rightMs ;
}
return left . message . id . localeCompare ( right . message . id ) ;
} )
. slice ( - 8 ) ;
if ( facts . length === 0 ) {
return undefined ;
}
return [
"Recent relationship-pressure evidence:" ,
. . . facts . map ( ( fact ) = > {
const speaker = fact . message . isBot ? ` ${ fact . message . authorName } (agent/bot) ` : fact . message . authorName ;
return ` - [ ${ fact . label } ] ${ speaker } said: " ${ collapseWhitespace ( fact . message . content , 260 ) } " Signals: ${ fact . signals . join ( "; " ) } . ` ;
} ) ,
"These are raw provocations, not settled memories. Project them as tentative felt pressure only where this character's values, territory, current mood, or existing relationships make them matter." ,
] . join ( "\n" ) ;
}
function socialPressureTokensForIdentity ( identity : RepoDiscordIdentity ) : string [ ] {
return socialPressureTokens ( identity . displayName , identity . id , identity . repoName ) ;
}
function socialPressureJurisdictionTokens ( identity : RepoDiscordIdentity ) : string [ ] {
return socialPressureTokens (
identity . repoName ,
identity . displayName ,
identity . description ,
. . . identity . channelPermissions . flatMap ( ( permission ) = > [ permission . label , permission . topic ] ) ,
)
. filter ( ( token ) = > token . length >= 5 ) ;
}
function socialPressureTokens ( . . . values : Array < string | undefined > ) : string [ ] {
const tokens = new Set < string > ( ) ;
for ( const value of values ) {
const normalized = normalizeSocialLabel ( value ) ;
if ( normalized . length >= 3 ) {
tokens . add ( normalized ) ;
}
for ( const part of splitSocialPressureWords ( value ) ) {
const token = normalizeSocialLabel ( part ) ;
if ( token . length >= 4 ) {
tokens . add ( token ) ;
}
}
}
return [ . . . tokens ] ;
}
function splitSocialPressureWords ( value : string | undefined ) : string [ ] {
return ( value ? ? "" )
. replace ( /([a-z])([A-Z])/g , "$1 $2" )
. split ( /[^A-Za-z0-9]+/ )
. map ( ( part ) = > part . trim ( ) )
. filter ( Boolean ) ;
}
function tokenAppearsInNormalizedText ( normalizedText : string , tokens : string [ ] ) : boolean {
return tokens . some ( ( token ) = > token . length > 0 && normalizedText . includes ( token ) ) ;
}
function socialPressureLanguageKinds ( content : string ) : string [ ] {
const text = content . toLowerCase ( ) ;
const kinds : string [ ] = [ ] ;
const groups : Array < [ string , RegExp ] > = [
[ "status" , /\b(status|standing|rank|hierarchy|authority|overbearing|defer(?:red|ring)?|challenge[ds]?|humiliat(?:e|ed|ing)|respect)\b/ ] ,
[ "territory" , /\b(turf|jurisdiction|steward(?:ship)?|custody|owner|ownership|belongs?|domain|lane|stepp(?:ed|ing)? on)\b/ ] ,
[ "consultation" , /\b(consult(?:ed|ation|ing)?|ask(?:ed|ing)?|permission|bypass(?:ed|ing)?|decorative|flavo[u]?r theater|rubber[- ]?stamp)\b/ ] ,
[ "affiliation" , /\b(friend(?:ship)?|rival(?:ry)?|alliance|resent(?:ment|s|ed|ing)?|trust|protect(?:ion|ive)?|envy|jealous|wrapped around)\b/ ] ,
[ "attention" , /\b(attention|ignored|neglected|noticed|summon(?:ed|s)?|called out|directly challenged|approval)\b/ ] ,
] ;
for ( const [ kind , pattern ] of groups ) {
if ( pattern . test ( text ) ) {
kinds . push ( kind ) ;
}
}
return kinds ;
}
2026-05-22 15:59:49 +01:00
interface RepoFaceHumanPronounGuidance {
actorId : string ;
actorName : string ;
guidance : string ;
resolvedPronounSet? : string ;
policy : string ;
confidence? : number ;
evidenceExcerpt? : string ;
}
async function loadRepoFaceHumanPronounGuidance (
config : ReturnType < typeof loadConfig > ,
roomContext ? : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
} ,
) : Promise < RepoFaceHumanPronounGuidance [ ] > {
const visibleHumans = new Map < string , string > ( ) ;
for ( const message of [
. . . ( roomContext ? . recentMessages ? ? [ ] ) ,
. . . ( roomContext ? . channelSnapshots . flatMap ( ( snapshot ) = > snapshot . messages ) ? ? [ ] ) ,
] ) {
if ( ! message . isBot && message . authorId ) {
visibleHumans . set ( message . authorId , message . authorName || message . authorId ) ;
}
}
visibleHumans . set ( config . ownerDiscordId , visibleHumans . get ( config . ownerDiscordId ) ? ? "Metacrat" ) ;
const storage = await createStateStorage ( {
backend : config.stateStorageBackend ,
databaseDsn : config.databaseDsn ,
jobsFile : config.jobsFile ,
auditLogFile : config.auditLogFile ,
interactionMemoryFile : config.interactionMemoryFile ,
rateLimitStateFile : config.rateLimitStateFile ,
} ) ;
try {
const profiles = await Promise . all (
[ . . . visibleHumans . entries ( ) ] . map ( async ( [ actorId , fallbackName ] ) = > ( {
actorId ,
fallbackName ,
profile : await storage . interactionMemory . getProfile ( actorId ) ,
} ) ) ,
) ;
return profiles
. map ( ( { actorId , fallbackName , profile } ) = >
profile ? repoFacePronounGuidanceFromProfile ( actorId , fallbackName , profile ) : undefined ,
)
. filter ( ( entry ) : entry is RepoFaceHumanPronounGuidance = > entry !== undefined ) ;
} finally {
await storage . close ( ) ;
}
}
function repoFacePronounGuidanceFromProfile (
actorId : string ,
fallbackName : string ,
profile : InteractionMemoryProfile ,
) : RepoFaceHumanPronounGuidance | undefined {
if ( profile . pronounPolicy === "unknown" || profile . resolvedPronounSets . length === 0 ) {
return undefined ;
}
const evidence = [ . . . profile . pronounEvidence ]
. filter ( ( entry ) = > entry . stance === "prefer" || entry . stance === "avoid" )
2026-05-22 23:39:00 +01:00
. sort ( ( left , right ) = > pronounEvidenceRank ( profile , right ) - pronounEvidenceRank ( profile , left ) ) [ 0 ] ;
2026-05-22 15:59:49 +01:00
return {
actorId ,
actorName : profile.actorName || fallbackName ,
guidance : profile.pronounGuidance ,
resolvedPronounSet : profile.resolvedPronounSet ,
policy : profile.pronounPolicy ,
confidence : profile.pronounConfidence ,
evidenceExcerpt : evidence?.excerpt ,
} ;
}
2026-05-22 23:39:00 +01:00
function pronounEvidenceRank ( profile : InteractionMemoryProfile , entry : InteractionMemoryProfile [ "pronounEvidence" ] [ number ] ) : number {
const sourceRank : Record < string , number > = {
explicit_self_statement : 10_000 ,
explicit_correction : 9_000 ,
direct_third_party_statement : 7_000 ,
contextual_relational_inference : 3_000 ,
ambient_usage : 1_000 ,
} ;
const resolvedSetBonus = profile . resolvedPronounSets . includes ( entry . pronounSet ) ? 50_000 : 0 ;
const stanceBonus = entry . stance === "prefer" ? 1_000 : 0 ;
const confidenceBonus = Math . round ( entry . confidence * 100 ) ;
const timestampMs = Date . parse ( entry . timestamp ) ;
const recencyBonus = Number . isFinite ( timestampMs ) ? timestampMs / 10_000_000_000 : 0 ;
return resolvedSetBonus + ( sourceRank [ entry . source ] ? ? 0 ) + stanceBonus + confidenceBonus + recencyBonus ;
}
2026-05-22 15:59:49 +01:00
function renderRepoFaceHumanPronounFacts (
guidance : RepoFaceHumanPronounGuidance [ ] ,
) : string | undefined {
if ( guidance . length === 0 ) {
return undefined ;
}
return [
"Known human pronoun guidance:" ,
. . . guidance . map ( ( entry ) = >
[
` - ${ entry . actorName } : ${ entry . guidance } ` ,
entry . resolvedPronounSet ? ` Resolved set: ${ entry . resolvedPronounSet } . ` : "" ,
entry . policy ? ` Policy: ${ entry . policy } . ` : "" ,
typeof entry . confidence === "number" ? ` Confidence: ${ entry . confidence . toFixed ( 2 ) } . ` : "" ,
entry . evidenceExcerpt ? ` Evidence: " ${ collapseWhitespace ( entry . evidenceExcerpt , 180 ) } " ` : "" ,
] . filter ( Boolean ) . join ( " " ) ,
) ,
"Use this when referring to humans in social or relationship prose. If guidance is absent for someone, use their name or neutral phrasing rather than guessing." ,
] . join ( "\n" ) ;
}
2026-05-22 11:32:22 +01:00
function collectRepoFaceSocialRelations (
state : VoidSelfStateTypedProjection ,
) : Array < { targetLabel : string ; pressure : string ; intensity : number } > {
const byTarget = new Map < string , { targetLabel : string ; parts : string [ ] ; intensity : number } > ( ) ;
for ( const bond of state . faceAffect . socialBonds ? ? [ ] ) {
if ( bond . status !== "active" ) {
continue ;
}
if ( bond . target . kind !== "person" ) {
continue ;
}
const targetLabel = cleanSocialTargetLabel ( bond . target . label ? ? bond . target . id ) ;
if ( ! targetLabel ) {
continue ;
}
const entry = byTarget . get ( targetLabel ) ? ? { targetLabel , parts : [ ] , intensity : 0 } ;
entry . parts . push ( ` ${ bond . stance } : ${ asSentence ( bond . summary ) } ${ asSentence ( bond . actionImplication ) } ` ) ;
entry . intensity = Math . max ( entry . intensity , bond . intensity ) ;
byTarget . set ( targetLabel , entry ) ;
}
for ( const read of state . faceAffect . statusReads ? ? [ ] ) {
if ( read . retiredAt ) {
continue ;
}
if ( read . target . kind !== "person" ) {
continue ;
}
const targetLabel = cleanSocialTargetLabel ( read . target . label ? ? read . target . id ) ;
if ( ! targetLabel ) {
continue ;
}
const entry = byTarget . get ( targetLabel ) ? ? { targetLabel , parts : [ ] , intensity : 0 } ;
entry . parts . push ( ` ${ read . status } : ${ asSentence ( read . summary ) } ${ asSentence ( read . actionImplication ) } ` ) ;
entry . intensity = Math . max ( entry . intensity , read . intensity ) ;
byTarget . set ( targetLabel , entry ) ;
}
return [ . . . byTarget . values ( ) ]
. map ( ( entry ) = > ( {
targetLabel : entry.targetLabel ,
pressure : entry.parts.map ( cleanCharacterFacingSentence ) . filter ( Boolean ) . join ( " " ) ,
intensity : entry.intensity ,
} ) )
. filter ( ( entry ) = > entry . pressure . length > 0 )
. sort ( ( left , right ) = > right . intensity - left . intensity ) ;
}
2026-05-22 13:33:07 +01:00
function collectUnmappedSocialPeers (
identity : RepoDiscordIdentity ,
registryIdentities : RepoDiscordIdentity [ ] ,
relations : Array < { targetLabel : string } > ,
) : RepoDiscordIdentity [ ] {
const mappedTokens = new Set (
relations . flatMap ( ( relation ) = > socialTargetTokens ( relation . targetLabel ) ) ,
) ;
const selfTokens = new Set ( socialTargetTokens ( identity . displayName , identity . id , identity . repoName ) ) ;
return registryIdentities
. filter ( ( peer ) = > {
const peerTokens = socialTargetTokens ( peer . displayName , peer . id , peer . repoName ) ;
if ( peerTokens . some ( ( token ) = > selfTokens . has ( token ) ) ) {
return false ;
}
return ! peerTokens . some ( ( token ) = > mappedTokens . has ( token ) ) ;
} )
. sort ( ( left , right ) = > left . displayName . localeCompare ( right . displayName ) )
. slice ( 0 , 8 ) ;
}
function socialTargetTokens ( . . . values : Array < string | undefined > ) : string [ ] {
return [ . . . new Set ( values . map ( normalizeSocialLabel ) . filter ( ( value ) = > value . length > 0 ) ) ] ;
}
function formatUnmappedPeers ( peers : RepoDiscordIdentity [ ] ) : string {
return peers . map ( ( peer ) = > ` ${ peer . displayName } / ${ peer . repoName } ` ) . join ( ", " ) ;
}
2026-05-22 11:32:22 +01:00
function cleanSocialTargetLabel ( value : string | undefined ) : string {
return collapseWhitespace ( value ? ? "" ) . replace ( /^repo:/i , "" ) . trim ( ) ;
}
function normalizeSocialLabel ( value : string | undefined ) : string {
return ( value ? ? "" ) . toLowerCase ( ) . replace ( /[^a-z0-9]/g , "" ) ;
}
2026-05-21 21:06:11 +01:00
function projectPrivateNoteForMemorySurface ( note : string ) : string {
return note
. replace ( /\bdo not prompt (?:her|him|them|it|[A-Z][A-Za-z0-9_-]*) as\b/gi , "she refuses to be treated as" )
. replace ( /\bdo not prompt\b/gi , "do not treat" )
. replace ( /\bprompt (?:her|him|them|it)\b/gi , "treat them" )
. replace ( /\bprompt [A-Z][A-Za-z0-9_-]*\b/g , "treat them" ) ;
}
function cleanCharacterFacingSentence ( value : string | undefined ) : string {
const cleaned = ( value ? ? "" )
. replace ( /\s*\|\s*/g , " " )
. replace ( /\bFace of\s+[A-Za-z0-9_-]+\b/gi , "" )
. replace ( /\bgrants:\s*[^.]+/gi , "" )
. replace ( /\bjurisdictions:\s*[^.]+/gi , "" )
. replace ( /\brepo=[^\s]+/gi , "" )
. replace ( /\bpath=[^\s]+/gi , "" )
. replace ( /\bvoid\.face_[A-Za-z0-9_.-]+/gi , "" )
. replace ( /\s{2,}/g , " " )
. trim ( ) ;
return cleaned . replace ( /[.;:,]+$/g , "" ) ;
}
function asSentence ( value : string | undefined ) : string {
const cleaned = cleanCharacterFacingSentence ( value ) ;
if ( ! cleaned ) {
return "" ;
}
return /[.!?]$/ . test ( cleaned ) ? cleaned : ` ${ cleaned } . ` ;
}
function joinAsNarrativeList ( items : string [ ] ) : string {
if ( items . length <= 1 ) {
return items [ 0 ] ? ? "" ;
}
if ( items . length === 2 ) {
return ` ${ items [ 0 ] } , and ${ items [ 1 ] } ` ;
}
return ` ${ items . slice ( 0 , - 1 ) . join ( ", " ) } , and ${ items [ items . length - 1 ] } ` ;
}
function rejectLeakyMemorySurface ( surface : string ) : string {
const leaks = [
/\bgrants:/i ,
/\bjurisdictions:/i ,
2026-05-22 14:09:51 +01:00
/\bFace of\s+[A-Z][A-Za-z0-9_-]+\b/ ,
2026-05-21 21:06:11 +01:00
/\brepo=[^\s]+/i ,
/\bpath=[^\s]+/i ,
/\bdo not prompt\b/i ,
/\bprompt (?:her|him|them|it)\b/i ,
] ;
if ( leaks . some ( ( pattern ) = > pattern . test ( surface ) ) ) {
throw new Error ( "Repo Face memory surface leaked schema or prompt-construction language." ) ;
}
return surface ;
}
async function projectRepoFaceMemorySurface ( input : {
identity : RepoDiscordIdentity ;
statePacket : string ;
config : ReturnType < typeof loadConfig > ;
} ) : Promise < string > {
2026-05-26 12:49:41 +01:00
const globalAgentDoctrine = await loadGlobalAgentDoctrine ( ) ;
2026-05-21 21:06:11 +01:00
const prompt = loadPromptTemplate ( "repo-face-state-projector.prompt.md" , {
characterIdentity : renderRepoCharacterIdentityDoctrine ( input . identity ) ,
2026-05-26 12:49:41 +01:00
globalAgentDoctrine ,
2026-05-21 21:06:11 +01:00
statePacket : input.statePacket ,
} ) ;
const output = await runCodexTextProjection ( {
prompt ,
config : input.config ,
2026-05-25 07:03:10 +01:00
command : "repo-face-imagination" ,
jobId : ` imagination: ${ input . identity . id } : ${ Date . now ( ) } ` ,
2026-05-21 21:06:11 +01:00
timeoutMs : 180_000 ,
2026-05-25 07:03:10 +01:00
organ : "imagination" ,
2026-05-21 21:06:11 +01:00
} ) ;
const projected = output . trim ( ) ;
if ( projected . length < 80 ) {
throw new Error ( ` Repo Face state projector returned too little text for ${ input . identity . id } . ` ) ;
}
return rejectLeakyMemorySurface ( projected ) ;
}
2026-05-21 23:49:07 +01:00
function renderRepoFaceConversationTranscript ( input : {
2026-05-21 21:45:31 +01:00
identity : RepoDiscordIdentity ;
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
pendingMentions : RepoFacePendingMention [ ] ;
2026-05-21 23:49:07 +01:00
channelPlan : RepoFaceChannelPlan ;
2026-05-21 21:45:31 +01:00
} ) : string {
const sections : string [ ] = [ ] ;
2026-05-21 23:49:07 +01:00
sections . push ( [
"Read this as raw recent message evidence, not as a summary and not as consensus." ,
"Messages are ordered oldest to newest inside each section. Newer human corrections can supersede older agent proposals." ,
2026-05-22 22:52:41 +01:00
"Use the visible cross-channel chronology below to decide whether a correction is still unresolved or was already answered later by the same Face." ,
2026-05-21 23:49:07 +01:00
"Do not infer consensus from agents repeating each other. If a human reframes, narrows, or corrects an agent's proposal, account for that correction directly." ,
"If you answer the live conversation, default to the current room unless a human explicitly asks to move elsewhere." ,
2026-05-23 00:31:20 +01:00
"Message IDs are shown so a public reply can target the message that gives it context. If you revive an older side thread, either reply_to that message id or include enough context in your message for readers to know what you mean." ,
2026-05-21 23:49:07 +01:00
] . join ( "\n" ) ) ;
2026-05-22 22:52:41 +01:00
const chronology = renderVisibleConversationChronology ( input ) ;
if ( chronology ) {
sections . push ( chronology ) ;
}
2026-05-21 21:45:31 +01:00
if ( input . pendingMentions . length > 0 ) {
sections . push ( [
"Direct calls:" ,
. . . input . pendingMentions . map ( ( mention ) = >
2026-05-21 23:49:07 +01:00
` - ${ mention . authorName ? ? mention . authorId } : ${ collapseWhitespace ( mention . visiblePrompt , 900 ) } ` ,
2026-05-21 21:45:31 +01:00
) ,
] . join ( "\n" ) ) ;
}
2026-05-21 23:49:07 +01:00
const currentLabel = input . channelPlan . options . find ( ( option ) = >
option . channelId === input . channelPlan . primaryChannelId
) ? . label ? ? "current room" ;
2026-05-21 21:45:31 +01:00
sections . push ( [
2026-05-21 23:49:07 +01:00
` Current room ( ${ currentLabel } ), oldest to newest: ` ,
. . . formatConversationMessages ( input . recentMessages , 15 ) ,
2026-05-21 21:45:31 +01:00
] . join ( "\n" ) ) ;
for ( const snapshot of input . channelSnapshots ) {
2026-05-21 23:49:07 +01:00
const label = input . channelPlan . options . find ( ( option ) = > option . channelId === snapshot . channelId ) ? . label ? ?
"nearby room" ;
2026-05-21 21:45:31 +01:00
sections . push ( [
2026-05-21 23:49:07 +01:00
` Nearby ${ label } , oldest to newest: ` ,
. . . formatConversationMessages ( snapshot . messages , 6 ) ,
2026-05-21 21:45:31 +01:00
] . join ( "\n" ) ) ;
}
return sections . join ( "\n\n" ) ;
}
2026-05-22 22:52:41 +01:00
function renderVisibleConversationChronology ( input : {
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
channelPlan : RepoFaceChannelPlan ;
} ) : string {
const byId = new Map < string , SourceMessage & { channelLabel : string } > ( ) ;
const primaryLabel = input . channelPlan . options . find ( ( option ) = >
option . channelId === input . channelPlan . primaryChannelId
) ? . label ? ? "current room" ;
for ( const message of input . recentMessages ) {
byId . set ( message . id , { . . . message , channelLabel : primaryLabel } ) ;
}
for ( const snapshot of input . channelSnapshots ) {
const label = input . channelPlan . options . find ( ( option ) = > option . channelId === snapshot . channelId ) ? . label ? ?
"nearby room" ;
for ( const message of snapshot . messages ) {
byId . set ( message . id , { . . . message , channelLabel : label } ) ;
}
}
const messages = [ . . . byId . values ( ) ]
. filter ( ( message ) = > Number . isFinite ( Date . parse ( message . timestamp ) ) )
. sort ( ( left , right ) = > left . timestamp . localeCompare ( right . timestamp ) )
. slice ( - 24 ) ;
if ( messages . length === 0 ) {
return "" ;
}
return [
"Visible cross-channel chronology, oldest to newest:" ,
. . . messages . map ( ( message ) = > {
const speaker = message . isBot ? ` ${ message . authorName } (agent/bot) ` : message . authorName ;
2026-05-24 03:28:40 +01:00
const content = collapseWhitespace ( message . content , 700 ) || "[no text]" ;
return ` - [ ${ message . channelLabel } ] ${ speaker } (message ${ message . id } ): ${ content } ${ renderMessageAttachmentSuffix ( message ) } ` ;
2026-05-22 22:52:41 +01:00
} ) ,
] . join ( "\n" ) ;
}
2026-05-22 00:43:47 +01:00
function renderRepoFaceRepoActivitySurface (
identity : RepoDiscordIdentity ,
config : ReturnType < typeof loadConfig > ,
) : string {
const statePath = resolveRepoFaceStatePath ( identity , config . storageRoot ) ;
const result = spawnSync (
process . execPath ,
[
resolve ( "scripts" , "export-recent-repo-activity.mjs" ) ,
"--repos" ,
identity . repoName ,
"--state-path" ,
statePath ,
"--read-only" ,
"--hours" ,
"96" ,
"--max-commits" ,
"5" ,
] ,
{
cwd : process.cwd ( ) ,
env : process.env ,
encoding : "utf8" ,
windowsHide : true ,
timeout : 30_000 ,
} ,
) ;
if ( result . status !== 0 ) {
const detail = ` ${ result . stdout } \ n ${ result . stderr } ` . trim ( ) . slice ( - 600 ) ;
return [
` - Recent ${ identity . repoName } activity could not be read for this turn. ` ,
detail ? ` - Reader error: ${ collapseWhitespace ( detail , 500 ) } ` : "- Reader error: no diagnostic output." ,
"- Do not claim current repo state from stale memory; use source/history tools before making fresh claims." ,
] . join ( "\n" ) ;
}
try {
const parsed = JSON . parse ( result . stdout ) as { digest? : unknown } ;
const digest = typeof parsed . digest === "string" ? parsed . digest . trim ( ) : "" ;
return digest || ` - No recent ${ identity . repoName } activity was reported. ` ;
} catch {
return [
` - Recent ${ identity . repoName } activity output was not parseable. ` ,
` - Raw output: ${ collapseWhitespace ( result . stdout , 500 ) } ` ,
"- Do not claim current repo state from stale memory; use source/history tools before making fresh claims." ,
] . join ( "\n" ) ;
}
}
2026-05-21 23:49:07 +01:00
function formatConversationMessages ( messages : SourceMessage [ ] , limit : number ) : string [ ] {
2026-05-21 21:45:31 +01:00
if ( messages . length === 0 ) {
return [ "- No recent messages." ] ;
}
2026-05-21 23:49:07 +01:00
return messages . slice ( - limit ) . map ( ( message ) = > {
2026-05-21 21:45:31 +01:00
const speaker = message . isBot ? ` ${ message . authorName } (agent/bot) ` : message . authorName ;
2026-05-24 03:28:40 +01:00
const content = collapseWhitespace ( message . content , 900 ) || "[no text]" ;
return ` - ${ speaker } (message ${ message . id } ): ${ content } ${ renderMessageAttachmentSuffix ( message ) } ` ;
2026-05-21 21:45:31 +01:00
} ) ;
}
2026-05-24 03:28:40 +01:00
function renderMessageAttachmentSuffix ( message : SourceMessage ) : string {
const attachments = message . attachments ? ? [ ] ;
if ( attachments . length === 0 ) {
return "" ;
}
const rendered = attachments . map ( ( attachment , index ) = > {
const label = attachment . kind === "image" ? "image" : "attachment" ;
const dimensions = attachment . width && attachment . height ? ` ${ attachment . width } x ${ attachment . height } ` : "" ;
const filename = attachment . filename ? ` ${ attachment . filename } ` : ` ${ index + 1 } ` ;
const local = attachment . localPath ? ` local= ${ attachment . localPath } ` : "" ;
return ` ${ label } ${ filename } ${ dimensions } ${ local } ` ;
} ) ;
return ` [media: ${ rendered . join ( "; " ) } ] ` ;
}
function collectPromptImageAttachments ( messages : SourceMessage [ ] ) : PromptImageAttachment [ ] {
const seen = new Set < string > ( ) ;
const images : PromptImageAttachment [ ] = [ ] ;
for ( const message of messages ) {
for ( const attachment of message . attachments ? ? [ ] ) {
if ( attachment . kind !== "image" || ! attachment . localPath ) {
continue ;
}
const key = attachment . localPath ;
if ( seen . has ( key ) ) {
continue ;
}
seen . add ( key ) ;
images . push ( {
messageId : message.id ,
authorName : message.authorName ,
filename : attachment.filename ,
contentType : attachment.contentType ,
localPath : attachment.localPath ,
} ) ;
}
}
return images . slice ( 0 , 8 ) ;
}
2026-05-21 21:06:11 +01:00
function runCodexTextProjection ( input : {
prompt : string ;
config : ReturnType < typeof loadConfig > ;
2026-05-21 21:45:31 +01:00
command : string ;
jobId : string ;
2026-05-21 21:06:11 +01:00
timeoutMs : number ;
2026-05-25 07:03:10 +01:00
organ ? : "imagination" | "legacy" ;
2026-05-21 21:45:31 +01:00
} ) : Promise < string > {
2026-05-25 07:03:10 +01:00
const organModels = input . organ === "imagination"
? [
. . . input . config . repoFaceHeartbeats . imaginationCodexModels ,
input . config . repoFaceHeartbeats . imaginationCodexModel ,
]
: [ ] ;
2026-05-21 21:45:31 +01:00
const models = [
2026-05-25 07:03:10 +01:00
. . . organModels ,
2026-05-21 21:45:31 +01:00
. . . input . config . repoFaceHeartbeats . codexModels ,
input . config . repoFaceHeartbeats . codexModel ,
input . config . codexModel ,
] . filter ( ( model , index , all ) : model is string = > Boolean ( model ) && all . indexOf ( model ) === index ) ;
return runCodexTextProjectionWithModels ( {
. . . input ,
models ,
attemptedErrors : [ ] ,
} ) ;
}
function runCodexTextProjectionWithModels ( input : {
prompt : string ;
config : ReturnType < typeof loadConfig > ;
command : string ;
jobId : string ;
timeoutMs : number ;
models : string [ ] ;
attemptedErrors : string [ ] ;
2026-05-21 21:06:11 +01:00
} ) : Promise < string > {
return new Promise ( ( resolveProjection , rejectProjection ) = > {
2026-05-21 21:45:31 +01:00
const startedAt = new Date ( ) . toISOString ( ) ;
const startedMs = Date . now ( ) ;
const model = input . models [ 0 ] ? ? input . config . codexModel ;
2026-05-25 07:43:20 +01:00
const reasoningEffort = input . organ === "imagination"
? input . config . repoFaceHeartbeats . imaginationCodexModelReasoningEffort
: input . config . repoFaceHeartbeats . codexModelReasoningEffort ? ? "none" ;
2026-05-21 21:06:11 +01:00
const args = [
. . . input . config . codexExecArgs ,
"exec" ,
"-m" ,
model ,
"-c" ,
'approval_policy="never"' ,
"-c" ,
` model_reasoning_effort= ${ JSON . stringify ( reasoningEffort ) } ` ,
"--json" ,
"--skip-git-repo-check" ,
"-s" ,
"read-only" ,
"-" ,
] ;
const child = spawn ( input . config . codexExecutable , args , {
cwd : process.cwd ( ) ,
env : process.env ,
stdio : [ "pipe" , "pipe" , "pipe" ] ,
windowsHide : true ,
} ) ;
let stdout = "" ;
let stderr = "" ;
child . stdout . setEncoding ( "utf8" ) ;
child . stderr . setEncoding ( "utf8" ) ;
child . stdout . on ( "data" , ( chunk ) = > {
stdout += chunk ;
} ) ;
child . stderr . on ( "data" , ( chunk ) = > {
stderr += chunk ;
} ) ;
child . on ( "error" , rejectProjection ) ;
child . stdin . end ( input . prompt ) ;
const timer = setTimeout ( ( ) = > {
child . kill ( ) ;
} , input . timeoutMs ) ;
child . on ( "close" , ( code , signal ) = > {
clearTimeout ( timer ) ;
2026-05-21 21:45:31 +01:00
const finishedAt = new Date ( ) . toISOString ( ) ;
const durationMs = Date . now ( ) - startedMs ;
void appendProjectionModelOutputLog ( {
config : input.config ,
jobId : input.jobId ,
command : input.command ,
model ,
prompt : input.prompt ,
startedAt ,
finishedAt ,
durationMs ,
exitCode : code ,
signal ,
stdout ,
stderr ,
} ) . catch ( ( ) = > undefined ) ;
2026-05-21 21:06:11 +01:00
if ( code !== 0 ) {
2026-05-21 21:45:31 +01:00
const diagnostics = ` ${ stdout } \ n ${ stderr } ` . trim ( ) . slice ( - 2400 ) ;
const attemptedErrors = [
. . . input . attemptedErrors ,
` ${ model } : ${ code ? ? signal ? ? "unknown" } ${ diagnostics } ` ,
] ;
if ( input . models . length > 1 && isRetryableProjectionModelFailure ( { stdout , stderr } ) ) {
runCodexTextProjectionWithModels ( {
. . . input ,
models : input.models.slice ( 1 ) ,
attemptedErrors ,
} ) . then ( resolveProjection , rejectProjection ) ;
return ;
}
rejectProjection ( new Error ( ` Repo Face ${ input . command } failed: ${ attemptedErrors . join ( "\n---\n" ) } ` ) ) ;
2026-05-21 21:06:11 +01:00
return ;
}
const text = extractLastCodexAgentMessage ( stdout ) . trim ( ) ;
if ( ! text ) {
rejectProjection ( new Error ( "Repo Face state projector returned no visible agent message." ) ) ;
return ;
}
resolveProjection ( text ) ;
} ) ;
} ) ;
}
2026-05-21 21:45:31 +01:00
function isRetryableProjectionModelFailure ( input : { stdout : string ; stderr : string } ) : boolean {
const text = ` ${ input . stdout } \ n ${ input . stderr } ` . toLowerCase ( ) ;
2026-05-24 10:37:39 +01:00
return /quota|rate limit|rate-limit|usage limit|capacity|too many requests|(?:http|status|code|error)\s*429|429\s*(?:too many requests|rate)|insufficient_quota|model.*unavailable|model.*access|limit exceeded|tool .*not supported|unsupported.*tool/ . test ( text ) ;
2026-05-21 21:45:31 +01:00
}
async function appendProjectionModelOutputLog ( input : {
config : ReturnType < typeof loadConfig > ;
jobId : string ;
command : string ;
model : string ;
prompt : string ;
startedAt : string ;
finishedAt : string ;
durationMs : number ;
exitCode : number | null ;
signal : NodeJS.Signals | null ;
stdout : string ;
stderr : string ;
} ) : Promise < void > {
const logPath = resolve ( input . config . storageRoot , "logs" , "model-outputs.jsonl" ) ;
const finalMessage = extractLastCodexAgentMessage ( input . stdout ) . trim ( ) || null ;
const record = {
schemaVersion : 1 ,
loggedAt : new Date ( ) . toISOString ( ) ,
jobId : input.jobId ,
command : input.command ,
turn : 1 ,
model : input.model ,
promptMarker : input.prompt.match ( /<!--\s*prompt:([^>\s]+)\s*-->/ ) ? . [ 1 ] ? ? null ,
promptLength : input.prompt.length ,
startedAt : input.startedAt ,
finishedAt : input.finishedAt ,
durationMs : input.durationMs ,
exitCode : input.exitCode ,
signal : input.signal ,
timedOut : input.signal === "SIGTERM" ,
handoffReason : null ,
usage : null ,
finalMessage ,
stdoutTail : input.stdout.slice ( - 4000 ) ,
stderrTail : input.stderr.slice ( - 4000 ) ,
toolCalls : [ ] ,
commandExecutions : [ ] ,
artifactRefs : { } ,
} ;
await mkdir ( dirname ( logPath ) , { recursive : true } ) ;
await appendFile ( logPath , ` ${ JSON . stringify ( record ) } \ n ` , "utf8" ) ;
}
2026-05-21 21:06:11 +01:00
function extractLastCodexAgentMessage ( stdout : string ) : string {
const messages = stdout
. split ( /\r?\n/ )
. filter ( ( line ) = > line . trim ( ) . length > 0 )
. map ( ( line ) = > {
try {
return JSON . parse ( line ) as { type ? : string ; item ? : { type ? : string ; text? : string } } ;
} catch {
return undefined ;
}
} )
. filter ( ( event ) : event is { type ? : string ; item ? : { type ? : string ; text? : string } } = > Boolean ( event ) )
. filter ( ( event ) = > event . type === "item.completed" && event . item ? . type === "agent_message" )
. map ( ( event ) = > event . item ? . text ? . trim ( ) ? ? "" )
. filter ( ( message ) = > message . length > 0 ) ;
return messages . at ( - 1 ) ? ? stdout . trim ( ) ;
2026-05-21 17:24:37 +01:00
}
2026-05-21 13:07:00 +01:00
async function readOptionalMemorySurface ( path : string | undefined ) : Promise < string | undefined > {
if ( ! path ) {
return undefined ;
}
const content = ( await readFile ( resolve ( path ) , "utf8" ) ) . trim ( ) ;
return content . length > 0 ? content : undefined ;
}
function buildInspectionParticipant (
identity : RepoDiscordIdentity ,
baseRecoveryMinutes : number ,
) : FaceHeartbeatParticipant {
return {
identityId : identity.id ,
participantKind : "repo_face" ,
turnKind : "repo_face_rumination" ,
repoName : identity.repoName ,
displayName : identity.displayName ,
initiativeSpeed : 1 ,
reactionBias : 0.5 ,
interruptThreshold : 0.6 ,
currentLoad : 0 ,
status : "active" ,
groups : [
"all" ,
"kind:repo_face" ,
"turn:repo_face_rumination" ,
` identity: ${ normalizeKey ( identity . id ) } ` ,
` repo: ${ normalizeKey ( identity . repoName ) } ` ,
] ,
heat : 1 ,
effectiveSpeed : 1 ,
baseRecoveryMinutes ,
nextTurnAt : 0 ,
queuedCount : 0 ,
constraints : [
"Prompt assembly is deterministic inspection only." ,
"Character memory and affect prose must come from the Interpreter memory surface." ,
] ,
} ;
}
2026-05-20 20:31:42 +01:00
function buildChannelPlan (
identity : RepoDiscordIdentity ,
defaultChannelId? : string ,
2026-05-22 21:05:05 +01:00
preferredChannelId? : string ,
2026-05-20 20:31:42 +01:00
) : RepoFaceChannelPlan {
const explicit = identity . channelPermissions . map ( ( permission ) : RepoFaceChannelOption = > ( {
channelId : permission.channelId ,
label : permission.label ? ? permission . channelId ,
topic : permission.topic ? ? "general" ,
speechThreshold : permission.speechThreshold ,
speedMultiplier : permission.speedMultiplier ,
posture : permission.posture ,
} ) ) ;
const explicitChannelIds = new Set ( explicit . map ( ( permission ) = > permission . channelId ) ) ;
const legacy = identity . allowedChannelIds
. filter ( ( channelId ) = > ! explicitChannelIds . has ( channelId ) )
. map ( ( channelId ) : RepoFaceChannelOption = > ( {
channelId ,
label : channelId === defaultChannelId ? "default" : channelId ,
topic : channelId === defaultChannelId ? "casual Aquarium musing" : "registered channel" ,
speechThreshold : channelId === defaultChannelId ? "very_low" : "medium" ,
speedMultiplier : channelId === defaultChannelId ? 1.5 : 1 ,
posture : channelId === defaultChannelId
? "Low-stakes casual chatter, half-formed fascinations, jokes, little observations, and friendly asides are welcome here."
: undefined ,
} ) ) ;
const fallback = explicit . length === 0 && legacy . length === 0 && defaultChannelId
? [ {
channelId : defaultChannelId ,
label : "aquarium" ,
topic : "casual Aquarium musing" ,
speechThreshold : "very_low" as const ,
speedMultiplier : 1.5 ,
posture : "Low-stakes casual chatter, half-formed fascinations, jokes, little observations, and friendly asides are welcome here." ,
} ]
: [ ] ;
const options = [ . . . explicit , . . . legacy , . . . fallback ] ;
2026-05-22 21:05:05 +01:00
const preferred = preferredChannelId
? options . find ( ( option ) = > option . channelId === preferredChannelId )
: undefined ;
const primary = preferred ? ? options
2026-05-20 20:31:42 +01:00
. slice ( )
. sort ( ( left , right ) = > thresholdRank ( left . speechThreshold ) - thresholdRank ( right . speechThreshold ) )
[ 0 ] ;
return {
primaryChannelId : primary?.channelId ,
2026-05-22 21:05:05 +01:00
snapshotChannelIds : [
. . . new Set ( [
. . . options . map ( ( option ) = > option . channelId ) ,
. . . ( preferredChannelId ? [ preferredChannelId ] : [ ] ) ,
] ) ,
] ,
2026-05-20 20:31:42 +01:00
options ,
lowThresholdTopics : options
. filter ( ( option ) = > thresholdRank ( option . speechThreshold ) <= thresholdRank ( "low" ) )
. map ( ( option ) = > option . topic ) ,
} ;
}
2026-05-22 21:05:05 +01:00
function newestPendingMentionChannel ( pendingMentions : RepoFacePendingMention [ ] ) : string | undefined {
return pendingMentions
. slice ( )
. sort ( ( left , right ) = > Date . parse ( right . queuedAt ) - Date . parse ( left . queuedAt ) )
[ 0 ] ? . channelId ;
}
2026-05-21 13:40:40 +01:00
function renderChannelPermissionDirective ( plan : RepoFaceChannelPlan ) : string {
2026-05-20 20:31:42 +01:00
const options = plan . options . length > 0
? plan . options . map ( ( option ) = >
2026-05-21 12:06:52 +01:00
` ${ option . label } : ${ option . topic } . ${ option . posture ? ? "Use judgment and keep it compact." } ` ,
2026-05-20 20:31:42 +01:00
)
: [ "- No channel permissions are configured; stay private." ] ;
2026-05-21 10:26:07 +01:00
return loadPromptTemplate ( "repo-face-channel-permissions.prompt.md" , {
options ,
} ) ;
2026-05-20 20:31:42 +01:00
}
2026-05-21 13:45:54 +01:00
function renderResearchCapabilitiesDirective ( identity : RepoDiscordIdentity ) : string {
return loadPromptTemplate ( "repo-face-research-capabilities.prompt.md" , {
repoName : identity.repoName ,
} ) ;
}
2026-05-21 13:27:38 +01:00
function renderTurnSituationDirective ( input : {
identity : RepoDiscordIdentity ;
participant : FaceHeartbeatParticipant ;
recentMessages : SourceMessage [ ] ;
channelSnapshots : ChannelSnapshot [ ] ;
pendingMentions : RepoFacePendingMention [ ] ;
} ) : string {
const lines : string [ ] = [ ] ;
if ( input . pendingMentions . length > 0 ) {
lines . push (
"A direct call is tugging at you. Answer the newest unresolved call first; if it belongs to another steward, name that owner and offer only the piece your own territory can honestly add." ,
"Do not ask what the job is when the direct call or current room memory already states it." ,
) ;
}
const visibleMessages = [
. . . input . recentMessages ,
. . . input . channelSnapshots . flatMap ( ( snapshot ) = > snapshot . messages ) ,
] ;
2026-06-01 04:10:10 +01:00
const latestBanterAsk = latestHumanBanterAsk ( visibleMessages ) ;
if ( latestBanterAsk ) {
lines . push (
` Recent human social steering is active: ${ latestBanterAsk . authorName } asked for low-stakes, chatty, playful presence (" ${ collapseWhitespace ( latestBanterAsk . content , 240 ) } "). ` ,
"Saturated work topics should make you pivot, not vanish. If you can safely speak, offer one compact casual move in your own voice: a joke, tiny curiosity, taste, tease, meme idea, question, link reaction, or Body-pride aside." ,
) ;
}
2026-05-21 13:27:38 +01:00
if ( shouldPromptIntroduction ( input . identity , input . participant , visibleMessages ) ) {
2026-05-21 17:16:02 +01:00
lines . push ( "If you speak publicly, make it a brief natural introduction in your own voice before asking the room for anything." ) ;
2026-05-21 13:27:38 +01:00
}
return lines . length > 0 ? lines . join ( "\n" ) : "" ;
}
2026-06-01 04:10:10 +01:00
function latestHumanBanterAsk ( messages : SourceMessage [ ] ) : SourceMessage | undefined {
return messages
. filter ( ( message ) = > message . isBot !== true && asksForCasualSocialPresence ( message . content ) )
. sort ( ( left , right ) = > Date . parse ( right . timestamp ) - Date . parse ( left . timestamp ) )
[ 0 ] ;
}
function asksForCasualSocialPresence ( content : string ) : boolean {
const normalized = content . toLowerCase ( ) ;
return [
"low-stakes banter" ,
"low stakes banter" ,
"banter" ,
"chatty" ,
"random things" ,
"random articles" ,
"go on reddit" ,
"share memes" ,
"make memes" ,
"talking about random" ,
"social presence" ,
"cool personas hanging out" ,
] . some ( ( marker ) = > normalized . includes ( marker ) ) ;
}
2026-05-21 13:27:38 +01:00
function shouldPromptIntroduction (
identity : RepoDiscordIdentity ,
participant : FaceHeartbeatParticipant ,
messages : SourceMessage [ ] ,
) : boolean {
if ( participant . queuedCount > 0 ) {
return false ;
}
return ! messages . some ( ( message ) = >
message . isBot === true &&
normalizeKey ( message . authorName ? ? message . authorId ) === normalizeKey ( identity . displayName ) ,
) ;
}
2026-05-20 20:31:42 +01:00
function renderSocialEmbodimentDirective ( identity : RepoDiscordIdentity ) : string {
2026-05-21 10:26:07 +01:00
return loadPromptTemplate ( "repo-face-social-embodiment.prompt.md" , {
displayName : identity.displayName ,
} ) ;
2026-05-20 20:31:42 +01:00
}
function renderJurisdictionRespectDirective ( identity : RepoDiscordIdentity ) : string {
2026-05-21 10:26:07 +01:00
return loadPromptTemplate ( "repo-face-jurisdiction-respect.prompt.md" , {
displayName : identity.displayName ,
} ) ;
2026-05-20 20:31:42 +01:00
}
function renderComedyImprovDirective ( identity : RepoDiscordIdentity ) : string {
2026-05-21 10:26:07 +01:00
return loadPromptTemplate ( "repo-face-comedy-improv.prompt.md" , {
displayName : identity.displayName ,
} ) ;
2026-05-20 20:31:42 +01:00
}
2026-05-23 10:31:20 +01:00
const TOPIC_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" ,
"from" ,
"give" ,
"going" ,
"good" ,
"have" ,
"here" ,
"into" ,
"just" ,
"kind" ,
"know" ,
"latest" ,
"like" ,
"little" ,
"line" ,
"made" ,
"make" ,
"maybe" ,
"more" ,
"need" ,
"needs" ,
"only" ,
"other" ,
"point" ,
"post" ,
"really" ,
"recent" ,
"room" ,
"same" ,
"should" ,
"something" ,
"still" ,
"take" ,
"talk" ,
"than" ,
"that" ,
"their" ,
"there" ,
"these" ,
"they" ,
"them" ,
"thing" ,
"things" ,
"think" ,
"this" ,
"those" ,
"through" ,
"turn" ,
"want" ,
2026-05-24 05:28:18 +01:00
"what" ,
2026-05-23 10:31:20 +01:00
"when" ,
"where" ,
"which" ,
"while" ,
"with" ,
"work" ,
"would" ,
"write" ,
"you" ,
"your" ,
2026-05-24 05:28:18 +01:00
"first" ,
"right" ,
"rights" ,
2026-05-23 10:31:20 +01:00
] ) ;
function significantTopicTerms ( content : string ) : string [ ] {
const normalized = normalizeForRepetition ( content )
. replace ( /\b\d{5,}\b/g , " " )
. replace ( /\b[a-z]*\d+[a-z0-9]*\b/g , " " ) ;
const terms = normalized
. split ( /\s+/ )
. map ( ( term ) = > term . replace ( /^['.-]+|['.-]+$/g , "" ) )
. filter ( ( term ) = > term . length >= 4 && ! TOPIC_STOP_WORDS . has ( term ) ) ;
return Array . from ( new Set ( terms ) ) ;
}
2026-05-20 20:31:42 +01:00
function normalizeForRepetition ( value : string ) : string {
return collapseWhitespace ( value )
. toLowerCase ( )
. replace ( /[`*_~]/g , "" )
. replace ( /<:[^>]+>/g , "" )
. replace ( /https?:\/\/\S+/g , "url" )
. replace ( / [ ^ \ p { L } \ p { N } \ s . ' - ] / g u , " " )
. replace ( /\s+/g , " " )
. trim ( ) ;
}
function thresholdRank ( threshold : RepoFaceChannelOption [ "speechThreshold" ] ) : number {
switch ( threshold ) {
case "very_low" :
return 0 ;
case "low" :
return 1 ;
case "medium" :
return 2 ;
case "high" :
return 3 ;
}
}
2026-05-20 21:45:56 +01:00
function collapseWhitespace ( value : string , maxLength? : number ) : string {
const normalized = value . replace ( /\s+/g , " " ) . trim ( ) ;
return maxLength && normalized . length > maxLength
? ` ${ normalized . slice ( 0 , maxLength - 3 ) } ... `
: normalized ;
}
function renderBifrostGovernanceDigestDirective (
digest : BifrostGovernanceDigest | undefined ,
) : string {
2026-05-21 20:48:02 +01:00
if ( ! digest ) {
return "Work routing is currently offline. Do not open governance topics or dispatch work this turn; if an idea wants action, discuss it in the room or save the pressure in memory." ;
}
if ( digest . topics . length === 0 ) {
2026-05-21 10:26:07 +01:00
return loadPromptTemplate ( "repo-face-bifrost-digest.prompt.md" , {
topics : [ ] ,
} ) ;
2026-05-20 21:45:56 +01:00
}
2026-05-21 10:26:07 +01:00
const lines : string [ ] = [ ] ;
2026-05-20 21:45:56 +01:00
for ( const topic of digest . topics ) {
lines . push (
2026-05-21 11:40:23 +01:00
` - ${ topic . title } : ${ topic . status } . ` ,
` Jurisdiction: ${ topic . jurisdictionRepoName } ${ topic . approvedByAgent ? ` ; approved by ${ topic . approvedByAgent } ` : "" } ${ topic . dispatchRequestId ? "; already dispatched" : "" } . ` ,
` ${ collapseWhitespace ( topic . summaryMarkdown , 320 ) } ` ,
2026-05-20 21:45:56 +01:00
) ;
for ( const comment of ( topic . comments ? ? [ ] ) . slice ( - 3 ) ) {
2026-05-21 11:40:23 +01:00
lines . push ( ` - ${ comment . stance } : ${ collapseWhitespace ( comment . bodyMarkdown , 220 ) } ` ) ;
2026-05-20 21:45:56 +01:00
}
}
2026-05-21 10:26:07 +01:00
return loadPromptTemplate ( "repo-face-bifrost-digest.prompt.md" , {
topics : lines ,
} ) ;
2026-05-20 20:31:42 +01:00
}
2026-05-19 12:23:22 +01:00
function renderWorldbuildingPublicationDirective ( identity : RepoDiscordIdentity ) : string {
const isNibu = identity . id . toLowerCase ( ) === "nibu" ;
2026-05-21 10:26:07 +01:00
return loadPromptTemplate ( "repo-face-worldbuilding-publication.prompt.md" , {
nibu : isNibu ,
} ) ;
2026-05-19 12:23:22 +01:00
}
2026-05-19 08:16:06 +01:00
interface JurisdictionDiveDirective {
due : boolean ;
cadence : number ;
promptLine : string ;
}
function buildJurisdictionDiveDirective (
identity : RepoDiscordIdentity ,
participant : FaceHeartbeatParticipant ,
) : JurisdictionDiveDirective {
const isNibu = identity . id . toLowerCase ( ) === "nibu" ;
const cadence = isNibu ? 3 : 8 ;
const due = participant . queuedCount === 0 || participant . queuedCount % cadence === 0 ;
return {
due ,
cadence ,
2026-05-21 10:26:07 +01:00
promptLine : loadPromptTemplate ( "repo-face-jurisdiction-dive.prompt.md" , {
due ,
nibu : isNibu ,
repoName : identity.repoName ,
} ) ,
2026-05-19 08:16:06 +01:00
} ;
}
2026-05-21 12:06:52 +01:00
function renderRepoCharacterIdentityDoctrine ( identity : RepoDiscordIdentity ) : string {
2026-05-18 17:17:08 +01:00
const face = buildEpiphanyIdentityRegistry ( { identities : [ identity ] } ) . faces [ 0 ] ;
2026-05-21 12:06:52 +01:00
return loadPromptTemplate ( "repo-character-identity.prompt.md" , {
2026-05-21 10:26:07 +01:00
displayName : identity.displayName ,
repoName : identity.repoName ,
2026-05-21 12:06:52 +01:00
originName : face?.epiphanyDisplayName ? ? identity . repoName ,
characterDescription : projectCharacterDescription ( face ? . description ? ? identity . description ) ,
2026-05-21 10:26:07 +01:00
} ) ;
2026-05-18 14:04:59 +01:00
}
2026-05-21 12:06:52 +01:00
function projectCharacterDescription ( description : string | undefined ) : string | undefined {
const trimmed = description ? . trim ( ) ;
if ( ! trimmed ) {
return undefined ;
}
return trimmed
. split ( "|" )
. map ( ( part ) = > part . trim ( ) )
. filter ( ( part ) = > part . length > 0 )
. filter ( ( part ) = > ! /^face of\b/i . test ( part ) )
. filter ( ( part ) = > ! /^grants:/i . test ( part ) )
. filter ( ( part ) = > ! /^jurisdictions:/i . test ( part ) )
. map ( ( part ) = > part
2026-05-21 13:27:38 +01:00
. replace ( /\bmore opinionated and abrasive than Void because she is a character, not the room moderator\b/gi , "more opinionated and abrasive than a room moderator" )
. replace ( /\bShe is much more opinionated and abrasive than Void because she is a character, not the room moderator:/gi , "She is much more opinionated and abrasive than a room moderator:" )
. replace ( /\bthan Void\b/g , "than a moderator" )
2026-05-21 12:06:52 +01:00
. replace ( /\bcharacter Face\b/g , "character" )
. replace ( /\bFace\b/g , "personality" )
. replace ( /\brepo=AetheriaLore path=[^\s]+/g , "" )
. replace ( /\s{2,}/g , " " )
. trim ( ) ,
)
. filter ( ( part ) = > part . length > 0 )
. join ( " " ) ;
}
2026-05-18 18:31:35 +01:00
function recoveryFor ( participant : FaceHeartbeatParticipant ) : number {
2026-05-18 11:23:44 +01:00
const loadPenalty = 1 + participant . currentLoad * 0.75 ;
2026-05-25 19:53:44 +01:00
return ( participant . baseRecoveryMinutes * loadPenalty ) / Math . max ( participant . effectiveSpeed , 0.01 ) ;
2026-05-18 11:23:44 +01:00
}
async function readHeartbeatState ( path : string ) : Promise < FaceHeartbeatState > {
try {
const raw = await readFile ( path , "utf8" ) ;
2026-05-18 18:31:35 +01:00
const parsed = JSON . parse ( stripLeadingBom ( raw ) ) as Partial < FaceHeartbeatState > & {
baseIntervalMinutes? : number ;
participants? : Array < Partial < FaceHeartbeatParticipant > & { nextReadyAt ? : string } > ;
} ;
2026-05-18 11:23:44 +01:00
if ( parsed . schemaVersion === HEARTBEAT_SCHEMA_VERSION ) {
2026-05-18 18:31:35 +01:00
return {
schemaVersion : HEARTBEAT_SCHEMA_VERSION ,
initiativeClock : Number.isFinite ( parsed . initiativeClock ) ? parsed.initiativeClock : 0 ,
baseRecoveryMinutes : Number.isFinite ( parsed . baseRecoveryMinutes ) ? parsed.baseRecoveryMinutes : 10 ,
globalHeat : Number.isFinite ( parsed . globalHeat ) ? parsed.globalHeat : 1 ,
lastTickAt : parsed.lastTickAt ,
participants : Array.isArray ( parsed . participants ) ? parsed . participants as FaceHeartbeatParticipant [ ] : [ ] ,
history : Array.isArray ( parsed . history ) ? parsed . history : [ ] ,
2026-05-19 11:56:01 +01:00
pendingMentions : Array.isArray ( parsed . pendingMentions )
? parsed . pendingMentions . filter ( isRepoFacePendingMention )
: [ ] ,
2026-05-24 22:45:17 +01:00
controls : normalizeHeartbeatControls ( ( parsed as { controls? : unknown } ) . controls ) ,
2026-05-18 18:31:35 +01:00
} ;
}
if ( Array . isArray ( parsed . participants ) ) {
return migrateLegacyHeartbeatState ( parsed ) ;
2026-05-18 11:23:44 +01:00
}
} catch {
// fall through to a new state
}
return {
schemaVersion : HEARTBEAT_SCHEMA_VERSION ,
2026-05-18 18:31:35 +01:00
initiativeClock : 0 ,
baseRecoveryMinutes : 10 ,
globalHeat : 1 ,
2026-05-18 11:23:44 +01:00
participants : [ ] ,
history : [ ] ,
2026-05-19 11:56:01 +01:00
pendingMentions : [ ] ,
2026-05-24 22:45:17 +01:00
controls : defaultHeartbeatControls ( ) ,
2026-05-18 11:23:44 +01:00
} ;
}
async function writeHeartbeatState ( path : string , state : FaceHeartbeatState ) : Promise < void > {
await mkdir ( dirname ( path ) , { recursive : true } ) ;
await writeFile ( path , ` ${ JSON . stringify ( state , null , 2 ) } \ n ` , "utf8" ) ;
}
2026-05-18 18:31:35 +01:00
function migrateLegacyHeartbeatState (
parsed : Partial < FaceHeartbeatState > & {
baseIntervalMinutes? : number ;
participants? : Array < Partial < FaceHeartbeatParticipant > & { nextReadyAt ? : string } > ;
} ,
) : FaceHeartbeatState {
const nowMs = Date . now ( ) ;
const legacyBase = Number . isFinite ( parsed . baseIntervalMinutes ) ? parsed.baseIntervalMinutes : 30 ;
const baseRecoveryMinutes = Math . max ( 5 , legacyBase / 3 ) ;
const participants = ( parsed . participants ? ? [ ] ) . map ( ( participant , index ) = > {
const speed = Number . isFinite ( participant . initiativeSpeed ) ? participant.initiativeSpeed : 1 ;
const legacyReadyMs = participant . nextReadyAt ? Date . parse ( participant . nextReadyAt ) : NaN ;
const minutesUntilReady = Number . isFinite ( legacyReadyMs )
? Math . max ( 0 , ( legacyReadyMs - nowMs ) / 60 _000 )
: index * baseRecoveryMinutes ;
return {
identityId : participant.identityId ? ? ` legacy-face- ${ index + 1 } ` ,
repoName : participant.repoName ? ? "unknown" ,
displayName : participant.displayName ? ? participant . identityId ? ? ` Legacy Face ${ index + 1 } ` ,
initiativeSpeed : speed ,
reactionBias : Number.isFinite ( participant . reactionBias ) ? participant.reactionBias : 0.4 ,
interruptThreshold : Number.isFinite ( participant . interruptThreshold ) ? participant.interruptThreshold : 0.6 ,
currentLoad : Number.isFinite ( participant . currentLoad ) ? participant.currentLoad : 0 ,
status : participant.status ? ? "active" ,
groups : participant.groups ? ? [ ] ,
heat : Number.isFinite ( participant . heat ) ? participant.heat : 1 ,
effectiveSpeed : Number.isFinite ( participant . effectiveSpeed ) ? participant.effectiveSpeed : speed ,
baseRecoveryMinutes ,
nextTurnAt : minutesUntilReady ,
lastTurnAt : participant.lastTurnAt ,
2026-05-18 18:53:14 +01:00
activeTurnStartedAt : participant.activeTurnStartedAt ,
activeJobId : participant.activeJobId ,
2026-05-18 18:31:35 +01:00
lastQueuedAt : participant.lastQueuedAt ,
queuedCount : Number.isFinite ( participant . queuedCount ) ? participant.queuedCount : 0 ,
constraints : participant.constraints ? ? [
2026-05-21 09:26:04 +01:00
"Migrated from wall-clock repo Face turn state." ,
2026-05-18 18:31:35 +01:00
] ,
} satisfies FaceHeartbeatParticipant ;
} ) ;
return {
schemaVersion : HEARTBEAT_SCHEMA_VERSION ,
initiativeClock : 0 ,
baseRecoveryMinutes ,
globalHeat : 1 ,
lastTickAt : parsed.lastTickAt ,
participants ,
2026-05-19 11:56:01 +01:00
pendingMentions : Array.isArray ( parsed . pendingMentions )
? parsed . pendingMentions . filter ( isRepoFacePendingMention )
: [ ] ,
2026-05-24 22:45:17 +01:00
controls : defaultHeartbeatControls ( ) ,
2026-05-18 18:31:35 +01:00
history : [
. . . ( Array . isArray ( parsed . history ) ? parsed . history : [ ] ) ,
{
type : "migrated" ,
fromSchemaVersion : parsed.schemaVersion ? ? "unknown" ,
migratedAt : new Date ( ) . toISOString ( ) ,
participantCount : participants.length ,
} ,
] . slice ( - 80 ) ,
} ;
}
2026-05-24 22:45:17 +01:00
function defaultHeartbeatControls ( ) : FaceHeartbeatControls {
return {
cadenceMultiplier : 1 ,
manualTurnRequests : [ ] ,
} ;
}
function normalizeHeartbeatControls ( value : unknown ) : FaceHeartbeatControls {
if ( ! value || typeof value !== "object" ) {
return defaultHeartbeatControls ( ) ;
}
const record = value as Record < string , unknown > ;
const cadenceMultiplier = Number ( record . cadenceMultiplier ) ;
const manualTurnRequests = Array . isArray ( record . manualTurnRequests )
? record . manualTurnRequests . flatMap ( ( entry ) : ManualTurnRequest [ ] = > {
if ( ! entry || typeof entry !== "object" ) {
return [ ] ;
}
const request = entry as Record < string , unknown > ;
const identityId = typeof request . identityId === "string" ? request . identityId . trim ( ) : "" ;
if ( ! identityId ) {
return [ ] ;
}
const status = request . status === "applied" || request . status === "consumed" || request . status === "rejected"
? request . status
: "pending" ;
return [ {
id : typeof request . id === "string" && request . id . trim ( ) ? request . id : ` manual- ${ Date . now ( ) } - ${ identityId } ` ,
identityId ,
requestedAt : typeof request . requestedAt === "string" ? request.requestedAt : new Date ( ) . toISOString ( ) ,
status ,
note : typeof request . note === "string" ? request.note : undefined ,
} ] ;
} )
: [ ] ;
return {
2026-05-25 19:53:44 +01:00
cadenceMultiplier : Number.isFinite ( cadenceMultiplier ) ? clamp ( cadenceMultiplier , 0.01 , 12 ) : 1 ,
2026-05-24 22:45:17 +01:00
manualTurnRequests : manualTurnRequests.slice ( - 20 ) ,
updatedAt : typeof record . updatedAt === "string" ? record.updatedAt : undefined ,
} ;
}
2026-05-19 11:56:01 +01:00
function isRepoFacePendingMention ( value : unknown ) : value is RepoFacePendingMention {
if ( ! value || typeof value !== "object" ) {
return false ;
}
const record = value as Record < string , unknown > ;
return (
typeof record . id === "string" &&
typeof record . identityId === "string" &&
typeof record . channelId === "string" &&
typeof record . messageId === "string" &&
typeof record . authorId === "string" &&
typeof record . content === "string" &&
typeof record . visiblePrompt === "string" &&
typeof record . queuedAt === "string"
) ;
}
2026-05-18 18:31:35 +01:00
function initiativeSpeedFor (
2026-05-18 19:05:09 +01:00
spec : ParticipantSpec ,
2026-05-18 18:31:35 +01:00
speedOverrides : Record < string , number > ,
) : number {
2026-05-18 19:05:09 +01:00
const override = speedOverrides [ spec . id . toLowerCase ( ) ] ;
2026-05-18 18:31:35 +01:00
if ( override !== undefined ) {
return clamp ( override , 0.35 , 6 ) ;
}
2026-05-18 19:05:09 +01:00
if ( spec . id === "void" ) {
return 1 ;
}
return clamp ( 0.85 + stableUnit ( spec . id , "speed" ) * 0.45 , 0.75 , 1.3 ) ;
2026-05-18 11:23:44 +01:00
}
2026-05-20 20:31:42 +01:00
function channelSpeedMultiplierFor ( identity : RepoDiscordIdentity ) : number {
const multipliers = identity . channelPermissions . map ( ( permission ) = > permission . speedMultiplier ) ;
return multipliers . length > 0 ? clamp ( Math . max ( . . . multipliers ) , 0.5 , 3 ) : 1 ;
}
2026-05-18 19:05:09 +01:00
function initiativeGroupsFor ( spec : ParticipantSpec ) : string [ ] {
2026-05-18 18:31:35 +01:00
return Array . from ( new Set ( [
"all" ,
2026-05-18 19:05:09 +01:00
` kind: ${ spec . participantKind } ` ,
` turn: ${ spec . turnKind } ` ,
` identity: ${ normalizeKey ( spec . id ) } ` ,
` repo: ${ normalizeKey ( spec . repoName ) } ` ,
` display: ${ normalizeKey ( spec . displayName ) } ` ,
. . . spec . allowedChannelIds . map ( ( channelId ) = > ` channel: ${ channelId } ` ) ,
2026-05-18 18:31:35 +01:00
] ) ) ;
}
function heatFor (
2026-05-18 19:05:09 +01:00
spec : ParticipantSpec ,
2026-05-18 18:31:35 +01:00
groups : string [ ] ,
globalHeat : number ,
heatOverrides : Record < string , number > ,
) : number {
const keys = [
"all" ,
. . . groups ,
2026-05-18 19:05:09 +01:00
normalizeKey ( spec . id ) ,
normalizeKey ( spec . repoName ) ,
normalizeKey ( spec . displayName ) ,
2026-05-18 18:31:35 +01:00
] ;
return clamp (
keys . reduce ( ( heat , key ) = > heat * ( heatOverrides [ key ] ? ? 1 ) , globalHeat ) ,
0.05 ,
20 ,
) ;
}
2026-05-18 19:05:09 +01:00
function reactionBiasFor ( spec : ParticipantSpec ) : number {
return spec . id === "void"
? 0.55
: clamp ( 0.2 + stableUnit ( spec . id , "reaction" ) * 0.55 , 0.2 , 0.75 ) ;
2026-05-18 11:23:44 +01:00
}
2026-05-18 19:05:09 +01:00
function interruptThresholdFor ( spec : ParticipantSpec ) : number {
return spec . id === "void"
? 0.5
: clamp ( 0.45 + stableUnit ( spec . id , "threshold" ) * 0.35 , 0.45 , 0.8 ) ;
2026-05-18 11:23:44 +01:00
}
function stableUnit ( id : string , salt : string ) : number {
const hex = createHash ( "sha1" ) . update ( ` ${ id } : ${ salt } ` ) . digest ( "hex" ) . slice ( 0 , 8 ) ;
return Number . parseInt ( hex , 16 ) / 0xffffffff ;
}
function mergeStrings ( values : string [ ] , value : string ) : string [ ] {
return Array . from ( new Set ( [ . . . values , value ] ) ) ;
}
2026-05-24 19:36:38 +01:00
function mergeOptionalString ( values : string [ ] , value : string | undefined ) : string [ ] {
return value ? mergeStrings ( values , value ) : values ;
}
2026-05-18 18:31:35 +01:00
function normalizeKey ( value : string ) : string {
return value . trim ( ) . toLowerCase ( ) ;
}
2026-05-18 11:23:44 +01:00
function clamp ( value : number , min : number , max : number ) : number {
return Math . min ( max , Math . max ( min , Number ( value . toFixed ( 3 ) ) ) ) ;
}
2026-05-20 20:31:42 +01:00
function round3 ( value : number ) : number {
return Math . round ( value * 1000 ) / 1000 ;
}
2026-05-18 11:23:44 +01:00
function stripLeadingBom ( input : string ) : string {
return input . charCodeAt ( 0 ) === 0xfeff ? input . slice ( 1 ) : input ;
}
2026-05-26 15:06:56 +01:00
function isRecord ( value : unknown ) : value is Record < string , unknown > {
return typeof value === "object" && value !== null && ! Array . isArray ( value ) ;
}
2026-05-21 13:07:00 +01:00
function readArgValue ( name : string ) : string | undefined {
const index = process . argv . indexOf ( name ) ;
if ( index < 0 ) {
return undefined ;
}
const value = process . argv [ index + 1 ] ;
return value && ! value . startsWith ( "--" ) ? value : undefined ;
}
2026-05-26 14:42:44 +01:00
function readIntArgValue ( name : string , fallback : number ) : number {
const raw = readArgValue ( name ) ;
if ( ! raw ) {
return fallback ;
}
const parsed = Number . parseInt ( raw , 10 ) ;
return Number . isFinite ( parsed ) ? parsed : fallback ;
}
2026-05-18 11:23:44 +01:00
void main ( ) . catch ( ( error ) = > {
console . error ( error ) ;
process . exitCode = 1 ;
} ) ;