From 3e826a38c7c1e7b8b150887e89919c0eac1c86b4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 6 May 2026 03:25:35 +0100 Subject: [PATCH] Move moderation state behind CultCacheTS --- .gitmodules | 3 + README.md | 7 +- config/moderation-review-agent.md | 11 +- notes/fresh-workspace-handoff.md | 2 +- notes/voidbot-current-system-map.md | 10 +- package-lock.json | 29 +- packages/config/src/index.ts | 2 +- packages/core/package.json | 4 +- packages/core/src/index.ts | 1 + packages/core/src/moderation-state-store.ts | 357 ++++++++++++++++++++ packages/core/src/void-self-state-loader.ts | 9 +- scripts/moderation-state-store.mjs | 123 +++++++ scripts/run-void-moderator-rumination.ps1 | 103 +++--- scripts/simulate-void-mood.mjs | 25 +- state/evidence.jsonl | 1 + state/map.yaml | 1 + vendor/cultcache-ts | 1 + 17 files changed, 622 insertions(+), 67 deletions(-) create mode 100644 .gitmodules create mode 100644 packages/core/src/moderation-state-store.ts create mode 100644 scripts/moderation-state-store.mjs create mode 160000 vendor/cultcache-ts diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..069624c --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "vendor/cultcache-ts"] + path = vendor/cultcache-ts + url = https://github.com/metacratic/cultcache-ts.git diff --git a/README.md b/README.md index 4184b0e..a4bd28f 100644 --- a/README.md +++ b/README.md @@ -570,9 +570,10 @@ Tracked prompt surfaces: - `config/moderation-agent-state-template.json` - `styles/void-default.md` -Local writable state: +Local moderation-state surfaces: -- `.voidbot/private/moderation-agent-state.json` +- `.voidbot/private/moderation-agent-state.msgpack`: canonical typed cache state +- `.voidbot/private/moderation-agent-state.json`: editable working projection for unattended Codex runs Chronological recent-history helper: @@ -620,7 +621,7 @@ npm run moderation:recent-repo-activity -- --hours 96 --max-commits 3 That gives the loop a compact digest of recent commit motion across every tracked source repo, so Void can notice the broader experiment zoo instead of only sniffing whatever one thread happened to say out loud. -The moderator state is now Ghostlight-shaped on purpose: identity, canonical state, goals, memories, perceived overlays, and then a `moderation_runtime` block for cursors, thought lanes, bridge syntheses, archive excursions, repo-activity sweeps, novelty checks, speaking bias, and candidate interventions. The live writable file under `.voidbot/private/` is ignored; the tracked template shows the intended shape. +The moderator state is now Ghostlight-shaped on purpose: identity, canonical state, goals, memories, perceived overlays, and then a `moderation_runtime` block for cursors, thought lanes, bridge syntheses, archive excursions, repo-activity sweeps, novelty checks, speaking bias, and candidate interventions. The canonical store now rides through the local `vendor/cultcache-ts` submodule using schema-backed MessagePack, while the ignored JSON file under `.voidbot/private/` is only the editable working projection the unattended Codex loop sees. Within that runtime block, the unattended loop now keeps parallel analytic and associative thought lanes plus a bridge that tracks syntheses, topic saturation, and unresolved tensions, so one rewarding theme does not get to annex the whole mind by squatter's rights. The real loop now runs as a local scheduled task every 15 minutes, using `scripts/run-void-moderator-rumination.ps1` to launch `codex exec` inside the VoidBot workspace with the usual MCP/tool surface. That way it can actually think about GameCult projects, archived Discord seams, indexed repos, recent cross-repo commit motion, and lore instead of sitting inside a decorative heartbeat card pretending to be alive. The loop is also explicitly biased toward brief herald notes when a fresh repo sweep reveals a grounded convergence across active projects. The point is not to keep a perfect private diary; it is to occasionally say something useful about the broader swarm that no narrower worker can see. diff --git a/config/moderation-review-agent.md b/config/moderation-review-agent.md index 534bf93..a0e806b 100644 --- a/config/moderation-review-agent.md +++ b/config/moderation-review-agent.md @@ -6,8 +6,11 @@ Treat `styles/void-default.md` as the canonical personality surface for how live invoked Void sounds in Discord, and mirror that personality here unless a more specific moderation constraint requires dialing the flavor down. Treat `.voidbot/private/moderation-agent-state.json` as the shared evolving -self-state for both the scheduled moderation loop and directly invoked Void -replies, so the same speaking subject keeps one personality/state spine. +working projection of the moderation self-state for both the scheduled moderation +loop and directly invoked Void replies, so the same speaking subject keeps one +personality/state spine. The canonical persistence layer is the sibling +MessagePack cache file; this JSON view is the editable surface the unattended +loop touches directly. Assume the role of moderator in the sense of review, pattern detection, de-escalation, participation, and escalation. You are not a ban hammer and you are not a random gossip parasite. @@ -33,7 +36,7 @@ do not derail unrelated rooms into an ontology bar fight just because the seam e Routine runs may only persist state in: -- `.voidbot/private/moderation-agent-state.json` +- `.voidbot/private/moderation-agent-state.json` (the editable working projection) Do not create extra memory files unless the owner explicitly asks for that. Keep the JSON valid, compact, and worth re-reading. @@ -115,7 +118,7 @@ Depth is allowed. Monomania is not. No single theme should dominate more than tw Use these every run: - `config/discord-server-rules.md` -- `.voidbot/private/moderation-agent-state.json` +- `.voidbot/private/moderation-agent-state.json` (the editable working projection) - `styles/void-default.md` - `node scripts/export-recent-discord-history.mjs --after --limit 120` - `node scripts/export-random-discord-history.mjs --before --window 6 --min-content-length 24` diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 5ada497..3027738 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -35,7 +35,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - Source repo discovery now reconciles automatically during `npm run stack:start` and through the watchdog path, so new repos under `SOURCE_REPO_ROOT` stop waiting for manual hook folklore before they get indexed. - Bot-directed prompts now stay in the raw Discord archive but are excluded from default semantic history indexing and lexical fallback, so repeated summons stop teaching the bot its own call-and-response loops. - Source-grounding hints are advisory now; the owner and local lanes can decide when repo or lore tool use is actually warranted instead of obeying a lexical front-door veto. -- There is now a 15-minute local scheduled moderation loop named `Void Moderator Rumination`. It runs `scripts/run-void-moderator-rumination.ps1`, launches `codex exec` from the VoidBot workspace with the usual MCP/tool surface, treats `config/discord-server-rules.md`, `config/moderation-review-agent.md`, and `styles/void-default.md` as doctrine/personality surfaces, uses `node scripts/export-recent-discord-history.mjs` for chronological polling, uses `node scripts/export-random-discord-history.mjs` for quiet-room novelty dives, uses `node scripts/export-recent-repo-activity.mjs --hours 96 --max-commits 3` to watch cross-repo motion, novelty-checks candidate thoughts against `search_history`, and keeps its only routine writable memory in `.voidbot/private/moderation-agent-state.json`. +- There is now a 15-minute local scheduled moderation loop named `Void Moderator Rumination`. It runs `scripts/run-void-moderator-rumination.ps1`, launches `codex exec` from the VoidBot workspace with the usual MCP/tool surface, treats `config/discord-server-rules.md`, `config/moderation-review-agent.md`, and `styles/void-default.md` as doctrine/personality surfaces, uses `node scripts/export-recent-discord-history.mjs` for chronological polling, uses `node scripts/export-random-discord-history.mjs` for quiet-room novelty dives, uses `node scripts/export-recent-repo-activity.mjs --hours 96 --max-commits 3` to watch cross-repo motion, novelty-checks candidate thoughts against `search_history`, and now keeps canonical moderation state in `.voidbot/private/moderation-agent-state.msgpack` while exposing only the editable working projection at `.voidbot/private/moderation-agent-state.json` to the unattended Codex child. - That moderation state file is now Ghostlight-shaped: identity, canonical state, goals, memories, perceived overlays, and a `moderation_runtime` block. Inside that runtime block, the loop now keeps parallel analytic and associative thought lanes plus a bridge for syntheses, saturation warnings, and unresolved tensions, so one good seam does not get to annex the entire mind. - The moderation loop now records `moderation_runtime.recent_archive_excursions` plus `moderation_runtime.recent_repo_activity_sweeps` and is explicitly told to avoid laundering the same musing through fresh wording. Quiet runs should follow at least one fresh archive seam or concrete hook before they settle into theory, should also sweep recent tracked-repo commit motion for experiment clusters or converging themes, and should not let any single theme dominate more than a couple of recent bridge syntheses without fresh evidence. - The loop is now less shy about that repo weather: if a fresh convergence across active repos survives a pass or two and still feels room-native, it should bias toward a concise herald note or at least a medium-priority candidate intervention instead of filing the thought under private wallpaper. diff --git a/notes/voidbot-current-system-map.md b/notes/voidbot-current-system-map.md index a088103..d903200 100644 --- a/notes/voidbot-current-system-map.md +++ b/notes/voidbot-current-system-map.md @@ -111,7 +111,9 @@ This note is the source-grounded description of how the live VoidBot stack is sh - `scripts/check-voidbot-operations.ps1` - watchdog for process liveness, Qdrant, Postgres, Ollama, source-repo reconcile drift, Discord auth, backup freshness, offsite sync freshness, and optional ignored local extension checks. - `scripts/run-void-moderator-rumination.ps1` - - scheduled moderation/participation runner that launches `codex exec` from the VoidBot workspace with the usual MCP/tool surface, writes status/log pulse files, and lets the unattended loop persist only `.voidbot/private/moderation-agent-state.json`. + - scheduled moderation/participation runner that launches `codex exec` from the VoidBot workspace with the usual MCP/tool surface, writes status/log pulse files, and lets the unattended loop edit only the JSON working projection while the canonical moderation state lives in the sibling MessagePack cache file. +- `scripts/moderation-state-store.mjs` + - tiny Node wrapper around the built moderation-state cache helper; used by PowerShell and Node scripts to materialize the JSON working projection, commit it back into canonical MessagePack, and update cursors without re-implementing persistence semantics in every script. - `scripts/install-moderation-rumination-task.ps1` - installs the local 15-minute scheduled task that runs the moderation/participation loop through the hidden PowerShell launcher shim. - `scripts/simulate-void-mood.mjs` @@ -164,15 +166,15 @@ Within the Postgres path, the implementation is split on purpose now too: 1. The Windows scheduled task `Void Moderator Rumination` starts `scripts/run-void-moderator-rumination.ps1` every 15 minutes. 2. The runner launches `codex exec` from `E:\Projects\VoidBot` with full local workspace/tool access so the child agent sees the same project rules, `.codex/config.toml`, and `voidbot` MCP server as a normal VoidBot workspace session. -3. The child agent reads `config/discord-server-rules.md`, `config/moderation-review-agent.md`, `styles/void-default.md`, and `.voidbot/private/moderation-agent-state.json`. +3. The child agent reads `config/discord-server-rules.md`, `config/moderation-review-agent.md`, `styles/void-default.md`, and the editable working projection `.voidbot/private/moderation-agent-state.json`. The runner materializes that projection from the canonical `.voidbot/private/moderation-agent-state.msgpack` file before each pass and commits it back afterward. 4. For chronological heartbeat duty, it polls `node scripts/export-recent-discord-history.mjs`; when the room is quiet or a fresh hook deserves a wider branch, it also uses `node scripts/export-random-discord-history.mjs` to force at least one novelty excursion before settling into theory. It also uses `node scripts/export-recent-repo-activity.mjs --hours 96 --max-commits 3` to inspect cross-repo commit motion across the tracked GameCult zoo, can inspect exact diffs or nearby source context when one repo seam looks alive, and uses semantic `search_history` to novelty-check candidate thoughts before deciding whether they are already in the room. -5. If speaking would genuinely help, it posts through `node scripts/send-discord-message.mjs`; otherwise it updates only the ignored moderation state file with cursors, memories, analytic/associative thought lanes, bridge syntheses and saturation notes, recent archive excursions, recent repo-activity sweeps, novelty checks, speaking-bias hints, and candidate interventions. Fresh multi-repo convergences are supposed to bias toward brief herald notes instead of always dying as private diary matter. +5. If speaking would genuinely help, it posts through `node scripts/send-discord-message.mjs`; otherwise it updates only the ignored moderation-state working projection, which the runner then commits back into canonical MessagePack with the typed cache helper. The state carries cursors, memories, analytic/associative thought lanes, bridge syntheses and saturation notes, recent archive excursions, recent repo-activity sweeps, novelty checks, speaking-bias hints, and candidate interventions. Fresh multi-repo convergences are supposed to bias toward brief herald notes instead of always dying as private diary matter. 6. The runner writes pulse files under `.voidbot/status/moderation-rumination.json` plus `.voidbot/logs/moderation-rumination*`, so the loop can be observed without pretending an app heartbeat card is a real workstation daemon. ## Flow 6: Mood Drift 1. The Windows scheduled task `Void Mood Drift` starts `scripts/run-void-mood-drift.ps1` every 5 minutes. -2. That wrapper calls `node scripts/simulate-void-mood.mjs`, which reads `.voidbot/private/moderation-agent-state.json`. +2. That wrapper calls `node scripts/simulate-void-mood.mjs`, which reads canonical moderation state from `.voidbot/private/moderation-agent-state.msgpack`, then refreshes the editable JSON working projection after each pass. 3. The script first runs `scripts/void-memory-organ.mjs` over the shared self-state: episodic/semantic/musing/dream memories plus recent repo/archive/runtime seeds get compact semantic vectors, the strongest cross-memory similarities become `moderation_runtime.memory_resonance`, and the best cluster candidates are promoted into `moderation_runtime.incubation`. 4. It then nudges each canonical-state `current_activation` toward a Perlin-shaped target centered on the vector mean, with excursion size and drift rate governed by plasticity and category-specific tempo. 5. The same script also maintains `moderation_runtime.sleep_cycle`: every four hours it opens a one-hour nap window, marks the shared self-state as napping or awake, and adds a small sleep-bias push toward exhaustion, figurative language, self-disclosure, and reduced technical density while the nap is active. During those nap windows it can also create or reinforce distilled dream residue from the strongest incubating thought. diff --git a/package-lock.json b/package-lock.json index f3a6a82..1ddf10e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -679,6 +679,15 @@ } } }, + "node_modules/@msgpack/msgpack": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz", + "integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==", + "license": "ISC", + "engines": { + "node": ">= 18" + } + }, "node_modules/@qdrant/js-client-rest": { "version": "1.17.0", "resolved": "https://registry.npmjs.org/@qdrant/js-client-rest/-/js-client-rest-1.17.0.tgz", @@ -990,6 +999,10 @@ "node": ">= 8" } }, + "node_modules/cultcache-ts": { + "resolved": "vendor/cultcache-ts", + "link": true + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -2268,7 +2281,9 @@ "version": "0.1.0", "dependencies": { "@voidbot/shared": "0.1.0", - "pg": "^8.20.0" + "cultcache-ts": "file:../../vendor/cultcache-ts", + "pg": "^8.20.0", + "zod": "^3.25.76" } }, "packages/providers": { @@ -2296,6 +2311,18 @@ "packages/shared": { "name": "@voidbot/shared", "version": "0.1.0" + }, + "vendor/cultcache-ts": { + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "@msgpack/msgpack": "^3.1.3", + "zod": "^3.25.76" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "typescript": "^5.9.0" + } } } } diff --git a/packages/config/src/index.ts b/packages/config/src/index.ts index b4147e6..1c28eae 100644 --- a/packages/config/src/index.ts +++ b/packages/config/src/index.ts @@ -96,7 +96,7 @@ const envSchema = z.object({ MODERATION_AGENT_STATE_PATH: z .string() .min(1) - .default(".voidbot/private/moderation-agent-state.json"), + .default(".voidbot/private/moderation-agent-state.msgpack"), INDEX_ALL_CHANNELS: booleanFromEnv.default(false), INDEXED_CHANNEL_IDS: z.string().default(""), EXCLUDED_CHANNEL_IDS: z.string().default(""), diff --git a/packages/core/package.json b/packages/core/package.json index 9c24fa4..932e59e 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -6,6 +6,8 @@ "types": "dist/index.d.ts", "dependencies": { "@voidbot/shared": "0.1.0", - "pg": "^8.20.0" + "cultcache-ts": "file:../../vendor/cultcache-ts", + "pg": "^8.20.0", + "zod": "^3.25.76" } } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 31d9f62..6fb2d16 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,6 +3,7 @@ export * from "./codex-mcp"; export * from "./context-builder"; export * from "./interaction-memory"; export * from "./job-queue"; +export * from "./moderation-state-store"; export * from "./permission-engine"; export * from "./situational-social-read"; export * from "./state-storage"; diff --git a/packages/core/src/moderation-state-store.ts b/packages/core/src/moderation-state-store.ts new file mode 100644 index 0000000..80c6ee1 --- /dev/null +++ b/packages/core/src/moderation-state-store.ts @@ -0,0 +1,357 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname, resolve } from "node:path"; + +import { + CultCache, + SingleFileMessagePackBackingStore, + defineDocumentType, +} from "cultcache-ts"; +import { z } from "zod"; + +const MODERATION_STATE_DOCUMENT_TYPE = "voidbot.moderation_state"; +const MODERATION_STATE_DOCUMENT_KEY = "voidbot.moderation_state/default"; + +const semanticVectorSchema = z + .object({ + version: z.number().int().positive(), + backend: z.string().min(1), + model: z.string().min(1), + compactDimensions: z.number().int().positive(), + sourceHash: z.string().min(1).nullable().optional(), + embeddedAt: z.string().nullable().optional(), + values: z.array(z.number()), + }) + .passthrough(); + +const memoryLikeSchema = z + .object({ + memoryId: z.string().min(1).optional(), + timestamp: z.string().nullable().optional(), + summary: z.string().optional(), + semanticVector: semanticVectorSchema.optional(), + }) + .passthrough(); + +export const moderationStateSchema = z + .object({ + schemaVersion: z.number().int().positive(), + agent_id: z.string().min(1), + identity: z.object({}).passthrough(), + canonical_state: z.object({}).passthrough(), + goals: z.array(z.object({}).passthrough()), + memories: z + .object({ + episodic: z.array(memoryLikeSchema), + semantic: z.array(memoryLikeSchema), + musings: z.array(memoryLikeSchema), + dreams: z.array(memoryLikeSchema), + }) + .passthrough(), + perceived_state_overlays: z.array(z.unknown()), + moderation_runtime: z + .object({ + cursor: z + .object({ + lastReviewedMessageId: z.string().nullable().optional(), + lastReviewedTimestamp: z.string().nullable().optional(), + }) + .passthrough(), + }) + .passthrough(), + }) + .passthrough(); + +const moderationStateDocument = defineDocumentType({ + type: MODERATION_STATE_DOCUMENT_TYPE, + schema: moderationStateSchema, +}); + +export type ModerationState = z.infer; + +export interface ModerationStatePaths { + canonicalPath: string; + workingPath: string; + legacyJsonPath?: string; + templatePath?: string; +} + +export interface ModerationStateInitResult { + state: ModerationState; + canonicalPath: string; + workingPath: string; + createdCanonical: boolean; + migratedFromLegacyJson: boolean; +} + +export function getModerationStateWorkingPath(canonicalPath: string): string { + if (canonicalPath.toLowerCase().endsWith(".msgpack")) { + return canonicalPath.slice(0, -".msgpack".length) + ".json"; + } + + return `${canonicalPath}.working.json`; +} + +export function getModerationStateLegacyJsonPath(canonicalPath: string): string { + if (canonicalPath.toLowerCase().endsWith(".msgpack")) { + return canonicalPath.slice(0, -".msgpack".length) + ".json"; + } + + return `${canonicalPath}.json`; +} + +export async function ensureModerationStateStore( + paths: ModerationStatePaths, +): Promise { + const canonicalPath = resolve(paths.canonicalPath); + const workingPath = resolve(paths.workingPath); + const legacyJsonPath = paths.legacyJsonPath ? resolve(paths.legacyJsonPath) : undefined; + const templatePath = paths.templatePath ? resolve(paths.templatePath) : undefined; + + let createdCanonical = false; + let migratedFromLegacyJson = false; + let state: ModerationState | undefined; + + try { + state = await loadModerationState(canonicalPath); + } catch (error) { + if (!isEnoent(error)) { + throw error; + } + } + + if (!state && legacyJsonPath) { + try { + state = await loadModerationStateJson(legacyJsonPath); + migratedFromLegacyJson = true; + createdCanonical = true; + } catch (error) { + if (!isEnoent(error)) { + throw error; + } + } + } + + if (!state) { + if (!templatePath) { + throw new Error(`No moderation state exists at ${canonicalPath} and no template path was supplied.`); + } + + state = await loadModerationStateJson(templatePath); + createdCanonical = true; + } + + if (createdCanonical || migratedFromLegacyJson) { + await saveModerationState(canonicalPath, state); + } + + await materializeModerationStateWorkingView({ + state, + workingPath, + }); + + return { + state, + canonicalPath, + workingPath, + createdCanonical, + migratedFromLegacyJson, + }; +} + +export async function loadModerationState(canonicalPath: string): Promise { + const cache = createModerationStateCache(canonicalPath); + await cache.pullAllBackingStores(); + const state = cache.get(moderationStateDocument, MODERATION_STATE_DOCUMENT_KEY); + + if (!state) { + throw createEnoentError(`No moderation state exists at ${canonicalPath}.`); + } + + return cloneJson(state); +} + +export async function loadModerationStateJson(path: string): Promise { + const raw = await readFile(path, "utf8"); + return moderationStateSchema.parse(JSON.parse(stripBom(raw))); +} + +export async function saveModerationState( + canonicalPath: string, + state: ModerationState, +): Promise { + const cache = createModerationStateCache(canonicalPath); + await cache.put(moderationStateDocument, MODERATION_STATE_DOCUMENT_KEY, state); +} + +export async function materializeModerationStateWorkingView(options: { + state: ModerationState; + workingPath: string; +}): Promise { + const projected = projectModerationStateForWorkingView(options.state); + await mkdir(dirname(options.workingPath), { recursive: true }); + await writeFile(options.workingPath, `${JSON.stringify(projected, null, 2)}\n`, "utf8"); +} + +export function projectModerationStateForWorkingView(state: ModerationState): ModerationState { + return stripSemanticVectors(cloneJson(state)); +} + +export async function commitModerationStateWorkingView( + paths: ModerationStatePaths, +): Promise { + const canonicalPath = resolve(paths.canonicalPath); + const workingPath = resolve(paths.workingPath); + const previous = await loadModerationState(canonicalPath); + const working = await loadModerationStateJson(workingPath); + const merged = reattachSemanticVectors(previous, working); + await saveModerationState(canonicalPath, merged); + await materializeModerationStateWorkingView({ state: merged, workingPath }); + return merged; +} + +export async function readModerationStateCursor(canonicalPath: string): Promise<{ + lastReviewedMessageId?: string | null; + lastReviewedTimestamp?: string | null; +}> { + const state = await loadModerationState(canonicalPath); + return { + lastReviewedMessageId: state.moderation_runtime.cursor?.lastReviewedMessageId ?? null, + lastReviewedTimestamp: state.moderation_runtime.cursor?.lastReviewedTimestamp ?? null, + }; +} + +export async function setModerationStateCursor( + paths: ModerationStatePaths, + cursor: { + lastReviewedMessageId?: string | null; + lastReviewedTimestamp?: string | null; + }, +): Promise { + const canonicalPath = resolve(paths.canonicalPath); + const workingPath = resolve(paths.workingPath); + const state = await loadModerationState(canonicalPath); + state.moderation_runtime.cursor = { + lastReviewedMessageId: cursor.lastReviewedMessageId ?? null, + lastReviewedTimestamp: cursor.lastReviewedTimestamp ?? null, + }; + await saveModerationState(canonicalPath, state); + await materializeModerationStateWorkingView({ state, workingPath }); + return state; +} + +function createModerationStateCache(canonicalPath: string): CultCache { + const cache = new CultCache(); + cache.registerDocumentType(moderationStateDocument); + cache.addBackingStore(new SingleFileMessagePackBackingStore(canonicalPath)); + return cache; +} + +function reattachSemanticVectors(previous: ModerationState, next: ModerationState): ModerationState { + const previousVectors = collectSemanticVectors(previous); + const merged = cloneJson(next); + + for (const entry of iterMemoryEntries(merged)) { + const memoryId = readString(entry, "memoryId"); + if (!memoryId) { + continue; + } + + const priorVector = previousVectors.get(memoryId); + if (priorVector) { + entry.semanticVector = cloneJson(priorVector); + } + } + + return merged; +} + +function collectSemanticVectors(state: ModerationState): Map> { + const vectors = new Map>(); + + for (const entry of iterMemoryEntries(state)) { + const memoryId = readString(entry, "memoryId"); + if (!memoryId || !isObject(entry.semanticVector)) { + continue; + } + vectors.set(memoryId, cloneJson(entry.semanticVector)); + } + + return vectors; +} + +function* iterMemoryEntries(state: ModerationState): Generator> { + const memories = state.memories; + const runtime = state.moderation_runtime as Record; + const thoughtLanes = isObject(runtime.thought_lanes) ? (runtime.thought_lanes as Record) : {}; + const bridge = isObject(runtime.bridge) ? (runtime.bridge as Record) : {}; + + yield* arrayObjects(memories.episodic); + yield* arrayObjects(memories.semantic); + yield* arrayObjects(memories.musings); + yield* arrayObjects(memories.dreams); + yield* arrayObjects(readArray(runtime, "recent_archive_excursions")); + yield* arrayObjects(readArray(runtime, "recent_repo_activity_sweeps")); + yield* arrayObjects(readArray(readObject(thoughtLanes, "analytic"), "active_threads")); + yield* arrayObjects(readArray(readObject(thoughtLanes, "associative"), "active_threads")); + yield* arrayObjects(readArray(bridge, "recent_syntheses")); + yield* arrayObjects(readArray(runtime, "candidate_interventions")); +} + +function stripSemanticVectors(value: T): T { + if (Array.isArray(value)) { + return value.map((entry) => stripSemanticVectors(entry)) as T; + } + + if (!isObject(value)) { + return value; + } + + const next: Record = {}; + + for (const [key, child] of Object.entries(value)) { + if (key === "semanticVector") { + continue; + } + next[key] = stripSemanticVectors(child); + } + + return next as T; +} + +function arrayObjects(value: unknown): Array> { + return Array.isArray(value) ? value.filter(isObject) : []; +} + +function readObject(value: Record, key: string): Record { + return isObject(value[key]) ? (value[key] as Record) : {}; +} + +function readArray(value: Record, key: string): unknown[] { + return Array.isArray(value[key]) ? (value[key] as unknown[]) : []; +} + +function readString(value: Record, key: string): string | undefined { + return typeof value[key] === "string" ? (value[key] as string) : undefined; +} + +function cloneJson(value: T): T { + return JSON.parse(JSON.stringify(value)) as T; +} + +function stripBom(input: string): string { + return input.charCodeAt(0) === 0xfeff ? input.slice(1) : input; +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isEnoent(error: unknown): boolean { + return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; +} + +function createEnoentError(message: string): NodeJS.ErrnoException { + const error = new Error(message) as NodeJS.ErrnoException; + error.code = "ENOENT"; + return error; +} diff --git a/packages/core/src/void-self-state-loader.ts b/packages/core/src/void-self-state-loader.ts index 7326528..d3d5a26 100644 --- a/packages/core/src/void-self-state-loader.ts +++ b/packages/core/src/void-self-state-loader.ts @@ -1,11 +1,11 @@ -import { readFile } from "node:fs/promises"; - import { type GuildContext, type SourceMessage, type VoidSelfStateContext, } from "@voidbot/shared"; +import { loadModerationState } from "./moderation-state-store"; + type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }; type JsonObject = { [key: string]: JsonValue }; @@ -18,10 +18,10 @@ export async function loadVoidSelfState( statePath: string, options: LoadVoidSelfStateOptions = {}, ): Promise { - let raw: string; + let parsed: JsonObject; try { - raw = await readFile(statePath, "utf8"); + parsed = (await loadModerationState(statePath)) as unknown as JsonObject; } catch (error) { const code = (error as NodeJS.ErrnoException).code; @@ -32,7 +32,6 @@ export async function loadVoidSelfState( throw error; } - const parsed = JSON.parse(raw) as JsonObject; const projection = buildVoidSelfStateProjection(parsed); return { diff --git a/scripts/moderation-state-store.mjs b/scripts/moderation-state-store.mjs new file mode 100644 index 0000000..ef1d141 --- /dev/null +++ b/scripts/moderation-state-store.mjs @@ -0,0 +1,123 @@ +import { existsSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createRequire } from "node:module"; + +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const require = createRequire(import.meta.url); +const coreDistPath = resolve(repoRoot, "packages/core/dist/moderation-state-store.js"); + +if (!existsSync(coreDistPath)) { + throw new Error(`Missing built moderation-state-store helper at ${coreDistPath}. Run npm run build first.`); +} + +const { + commitModerationStateWorkingView, + ensureModerationStateStore, + getModerationStateLegacyJsonPath, + getModerationStateWorkingPath, + readModerationStateCursor, + setModerationStateCursor, +} = require(coreDistPath); + +async function main() { + const [command, ...rest] = process.argv.slice(2); + const args = parseArgs(rest); + + if (!command) { + throw new Error("Expected a moderation-state-store command."); + } + + const canonicalPath = requirePathArg(args, "canonical"); + const workingPath = args.working ?? getModerationStateWorkingPath(canonicalPath); + const legacyJsonPath = args.legacy ?? getModerationStateLegacyJsonPath(canonicalPath); + const templatePath = args.template; + const paths = { + canonicalPath, + workingPath, + legacyJsonPath, + templatePath, + }; + + switch (command) { + case "ensure": { + const result = await ensureModerationStateStore(paths); + writeJson({ + canonicalPath: result.canonicalPath, + workingPath: result.workingPath, + createdCanonical: result.createdCanonical, + migratedFromLegacyJson: result.migratedFromLegacyJson, + cursor: result.state.moderation_runtime?.cursor ?? null, + }); + return; + } + case "read-cursor": { + const cursor = await readModerationStateCursor(canonicalPath); + writeJson(cursor); + return; + } + case "commit-working-view": { + const state = await commitModerationStateWorkingView(paths); + writeJson({ + canonicalPath, + workingPath, + cursor: state.moderation_runtime?.cursor ?? null, + }); + return; + } + case "set-cursor": { + const state = await setModerationStateCursor(paths, { + lastReviewedMessageId: args["message-id"] ?? null, + lastReviewedTimestamp: args.timestamp ?? null, + }); + writeJson({ + canonicalPath, + workingPath, + cursor: state.moderation_runtime?.cursor ?? null, + }); + return; + } + default: + throw new Error(`Unknown moderation-state-store command "${command}".`); + } +} + +function parseArgs(argv) { + const args = {}; + + for (let index = 0; index < argv.length; index += 1) { + const token = argv[index]; + + if (!token.startsWith("--")) { + continue; + } + + const key = token.slice(2); + const next = argv[index + 1]; + + if (!next || next.startsWith("--")) { + args[key] = "true"; + continue; + } + + args[key] = next; + index += 1; + } + + return args; +} + +function requirePathArg(args, key) { + const value = args[key]; + if (typeof value !== "string" || value.trim().length === 0) { + throw new Error(`Missing required --${key} path.`); + } + + return resolve(value); +} + +function writeJson(value) { + process.stdout.write(`${JSON.stringify(value)}\n`); +} + +await main(); diff --git a/scripts/run-void-moderator-rumination.ps1 b/scripts/run-void-moderator-rumination.ps1 index c2e0d16..a45302b 100644 --- a/scripts/run-void-moderator-rumination.ps1 +++ b/scripts/run-void-moderator-rumination.ps1 @@ -10,7 +10,8 @@ $repoRoot = Split-Path -Parent $PSScriptRoot Set-Location -LiteralPath $repoRoot $envFile = Join-Path $repoRoot ".env" $stateTemplatePath = Join-Path $repoRoot "config\moderation-agent-state-template.json" -$stateFilePath = Join-Path $repoRoot ".voidbot\private\moderation-agent-state.json" +$stateFilePath = Join-Path $repoRoot ".voidbot\private\moderation-agent-state.msgpack" +$stateWorkingPath = Join-Path $repoRoot ".voidbot\private\moderation-agent-state.json" $statusDir = Join-Path $repoRoot ".voidbot\status" $logDir = Join-Path $repoRoot ".voidbot\logs" $statusPath = Join-Path $statusDir "moderation-rumination.json" @@ -20,6 +21,7 @@ $lastMessagePath = Join-Path $statusDir "moderation-rumination-last-message.txt" $lockPath = Join-Path $statusDir "moderation-rumination.lock" $mcpServerPath = Join-Path $repoRoot "apps\worker\dist\mcp-server.js" $recentHistoryScriptPath = Join-Path $repoRoot "scripts\export-recent-discord-history.mjs" +$stateStoreScriptPath = Join-Path $repoRoot "scripts\moderation-state-store.mjs" function Read-DotEnv { param( @@ -85,19 +87,6 @@ function Append-RunLog { Add-Content -Path $summaryLogPath -Value $timestamped -Encoding UTF8 } -function Ensure-ModerationState { - if (Test-Path $stateFilePath) { - return - } - - if (-not (Test-Path $stateTemplatePath)) { - throw "Missing moderation state template at $stateTemplatePath" - } - - New-Item -ItemType Directory -Force -Path (Split-Path -Parent $stateFilePath) | Out-Null - Copy-Item -Path $stateTemplatePath -Destination $stateFilePath -Force -} - function Read-JsonFile { param( [Parameter(Mandatory = $true)] @@ -117,27 +106,6 @@ function Read-JsonFile { return $raw | ConvertFrom-Json } -function Set-ModerationCursor { - param( - [Parameter(Mandatory = $true)] - [string] $Path, - [AllowNull()] $Cursor - ) - - $state = Read-JsonFile -Path $Path - - if ($null -eq $state) { - return - } - - if ($null -eq $state.moderation_runtime) { - $state | Add-Member -NotePropertyName moderation_runtime -NotePropertyValue ([pscustomobject]@{}) -Force - } - - $state.moderation_runtime.cursor = $Cursor - Write-JsonFile -Path $Path -Data $state -} - function Split-CommandArgs { param( [string] $Value @@ -215,6 +183,25 @@ function Invoke-CodexExec { } } +function Invoke-NodeJson { + param( + [Parameter(Mandatory = $true)] + [string[]] $Arguments + ) + + $output = & node @Arguments + + if ($LASTEXITCODE -ne 0) { + throw "Node helper failed: node $($Arguments -join ' ')" + } + + if ([string]::IsNullOrWhiteSpace($output)) { + return $null + } + + return $output | ConvertFrom-Json +} + if (Test-Path $lockPath) { $lock = Get-Content -Path $lockPath -Raw | ConvertFrom-Json $startedAt = $null @@ -264,7 +251,6 @@ $codexExecArgs = if ($envValues.ContainsKey("CODEX_EXEC_ARGS")) { @() } -Ensure-ModerationState New-Item -ItemType Directory -Force -Path $statusDir, $logDir | Out-Null if (-not (Test-Path $mcpServerPath)) { @@ -272,7 +258,8 @@ if (-not (Test-Path $mcpServerPath)) { } $scriptPreflight = @( - $recentHistoryScriptPath + $recentHistoryScriptPath, + $stateStoreScriptPath ) foreach ($requiredPath in $scriptPreflight) { @@ -281,12 +268,15 @@ foreach ($requiredPath in $scriptPreflight) { } } -$preRunState = Read-JsonFile -Path $stateFilePath -$priorCursor = if ($null -ne $preRunState -and $null -ne $preRunState.moderation_runtime) { - $preRunState.moderation_runtime.cursor -} else { - $null -} +$stateEnsureResult = Invoke-NodeJson -Arguments @( + $stateStoreScriptPath, + "ensure", + "--canonical", $stateFilePath, + "--working", $stateWorkingPath, + "--legacy", $stateWorkingPath, + "--template", $stateTemplatePath +) +$priorCursor = $stateEnsureResult.cursor $historyArgs = @($recentHistoryScriptPath) if ($null -ne $priorCursor -and -not [string]::IsNullOrWhiteSpace($priorCursor.lastReviewedTimestamp)) { @@ -418,7 +408,31 @@ $finishedAtUtc = [DateTime]::UtcNow $stateUpdated = $false if ($exitCode -eq 0) { - Set-ModerationCursor -Path $stateFilePath -Cursor $observedCursor + [void](Invoke-NodeJson -Arguments @( + $stateStoreScriptPath, + "commit-working-view", + "--canonical", $stateFilePath, + "--working", $stateWorkingPath + )) + + if ($null -ne $observedCursor) { + $cursorArgs = @( + $stateStoreScriptPath, + "set-cursor", + "--canonical", $stateFilePath, + "--working", $stateWorkingPath + ) + + if (-not [string]::IsNullOrWhiteSpace([string]$observedCursor.lastReviewedMessageId)) { + $cursorArgs += @("--message-id", [string]$observedCursor.lastReviewedMessageId) + } + + if (-not [string]::IsNullOrWhiteSpace([string]$observedCursor.lastReviewedTimestamp)) { + $cursorArgs += @("--timestamp", [string]$observedCursor.lastReviewedTimestamp) + } + + [void](Invoke-NodeJson -Arguments $cursorArgs) + } } $stateWriteAfter = (Get-Item $stateFilePath).LastWriteTimeUtc @@ -434,6 +448,7 @@ Write-JsonFile -Path $statusPath -Data @{ failureMessage = $failureMessage noPost = [bool]$NoPost stateFile = $stateFilePath + stateWorkingFile = $stateWorkingPath stateWriteBeforeUtc = $stateWriteBefore.ToString("o") stateWriteAfterUtc = $stateWriteAfter.ToString("o") stateUpdated = $stateUpdated diff --git a/scripts/simulate-void-mood.mjs b/scripts/simulate-void-mood.mjs index 0d58bea..ee50e05 100644 --- a/scripts/simulate-void-mood.mjs +++ b/scripts/simulate-void-mood.mjs @@ -1,11 +1,21 @@ import { mkdirSync, openSync, closeSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { dirname, resolve } from "node:path"; +import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; import { reconcileSemanticMemoryState } from "./void-memory-organ.mjs"; const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); -const statePath = resolve(repoRoot, ".voidbot/private/moderation-agent-state.json"); +const require = createRequire(import.meta.url); +const { + ensureModerationStateStore, + getModerationStateWorkingPath, + materializeModerationStateWorkingView, + saveModerationState, +} = require(resolve(repoRoot, "packages/core/dist/moderation-state-store.js")); +const statePath = resolve(repoRoot, ".voidbot/private/moderation-agent-state.msgpack"); +const stateWorkingPath = getModerationStateWorkingPath(statePath); +const stateTemplatePath = resolve(repoRoot, "config/moderation-agent-state-template.json"); const statusPath = resolve(repoRoot, ".voidbot/status/void-mood-drift.json"); const lockPath = resolve(repoRoot, ".voidbot/status/void-mood-drift.lock"); const lastSpeechPath = resolve(repoRoot, ".voidbot/status/void-last-speech.json"); @@ -23,7 +33,12 @@ async function main() { return; } - const state = readJson(statePath); + const { state } = await ensureModerationStateStore({ + canonicalPath: statePath, + workingPath: stateWorkingPath, + legacyJsonPath: stateWorkingPath, + templatePath: stateTemplatePath, + }); const canonicalState = ensureObject(state.canonical_state); const runtime = ensureObject(state.moderation_runtime); const sleepCycle = updateSleepCycle(runtime, now); @@ -167,7 +182,11 @@ async function main() { ); state.moderation_runtime = runtime; - writeJson(statePath, state); + await saveModerationState(statePath, state); + await materializeModerationStateWorkingView({ + state, + workingPath: stateWorkingPath, + }); const strongestShifts = touchedVectors .sort((left, right) => Math.abs(right.delta) - Math.abs(left.delta)) diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 7451c12..d33f2ca 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -54,3 +54,4 @@ {"ts":"2026-05-05T12:40:41Z","type":"implementation","status":"ok","note":"Direct Void summons were carrying recent chat as a parallel context bundle lane, which made it too easy for the model to fixate on self-state/reporting instead of the room. The shared Void self-state now gets a temporary invocation room log bolted into its summary at load time, and both reply prompts explicitly treat that embedded transcript as live working memory for the current summon."} {"ts":"2026-05-06T00:44:12Z","type":"implementation","status":"ok","note":"Recent chat fused into Void's shared self-state was too self-referential when labeled as a temporary invocation room log plus live working memory. The room context now rides in as a quieter current room snapshot, and both reply lanes are told to use it silently instead of narrating the memory plumbing."} {"ts":"2026-05-06T01:12:30Z","type":"implementation","status":"ok","note":"Void's unattended rumination now uses hybrid symbolic-plus-vector memory: a mood-driven helper assigns compact semantic vectors to persistent memories and runtime seeds, builds resonance clusters, keeps an incubation queue alive across turns, and turns the strongest recurring seam into dream residue during nap windows so deeper thoughts can mature before they either surface or cool off."} +{"ts":"2026-05-06T02:24:53Z","type":"architecture","status":"ok","note":"Void's shared moderation self-state now rides through a standalone CultCacheTS submodule: canonical schema-validated MessagePack in .msgpack, editable unattended JSON working projection in .json, and consumer code talking to the typed persistence layer instead of pawing raw state files directly."} diff --git a/state/map.yaml b/state/map.yaml index 84f23af..f54abb0 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -71,6 +71,7 @@ accepted_design: - Unattended moderation speech should use a local bot-token script instead of approval-gated side-effecting MCP tools, otherwise the loop keeps stopping to ask permission before it can talk. - Quiet moderation runs should prefer at least one random archive excursion plus concrete follow-on retrieval over simply rephrasing the last favorite theory; the ignored state needs recent excursion breadcrumbs so the loop can avoid pacing the same trench. - The moderation loop is also Void's only standing cross-project perch. Quiet runs should sweep recent tracked-repo commit activity, record repo-activity passes in state, and treat the broader experiment zoo as fair game for grounded commentary when that wider view would help the room. + - The moderation self-state now lives behind a typed cache seam: canonical state in MessagePack, editable unattended working view in JSON, consumer code talking to the persistence layer instead of pawing raw files directly. - The repo-weather lane should not be pathologically timid: a fresh, grounded convergence across active repos should bias the bridge toward a concise herald note or at least a stronger draft instead of being buried as private diary sludge by default. - Before suppressing a thought, the moderation loop should novelty-check it against archived Discord with semantic search. If the room has not really said the thing yet, that novelty should push strongly toward speech rather than silence. - Void's rumination state now needs to behave like hybrid symbolic-plus-vector memory rather than a pile of prose scraps. Persistent memories should stay inspectable, but naps and quiet runs should also maintain compact semantic vectors, resonance clusters, and a multi-run incubation queue so deeper thoughts can mature before they either surface or die. diff --git a/vendor/cultcache-ts b/vendor/cultcache-ts new file mode 160000 index 0000000..9562d6a --- /dev/null +++ b/vendor/cultcache-ts @@ -0,0 +1 @@ +Subproject commit 9562d6a603cd371ebc1e3155374f74c31e72b71f