From c504fb2cc6922eb6c1ed2664cf7a19cbe470342e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 26 May 2026 14:42:44 +0100 Subject: [PATCH] Separate repo face memory maintenance --- notes/fresh-workspace-handoff.md | 4 +- notes/voidbot-current-system-map.md | 8 +- package.json | 1 + prompts/void-memory-maintenance.md | 38 ++++- scripts/run-gamecult-orchestrator.ps1 | 19 +++ scripts/run-repo-face-heartbeats.ps1 | 7 +- scripts/run-repo-face-heartbeats.ts | 212 +++++++++++++++++++++++- scripts/run-void-memory-maintenance.ps1 | 11 +- state/evidence.jsonl | 1 + state/map.yaml | 8 +- 10 files changed, 291 insertions(+), 18 deletions(-) diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 7caf22c..f179ad1 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -36,7 +36,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - Prompt-facing rumination chronology is projected by `scripts/lib/void-rumination-context-projection.ps1`. Exact timestamps stay in typed state/status/cursors; the child context gets relative phrases like `5 minutes ago`, including recent Discord messages, repo activity, receipts, memory timestamps, and sleep/speech timing. - `scripts/simulate-void-mood.mjs` owns typed sleep/speaking-pressure over `.voidbot/private/void-self-state.cc`. During sleep, it invokes typed memory maintenance once per nap unless that nap already completed a pass; use `--skip-memory-maintenance` for smoke runs that must not call Codex. - `npm run moderation:memory-maintenance:sleep-fixture` now proves the non-skip sleep path without spending a live model call: it seeds a temporary `.cc`, forces mood drift through sleep maintenance, uses a fake Codex child to propose `apply_memory_distillation`, and verifies short-term residue is gone while the durable memory keeps subject, claim, tension, action implication, and anchor. -- The live local pulse is now one hidden scheduled task: `GameCult Local Orchestrator`. It invokes repo Face CTB heartbeats, Void mood drift, Void moderation rumination, and the operations watchdog with one lock, one status surface, per-organ logs, and per-organ timeouts. The Bifrost dispatch organ remains wired but is skipped unless `BIFROST_DISPATCH_ENABLED=true`. The old per-organ tasks are disabled and should remain disabled unless testing one organ in isolation. +- The live local pulse is now one hidden scheduled task: `GameCult Local Orchestrator`. It invokes repo Face CTB heartbeats, repo Face memory maintenance, Void mood drift, Void moderation rumination, and the operations watchdog with one lock, one status surface, per-organ logs, and per-organ timeouts. The Bifrost dispatch organ remains wired but is skipped unless `BIFROST_DISPATCH_ENABLED=true`. The repo Face memory-maintenance organ is deliberately not blocked by `state/agent-swarm-paused.json`; pause silences public swarm mouths, but Life still cleans state. The old per-organ tasks are disabled and should remain disabled unless testing one organ in isolation. - `scripts/start-voidbot-stack.ps1` now treats the local Bifrost container stack as a startup dependency. It reads `BIFROST_ROOT` and `BIFROST_HEALTH_URL`, runs `E:\Projects\Bifrost\compose.local.yaml` when the health endpoint is down, and records the result under `runtime-stack.json` as `bifrost`. - `npm run moderation:rumination:fixture` proves the non-skip typed rumination branch without spending a live model call: it seeds a temporary `.cc`, routes the runner through a fake Codex child, and verifies short-term memory, incubation, agency pressure, and candidate intervention proposals are parent-applied typed operations with no exact timestamp leakage in the prompt-facing context. - `npm run moderation:rumination:speech-fixture` proves queued speech has a parent-owned action loop: fake Codex queues one candidate with a delivery target, fake Discord send writes a receipt, and the parent runner marks the candidate spoken through typed state. The child prompt now forbids direct send-script calls. @@ -137,7 +137,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - Repo Face prompts now carry deterministic human pronoun guidance outside the model-projected state surface. The 2026-05-22 Nibu misgendering happened because Metacrat's interaction profile correctly resolved explicit `she/her`, but that fact was only inside the state packet handed to the projector, and the projector omitted it. `repo-face-turn.prompt.md` now renders `Known human pronoun guidance` near the transcript and again near the final writing instruction; the renderer also chooses evidence supporting the resolved pronoun set rather than the freshest contradictory ambient read. - Worker delivery must treat Interpreter channel names as Face-local labels, not raw Discord ids. `SAY channel: aquarium` or `channel: narrative` resolves through the registered identity's `channelPermissions` before allow-list checks and webhook delivery. Earlier live Aqua/Nibu turns parsed `say=1` but did not post because the worker literally checked whether the identity was allowed in channel id `aquarium`; the post path now resolves labels and has a live Epiphany webhook receipt after restart. - Repo Face rest projection now persists normalized sleep cycles back into each Face `.cc` state during heartbeat loading. Missed nap windows are treated as already missed/completed and rolled forward instead of starting a fresh nap at inspection time. This fixes the Aqua/Mimir/Epiphany failure mode where stale `nextNapStartsAt` values stayed raw, fresh projections repeatedly marked them as napping, and ready selection skipped them forever while their initiative was overdue. -- Repo Face short-term memory distillation is now wired into the heartbeat/recovery loop. The runner starts repo-local memory maintenance when a Face is napping with short-term residue or has stale short-term residue older than six hours. Status/logs live under the target repo's own `.voidbot/status` and `.voidbot/logs`; the shared maintenance runner has `-ForceDistillation`, identity-neutral prompt wording, exact-schema warnings, and whole-batch schema validation before any operation applies. Live cleanup forced Nibu from 3 short-term memories to 0 and Mimir from 5 to 0; all registered repo Faces currently have 0 short-term residue. +- Repo Face short-term memory distillation is now owned by a separate maintenance-only path, not by public CTB speech scheduling. `scripts/run-gamecult-orchestrator.ps1` runs `repo-face-memory-maintenance` every minute through `scripts/run-repo-face-heartbeats.ps1 --maintenance-only --max-maintenance-runs `, while `repo-face-heartbeats` remains skippable under the swarm pause brake. The maintenance path retries stale launcher `starting` records, runs `scripts/run-void-memory-maintenance.ps1` synchronously with stdout/stderr captured under the target repo's `.voidbot/logs`, and records completion/failure in heartbeat history. The shared maintenance runner now uses a bounded workspace-write sandbox rooted at the status directory and the prompt explicitly forbids repo inspection, tests, helpers, tracked-file edits, or background work. Live cleanup on 2026-05-26 consumed stale short-term residue across all registered repo Faces; current registered Face short-term counts are 0. - Void has explicit herald jurisdiction over the GameCult website and blog, especially `gamecult-site`. Routine rumination still cannot edit tracked files directly, but the prompt now tells Void to queue article-proposal candidates when a pressure wants to become a Void-authored site/blog piece rather than a Discord aside. - Nibu is locally registered as the `AetheriaLore` Face with state at `E:/Projects/AetheriaLore/.voidbot/state/nibu.cc`, avatar at `E:/Projects/AetheriaLore/.voidbot/voice/nibu.png`, Discord role id `1505918221453103247`, Aquarium channel allow-list `1501196543150264332`, plus topic permissions for narrative, gamedesign, concepts, and development. Her active doctrines are AetheriaLore-first map-building, a more abrasive character voice than Void, consensus-backed authority to propose canon/vault changes, stewardship of `Aetheria/Lore/Nibu.md`, permission to write Nibu-authored Aetheria lore essays without canon consensus, and special fascination with adjacent setting seams: embodied ship minds, junkyard abandonment, murderous autonomy, salvage, and save-scumming survival. Local `.env` has repo Face heartbeats enabled through the `GameCult Local Orchestrator` one-minute pulse, and local heat currently boosts `identity:nibu` so she gets substantially more turns when no prior Nibu job is still active. Above-baseline heat bypasses repo Face nap gating for live-room mode, but active-turn freeze still prevents overlapping thoughts. Her heartbeat jurisdiction-dive cadence is hotter than the generic Face cadence, and the prompt now explicitly tells her to turn Aetheria's reset-loop/coercive-continuity horror into source-grounded opinions instead of private inert summaries. - Nibu's heartbeat prompt now treats worldbuilding as an active interrogation workflow. When the room mentions a term such as wavecrafters, she should ask how it works, what the faction/organizations are called, who belongs, what constraints keep it interesting, and what article shape would make the setting clearer. For Nibu-bylined perspective articles, she may draft first and argue after; if she drafts or materially shapes an article, she is compelled to share that in-channel. diff --git a/notes/voidbot-current-system-map.md b/notes/voidbot-current-system-map.md index 5a34910..f973723 100644 --- a/notes/voidbot-current-system-map.md +++ b/notes/voidbot-current-system-map.md @@ -141,7 +141,8 @@ This note is the source-grounded description of how the live VoidBot stack is sh - `scripts/install-moderation-rumination-task.ps1` - legacy installer for isolating the moderation/participation loop. The live scheduled pulse is now `GameCult Local Orchestrator`; keep this per-organ task disabled unless testing the organ in isolation. - `scripts/run-gamecult-orchestrator.ps1` - - local pulse owner for agent transport/runtime chores. It runs Bifrost dispatch, repo Face CTB heartbeats, Void mood drift, Void moderation rumination, and the operations watchdog from one hidden scheduled task with one lock, per-organ status/log files, and per-organ timeouts. + - local pulse owner for agent transport/runtime chores. It runs Bifrost dispatch, repo Face CTB heartbeats, repo Face memory maintenance, Void mood drift, Void moderation rumination, and the operations watchdog from one hidden scheduled task with one lock, per-organ status/log files, and per-organ timeouts. + - The `repo-face-memory-maintenance` organ is intentionally outside the swarm pause set. `state/agent-swarm-paused.json` stops public swarm turns and Bifrost dispatch, but it does not stop repo Face memory distillation. - `scripts/install-gamecult-orchestrator-task.ps1` - installs scheduled task `GameCult Local Orchestrator` through the hidden PowerShell launcher and can disable the old per-organ tasks: `Bifrost Agent Dispatch`, `VoidBot Repo Face Heartbeats`, `Void Mood Drift`, `Void Moderator Rumination`, and `VoidBot Operations Watchdog`. - Scheduled organ `Void Mood Drift` @@ -154,6 +155,11 @@ This note is the source-grounded description of how the live VoidBot stack is sh - scheduled rumination skips during naps when there are no new room messages and no open cases, so sleep can distill the short-term surface without awake rumination immediately adding fresh residue. - `scripts/simulate-void-mood.mjs` - typed mood maintenance script that updates scheduled-runtime sleep cycle and speaking pressure in `.voidbot/private/void-self-state.cc`. It owns the sleep transition and invokes typed memory maintenance once per nap unless that nap already completed a maintenance pass. Speaking pressure now derives from queued candidates, incubation, and active typed agency pressure. The old personality-vector drift, memory organ, incubation, dream residue, cleanup, and legacy mirror behavior are offline pending typed replacements. +- `scripts/run-repo-face-heartbeats.ts --maintenance-only` + - repo Face Life path. It loads the registered Face states, projects sleep/rest state, starts repo-local memory maintenance for napping or stale short-term residue, and exits without queuing public CTB turns. The orchestrator calls this through `scripts/run-repo-face-heartbeats.ps1 --maintenance-only --max-maintenance-runs `. + - Maintenance starts are synchronous and observable: stale launcher-only `starting` records without process evidence stop blocking retries after a short grace period, stdout/stderr are captured under the target repo's `.voidbot/logs`, and success/failure is recorded in the shared heartbeat history. Detached launch is no longer treated as proof that distillation happened. +- `scripts/run-void-memory-maintenance.ps1` + - repo Face and Void typed memory-maintenance runner. It now runs the Codex child from the status directory with `workspace-write` sandbox by default, because the child only needs to read the provided context and write the operation output file. The prompt explicitly forbids repo inspection, tests, helper launches, tracked-file edits, and background work. - Repo Discord identities - `REPO_DISCORD_IDENTITIES_PATH` points at a private JSON registry of repo id, repo name, display name, optional avatar URL, optional role id, and allowed channel ids. The role is the Discord mention target; the webhook persona is the speech transport. - That registry may also carry `channelPermissions`: per-topic channel entries with a speech threshold and speed multiplier. These are not another transport; they are the permission/salience map for where a Face may speak. Aquarium is the low-threshold musing lane, while domain channels such as narrative, gamedesign, music, soundtrack, development, programming, visual-effects, machine-learning, and unity3d are available to matching Faces. diff --git a/package.json b/package.json index 6554ac3..829f328 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "agents:inspect-requests": "tsx scripts/inspect-agent-state-requests.ts", "agents:inspect-model-outputs": "node scripts/inspect-model-output-logs.mjs", "agents:assemble-character-prompt": "tsx scripts/run-repo-face-heartbeats.ts --assemble-prompt", + "agents:repo-face-memory-maintenance": "tsx scripts/run-repo-face-heartbeats.ts --maintenance-only", "agents:heartbeat-model-smoke": "node scripts/smoke-repo-face-heartbeat-model-scenarios.mjs", "agents:interpreter-loop-smoke": "node scripts/smoke-repo-face-interpreter-loop.mjs", "agents:memory-projection-smoke": "node scripts/smoke-repo-face-memory-projection.mjs", diff --git a/prompts/void-memory-maintenance.md b/prompts/void-memory-maintenance.md index 670d72d..1ce313e 100644 --- a/prompts/void-memory-maintenance.md +++ b/prompts/void-memory-maintenance.md @@ -10,7 +10,10 @@ operation payloads worth applying. ## Required Reading - `{{CONTEXT_PATH}}` -- `styles/void-default.md` + +Do not inspect the repository, run tests, launch helpers, edit tracked files, or +start background work. This organ is asleep-cleaning typed state, not doing repo +work. Read the supplied context packet and write only the operation array. ## State Boundary @@ -91,6 +94,39 @@ For `prune_short_term_memories`, the exact shape is: Do not use `memoryIds` for pruning. +For `apply_memory_distillation`, the exact shape is: + +```json +{ + "operation": "apply_memory_distillation", + "proposalId": "distill-short-stable-id", + "sourceMemoryIds": ["short-term-memory-id"], + "appliedAt": "2026-05-20T00:00:00.000Z", + "memory": { + "memoryId": "memory-stable-id", + "kind": "project_seam", + "target": { + "kind": "repo", + "id": "RepoName", + "label": "RepoName" + }, + "summary": "One sentence summary.", + "claim": "The concrete claim that should steer future behavior.", + "question": "Optional concrete question if the thought is still open.", + "tension": "The live counterweight or uncertainty.", + "actionImplication": "How this should affect future action.", + "anchorRefs": [{ "kind": "runtime", "ref": "job-or-message-or-file-anchor" }], + "evidenceRefs": [], + "createdAt": "2026-05-20T00:00:00.000Z", + "updatedAt": "2026-05-20T00:00:00.000Z", + "tags": ["repo:RepoName"] + } +} +``` + +`proposalId` and `appliedAt` are operation-level fields. They do not belong +inside `memory`, and they are not optional for `apply_memory_distillation`. + ## Pass Shape 1. Read the context file. diff --git a/scripts/run-gamecult-orchestrator.ps1 b/scripts/run-gamecult-orchestrator.ps1 index 3d173c0..8acea56 100644 --- a/scripts/run-gamecult-orchestrator.ps1 +++ b/scripts/run-gamecult-orchestrator.ps1 @@ -302,6 +302,25 @@ try { Executable = $powershell Arguments = @("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", (Join-Path $PSScriptRoot "run-repo-face-heartbeats.ps1")) }, + [pscustomobject]@{ + Id = "repo-face-memory-maintenance" + Label = "Repo Face memory maintenance" + IntervalMinutes = Get-ConfigInt -Config $config -Name "REPO_FACE_MEMORY_MAINTENANCE_INTERVAL_MINUTES" -Default 1 -Minimum 1 + TimeoutMinutes = Get-ConfigInt -Config $config -Name "REPO_FACE_MEMORY_MAINTENANCE_TIMEOUT_MINUTES" -Default 20 -Minimum 5 + Cwd = $repoRoot + Executable = $powershell + Arguments = @( + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-File", + (Join-Path $PSScriptRoot "run-repo-face-heartbeats.ps1"), + "--maintenance-only", + "--max-maintenance-runs", + (Get-ConfigInt -Config $config -Name "REPO_FACE_MEMORY_MAINTENANCE_MAX_RUNS" -Default 1 -Minimum 1) + ) + }, [pscustomobject]@{ Id = "void-mood-drift" Label = "Void mood drift" diff --git a/scripts/run-repo-face-heartbeats.ps1 b/scripts/run-repo-face-heartbeats.ps1 index cf54e7f..8c23ffe 100644 --- a/scripts/run-repo-face-heartbeats.ps1 +++ b/scripts/run-repo-face-heartbeats.ps1 @@ -1,3 +1,8 @@ +param( + [Parameter(ValueFromRemainingArguments = $true)] + [string[]] $RunnerArgs +) + Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" $ProgressPreference = "SilentlyContinue" @@ -16,7 +21,7 @@ if (-not (Test-Path -LiteralPath $runnerScript)) { Push-Location $repoRoot try { - & $nodePath $tsxCliPath $runnerScript + & $nodePath $tsxCliPath $runnerScript @RunnerArgs exit $LASTEXITCODE } finally { Pop-Location diff --git a/scripts/run-repo-face-heartbeats.ts b/scripts/run-repo-face-heartbeats.ts index 25daaf0..3c4bbdb 100644 --- a/scripts/run-repo-face-heartbeats.ts +++ b/scripts/run-repo-face-heartbeats.ts @@ -146,6 +146,22 @@ interface RepoFaceRuntimePressureSnapshot { noveltyPressure: number; } +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; +} + interface BifrostGovernanceDigest { generatedAt: string; topics: BifrostGovernanceTopic[]; @@ -182,6 +198,7 @@ interface ChannelSnapshot { async function main(): Promise { const config = loadConfig(); const dryRun = process.argv.includes("--dry-run"); + const maintenanceOnly = process.argv.includes("--maintenance-only"); const assemblePromptIdentity = readArgValue("--assemble-prompt"); if (assemblePromptIdentity) { const result = await assembleRepoFaceTurnPrompt({ @@ -195,6 +212,68 @@ async function main(): Promise { return; } + 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; + } + const pause = await readAgentSwarmPause(); if (pause.paused) { const state = await readHeartbeatState(config.repoFaceHeartbeats.statePath); @@ -252,7 +331,7 @@ async function main(): Promise { registry.identities, config.storageRoot, state, - { dryRun, idleCooling }, + { dryRun, idleCooling, startMemoryMaintenance: false }, ); advanceInitiativeClockFromWallClock(state, now); const activeTurnScan = dryRun @@ -641,13 +720,23 @@ async function loadRepoFaceRuntimeSnapshots( identities: RepoDiscordIdentity[], storageRoot: string, heartbeatState: FaceHeartbeatState, - options: { dryRun?: boolean; idleCooling?: IdleCoolingSnapshot } = {}, + options: { + dryRun?: boolean; + idleCooling?: IdleCoolingSnapshot; + startMemoryMaintenance?: boolean; + maxMaintenanceRuns?: number; + waitForMaintenanceCompletion?: boolean; + } = {}, ): Promise<{ restStates: Map; pressureByIdentity: Map; + maintenanceEvents: RepoFaceMemoryMaintenanceEvent[]; }> { const restStates = new Map(); const pressureByIdentity = new Map(); + const maintenanceEvents: RepoFaceMemoryMaintenanceEvent[] = []; + let maintenanceRunCount = 0; + const maxMaintenanceRuns = Math.max(0, options.maxMaintenanceRuns ?? Number.POSITIVE_INFINITY); const now = new Date(); for (const identity of identities) { @@ -713,7 +802,7 @@ async function loadRepoFaceRuntimeSnapshots( }, ); } - const maintenance = options.dryRun + const maintenance = options.dryRun || options.startMemoryMaintenance !== true || maintenanceRunCount >= maxMaintenanceRuns ? { started: false, reason: "dry_run", statusPath: undefined } : await maybeStartRepoFaceMemoryMaintenance({ identity, @@ -724,17 +813,31 @@ async function loadRepoFaceRuntimeSnapshots( napEndsAt: sleepCycle.currentNapEndsAt, nextNapStartsAt: sleepCycle.nextNapStartsAt, }, + waitForCompletion: options.waitForMaintenanceCompletion === true, }); if (maintenance.started || maintenance.failureReason) { - heartbeatState.history.push({ - type: maintenance.started ? "repo_face_memory_maintenance_started" : "repo_face_memory_maintenance_failed_to_start", + 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", identityId: identity.id, observedAt: now.toISOString(), reason: maintenance.reason, statusPath: maintenance.statusPath, pid: maintenance.pid, + exitCode: maintenance.exitCode, + durationSeconds: maintenance.durationSeconds, failureReason: maintenance.failureReason, - }); + }; + heartbeatState.history.push(event); + maintenanceEvents.push(event); } restStates.set(identity.id, { isNapping: sleepCycle.isNapping === true, @@ -749,7 +852,7 @@ async function loadRepoFaceRuntimeSnapshots( } } - return { restStates, pressureByIdentity }; + return { restStates, pressureByIdentity, maintenanceEvents }; } function projectSleepCycleForOperatorAbsence( @@ -886,11 +989,15 @@ async function maybeStartRepoFaceMemoryMaintenance(input: { statePath: string; typedState: Awaited>; projectedRest: RepoFaceRestSnapshot; + waitForCompletion?: boolean; }): Promise<{ started: boolean; + completed?: boolean; reason?: string; statusPath?: string; pid?: number; + exitCode?: number | null; + durationSeconds?: number; failureReason?: string; }> { const shortTerm = input.typedState.thoughtMemory.shortTerm ?? []; @@ -937,6 +1044,78 @@ async function maybeStartRepoFaceMemoryMaintenance(input: { ? new Date(newestTimestampMs(shortTerm)).toISOString() : undefined, }, null, 2)}\n`, "utf8"); + 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, + }; + } + const child = spawn( "powershell.exe", [ @@ -1015,7 +1194,15 @@ function isRecentRunningStatus(status: Record | undefined, maxA return false; } const startedAtMs = typeof status.startedAt === "string" ? Date.parse(status.startedAt) : NaN; - return Number.isFinite(startedAtMs) && Date.now() - startedAtMs < maxAgeMinutes * 60_000; + 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; } function isStatusCompletedAfter(status: Record | undefined, sourceTimestampMs: number): boolean { @@ -4970,6 +5157,15 @@ function readArgValue(name: string): string | undefined { return value && !value.startsWith("--") ? value : undefined; } +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; +} + void main().catch((error) => { console.error(error); process.exitCode = 1; diff --git a/scripts/run-void-memory-maintenance.ps1 b/scripts/run-void-memory-maintenance.ps1 index 97a87b5..08046f2 100644 --- a/scripts/run-void-memory-maintenance.ps1 +++ b/scripts/run-void-memory-maintenance.ps1 @@ -503,6 +503,13 @@ $codexExecArgs = if (-not [string]::IsNullOrWhiteSpace($env:CODEX_EXEC_ARGS)) { } else { @() } +$codexSandbox = if (-not [string]::IsNullOrWhiteSpace($env:VOID_MEMORY_MAINTENANCE_CODEX_SANDBOX)) { + $env:VOID_MEMORY_MAINTENANCE_CODEX_SANDBOX +} elseif ($envValues.ContainsKey("VOID_MEMORY_MAINTENANCE_CODEX_SANDBOX") -and -not [string]::IsNullOrWhiteSpace($envValues["VOID_MEMORY_MAINTENANCE_CODEX_SANDBOX"])) { + $envValues["VOID_MEMORY_MAINTENANCE_CODEX_SANDBOX"] +} else { + "workspace-write" +} $codexTimeoutSeconds = if (-not [string]::IsNullOrWhiteSpace($env:VOID_MEMORY_MAINTENANCE_CODEX_TIMEOUT_SECONDS)) { [int]$env:VOID_MEMORY_MAINTENANCE_CODEX_TIMEOUT_SECONDS } elseif ($envValues.ContainsKey("VOID_MEMORY_MAINTENANCE_CODEX_TIMEOUT_SECONDS") -and -not [string]::IsNullOrWhiteSpace($envValues["VOID_MEMORY_MAINTENANCE_CODEX_TIMEOUT_SECONDS"])) { @@ -591,14 +598,14 @@ if ($SkipModel) { "-m", $codexModel, "-c", 'approval_policy="never"', "-c", ("model_reasoning_effort={0}" -f (ConvertTo-Json $codexReasoningEffort -Compress)), - "--dangerously-bypass-approvals-and-sandbox", + "-s", $codexSandbox, "--skip-git-repo-check", "--json", "-o", $lastMessagePath, "-" ) - $execution = Invoke-CodexExec -Executable $codexExecutable -Arguments $codexArgs -WorkingDirectory $repoRoot -InputText $prompt -TimeoutSeconds $codexTimeoutSeconds + $execution = Invoke-CodexExec -Executable $codexExecutable -Arguments $codexArgs -WorkingDirectory $statusDir -InputText $prompt -TimeoutSeconds $codexTimeoutSeconds $exitCode = $execution.ExitCode $combinedText = (($execution.StdOut, $execution.StdErr) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) -join [Environment]::NewLine } diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 158d3be..d41e2f3 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -353,3 +353,4 @@ {"ts":"2026-05-26T12:18:09Z","type":"implementation","status":"ok","note":"Simplified parent Mind prompt after owner-reply leak: prompts/repo-face-turn-interpreter.prompt.md now asks for semantic route/retry/drop judgment with a hard STATE NOTE/ARTICLE/SAY DSL contract instead of incident-specific scar tissue. Verified with typecheck, build, agents:interpreter-loop-smoke, and gpt-5.4 heartbeat model smoke."} {"ts":"2026-05-26T12:32:40Z","type":"implementation","status":"ok","note":"Reduced deterministic repo Face compensators: Face prompt no longer receives separate room-weather, topic-saturation, pending-mention, human-steering, or repetition-sampling slabs; Imagination prompt now owns semantic projection from state/transcript/repo/context; removed regex human-clarity and witness/LocalCastBridge rewrite compensators from state packet rendering. Verified with typecheck, build, interpreter-loop smoke, and gpt-5.4 heartbeat model smoke."} {"ts":"2026-05-26T13:15:47Z","type":"implementation","status":"ok","note":"Added offline Socratic Ink article harness for CotSC Praxis: scripts/weave-face-socratic-ink.mjs reads scenario actors/phases, assembles real repo Face prompts, runs read-only Face child turns plus parent Mind normalization, simulates branch-local CTB initiative with three Face choices and selected-Face initiative spend, and writes articles/ink/cotsc-praxis-socratic-sermon.ink plus receipts without Discord/Bifrost/state side effects. Verified node --check, scenario JSON parse, typecheck, a depth-1 full article generation, and a depth-2 recursion smoke with resolved Ink targets/no duplicate knots/no non-ASCII."} +{"ts":"2026-05-26T13:41:41Z","type":"implementation","status":"ok","note":"Repo Face memory distillation is now an orchestrator-owned Life organ: repo-face-memory-maintenance runs even while the swarm pause brake suppresses public CTB turns, retries stale launcher-only starting records, runs memory maintenance synchronously with captured logs, and leaves all registered repo Face short-term counts at zero after the 2026-05-26 cleanup."} diff --git a/state/map.yaml b/state/map.yaml index 3d5e421..cdd4c69 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -152,7 +152,8 @@ accepted_design: - Agent standing heartbeats are owned by one CTB-style initiative scheduler, not by one task per agent. Wall-clock elapsed time advances initiative; the scheduled task only supplies frequent pulses. The scheduler stores per-agent speed/load/groups/heat/effective-speed/next-turn/active-turn state at `REPO_FACE_HEARTBEAT_STATE_PATH`, dispatches repo Faces as ordinary `repo-face-rumination` jobs, and dispatches built-in `void` as the existing moderation rumination runner. Heat can be turned up globally, by participant kind, turn kind, identity, repo, display name, channel, or `all` group without creating new schedulers, but heat only changes recovery speed; it must not fast-forward time. Typed Face speaking pressure is also scheduler-visible now: agency pressure, affect needs, status reads, social bonds, mood, and queued candidates derive `needToSpeak`, which raises initiative urgency and may pull the next turn closer. Active-turn freeze and rest gating remain hard brakes unless a direct mention creates room debt. An agent's initiative is frozen while its owner-Codex job or moderation lock is active; recovery is scheduled after completion, not when the job is queued. The Windows pulse task supports a one-minute floor; stream mode should raise heat or temporarily loosen fatigue, not compress wall-clock time. Idle cooling is also scheduler-owned: when watched Discord channels have no recent human activity, non-mentioned swarm turns are globally throttled to one unprompted dispatch per `REPO_FACE_HEARTBEAT_IDLE_RECOVERY_MINUTES` window, while pending mentions still pull their target forward. - Runtime liveness is not enough. The operations watchdog must also verify bot/worker freshness by comparing each live process start time against its built `dist/index.js` entrypoint timestamp. A process that predates its entrypoint is stale and must fail `runtime..freshness`; otherwise source/build repairs can silently sit beside an old in-memory worker that keeps eating new Face action DSL output as private summaries. - Active-turn freeze is bounded by actual job liveness, not blind faith in an old `running` row. Repo Face heartbeat jobs that remain approved/running past the stale-job window are marked failed through the job queue, recorded as `stale_active_turn_recovered`, and removed from the active-turn map so one dead worker claim cannot silence a Face indefinitely. - - Repo Face rest projection is parent-owned state, not a read-only scheduler illusion. If the heartbeat runner projects a Face sleep cycle forward, it must persist the normalized `update_sleep_cycle` operation to that Face's `.cc` state before ready selection. Missed nap windows roll forward as completed rest instead of starting a brand-new nap at inspection time; otherwise overdue agents can be skipped forever as "currently napping" while raw state keeps the same stale boundary. + - Repo Face rest projection is parent-owned state, not a read-only scheduler illusion. If the heartbeat runner or maintenance-only organ projects a Face sleep cycle forward, it must persist the normalized `update_sleep_cycle` operation to that Face's `.cc` state before ready selection. Missed nap windows roll forward as completed rest instead of starting a brand-new nap at inspection time; otherwise overdue agents can be skipped forever as "currently napping" while raw state keeps the same stale boundary. + - Repo Face memory maintenance is a Life organ, not public speech. `repo-face-memory-maintenance` runs from the orchestrator even while `agent_swarm_paused` suppresses Bifrost dispatch, CTB speech, Void mood drift, and moderation rumination. Public mouths may sleep; stale short-term memory still has to be distilled or fail visibly. - Repo Face memory distillation now shares Void's typed maintenance organ instead of relying on rumination turns to eventually clean themselves. `scripts/run-repo-face-heartbeats.ts` starts repo-local `run-void-memory-maintenance.ps1 -ForceDistillation` when a Face is napping with short-term memory or has stale short-term memory older than six hours, with status/logs isolated under the target repo's `.voidbot/status` and `.voidbot/logs`. `run-void-memory-maintenance.ps1` validates the entire proposed operation batch against `voidSelfStateOperationSchema` before applying anything, so one malformed late operation cannot leave a partial maintenance pass. The maintenance prompt is identity-neutral and explicitly forbids shorthand operation payloads, `type` instead of `operation`, `memoryIds` for pruning, and `null` optional fields. - Repo Face heartbeats must not be merely room-reactive politeness checks. The heartbeat prompt carries a jurisdiction-dive cadence, but it is background appetite, not a command that outranks live conversation. When no correction, direct call, social pressure, or stronger embodied need is tugging, the Face should inspect its repo/history terrain with source tools before making repo claims; when the live room is the real thing, answer the room and preserve the dive as later hunger. - Repo Face heartbeats are not ordinary owner Discord replies. The owner-Codex render wrapper must recognize both legacy `Repo Face identity doctrine` prompts and current `Epiphany Face identity doctrine` heartbeat prompts, forbid generic handoff for Face jobs, and preserve the repo identity action rail as parent-owned output. The preferred rail is now the small Face action DSL; legacy JSON sentinels remain accepted only as a compatibility surface. @@ -224,7 +225,8 @@ landed_baseline: - Long-term memory is durable but plastic. `revise_durable_memory`, `retire_durable_memory`, and `crystallize_memory_into_identity` make revision, contradiction/obsolescence, and self-doctrine crystallization explicit instead of silently overwriting older thoughts. - `npm run moderation:memory-lifecycle:fixture` verifies memory lifecycle flow: short-term promotion, durable revision, superseded-memory retirement, and crystallization into one active identity memory plus self-profile value. - The sleep-maintenance path has a model-branch fixture: `npm run moderation:memory-maintenance:sleep-fixture` seeds a temporary `.cc`, forces mood drift into sleep maintenance, routes the non-skip Codex branch through a fake child, and verifies short-term memory is consumed into one durable meaning-preserving record. - - The local `GameCult Local Orchestrator` scheduled task is installed as the hidden one-minute pulse for Bifrost dispatch, repo Face CTB heartbeats, Void mood drift, Void moderation rumination, and the operations watchdog. It writes per-organ logs under `.voidbot/logs/orchestrator`, summary/status under `.voidbot/status/gamecult-orchestrator*.json`, freezes overlap with one orchestrator lock, and enforces per-organ timeouts so a hung child cannot occupy the whole clock forever. + - The local `GameCult Local Orchestrator` scheduled task is installed as the hidden one-minute pulse for Bifrost dispatch, repo Face CTB heartbeats, repo Face memory maintenance, Void mood drift, Void moderation rumination, and the operations watchdog. It writes per-organ logs under `.voidbot/logs/orchestrator`, summary/status under `.voidbot/status/gamecult-orchestrator*.json`, freezes overlap with one orchestrator lock, and enforces per-organ timeouts so a hung child cannot occupy the whole clock forever. The repo Face memory-maintenance organ is intentionally not paused by the swarm brake. + - Repo Face sleep cleanup now has a separate maintenance-only runner path: `npm run agents:repo-face-memory-maintenance -- --max-maintenance-runs 1`. It projects rest state, retries stale launcher records, runs `scripts/run-void-memory-maintenance.ps1` synchronously with captured logs, and records completion/failure in the heartbeat history instead of treating detached launch as proof of distillation. - VoidBot stack startup now treats Bifrost's local Docker Compose stack as a dependency. `scripts/start-voidbot-stack.ps1` checks `BIFROST_HEALTH_URL`, runs `BIFROST_ROOT/compose.local.yaml` when needed, and records `runtime-stack.json.bifrost` before starting the bot and worker. - The typed rumination path now has a model-branch fixture: `npm run moderation:rumination:fixture` seeds a temporary `.cc`, routes the non-skip Codex branch through a fake child, and verifies short-term memory, incubation, agency-pressure, and candidate-intervention proposals cross only through parent-applied typed operations without leaking exact timestamps into the prompt-facing context. - The typed rumination speech path is parent-owned now. Candidate interventions can carry an optional delivery target; the child may queue candidates but must not call Discord send scripts. The parent runner delivers at most one newly queued deliverable candidate per pass, records a delivery receipt, and marks the candidate spoken through `mark_candidate_intervention_spoken`. `npm run moderation:rumination:speech-fixture` verifies this loop with fake Codex and fake Discord send helpers. @@ -255,5 +257,5 @@ rejected_paths: reason: sleep/distillation that collapses concrete claims into generic abstraction creates memory nonsense and then forces later cleanup compensators current_status: - summary: VoidBot's bot/worker/provider/RAG/Postgres/Qdrant/CultCache structure is live, but the repo Face swarm brake is active after live turns leaked owner-reply/Mind text into public Discord. The fixed worker stack was restarted on 2026-05-26, parent Mind prompts now bypass the owner-reply wrapper, malformed plain Mind output no longer becomes SAY, and the Mind prompt has been slimmed to semantic judgment plus a strict STATE NOTE/ARTICLE/SAY DSL contract. Imagination/Face prompt assembly now has fewer deterministic compensators; raw transcript/repo/state facts go to Imagination, and the Face prompt no longer gets duplicate room-weather/topic-saturation/human-steering/repetition slabs. gpt-5.4 typecheck/build/interpreter-loop/heartbeat-smoke checks pass. Bifrost work routing remains paused by default. + summary: VoidBot's bot/worker/provider/RAG/Postgres/Qdrant/CultCache structure is live, but the repo Face swarm brake is active after live turns leaked owner-reply/Mind text into public Discord. The fixed worker stack was restarted on 2026-05-26, parent Mind prompts now bypass the owner-reply wrapper, malformed plain Mind output no longer becomes SAY, and the Mind prompt has been slimmed to semantic judgment plus a strict STATE NOTE/ARTICLE/SAY DSL contract. Imagination/Face prompt assembly now has fewer deterministic compensators; raw transcript/repo/state facts go to Imagination, and the Face prompt no longer gets duplicate room-weather/topic-saturation/human-steering/repetition slabs. Repo Face memory maintenance is now a separate orchestrator organ that runs while the swarm brake is active, and the 2026-05-26 cleanup left all registered repo Faces with zero short-term residue. gpt-5.4 typecheck/build/interpreter-loop/heartbeat-smoke checks pass. Bifrost work routing remains paused by default. next_action: Keep the swarm paused until the operator explicitly asks to thaw it. Before thawing, run one controlled live repo Face turn or dry-run against the current room and confirm the latest model-output logs show an `INTERPRETATION` block plus explicit DSL actions, with no owner-reply/owner-question language crossing into Discord and no scar-tissue prompt prose leaking into public speech.