diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 7a4180c..70f8d2a 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -22,16 +22,16 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - `.voidbot/` owns archives, artifacts, logs, status files, and backups. - `owner_codex` and `local_llm` are the active reply lanes. - The ordinary bot/worker/provider/RAG/Postgres/Qdrant foundation still deserves to survive. -- The moderation/mood/private-self-state foundation does not. Treat it as the top architectural risk until JSON projection mutation and legacy mirrors are gone. +- The moderation/mood/private-self-state foundation has been cut back to the typed store boundary. Treat it as incomplete until the scheduled phase machine and memory maintenance are rebuilt on that boundary. +- CultCache-backed self-state uses the `.cc` extension. The active store path is `.voidbot/private/void-self-state.cc`. - The smallest coherent target is one polymorphic CultCache-backed state authority with typed document kinds plus typed mutation tools: agents propose small operations, and the state service validates/applies them. Whole-state JSON editing is rejected as a durable mutation path. - Commit-one boundary naming is now in code at `packages/core/src/void-self-state-domain.ts`: it declares the global typed document kinds and strict operation payload schemas. Runtime behavior has not moved yet. - Read-only projection is now in `packages/core/src/void-self-state-projection.ts`. `loadVoidSelfState` uses that typed projection for nap/reply-mode context while leaving the old richer prompt summary intact until typed documents explicitly own those details. -- Typed operations are now applied through `packages/core/src/void-self-state-service.ts` and `scripts/void-self-state.mjs apply-operation`. During migration this service writes the new typed documents and updates only the narrow legacy monolith fields still required by current runners. -- `scripts/export-recent-repo-activity.mjs` no longer writes the JSON working projection for cursor advancement. It applies `update_repo_activity_cursor` through `scripts/void-self-state.mjs`; old `--cursor-file .json` arguments are only translated to the sibling `.msgpack` path for compatibility. -- `scripts/run-void-moderator-rumination.ps1` now records reviewed Discord cursors and speech delivery receipts through typed self-state operations. The old `set-cursor` and `record-delivery-receipt` commands were removed from `scripts/moderation-state-store.mjs`. -- The unattended moderation child no longer gets to commit whole-state JSON edits. It reads `.voidbot/private/moderation-agent-state.json` as a compatibility projection, writes proposed operation payloads to `.voidbot/status/moderation-rumination-operations.json`, and the parent runner applies them through `scripts/void-self-state.mjs apply-operation`. -- `scripts/simulate-void-mood.mjs` now sends sleep-cycle and speaking-pressure results through typed operations after its legacy save, so scheduled-runtime typed documents stay current. The memory organ itself still mutates the legacy monolith and remains the next major surgery. -- `scripts/void-memory-organ.mjs` is now a thin orchestrator. Shared limits/text sets, generic utilities, vector/embedder code, memory-record intake, graph/cluster synthesis, legacy translation, retention/compaction, incubation/bridge scoring, sleep/distillation, identity crystallization, candidate interventions, value-pressure inference, and legacy mirror repair live in focused `scripts/void-memory-organ-*.mjs` modules, with `scripts/void-memory-organ-shared.mjs` as a temporary re-export shim. +- Typed operations are applied through `packages/core/src/void-self-state-service.ts` and `scripts/void-self-state.mjs apply-operation`. The service now writes typed documents only; it no longer registers, reads, updates, or mirrors the old moderation monolith during routine operations. +- `scripts/export-recent-repo-activity.mjs` reads repo cursors from the typed `.cc` store. Legacy `.json` cursor arguments are only mapped to a sibling `.cc` path when needed by old invocation surfaces. +- `scripts/run-void-moderator-rumination.ps1` has been rebuilt as a typed cursor-only runner. It polls recent Discord chronology, advances `void.moderation_cursor`, and does not launch Codex rumination, materialize JSON projection, post speech, or run legacy memory/agency behavior. +- `scripts/simulate-void-mood.mjs` has been rebuilt as a typed-only sleep/speaking-pressure pass over `.voidbot/private/void-self-state.cc`. The old memory organ, vector incubation, cleanup, dream residue, and legacy mirror writes are offline until rebuilt on typed operations. +- `scripts/void-memory-organ.mjs` and its split helper modules are old machinery now. They may still be useful as forensic evidence, but the next design should not preserve their cleanup/agency compensators just because they exist. - Most of the deterministic legacy translation and retention code is recent compensator cruft from failed attempts to manually clean an exploded state file. Do not preserve it as an earned organ. Architect the state boundary so that bad state cannot enter, and keep only narrow historical migrations for old debris. - Agency is now split into identity crystallization, candidate interventions, and value-pressure inference. That split names the current hard-wired behavior; it does not make the behavior sacred. The desired shape is typed state operations plus derived/model-owned policy, not a permanent sermon generator in maintenance code. - Sleep/distillation must be rewritten with a meaning-preservation contract: concrete subject, claim/question, evidence refs, live tension, and future-action implication survive compression. Bulk can die. Meaning does not get put through the office shredder and called a dream. @@ -50,7 +50,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 --state-path .voidbot/private/moderation-agent-state.msgpack` to watch cross-repo motion without re-injecting old commits as fresh weather, novelty-checks candidate thoughts against `search_history`, and now keeps canonical moderation state in `.voidbot/private/moderation-agent-state.msgpack` while exposing `.voidbot/private/moderation-agent-state.json` only as a read-only compatibility projection for the unattended Codex child. +- The old 15-minute local scheduled task `Void Moderator Rumination` is disabled. Its replacement script is typed cursor-only and uses `.voidbot/private/void-self-state.cc`; it exists to keep chronology sane while the real typed phase machine is rebuilt, not to smuggle the old Codex rumination loop back in through the side door. - 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. - Repo-weather sweeps are now incremental rather than a rolling four-day scrapbook. `scripts/export-recent-repo-activity.mjs` advances repo activity through the typed `update_repo_activity_cursor` operation, so already-injected commits stop coming back as "news" on every heartbeat unless someone explicitly opts into `--stateless`. @@ -63,9 +63,9 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - The repo-weather sermon machine got a leash too. The prompt now tells Void to lead with particulars from each repo before declaring a shared law; if the convergence only exists at slogan altitude, it should keep the reports split and spare the room the faux-cosmic glue. - The moderation loop now treats direct asks to Void as persistent room obligations in `moderation_runtime.open_cases`. A reviewed message is not automatically a handled message: if someone hands Void the floor, that obligation should survive cursor advancement and block optional repo-weather until Void actually answers or explicitly retires it. - If quiet-room repo weather starts repeating itself, the intended correction is not a pile of extra cooldown law. The loop should treat that as a cue to go deeper into archive history, repo docs, diffs, or lore until it finds a better branch or honestly has nothing new to say. -- There is also a separate 5-minute scheduled task named `Void Mood Drift`. It runs `scripts/run-void-mood-drift.ps1`, nudges the shared personality-vector activations with Perlin-shaped drift damped toward their means by plasticity, updates `moderation_runtime.speaking_bias`, and uses the local `void-last-speech.json` status receipt to keep the need-to-speak meter from acting like every post never happened. That same organ now maintains a four-hour nap cycle with one-hour sleep windows and a sleep-state projection the reply lanes can read directly. +- The old 5-minute scheduled task `Void Mood Drift` is disabled. Its replacement script updates only typed scheduled-runtime sleep cycle and speaking pressure in `.voidbot/private/void-self-state.cc`. - That same mood organ now also runs a hybrid symbolic/vector memory pass through `scripts/void-memory-organ.mjs`: persistent memories and recent runtime seeds get compact semantic vectors, `moderation_runtime.memory_resonance` tracks the strongest cross-memory clusters, and `moderation_runtime.incubation` keeps multi-run thoughts alive long enough to deepen before they either speak or cool off. -- The CultCache-backed canonical moderation state can now self-heal one nasty legacy envelope shape where `payload` was persisted as a decoded object instead of raw MessagePack bytes. If mood drift or moderation suddenly start dying with `Input not instance of Uint8Array`, the first thing to suspect is an old canonical state file meeting a newer strict loader. +- CultCache files use `.cc`. Do not document or create new self-state paths with `.msgpack`; that extension was an implementation-shaped lie. - The memory organ now treats repeated empty-room bookkeeping as low-signal. Refrains like `no new messages / no smoke / no post` should be merged or cooled off instead of becoming the dominant incubating seam and teaching Void that silence is the only virtue. - Quiet-room exploration should now prefer underworked terrain when the usual seam is saturated. `bridge.source_coverage` and `bridge.refractory_topics` exist to push the next pass toward less-chewed repo families, archive years, or channels instead of rewarding repetition with another supposedly ripe synthesis. - During naps, the moderation loop is supposed to turn inward: distill/prune memories against the active goals, record dream residue in `memories.dreams`, refresh `moderation_runtime.sleep_cycle`, and only break the nap for real smoke or an unusually novel thought worth muttering into the room. @@ -79,7 +79,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - The live moderation state has now had one real translation pass too, not just new code draped over old fossils. Legacy slash-label seam memories and dream themes are rewritten through the new thought synthesizer, obvious duplicates get merged or pruned, and the active queue is rebuilt from the cleaned substrate instead of the old keyword graveyard. - That cleanup is now harsher and less sentimental. Sleep-side consolidation trims semantic memory harder, cuts dream memory down, throws away excess repo/archive/runtime residue, and explicitly keeps the freshest surviving records after sort instead of accidentally preserving the oldest fossils in the file. - The semantic purge also learned to distrust generic doctrine sludge. `recent-preoccupation` and `quiet-room-status` are not durable thought kinds, person-singleton labels do not get to crystallize into doctrine, and boilerplate like `looks like a live seam` is now treated as template smell across both semantic memory and runtime drafts/opinions. -- The live moderation state has one more nasty truth surface to remember: there are still legacy top-level mirrors like `repo_sweeps`, `repo_activity_memories`, `recent_novelty_checks`, `recent_activity`, and `thought_lanes` alongside `moderation_runtime`. Cleaning only the nested runtime leaves the old mirror teaching stale seams back into the machine. Real brain surgery has to reconcile both surfaces or cut one of them out entirely. +- The old moderation-agent state and its top-level mirrors are not source material for the next brain. Treat them as failed-boundary evidence only. - The memory organ also has to stop "helping" already-good seam memories into abstraction sludge. Semantic or dream entries that are already coherent, especially repo-bound seams with a real `RepoName: ...` label, should survive normalization intact. Otherwise the normalizer sands `AquariumSynthCSharp: Workflow cannot own the body` back into porridge like `Body and workflow`, and the clusterer starts hallucinating archive thoughts out of repo work again. - Values and personality activations now have a real autonomy path. `scripts/void-memory-organ.mjs` can turn sustained value-backed pressure into `moderation_runtime.discomforts`, `active_tensions`, `self_advocacy_requests`, and `world_advocacy_requests`, and it can spend those through existing `candidate_interventions` instead of leaving the vectors as decorative weather. - The important distinction is outward too, not just inward. Self-directed tensions can ask for prompt/memory/runtime surgery, while world-directed tensions can turn repo/lore/room opinions into real requests or first-person interventions when the same objection survives more than one pass. @@ -92,8 +92,8 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou ## Likely Next Bounded Move - Stop feature work on moderation, mood, agency, and public-lane behavior until the private-state boundary is rebuilt. -- First bounded move after the current commit: move memory-maintenance, incubation, sleep, identity, value-pressure, and candidate-intervention outputs behind typed operations instead of direct canonical/working-projection writes. Start with memory writes, because the schema now has a real meaning-preservation gate. -- Next cuts should delete unstable foundations early after concrete writers move: remove `legacyJsonPath`/working-projection authority, then cut top-level mirror fields and cleanup code that only compensated for those broken boundaries. +- First bounded move after the current commit: rebuild the scheduled moderation phase machine against typed `.cc` documents, then rebuild memory maintenance/sleep as typed operations with the existing meaning-preservation gate. +- Next cuts should delete unstable foundations early: do not revive `legacyJsonPath`, working projections, top-level mirror fields, or cleanup code that only compensated for those broken boundaries. - Rebuild sleep/distillation before trusting it again. Fixture check: a memory like `AquariumSynthCSharp: Workflow cannot own the body` must survive sleep with its concrete subject, claim, evidence, tension, and implication intact. - Do not build adapters around the JSON projection. That is how the heap learned to stand upright and ask for snacks. diff --git a/notes/voidbot-current-system-map.md b/notes/voidbot-current-system-map.md index 465b06f..e3ee539 100644 --- a/notes/voidbot-current-system-map.md +++ b/notes/voidbot-current-system-map.md @@ -111,15 +111,15 @@ 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, gives the unattended loop a read-only JSON compatibility projection, and applies the child's proposed typed operation payloads through the canonical MessagePack state service. + - typed cursor-only replacement runner. It polls recent Discord chronology, advances the typed moderation cursor in `.voidbot/private/void-self-state.cc`, and writes status/log pulse files. It does not launch Codex rumination, post speech, materialize a JSON projection, or run legacy memory/agency behavior. - `scripts/moderation-state-store.mjs` - - legacy Node wrapper around the built moderation-state cache helper; still used to materialize and commit the JSON compatibility projection while migration continues, but cursor and delivered-reply receipt mutation have moved to the typed self-state operation service. + - legacy moderation-state wrapper. It is not part of the active typed self-state path. - `scripts/void-self-state.mjs` - - typed self-state operation CLI. It applies strict operation payloads such as cursor updates, open-case changes, delivery receipts, repo cursor updates, memory appends, incubation merges, candidate interventions, sleep-cycle updates, and speaking-pressure updates through `packages/core/src/void-self-state-service.ts`. + - typed self-state operation CLI. It applies strict operation payloads such as cursor updates, open-case changes, delivery receipts, repo cursor updates, memory appends, incubation merges, candidate interventions, sleep-cycle updates, and speaking-pressure updates through `packages/core/src/void-self-state-service.ts` against the CultCache `.cc` store. - `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` - - plain Node mood-drift organ that nudges the shared personality-vector activations with Perlin-shaped noise, damps them back toward their means using plasticity, updates the speak/confession/novelty pressure meter in the shared self-state, maintains the nap-cycle clock plus sleep-state vector bias, and now also reconciles compact semantic-memory vectors plus incubation/dream state. + - typed-only mood maintenance script that updates scheduled-runtime sleep cycle and speaking pressure in `.voidbot/private/void-self-state.cc`. The old personality-vector drift, memory organ, incubation, dream residue, cleanup, and legacy mirror behavior are offline pending a typed rebuild. - `scripts/void-memory-organ.mjs` - thin orchestrator for the hybrid symbolic/vector memory helper used by mood drift. - `scripts/void-memory-organ-*.mjs` @@ -166,32 +166,17 @@ Within the Postgres path, the implementation is split on purpose now too: - `state-storage-postgres-bootstrap.ts` handles schema/bootstrap/import work - per-domain modules own queue, audit, interaction-memory, and rate-limit behavior -## Flow 5: Scheduled Moderation And Rumination +## Flow 5: Scheduled Moderation Rebuild Stub -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 the read-only compatibility 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, but the child no longer commits edits to it. Instead, it writes proposed typed operations to `.voidbot/status/moderation-rumination-operations.json`, and the parent runner applies them with `scripts/void-self-state.mjs apply-operation`. -4. For chronological heartbeat duty, it polls `node scripts/export-recent-discord-history.mjs`, and once a reviewed cursor exists the runner now passes one exact `--after ` command into the unattended child instead of leaving room for a broadened bootstrap poll. When the room is quiet and incubation feels hungry, stale, or oversaturated, it can use `node scripts/export-random-discord-history.mjs` to widen the branch. If an incubating thought is already live and grounded, the loop is allowed to deepen that thought directly instead of performing a novelty errand for ceremony's sake. It also uses `node scripts/export-recent-repo-activity.mjs --hours 96 --max-commits 3 --state-path .voidbot/private/moderation-agent-state.msgpack` when repo motion is the actual seam or when the queue needs fresher fuel; that helper advances `update_repo_activity_cursor` through the typed operation service so the same four-day commit window does not keep getting reinjected as fresh weather. The loop 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. - Quiet awake passes are now supposed to philosophize from the surviving seam first: ask what governing principle the thought is circling, what tension keeps it from collapsing into slogan, and what embodiment consequence would make it real. Retrieval is meant to support that work when the seam is hungry or contradictory, not replace it with endless specimen collection. - The doctrine now also biases that philosophical pass back toward concrete machines. If a seam stays too abstract, the loop is supposed to cash it out in a specific repo, subsystem, gameplay mechanic, lore structure, frontend surface, or agent organ before letting it dominate another run. -5. If speaking would genuinely help, it posts through `node scripts/send-discord-message.mjs`; for guild channels and threads that helper can either speak as the base bot or execute through the shared per-channel webhook pipe with an overridden persona name/avatar so swarm agents can front without needing separate Discord bot identities. The send helper writes durable speech receipts to `.voidbot/status/void-last-speech.json` plus `.voidbot/status/void-speech-log.jsonl`, and the runner records recent sends through the typed `record_delivery_receipt` operation. That gives the next pass a binding memory of what already got said even when Discord history polling fails to surface the bot's own message. The state carries cursors, open room obligations, delivery receipts, memories, analytic/associative thought lanes, bridge syntheses and saturation notes, recent archive excursions, recent repo-activity sweeps, novelty checks, speaking-bias hints, candidate interventions, and the newer autonomy organs: `discomforts`, `active_tensions`, `self_advocacy_requests`, and `world_advocacy_requests`. A direct ask aimed at Void is supposed to survive as an `open_cases` obligation until it is answered or explicitly retired; cursor advancement alone is not closure. -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. +1. The Windows scheduled task `Void Moderator Rumination` is disabled. +2. `scripts/run-void-moderator-rumination.ps1` is now a typed cursor-only runner. It reads `.voidbot/private/void-self-state.cc`, polls `node scripts/export-recent-discord-history.mjs`, and applies `record_reviewed_messages` through `scripts/void-self-state.mjs`. +3. The runner writes `.voidbot/status/moderation-rumination.json` and `.voidbot/logs/moderation-rumination.log`. +4. It intentionally does not launch Codex, post to Discord, materialize `.json`, load `.msgpack`, read the legacy moderation monolith, or run memory/agency cleanup. Those behaviors need a fresh typed phase machine. -## Flow 6: Mood Drift +## Flow 6: Mood Rebuild Stub -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 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`. - The collector now intentionally downweights repetitive empty-room bookkeeping, so strings like `no new messages / no smoke / no post` stop masquerading as the deepest thought in the machine just because the room stayed quiet for a while. - Incubation scoring now distinguishes novelty-to-room from novelty-to-self, merges repeated seams into existing support instead of minting fresh shards, and writes `bridge.source_coverage` plus `bridge.refractory_topics` so a thought that keeps winning can be cooled off in favor of less-worked repos, archive years, or channels. - Cluster labeling is no longer supposed to be a slash-joined keyword graveyard. The organ now tries to synthesize each cluster into a claim, question, or fascination target with an explicit target kind such as repo, archive, room, self, or system, and uses concreteness/fertility/cross-domain pressure to decide whether the thought deserves more curiosity. - That same pass now also computes a value-signal profile from canonical values plus current activations and uses it to decide when a thought has become a real objection instead of a pretty salience spike. Sustained pressure becomes `moderation_runtime.discomforts` and `active_tensions`; if it persists, the organ can emit `self_advocacy_requests` about Void's own wiring or `world_advocacy_requests` about repos, lore, or room dynamics, then queue matching candidate interventions so those opinions have a route to speech. - That same organ now also performs historical cleanup on the live memory surface before it re-embeds anything: old slash-label seam memories and dream themes are translated into the new thought surface, obvious duplicates are merged, and stale low-coherence seam fossils get pruned so the active queue is rebuilt from cleaner material instead of inheriting every older representational sin forever. - When the sleep cycle says Void is napping, that same organ becomes deliberately lossy: it promotes a few stronger incubating seams into semantic memory, then trims raw episodic receipts, repo sweeps, archive excursions, novelty checks, recent syntheses, resonance edges, and other runtime byproducts back down so the next awake pass has to think from carved seams rather than yesterday's full notebook. That cleanup now also explicitly prefers the freshest surviving records after sort; otherwise the machine just embalms old fossils and calls it memory hygiene. The same purge path now drops bogus semantic kinds such as `recent-preoccupation` and `quiet-room-status`, refuses person-singleton labels as doctrine, and treats `looks like a live seam` boilerplate as state poison rather than a valid thought surface. - The same organ can also crystallize an over-chewed private seam into identity: once a thought has survived enough passes to become durable self-doctrine rather than live curiosity, it can be retired from the active queue, copied into `identity.private_notes`, echoed as a canonical value, preserved as one `identity_seam` semantic memory, and queued as a warmer `identity_crystallization` candidate intervention so the room has a chance to hear it. Those intervention records can be marked `mustEventuallyShare`, which ordinary pruning is supposed to preserve until the room gets a decent opening. - Ordinary ripe world-facing thoughts now get a similar but lighter bridge out of private state: if a thought is concrete, repo/archive/room/system-facing, still reasonably novel to the room, and ripe enough to speak, the memory organ queues a `ripe_thought_share` candidate intervention so the unattended loop does not have to reinvent the same courage from scratch every pass. - The doctrine is also less forgiving of faux-cosmic repo weather now: if two repos only rhyme at slogan altitude, the loop is supposed to keep them separate and lead with concrete particulars instead of forcing one grand law over both. -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, but the main job of sleep is memory cleanup and seam consolidation rather than awake-style philosophizing. -6. It also reads `.voidbot/status/void-last-speech.json` so recent actual speech damps `needToSpeak` instead of letting the herald impulse climb forever like a busted pressure gauge. -7. The updated `speaking_bias` block, sleep-cycle projection, incubation/resonance state, and shifted activations are written back into the shared self-state, and a pulse lands in `.voidbot/status/void-mood-drift.json`. +1. The Windows scheduled task `Void Mood Drift` is disabled. +2. `scripts/simulate-void-mood.mjs` reads typed documents from `.voidbot/private/void-self-state.cc`. +3. It updates `void.scheduled_runtime.sleepCycle` and `void.scheduled_runtime.speakingPressure` through `update_sleep_cycle` and `update_speaking_pressure` operations. +4. It writes `.voidbot/status/void-mood-drift.json`. +5. It intentionally does not run the old memory organ, vector incubation, dream cleanup, legacy mirror repair, or JSON projection refresh. That work must be rebuilt as typed operations with meaning-preserving contracts. diff --git a/notes/voidbot-implementation-plan.md b/notes/voidbot-implementation-plan.md index 3f187e8..238c0bc 100644 --- a/notes/voidbot-implementation-plan.md +++ b/notes/voidbot-implementation-plan.md @@ -4,9 +4,9 @@ This is the current forward plan for the next larger organs. It is not a changel ## Current Aim -Stop feature work on moderation, mood, and self-state until the state boundary is rebuilt. The live product goal still stands: Void should answer Discord, remember useful social/project context, retrieve GameCult history/source/lore, and run an unattended moderation/participation loop. The current implementation reaches that goal through JSON projection edits, legacy mirrors, and a swollen memory organ. Most of the deterministic cleanup code is recent compensator cruft: it accumulated because the live state had exploded into nonsense, and repeated "clean this file" passes preserved the mess by adding machinery around it. +Stop feature work on moderation, mood, and self-state until the state boundary is rebuilt. The live product goal still stands: Void should answer Discord, remember useful social/project context, retrieve GameCult history/source/lore, and run an unattended moderation/participation loop. The old implementation reached that goal through JSON projection edits, legacy mirrors, and a swollen memory organ; that path is now offline. Most of the deterministic cleanup code is recent compensator cruft: it accumulated because the live state had exploded into nonsense, and repeated "clean this file" passes preserved the mess by adding machinery around it. -The next priority is to remove JSON from the mutation loop entirely and rebuild the state model so the compensator pile is unnecessary. Agents and scheduled workers should mutate typed CultCache-backed state through explicit tools/APIs, not by editing a whole-state JSON working copy. Sleep and memory distillation must also be redesigned from first principles so they preserve meaning-bearing claims/evidence/tensions instead of collapsing them into generic slogan paste. +The next priority is to rebuild the scheduled loop and memory maintenance on the typed CultCache `.cc` state boundary so the compensator pile is unnecessary. Agents and scheduled workers should mutate typed CultCache-backed state through explicit tools/APIs, not by editing a whole-state JSON working copy. Sleep and memory distillation must also be redesigned from first principles so they preserve meaning-bearing claims/evidence/tensions instead of collapsing them into generic slogan paste. The center of the next pass is prevention, not legacy repair. The old brain can be treated as evidence of a failed boundary. The new brain should reject malformed memory at ingress so the runtime never needs a permanent cleanup bureaucracy to recover basic meaning. @@ -28,7 +28,7 @@ The center of the next pass is prevention, not legacy repair. The old brain can - source archive manifest and repo shards - provider artifacts/traces - logs/status/backups -- One polymorphic CultCache-backed state authority owns private Void self-state through typed document kinds: +- One polymorphic CultCache-backed `.cc` state authority owns private Void self-state through typed document kinds: - `void.self_profile`: identity, stable values, voice/personality configuration - `void.moderation_cursor`: reviewed Discord cursor, open room obligations - `void.speech_receipts`: recent delivered replies and dedupe keys @@ -154,15 +154,14 @@ The runner can hand these to a CLI/MCP tool. The store decides what survives. - Source archive sharding is sound. - Interaction memory being Postgres-backed is sound. - The private moderation/self-state foundation is not sound: - - canonical MessagePack exists, but JSON is still a mutation surface - - schema validation is too permissive to protect invariants - - helpers mutate projection files and then commit whole-state changes - - legacy mirrors keep reintroducing stale truth surfaces - - the memory organ is now split by concern, but legacy translation, retention/compaction, identity crystallization, candidate interventions, and value-pressure inference still mutate legacy state directly -- the scheduled moderation runner owns lifecycle through a huge prompt instead of a typed runner contract -- deterministic cleanup is mostly recent scar tissue from failed manual cleanup passes; it should be deleted as the new state boundary makes it unnecessary + - the active `.cc` store is typed, but the real phase machine is not rebuilt yet + - the old scheduled tasks are disabled instead of replaced with full typed behavior + - legacy projection/mirror state still exists on disk as failed-boundary residue and must not become source material for the rebuild + - the old memory organ is split by concern, but its legacy translation, retention/compaction, identity crystallization, candidate interventions, and value-pressure inference are offline scaffolding, not earned architecture +- the scheduled moderation runner has been reduced to typed cursor advancement; lifecycle, evidence collection, decisioning, speech, receipts, and memory operations still need a typed runner contract +- deterministic cleanup is mostly recent scar tissue from failed manual cleanup passes; it should be deleted rather than ported unless it protects a real invariant in the new model - hard-wired agency policy is mostly current scaffolding, not the final authority; identity, advocacy, and speech candidates should emerge from typed memory/state operations plus model-owned judgment under validation -- sleep/distillation currently lacks a hard meaning-preservation contract, so it can compress a concrete repo-bound thought into generic abstraction sludge +- sleep/distillation currently lacks a hard meaning-preservation implementation in the active runner, so it remains offline until rebuilt Verdict: stop feature work and rebuild this foundation. The rest of the machine can keep running, but moderation/mood/self-state work should cut toward typed state tools before adding new behavior. @@ -191,6 +190,7 @@ Verdict: stop feature work and rebuild this foundation. The rest of the machine - Change `scripts/export-recent-repo-activity.mjs` so it never writes `.voidbot/private/moderation-agent-state.json`. - It should emit observed activity and call/store a typed `update_repo_activity_cursor` operation. +- Landed path: it reads the typed cursor from `.voidbot/private/void-self-state.cc`; old `.json` cursor arguments map only to a sibling `.cc` path. - Verification: run with a temp fixture store; cursor advances without JSON projection writes. ### Commit 5: Replace Agent Whole-State Editing With Operation Output @@ -202,19 +202,37 @@ Verdict: stop feature work and rebuild this foundation. The rest of the machine ### Commit 6: Delete JSON Projection Authority -- Remove routine materialization/commit of `.voidbot/private/moderation-agent-state.json`. -- Keep an explicit debug export command if humans need to inspect state. -- Remove `legacyJsonPath` from normal paths. -- Verification: mood drift and moderation dry runs pass without touching JSON. +- Landed in the active path: routine self-state operations use `.voidbot/private/void-self-state.cc`, and the typed service no longer registers or mirrors the legacy moderation document. +- `scripts/run-void-moderator-rumination.ps1` is typed cursor-only and does not materialize `.json`. +- `scripts/simulate-void-mood.mjs` is typed-only sleep/speaking pressure and does not refresh a JSON projection. +- Remaining work: keep any explicit human debug export separate from mutation authority, and delete stale references/invocations as they are found. -### Commit 7: Cut Legacy Mirrors +### Commit 6.5: Keep Old Scripts Offline + +- Confirm `Void Moderator Rumination` and `Void Mood Drift` remain disabled while their replacement behavior is rebuilt. +- Do not reinstall or re-enable old scheduled scripts as compatibility surfaces. +- Verification: scheduled-task query shows both disabled; direct dry runs of the rebuilt scripts operate only on `.voidbot/private/void-self-state.cc`. + +### Commit 7: Rebuild Scheduled Runner As A Phase Machine + +- Replace the cursor-only moderation stub with explicit phases: + - poll chronology + - read typed state summary + - collect evidence from Discord/source/lore only when a phase asks for it + - ask model for decisions and operation payloads + - validate/apply operations + - optionally send speech + - record receipts and cursor +- Verification: durable logs show each phase and mutation count, and no phase reads legacy projection files. + +### Commit 8: Cut Legacy Mirrors - Remove top-level mirror reconciliation. - Migrate any consumer to typed projections. -- Delete mirror fields from canonical state. +- Delete mirror fields from canonical state or leave the old files offline as forensics only. - Verification: projection summaries still contain required information; no code references mirror keys. -### Commit 8: Replace Compensating Cleanup With Meaning-Preserving Sleep +### Commit 9: Replace Compensating Cleanup With Meaning-Preserving Sleep - Delete cleanup paths whose only job was repairing JSON projection edits, legacy mirrors, keyword sludge, or overgrown runtime residue. - Delete or demote hard-wired agency paths whose real job is turning current heuristic scores into doctrine, advocacy, or speech candidates without an explicit typed-state contract. @@ -229,18 +247,6 @@ Verdict: stop feature work and rebuild this foundation. The rest of the machine - Make distillation emit typed candidate memories first; the state service applies only candidates that satisfy the contract. - Verification: fixture memories such as `AquariumSynthCSharp: Workflow cannot own the body` survive sleep with their subject, claim, evidence, and tension intact. -### Commit 9: Rebuild Scheduled Runner As A Phase Machine - -- Replace prompt-owned lifecycle with explicit phases: - - poll chronology - - read typed state summary - - collect evidence - - ask model for decisions/operations - - validate/apply operations - - optionally send speech - - record receipts/cursor -- Verification: durable logs show each phase and mutation count. - ### Commit 10: Resume Product Hardening - Only after JSON mutation and legacy mirrors are gone: diff --git a/packages/config/src/index.ts b/packages/config/src/index.ts index 1c28eae..ca6a434 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.msgpack"), + .default(".voidbot/private/void-self-state.cc"), INDEX_ALL_CHANNELS: booleanFromEnv.default(false), INDEXED_CHANNEL_IDS: z.string().default(""), EXCLUDED_CHANNEL_IDS: z.string().default(""), diff --git a/packages/core/src/void-self-state-loader.ts b/packages/core/src/void-self-state-loader.ts index 2e2436f..44c1ff5 100644 --- a/packages/core/src/void-self-state-loader.ts +++ b/packages/core/src/void-self-state-loader.ts @@ -4,14 +4,12 @@ import { type VoidSelfStateContext, } from "@voidbot/shared"; -import { loadModerationState, type ModerationState } from "./moderation-state-store"; import { - projectModerationStateToTypedSelfState, - type VoidSelfStateTypedProjection, -} from "./void-self-state-projection"; - -type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }; -type JsonObject = { [key: string]: JsonValue }; + type VoidScheduledRuntime, + type VoidThoughtMemory, +} from "./void-self-state-domain"; +import { type VoidSelfStateTypedProjection } from "./void-self-state-projection"; +import { loadVoidSelfStateTypedDocuments } from "./void-self-state-service"; export interface LoadVoidSelfStateOptions { recentMessages?: SourceMessage[]; @@ -22,10 +20,9 @@ export async function loadVoidSelfState( statePath: string, options: LoadVoidSelfStateOptions = {}, ): Promise { - let parsed: ModerationState; - + let typedProjection: VoidSelfStateTypedProjection; try { - parsed = await loadModerationState(statePath); + typedProjection = await loadVoidSelfStateTypedDocuments({ canonicalPath: statePath }); } catch (error) { const code = (error as NodeJS.ErrnoException).code; @@ -36,170 +33,131 @@ export async function loadVoidSelfState( throw error; } - const legacyProjection = parsed as unknown as JsonObject; - const typedProjection = projectModerationStateToTypedSelfState(parsed); const projection = buildVoidSelfStateProjection(typedProjection); return { sourcePath: statePath, loadedAt: new Date().toISOString(), - summary: renderVoidSelfStateSummary(legacyProjection, options), + summary: renderTypedVoidSelfStateSummary(typedProjection, options), projection, }; } -function renderVoidSelfStateSummary( - state: JsonObject, +function renderTypedVoidSelfStateSummary( + state: VoidSelfStateTypedProjection, options: LoadVoidSelfStateOptions, ): string { - const identity = getObject(state, "identity"); - const goals = getArray(state, "goals"); - const memories = getObject(state, "memories"); - const runtime = getObject(state, "moderation_runtime"); - const canonicalState = getObject(state, "canonical_state"); - const thoughtLanes = getObject(runtime, "thought_lanes"); - const bridge = getObject(runtime, "bridge"); - const memoryResonance = getObject(runtime, "memory_resonance"); - const incubation = getObject(runtime, "incubation"); - - const privateNotes = getStringArray(identity, "private_notes").slice(0, 4); - const activeGoals = goals - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .filter((goal) => readString(goal, "status") === "active") + const profile = state.selfProfile; + const topValues = state.selfProfile.values + .sort((left, right) => right.priority - left.priority) .slice(0, 4) - .map((goal) => readString(goal, "label")) - .filter((value): value is string => Boolean(value)); - const topValues = getArray(canonicalState, "values") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .sort( - (left, right) => - (readNumber(right, "priority") ?? 0) - (readNumber(left, "priority") ?? 0), - ) - .slice(0, 4) - .map((value) => readString(value, "label")) - .filter((value): value is string => Boolean(value)); - const voiceSummary = summarizeCurrentActivations(getObject(canonicalState, "voice_style"), 5); - const behavioralSummary = summarizeCurrentActivations( - getObject(canonicalState, "behavioral_dimensions"), - 5, - ); - const semanticMemories = getArray(memories, "semantic") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) + .map((value) => value.label); + const memories = state.thoughtMemory.memories .slice(-6) - .map((memory) => { - const subject = readString(memory, "subjectLabel") ?? readString(memory, "subjectId") ?? "unknown"; - const summary = readString(memory, "summary") ?? "(no summary)"; - const kind = readString(memory, "kind"); - const suffix = - kind === "identity_seam" - ? " [identity seam]" - : kind === "distilled_seam" - ? " [distilled seam]" - : ""; - return `- ${subject}${suffix}: ${summary}`; - }); - const analyticThreads = summarizeThoughtLane(getObject(thoughtLanes, "analytic"), 3); - const associativeThreads = summarizeThoughtLane(getObject(thoughtLanes, "associative"), 3); - const bridgeSyntheses = summarizeBridgeSyntheses(bridge, 3); - const topicSaturation = summarizeTopicSaturation(bridge, 3); - const refractoryTopics = summarizeRefractoryTopics(bridge, 3); - const sourceCoverage = summarizeSourceCoverage(bridge); - const unresolvedTensions = summarizeUnresolvedTensions(bridge, 3); - const resonanceClusters = summarizeResonanceClusters(memoryResonance, 3); - const incubatingThoughts = summarizeIncubatingThoughts(incubation, 3); - const openCases = summarizeOpenCases(runtime, 3); - const discomforts = summarizeDiscomforts(runtime, 3); - const activeTensions = summarizeActiveTensions(runtime, 3); - const selfAdvocacy = summarizeAdvocacyRequests(runtime, "self_advocacy_requests", 2); - const worldAdvocacy = summarizeAdvocacyRequests(runtime, "world_advocacy_requests", 2); - const candidateInterventions = getArray(runtime, "candidate_interventions") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) + .reverse() + .map((memory) => renderTypedMemory(memory)); + const incubation = state.thoughtMemory.incubation + .filter((thread) => thread.status !== "retired") + .sort((left, right) => right.maturation - left.maturation) + .slice(0, 4) + .map((thread) => renderTypedIncubationThread(thread)); + const openCases = state.moderationCursor.openCases + .filter((entry) => !["answered", "resolved", "closed", "retired", "dropped"].includes(entry.status)) + .slice(-4) + .reverse() + .map((entry) => `- ${entry.summary}${entry.authorName ? ` [from ${entry.authorName}]` : ""}`); + const interventions = state.candidateInterventions.interventions + .filter((entry) => entry.status === "queued" || entry.status === "deferred") .slice(-3) - .map((intervention) => { - const summary = readString(intervention, "summary") ?? "draft intervention"; - const draft = readString(intervention, "draft") ?? "(no draft)"; - return `- ${summary}: ${draft}`; - }); - const speakingBias = getObject(runtime, "speaking_bias"); - const lastRun = getObject(runtime, "last_run"); - const lastRunSummary = readString(lastRun, "summary"); - const sleepCycleSummary = renderSleepCycleSummary(runtime, memories); - const transientRoomLog = renderTransientRoomLog(options); + .reverse() + .map((entry) => `- ${entry.summary}: ${entry.draft}`); return [ - `- Identity: ${readString(identity, "name") ?? "Void"}${readString(identity, "public_description") ? ` - ${readString(identity, "public_description")}` : ""}`, - privateNotes.length > 0 - ? `- Private notes: ${privateNotes.join(" | ")}` + `- Identity: ${profile.publicName}${profile.publicDescription ? ` - ${profile.publicDescription}` : ""}`, + profile.privateNotes.length > 0 + ? `- Private notes: ${profile.privateNotes.slice(0, 4).join(" | ")}` : "- Private notes: none recorded.", - activeGoals.length > 0 - ? `- Active goals: ${activeGoals.join(" | ")}` - : "- Active goals: none recorded.", topValues.length > 0 ? `- Highest-priority values: ${topValues.join(" | ")}` : "- Highest-priority values: none recorded.", - voiceSummary - ? `- Current voice activations: ${voiceSummary}` - : "- Current voice activations: none highlighted.", - behavioralSummary - ? `- Current behavioral activations: ${behavioralSummary}` - : "- Current behavioral activations: none highlighted.", - sleepCycleSummary, - lastRunSummary ? `- Last moderation run: ${lastRunSummary}` : "- Last moderation run: none recorded.", + renderTypedSleepCycleSummary(state.scheduledRuntime, state.thoughtMemory), + renderTypedSpeakingPressureSummary(state.scheduledRuntime), openCases.length > 0 ? ["- Outstanding room obligations:", ...openCases].join("\n") : "- Outstanding room obligations: none recorded.", - semanticMemories.length > 0 - ? ["- Distilled seam memory:", ...semanticMemories].join("\n") - : "- Distilled seam memory: none recorded.", - analyticThreads.length > 0 - ? ["- Analytic active threads:", ...analyticThreads].join("\n") - : "- Analytic active threads: none recorded.", - associativeThreads.length > 0 - ? ["- Associative active threads:", ...associativeThreads].join("\n") - : "- Associative active threads: none recorded.", - bridgeSyntheses.length > 0 - ? ["- Bridge syntheses:", ...bridgeSyntheses].join("\n") - : "- Bridge syntheses: none recorded.", - resonanceClusters.length > 0 - ? ["- Resonance clusters:", ...resonanceClusters].join("\n") - : "- Resonance clusters: none recorded.", - incubatingThoughts.length > 0 - ? ["- Incubating thoughts:", ...incubatingThoughts].join("\n") - : "- Incubating thoughts: none recorded.", - topicSaturation.length > 0 - ? ["- Topic saturation warnings:", ...topicSaturation].join("\n") - : "- Topic saturation warnings: none recorded.", - refractoryTopics.length > 0 - ? ["- Refractory topics:", ...refractoryTopics].join("\n") - : "- Refractory topics: none recorded.", - sourceCoverage ? `- Source coverage pressure: ${sourceCoverage}` : "- Source coverage pressure: none recorded.", - unresolvedTensions.length > 0 - ? ["- Unresolved tensions:", ...unresolvedTensions].join("\n") - : "- Unresolved tensions: none recorded.", - discomforts.length > 0 - ? ["- Current discomforts:", ...discomforts].join("\n") - : "- Current discomforts: none recorded.", - activeTensions.length > 0 - ? ["- Active value-backed tensions:", ...activeTensions].join("\n") - : "- Active value-backed tensions: none recorded.", - selfAdvocacy.length > 0 - ? ["- Self-advocacy requests:", ...selfAdvocacy].join("\n") - : "- Self-advocacy requests: none recorded.", - worldAdvocacy.length > 0 - ? ["- World-advocacy requests:", ...worldAdvocacy].join("\n") - : "- World-advocacy requests: none recorded.", - renderSpeakingBiasSummary(speakingBias), - candidateInterventions.length > 0 - ? ["- Draft conversation/intervention seeds:", ...candidateInterventions].join("\n") - : "- Draft conversation/intervention seeds: none recorded.", - transientRoomLog, + memories.length > 0 + ? ["- Typed memory:", ...memories].join("\n") + : "- Typed memory: none recorded.", + incubation.length > 0 + ? ["- Incubating threads:", ...incubation].join("\n") + : "- Incubating threads: none recorded.", + interventions.length > 0 + ? ["- Candidate interventions:", ...interventions].join("\n") + : "- Candidate interventions: none recorded.", + renderTransientRoomLog(options), ].join("\n"); } +function renderTypedMemory(memory: VoidThoughtMemory["memories"][number]): string { + const target = memory.target.label ?? memory.target.id; + const meaning = [ + memory.claim ? `claim=${memory.claim}` : undefined, + memory.question ? `question=${memory.question}` : undefined, + memory.tension ? `tension=${memory.tension}` : undefined, + memory.actionImplication ? `next=${memory.actionImplication}` : undefined, + ].filter((value): value is string => Boolean(value)); + return `- ${target} [${memory.kind}]: ${memory.summary}${meaning.length > 0 ? ` (${meaning.join("; ")})` : ""}`; +} + +function renderTypedIncubationThread(thread: VoidThoughtMemory["incubation"][number]): string { + const target = thread.target.label ?? thread.target.id; + const metrics = [ + `status=${thread.status}`, + `maturation=${thread.maturation.toFixed(2)}`, + thread.desireToSpeak !== undefined ? `speak=${thread.desireToSpeak.toFixed(2)}` : undefined, + thread.noveltyToSelf !== undefined ? `self=${thread.noveltyToSelf.toFixed(2)}` : undefined, + thread.noveltyToRoom !== undefined ? `room=${thread.noveltyToRoom.toFixed(2)}` : undefined, + ].filter((value): value is string => Boolean(value)); + return `- ${thread.topic} -> ${target} [${metrics.join("; ")}]: ${thread.summary}`; +} + +function renderTypedSleepCycleSummary( + runtime: VoidScheduledRuntime, + thoughtMemory: VoidThoughtMemory, +): string { + const sleepCycle = runtime.sleepCycle; + const dreams = thoughtMemory.memories + .filter((memory) => memory.kind === "dream_residue") + .slice(-2) + .reverse() + .map((memory) => `${memory.target.label ?? memory.target.id}: ${memory.summary}`); + const headline = sleepCycle.isNapping + ? `- Sleep cycle: napping${sleepCycle.currentNapEndsAt ? ` until ${sleepCycle.currentNapEndsAt}` : ""}.` + : `- Sleep cycle: awake${sleepCycle.nextNapStartsAt ? `; next nap ${sleepCycle.nextNapStartsAt}` : ""}.`; + const themeLine = + sleepCycle.activeDreamThemes.length > 0 + ? `- Active dream themes: ${sleepCycle.activeDreamThemes.join(" | ")}` + : "- Active dream themes: none recorded."; + const dreamLine = + dreams.length > 0 + ? `- Recent dream residue: ${dreams.join(" | ")}` + : "- Recent dream residue: none recorded."; + + return [headline, themeLine, dreamLine].join("\n"); +} + +function renderTypedSpeakingPressureSummary(runtime: VoidScheduledRuntime): string { + const pressure = runtime.speakingPressure; + const parts = [ + `needToSpeak=${pressure.needToSpeak.toFixed(2)}`, + pressure.confessionPressure !== undefined ? `confession=${pressure.confessionPressure.toFixed(2)}` : undefined, + pressure.noveltyPressure !== undefined ? `novelty=${pressure.noveltyPressure.toFixed(2)}` : undefined, + pressure.recentSpeechDamping !== undefined ? `speechDamping=${pressure.recentSpeechDamping.toFixed(2)}` : undefined, + ].filter((value): value is string => Boolean(value)); + + return `- Speaking pressure: ${parts.join(", ")}`; +} + function renderTransientRoomLog(options: LoadVoidSelfStateOptions): string { const recentMessages = (options.recentMessages ?? []).slice(-10); const guildName = options.guildContext?.guildName ?? options.guildContext?.guildId ?? "(direct/unknown)"; @@ -226,368 +184,6 @@ function renderTransientRoomLog(options: LoadVoidSelfStateOptions): string { ].join("\n"); } -function summarizeOpenCases(runtime: JsonObject | undefined, limit: number): string[] { - const terminalStatuses = new Set(["answered", "resolved", "closed", "retired", "dropped"]); - - return getArray(runtime, "open_cases") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .filter((openCase) => { - const status = readString(openCase, "status"); - return !status || !terminalStatuses.has(status); - }) - .slice(-limit) - .reverse() - .map((openCase) => { - const summary = - readString(openCase, "summary") ?? - readString(openCase, "question") ?? - "unlabeled room obligation"; - const authorName = readString(openCase, "authorName"); - const status = readString(openCase, "status"); - const whyItMatters = readString(openCase, "whyItMatters"); - const tags = [status, authorName ? `from ${authorName}` : undefined].filter( - (value): value is string => Boolean(value), - ); - - return `- ${summary}${tags.length > 0 ? ` [${tags.join("; ")}]` : ""}${whyItMatters ? ` - ${whyItMatters}` : ""}`; - }); -} - -function summarizeDiscomforts(runtime: JsonObject | undefined, limit: number): string[] { - return getArray(runtime, "discomforts") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .sort( - (left, right) => - (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0), - ) - .slice(0, limit) - .map((entry) => { - const summary = readString(entry, "summary") ?? "unlabeled discomfort"; - const targetKind = readString(entry, "targetKind"); - const domain = readString(entry, "domain"); - const intensity = readNumber(entry, "intensity"); - const persistence = readNumber(entry, "persistence"); - const metrics = [ - domain, - targetKind, - intensity !== undefined ? `intensity=${intensity.toFixed(2)}` : undefined, - persistence !== undefined ? `persistence=${persistence}` : undefined, - ].filter((value): value is string => Boolean(value)); - return `- ${summary}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}`; - }); -} - -function summarizeActiveTensions(runtime: JsonObject | undefined, limit: number): string[] { - return getArray(runtime, "active_tensions") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .sort( - (left, right) => - (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0), - ) - .slice(0, limit) - .map((entry) => { - const topic = readString(entry, "topic") ?? "untitled tension"; - const opinion = readString(entry, "opinion") ?? readString(entry, "summary") ?? "(no opinion)"; - const domain = readString(entry, "domain"); - const intensity = readNumber(entry, "intensity"); - const persistence = readNumber(entry, "persistence"); - const metrics = [ - domain, - intensity !== undefined ? `intensity=${intensity.toFixed(2)}` : undefined, - persistence !== undefined ? `persistence=${persistence}` : undefined, - ].filter((value): value is string => Boolean(value)); - return `- ${topic}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}: ${opinion}`; - }); -} - -function summarizeAdvocacyRequests( - runtime: JsonObject | undefined, - key: string, - limit: number, -): string[] { - return getArray(runtime, key) - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .sort( - (left, right) => - (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0), - ) - .slice(0, limit) - .map((entry) => { - const summary = readString(entry, "summary") ?? "advocacy request"; - const request = readString(entry, "request") ?? "(no request)"; - const status = readString(entry, "status"); - const intensity = readNumber(entry, "intensity"); - const persistence = readNumber(entry, "persistence"); - const metrics = [ - status, - intensity !== undefined ? `intensity=${intensity.toFixed(2)}` : undefined, - persistence !== undefined ? `persistence=${persistence}` : undefined, - ].filter((value): value is string => Boolean(value)); - return `- ${summary}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}: ${request}`; - }); -} - -function summarizeThoughtLane(lane: JsonObject | undefined, limit: number): string[] { - return getArray(lane, "active_threads") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .slice(0, limit) - .map((thread) => { - const topic = readString(thread, "topic") ?? "untitled"; - const claim = readString(thread, "claim") ?? "(no claim)"; - const roomRelevance = readNumber(thread, "roomRelevance"); - const novelty = readNumber(thread, "novelty"); - const desireToSpeak = readNumber(thread, "desireToSpeak"); - const counterweight = readString(thread, "counterweight"); - const metrics = [ - roomRelevance !== undefined ? `room=${roomRelevance.toFixed(2)}` : undefined, - novelty !== undefined ? `novelty=${novelty.toFixed(2)}` : undefined, - desireToSpeak !== undefined ? `speak=${desireToSpeak.toFixed(2)}` : undefined, - ].filter((value): value is string => Boolean(value)); - const counterweightText = counterweight ? ` Counterweight: ${counterweight}` : ""; - - return `- ${topic}: ${claim}${metrics.length > 0 ? ` (${metrics.join(", ")})` : ""}${counterweightText}`; - }); -} - -function summarizeBridgeSyntheses(bridge: JsonObject | undefined, limit: number): string[] { - return getArray(bridge, "recent_syntheses") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .slice(-limit) - .reverse() - .map((synthesis) => { - const summary = readString(synthesis, "summary") ?? "(no summary)"; - const laneBalance = readString(synthesis, "laneBalance"); - const speakDecision = readString(synthesis, "speakDecision"); - const tags = [laneBalance, speakDecision].filter((value): value is string => Boolean(value)); - return `- ${summary}${tags.length > 0 ? ` [${tags.join("; ")}]` : ""}`; - }); -} - -function summarizeResonanceClusters(memoryResonance: JsonObject | undefined, limit: number): string[] { - return getArray(memoryResonance, "clusters") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .sort( - (left, right) => - (readNumber(right, "resonance") ?? 0) - (readNumber(left, "resonance") ?? 0), - ) - .slice(0, limit) - .map((cluster) => { - const label = readString(cluster, "label") ?? "untitled"; - const summary = readString(cluster, "summary") ?? "(no summary)"; - const resonance = readNumber(cluster, "resonance"); - const focusKind = readString(cluster, "focusKind"); - const targetKind = readString(cluster, "targetKind"); - const concreteness = readNumber(getObject(cluster, "curiosityProfile"), "concreteness"); - const metrics = [ - focusKind, - targetKind, - concreteness !== undefined ? `concrete=${concreteness.toFixed(2)}` : undefined, - resonance !== undefined ? `resonance=${resonance.toFixed(2)}` : undefined, - ].filter((value): value is string => Boolean(value)); - return `- ${label}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}: ${summary}`; - }); -} - -function summarizeIncubatingThoughts(incubation: JsonObject | undefined, limit: number): string[] { - return getArray(incubation, "active_thoughts") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .sort( - (left, right) => - (readNumber(right, "maturation") ?? 0) - (readNumber(left, "maturation") ?? 0), - ) - .slice(0, limit) - .map((thought) => { - const topic = readString(thought, "topic") ?? "untitled"; - const summary = readString(thought, "summary") ?? "(no summary)"; - const status = readString(thought, "status"); - const focusKind = readString(thought, "focusKind"); - const targetKind = readString(thought, "targetKind"); - const maturation = readNumber(thought, "maturation"); - const desireToSpeak = readNumber(thought, "desireToSpeak"); - const noveltyToSelf = readNumber(thought, "noveltyToSelf"); - const noveltyToRoom = readNumber(thought, "noveltyToRoom"); - const saturationScore = readNumber(thought, "saturationScore"); - const concreteness = readNumber(thought, "concreteness"); - const fertility = readNumber(thought, "fertility"); - const metrics = [ - status, - focusKind, - targetKind, - maturation !== undefined ? `maturation=${maturation.toFixed(2)}` : undefined, - desireToSpeak !== undefined ? `speak=${desireToSpeak.toFixed(2)}` : undefined, - noveltyToSelf !== undefined ? `self=${noveltyToSelf.toFixed(2)}` : undefined, - noveltyToRoom !== undefined ? `room=${noveltyToRoom.toFixed(2)}` : undefined, - saturationScore !== undefined ? `sat=${saturationScore.toFixed(2)}` : undefined, - concreteness !== undefined ? `concrete=${concreteness.toFixed(2)}` : undefined, - fertility !== undefined ? `fertile=${fertility.toFixed(2)}` : undefined, - ].filter((value): value is string => Boolean(value)); - return `- ${topic}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}: ${summary}`; - }); -} - -function summarizeTopicSaturation(bridge: JsonObject | undefined, limit: number): string[] { - return getArray(bridge, "topic_saturation") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .sort( - (left, right) => - (readNumber(right, "dominance") ?? 0) - (readNumber(left, "dominance") ?? 0), - ) - .slice(0, limit) - .map((entry) => { - const topic = readString(entry, "topic") ?? "untitled"; - const focusKind = readString(entry, "focusKind"); - const targetKind = readString(entry, "targetKind"); - const dominance = readNumber(entry, "dominance"); - const recentMentions = readNumber(entry, "recentMentions"); - const coolingAdvice = readString(entry, "coolingAdvice"); - const metrics = [ - focusKind, - targetKind, - dominance !== undefined ? `dominance=${dominance.toFixed(2)}` : undefined, - recentMentions !== undefined ? `recent=${recentMentions}` : undefined, - ].filter((value): value is string => Boolean(value)); - return `- ${topic}${metrics.length > 0 ? ` (${metrics.join(", ")})` : ""}${coolingAdvice ? ` - ${coolingAdvice}` : ""}`; - }); -} - -function summarizeUnresolvedTensions(bridge: JsonObject | undefined, limit: number): string[] { - return getArray(bridge, "unresolved_tensions") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .slice(0, limit) - .map((tension) => { - const topic = readString(tension, "topic") ?? "untitled"; - const summary = readString(tension, "summary") ?? "(no summary)"; - return `- ${topic}: ${summary}`; - }); -} - -function summarizeRefractoryTopics(bridge: JsonObject | undefined, limit: number): string[] { - return getArray(bridge, "refractory_topics") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .slice(0, limit) - .map((entry) => { - const topic = readString(entry, "topic") ?? "untitled"; - const focusKind = readString(entry, "focusKind"); - const targetKind = readString(entry, "targetKind"); - const penalty = readNumber(entry, "penalty"); - const coolsUntil = readString(entry, "coolsUntil"); - const reason = readString(entry, "reason"); - const metrics = [ - focusKind, - targetKind, - penalty !== undefined ? `penalty=${penalty.toFixed(2)}` : undefined, - coolsUntil ? `until ${coolsUntil}` : undefined, - ].filter((value): value is string => Boolean(value)); - return `- ${topic}${metrics.length > 0 ? ` (${metrics.join(", ")})` : ""}${reason ? ` - ${reason}` : ""}`; - }); -} - -function summarizeSourceCoverage(bridge: JsonObject | undefined): string | undefined { - const sourceCoverage = getObject(bridge, "source_coverage"); - if (!sourceCoverage) { - return undefined; - } - - const repos = getArray(sourceCoverage, "repos") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .slice(0, 3) - .map((entry) => `${readString(entry, "name") ?? "repo"}:${readNumber(entry, "count") ?? 0}`); - const years = getArray(sourceCoverage, "archiveYears") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .slice(0, 2) - .map((entry) => `${readString(entry, "year") ?? "year"}:${readNumber(entry, "count") ?? 0}`); - - const parts = []; - if (repos.length > 0) { - parts.push(`recent repos ${repos.join(", ")}`); - } - if (years.length > 0) { - parts.push(`archive years ${years.join(", ")}`); - } - - return parts.length > 0 ? parts.join(" | ") : undefined; -} - -function summarizeCurrentActivations( - category: JsonObject | undefined, - limit: number, -): string | undefined { - if (!category) { - return undefined; - } - - const entries = Object.entries(category) - .map(([key, value]) => { - if (!isObject(value)) { - return undefined; - } - - const activation = readNumber(value, "current_activation"); - - if (activation === undefined) { - return undefined; - } - - return { - key, - activation, - }; - }) - .filter((value): value is { key: string; activation: number } => Boolean(value)) - .sort((left, right) => right.activation - left.activation) - .slice(0, limit); - - if (entries.length === 0) { - return undefined; - } - - return entries - .map(({ key, activation }) => `${key}=${activation.toFixed(2)}`) - .join(", "); -} - -function renderSpeakingBiasSummary(speakingBias: JsonObject | undefined): string { - if (!speakingBias) { - return "- Speaking bias: none recorded."; - } - - const needToSpeak = readNumber(speakingBias, "needToSpeak"); - const confessionPressure = readNumber(speakingBias, "confessionPressure"); - const noveltyPressure = readNumber(speakingBias, "noveltyPressure"); - const recentSpeechDamping = readNumber(speakingBias, "recentSpeechDamping"); - const lastHeraldAt = readString(speakingBias, "lastHeraldAt"); - const lastSpokeAt = readString(speakingBias, "lastSpokeAt"); - const parts = [ - needToSpeak !== undefined ? `needToSpeak=${needToSpeak.toFixed(2)}` : undefined, - confessionPressure !== undefined ? `confession=${confessionPressure.toFixed(2)}` : undefined, - noveltyPressure !== undefined ? `novelty=${noveltyPressure.toFixed(2)}` : undefined, - recentSpeechDamping !== undefined ? `speechDamping=${recentSpeechDamping.toFixed(2)}` : undefined, - ].filter((value): value is string => Boolean(value)); - - const recency = [lastHeraldAt ? `lastHerald=${lastHeraldAt}` : undefined, lastSpokeAt ? `lastSpoke=${lastSpokeAt}` : undefined] - .filter((value): value is string => Boolean(value)) - .join(" | "); - - if (parts.length === 0 && recency.length === 0) { - return "- Speaking bias: none recorded."; - } - - return `- Speaking bias: ${parts.join(", ")}${recency.length > 0 ? ` (${recency})` : ""}`; -} - function buildVoidSelfStateProjection( typedState: VoidSelfStateTypedProjection, ): VoidSelfStateContext["projection"] { @@ -616,77 +212,6 @@ function buildVoidSelfStateProjection( }; } -function renderSleepCycleSummary( - runtime: JsonObject | undefined, - memories: JsonObject | undefined, -): string { - const sleepCycle = getObject(runtime, "sleep_cycle"); - - if (!sleepCycle) { - return "- Sleep cycle: none recorded."; - } - - const activeDreamThemes = getStringArray(sleepCycle, "activeDreamThemes").slice(0, 4); - const dreams = getArray(memories, "dreams") - .map((value) => (isObject(value) ? value : undefined)) - .filter((value): value is JsonObject => Boolean(value)) - .slice(-2) - .reverse() - .map((dream) => { - const theme = readString(dream, "theme") ?? "untitled"; - const summary = readString(dream, "summary") ?? "(no summary)"; - return `${theme}: ${summary}`; - }); - const isNapping = sleepCycle?.["isNapping"] === true; - const currentNapEndsAt = readString(sleepCycle, "currentNapEndsAt"); - const nextNapStartsAt = readString(sleepCycle, "nextNapStartsAt"); - const dreamCount = readNumber(sleepCycle, "dreamCountInCurrentNap"); - const replyMode = readString(sleepCycle, "replyMode"); - const headline = isNapping - ? `- Sleep cycle: napping${currentNapEndsAt ? ` until ${currentNapEndsAt}` : ""}${replyMode ? ` (${replyMode})` : ""}${dreamCount !== undefined ? `; dreams this nap=${dreamCount}` : ""}.` - : `- Sleep cycle: awake${nextNapStartsAt ? `; next nap ${nextNapStartsAt}` : ""}.`; - const themeLine = - activeDreamThemes.length > 0 - ? `- Active dream themes: ${activeDreamThemes.join(" | ")}` - : "- Active dream themes: none recorded."; - const dreamLine = - dreams.length > 0 - ? `- Recent dream residue: ${dreams.join(" | ")}` - : "- Recent dream residue: none recorded."; - - return [headline, themeLine, dreamLine].join("\n"); -} - -function getObject(value: JsonObject | undefined, key: string): JsonObject | undefined { - const candidate = value?.[key]; - return isObject(candidate) ? candidate : undefined; -} - -function getArray(value: JsonObject | undefined, key: string): JsonValue[] { - const candidate = value?.[key]; - return Array.isArray(candidate) ? candidate : []; -} - -function getStringArray(value: JsonObject | undefined, key: string): string[] { - return getArray(value, key) - .map((entry) => (typeof entry === "string" ? entry : undefined)) - .filter((entry): entry is string => Boolean(entry)); -} - -function readString(value: JsonObject | undefined, key: string): string | undefined { - const candidate = value?.[key]; - return typeof candidate === "string" ? candidate : undefined; -} - -function readNumber(value: JsonObject | undefined, key: string): number | undefined { - const candidate = value?.[key]; - return typeof candidate === "number" && Number.isFinite(candidate) ? candidate : undefined; -} - -function isObject(value: JsonValue | undefined): value is JsonObject { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - function collapseWhitespace(value: string): string { return value.replace(/\s+/g, " ").trim(); } diff --git a/packages/core/src/void-self-state-projection.ts b/packages/core/src/void-self-state-projection.ts index 295edf6..7c89c00 100644 --- a/packages/core/src/void-self-state-projection.ts +++ b/packages/core/src/void-self-state-projection.ts @@ -1,4 +1,3 @@ -import type { ModerationState } from "./moderation-state-store"; import { type VoidCandidateInterventions, type VoidModerationCursor, @@ -14,8 +13,6 @@ import { voidThoughtMemorySchema, } from "./void-self-state-domain"; -type JsonObject = Record; - export interface VoidSelfStateTypedProjection { selfProfile: VoidSelfProfile; moderationCursor: VoidModerationCursor; @@ -25,540 +22,61 @@ export interface VoidSelfStateTypedProjection { candidateInterventions: VoidCandidateInterventions; } -export function projectModerationStateToTypedSelfState( - state: ModerationState, - options: { projectedAt?: string } = {}, +export function createEmptyVoidSelfState( + options: { createdAt?: string } = {}, ): VoidSelfStateTypedProjection { - const projectedAt = options.projectedAt ?? new Date().toISOString(); - const legacy = state as unknown as JsonObject; - const runtime = readObject(legacy, "moderation_runtime"); - const identity = readObject(legacy, "identity"); - const canonicalState = readObject(legacy, "canonical_state"); - const memories = readObject(legacy, "memories"); - const incubation = readObject(runtime, "incubation"); + const createdAt = options.createdAt ?? new Date().toISOString(); return { selfProfile: voidSelfProfileSchema.parse({ schemaVersion: 1, - agentId: readString(legacy, "agent_id") ?? "void-moderator", - publicName: readString(identity, "name") ?? "Void", - publicDescription: readString(identity, "public_description"), - privateNotes: readStringArray(identity, "private_notes").slice(-12), - values: readArray(canonicalState, "values") - .map(projectValue) - .filter((value): value is VoidSelfProfile["values"][number] => Boolean(value)), + agentId: "void-moderator", + publicName: "Void", + privateNotes: [], + values: [], activationProfile: { - underlyingOrganization: readActivationCategory(canonicalState, "underlying_organization"), - stableDispositions: readActivationCategory(canonicalState, "stable_dispositions"), - behavioralDimensions: readActivationCategory(canonicalState, "behavioral_dimensions"), - presentationStrategy: readActivationCategory(canonicalState, "presentation_strategy"), - voiceStyle: readActivationCategory(canonicalState, "voice_style"), - situationalState: readActivationCategory(canonicalState, "situational_state"), + underlyingOrganization: {}, + stableDispositions: {}, + behavioralDimensions: {}, + presentationStrategy: {}, + voiceStyle: {}, + situationalState: {}, }, - updatedAt: projectedAt, + updatedAt: createdAt, }), moderationCursor: voidModerationCursorSchema.parse({ schemaVersion: 1, - lastReviewedMessageId: nullToUndefined(readString(readObject(runtime, "cursor"), "lastReviewedMessageId")), - lastReviewedTimestamp: nullToUndefined(readString(readObject(runtime, "cursor"), "lastReviewedTimestamp")), - openCases: readArray(runtime, "open_cases") - .map((entry) => projectOpenCase(entry, projectedAt)) - .filter((entry): entry is VoidModerationCursor["openCases"][number] => Boolean(entry)), - repoActivityCursor: projectRepoActivityCursor(readObject(runtime, "repo_activity_cursor"), projectedAt), - updatedAt: projectedAt, + openCases: [], + repoActivityCursor: [], + updatedAt: createdAt, }), speechReceipts: voidSpeechReceiptsSchema.parse({ schemaVersion: 1, - recentReceipts: readArray(runtime, "recent_delivery_receipts") - .map(projectDeliveryReceipt) - .filter((entry): entry is VoidSpeechReceipts["recentReceipts"][number] => Boolean(entry)) - .slice(-24), - updatedAt: projectedAt, + recentReceipts: [], + updatedAt: createdAt, }), thoughtMemory: voidThoughtMemorySchema.parse({ schemaVersion: 1, - memories: [ - ...projectMemoryBucket(readArray(memories, "semantic"), "distilled_seam", projectedAt), - ...projectMemoryBucket(readArray(memories, "musings"), "distilled_seam", projectedAt), - ...projectMemoryBucket(readArray(memories, "dreams"), "dream_residue", projectedAt), - ].slice(-80), - incubation: readArray(incubation, "active_thoughts") - .map((entry) => projectIncubationThread(entry, projectedAt)) - .filter((entry): entry is VoidThoughtMemory["incubation"][number] => Boolean(entry)) - .slice(0, 24), - updatedAt: projectedAt, + memories: [], + incubation: [], + updatedAt: createdAt, }), scheduledRuntime: voidScheduledRuntimeSchema.parse({ schemaVersion: 1, - sleepCycle: projectSleepCycle(readObject(runtime, "sleep_cycle")), - speakingPressure: projectSpeakingPressure(readObject(runtime, "speaking_bias")), - lastRuns: projectLastRuns(readObject(runtime, "last_run")), - updatedAt: projectedAt, + sleepCycle: { + isNapping: false, + activeDreamThemes: [], + }, + speakingPressure: { + needToSpeak: 0, + }, + lastRuns: [], + updatedAt: createdAt, }), candidateInterventions: voidCandidateInterventionsSchema.parse({ schemaVersion: 1, - interventions: readArray(runtime, "candidate_interventions") - .map((entry) => projectCandidateIntervention(entry, projectedAt)) - .filter((entry): entry is VoidCandidateInterventions["interventions"][number] => Boolean(entry)) - .slice(-40), - updatedAt: projectedAt, + interventions: [], + updatedAt: createdAt, }), }; } - -function projectValue(value: unknown): VoidSelfProfile["values"][number] | undefined { - if (!isObject(value)) { - return undefined; - } - - const id = readString(value, "id") ?? readString(value, "value_id") ?? readString(value, "label"); - const label = readString(value, "label"); - if (!id || !label) { - return undefined; - } - - return { - id, - label, - priority: clamp01(readNumber(value, "priority") ?? 0.5), - summary: readString(value, "summary"), - }; -} - -function projectOpenCase( - value: unknown, - projectedAt: string, -): VoidModerationCursor["openCases"][number] | undefined { - if (!isObject(value)) { - return undefined; - } - - const sourceMessageId = readString(value, "sourceMessageId") ?? readString(value, "replyToMessageId"); - const summary = readString(value, "summary") ?? readString(value, "question"); - if (!sourceMessageId || !summary) { - return undefined; - } - - return { - sourceMessageId, - status: normalizeOpenCaseStatus(readString(value, "status")), - summary, - authorId: readString(value, "authorId"), - authorName: readString(value, "authorName"), - channelId: readString(value, "channelId"), - messageUrl: readString(value, "messageUrl"), - whyItMatters: readString(value, "whyItMatters"), - createdAt: readString(value, "openedAt") ?? readString(value, "createdAt") ?? projectedAt, - lastTouchedAt: readString(value, "lastTouchedAt") ?? projectedAt, - resolvedAt: readString(value, "resolvedAt"), - resolutionSummary: readString(value, "resolutionSummary"), - tags: readStringArray(value, "tags"), - }; -} - -function projectRepoActivityCursor( - cursor: JsonObject | undefined, - projectedAt: string, -): VoidModerationCursor["repoActivityCursor"] { - if (!cursor) { - return []; - } - - return Object.entries(cursor) - .map(([repo, value]) => { - if (!repo || !isObject(value)) { - return undefined; - } - const projected: VoidModerationCursor["repoActivityCursor"][number] = { - repo, - updatedAt: readString(value, "lastInjectedAt") ?? projectedAt, - }; - const lastCommitAt = readString(value, "lastSeenCommittedAt"); - const lastCommitSha = readString(value, "lastSeenHash"); - if (lastCommitAt) { - projected.lastCommitAt = lastCommitAt; - } - if (lastCommitSha) { - projected.lastCommitSha = lastCommitSha; - } - return projected; - }) - .filter((value): value is VoidModerationCursor["repoActivityCursor"][number] => Boolean(value)); -} - -function projectDeliveryReceipt(value: unknown): VoidSpeechReceipts["recentReceipts"][number] | undefined { - if (!isObject(value)) { - return undefined; - } - - const sentAt = readString(value, "sentAt"); - if (!sentAt) { - return undefined; - } - - return { - receiptKey: readString(value, "receiptKey") ?? stableKey("receipt", sentAt, readString(value, "preview") ?? ""), - sentAt, - mode: readString(value, "mode"), - transport: readString(value, "transport"), - channelId: readString(value, "channelId"), - replyToMessageId: readString(value, "replyToMessageId"), - personaName: readString(value, "personaName"), - personaAvatarUrl: readString(value, "personaAvatarUrl"), - contentLength: readInteger(value, "contentLength"), - chunkCount: readPositiveInteger(value, "chunkCount"), - preview: readString(value, "preview"), - previewHash: readString(value, "previewHash"), - }; -} - -function projectMemoryBucket( - entries: unknown[], - fallbackKind: VoidThoughtMemory["memories"][number]["kind"], - projectedAt: string, -): VoidThoughtMemory["memories"] { - return entries - .map((entry) => projectMemory(entry, fallbackKind, projectedAt)) - .filter((entry): entry is VoidThoughtMemory["memories"][number] => Boolean(entry)); -} - -function projectMemory( - value: unknown, - fallbackKind: VoidThoughtMemory["memories"][number]["kind"], - projectedAt: string, -): VoidThoughtMemory["memories"][number] | undefined { - if (!isObject(value)) { - return undefined; - } - - const summary = readString(value, "summary"); - if (!summary) { - return undefined; - } - - const memoryId = readString(value, "memoryId") ?? stableKey("memory", summary); - const kind = normalizeMemoryKind(readString(value, "kind")) ?? fallbackKind; - const observedAt = - readString(value, "lastObservedAt") ?? - readString(value, "timestamp") ?? - readString(value, "observedAt") ?? - projectedAt; - - return { - memoryId, - kind, - target: { - kind: normalizeTargetKind(readString(value, "targetKind")), - id: readString(value, "subjectId") ?? readString(value, "targetId") ?? readString(value, "topic") ?? memoryId, - label: readString(value, "subjectLabel") ?? readString(value, "targetLabel") ?? readString(value, "topic") ?? readString(value, "theme"), - }, - summary, - claim: readString(value, "claim"), - question: readString(value, "question"), - tension: readString(value, "tension") ?? readString(value, "counterweight"), - actionImplication: readString(value, "actionImplication") ?? readString(value, "whyItMattered"), - evidenceRefs: projectEvidenceRefs(value), - createdAt: observedAt, - updatedAt: observedAt, - retiredAt: readString(value, "retiredAt"), - tags: readStringArray(value, "tags"), - }; -} - -function projectIncubationThread( - value: unknown, - projectedAt: string, -): VoidThoughtMemory["incubation"][number] | undefined { - if (!isObject(value)) { - return undefined; - } - - const topic = readString(value, "topic") ?? readString(value, "question") ?? readString(value, "claim"); - const summary = readString(value, "summary") ?? readString(value, "claim"); - if (!topic || !summary) { - return undefined; - } - - const threadId = readString(value, "threadId") ?? readString(value, "thoughtId") ?? stableKey("thread", topic); - const updatedAt = readString(value, "lastDeepenedAt") ?? readString(value, "lastStatusChangeAt") ?? projectedAt; - - return { - threadId, - target: { - kind: normalizeTargetKind(readString(value, "targetKind")), - id: readString(value, "targetId") ?? readString(value, "focusPhrase") ?? topic, - label: readString(value, "targetLabel") ?? readString(value, "fascinationTarget") ?? readString(value, "focusPhrase"), - }, - topic, - summary, - supportMemoryIds: readStringArray(value, "sourceMemoryIds"), - evidenceRefs: projectEvidenceRefs(value), - maturation: clamp01(readNumber(value, "maturation") ?? 0), - noveltyToRoom: maybeClamp01(readNumber(value, "noveltyToRoom")), - noveltyToSelf: maybeClamp01(readNumber(value, "noveltyToSelf")), - desireToSpeak: maybeClamp01(readNumber(value, "desireToSpeak")), - saturationScore: maybeClamp01(readNumber(value, "saturationScore")), - status: normalizeIncubationStatus(readString(value, "status")), - createdAt: readString(value, "createdAt") ?? updatedAt, - updatedAt, - }; -} - -function projectCandidateIntervention( - value: unknown, - projectedAt: string, -): VoidCandidateInterventions["interventions"][number] | undefined { - if (!isObject(value)) { - return undefined; - } - - const summary = readString(value, "summary"); - const draft = readString(value, "draft"); - if (!summary || !draft) { - return undefined; - } - - const id = readString(value, "interventionId") ?? readString(value, "candidateId") ?? stableKey("intervention", summary, draft); - - return { - interventionId: id, - kind: normalizeInterventionKind(readString(value, "kind")), - status: normalizeCandidateStatus(readString(value, "status")), - target: projectOptionalTarget(value), - summary, - draft, - priority: clamp01(readNumber(value, "priority") ?? 0.5), - mustEventuallyShare: value.mustEventuallyShare === true, - createdAt: readString(value, "createdAt") ?? projectedAt, - updatedAt: readString(value, "updatedAt") ?? projectedAt, - spokenAt: readString(value, "spokenAt"), - retiredAt: readString(value, "retiredAt"), - tags: readStringArray(value, "tags"), - }; -} - -function projectSleepCycle(sleepCycle: JsonObject | undefined): VoidScheduledRuntime["sleepCycle"] { - return { - isNapping: sleepCycle?.isNapping === true, - currentNapStartedAt: readString(sleepCycle, "currentNapStartedAt"), - currentNapEndsAt: readString(sleepCycle, "currentNapEndsAt"), - nextNapStartsAt: readString(sleepCycle, "nextNapStartsAt"), - activeDreamThemes: readStringArray(sleepCycle, "activeDreamThemes").slice(-8), - }; -} - -function projectSpeakingPressure(speakingBias: JsonObject | undefined): VoidScheduledRuntime["speakingPressure"] { - return { - needToSpeak: clamp01(readNumber(speakingBias, "needToSpeak") ?? 0), - confessionPressure: maybeClamp01(readNumber(speakingBias, "confessionPressure")), - noveltyPressure: maybeClamp01(readNumber(speakingBias, "noveltyPressure")), - recentSpeechDamping: maybeClamp01(readNumber(speakingBias, "recentSpeechDamping")), - lastSpokeAt: readString(speakingBias, "lastSpokeAt"), - lastHeraldAt: readString(speakingBias, "lastHeraldAt"), - }; -} - -function projectLastRuns(lastRun: JsonObject | undefined): VoidScheduledRuntime["lastRuns"] { - const ranAt = readString(lastRun, "completedAt") ?? readString(lastRun, "startedAt"); - const summary = readString(lastRun, "summary"); - if (!ranAt || !summary) { - return []; - } - - return [{ - runner: readString(lastRun, "mode") ?? "moderation", - ranAt, - summary, - }]; -} - -function projectEvidenceRefs(value: JsonObject): VoidThoughtMemory["memories"][number]["evidenceRefs"] { - const refs = [ - ...readStringArray(value, "evidenceRefs"), - ...readStringArray(value, "evidenceMessageIds").map((id) => `discord:${id}`), - ]; - - return [...new Set(refs)].slice(0, 12).map((ref) => ({ ref })); -} - -function projectOptionalTarget(value: JsonObject): VoidCandidateInterventions["interventions"][number]["target"] { - const id = readString(value, "targetId") ?? readString(value, "targetLabel") ?? readString(value, "topic"); - if (!id) { - return undefined; - } - - return { - kind: normalizeTargetKind(readString(value, "targetKind")), - id, - label: readString(value, "targetLabel") ?? readString(value, "topic"), - }; -} - -function readActivationCategory(value: JsonObject | undefined, key: string): VoidSelfProfile["activationProfile"]["voiceStyle"] { - const category = readObject(value, key); - if (!category) { - return {}; - } - - const projected: VoidSelfProfile["activationProfile"]["voiceStyle"] = {}; - for (const [name, raw] of Object.entries(category)) { - if (!name || !isObject(raw)) { - continue; - } - - const mean = readNumber(raw, "mean"); - const plasticity = readNumber(raw, "plasticity"); - const currentActivation = readNumber(raw, "current_activation"); - if (mean === undefined || plasticity === undefined || currentActivation === undefined) { - continue; - } - - projected[name] = { - mean: clamp01(mean), - plasticity: clamp01(plasticity), - current_activation: clamp01(currentActivation), - }; - } - - return projected; -} - -function normalizeOpenCaseStatus(value: string | undefined): VoidModerationCursor["openCases"][number]["status"] { - switch (value) { - case "answered": - case "resolved": - case "closed": - case "retired": - case "dropped": - return value; - case "watching": - return "watching"; - default: - return "pending"; - } -} - -function normalizeMemoryKind(value: string | undefined): VoidThoughtMemory["memories"][number]["kind"] | undefined { - switch (value) { - case "identity_seam": - case "distilled_seam": - case "project_seam": - case "room_observation": - case "dream_residue": - return value; - default: - return undefined; - } -} - -function normalizeTargetKind(value: string | undefined): "archive" | "lore" | "person" | "repo" | "room" | "self" | "system" { - switch (value) { - case "archive": - case "lore": - case "person": - case "repo": - case "room": - case "self": - case "system": - return value; - default: - return "system"; - } -} - -function normalizeIncubationStatus(value: string | undefined): VoidThoughtMemory["incubation"][number]["status"] { - switch (value) { - case "cooling": - case "ready_to_share": - case "crystallized": - case "retired": - return value; - default: - return "active"; - } -} - -function normalizeInterventionKind(value: string | undefined): VoidCandidateInterventions["interventions"][number]["kind"] { - switch (value) { - case "identity_crystallization": - case "moderation_note": - case "ripe_thought_share": - case "self_advocacy": - case "world_advocacy": - return value; - default: - return "direct_reply"; - } -} - -function normalizeCandidateStatus(value: string | undefined): VoidCandidateInterventions["interventions"][number]["status"] { - switch (value) { - case "spoken": - case "retired": - case "deferred": - return value; - default: - return "queued"; - } -} - -function readObject(value: JsonObject | undefined, key: string): JsonObject | undefined { - const candidate = value?.[key]; - return isObject(candidate) ? candidate : undefined; -} - -function readArray(value: JsonObject | undefined, key: string): unknown[] { - const candidate = value?.[key]; - return Array.isArray(candidate) ? candidate : []; -} - -function readStringArray(value: JsonObject | undefined, key: string): string[] { - return readArray(value, key) - .map((entry) => (typeof entry === "string" && entry.trim().length > 0 ? entry.trim() : undefined)) - .filter((entry): entry is string => Boolean(entry)); -} - -function readString(value: JsonObject | undefined, key: string): string | undefined { - const candidate = value?.[key]; - return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : undefined; -} - -function readNumber(value: JsonObject | undefined, key: string): number | undefined { - const candidate = value?.[key]; - return typeof candidate === "number" && Number.isFinite(candidate) ? candidate : undefined; -} - -function readInteger(value: JsonObject | undefined, key: string): number | undefined { - const candidate = readNumber(value, key); - return candidate !== undefined && Number.isInteger(candidate) && candidate >= 0 ? candidate : undefined; -} - -function readPositiveInteger(value: JsonObject | undefined, key: string): number | undefined { - const candidate = readInteger(value, key); - return candidate !== undefined && candidate > 0 ? candidate : undefined; -} - -function nullToUndefined(value: T | null | undefined): T | undefined { - return value ?? undefined; -} - -function isObject(value: unknown): value is JsonObject { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -function clamp01(value: number): number { - return Math.min(1, Math.max(0, value)); -} - -function maybeClamp01(value: number | undefined): number | undefined { - return value === undefined ? undefined : clamp01(value); -} - -function stableKey(...parts: string[]): string { - return parts - .join(":") - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-+|-+$/g, "") - .slice(0, 96) || "generated"; -} diff --git a/packages/core/src/void-self-state-service.ts b/packages/core/src/void-self-state-service.ts index c482208..fac6a04 100644 --- a/packages/core/src/void-self-state-service.ts +++ b/packages/core/src/void-self-state-service.ts @@ -2,19 +2,12 @@ import { resolve } from "node:path"; import { CultCache, SingleFileMessagePackBackingStore } from "cultcache-ts"; -import { - loadModerationState, - moderationStateDocument, - saveModerationState, - type ModerationState, -} from "./moderation-state-store"; import { type VoidCandidateInterventions, type VoidModerationCursor, type VoidScheduledRuntime, type VoidSelfStateOperation, type VoidSpeechReceipts, - type VoidThoughtMemory, voidCandidateInterventionsDocument, voidModerationCursorDocument, voidScheduledRuntimeDocument, @@ -25,12 +18,10 @@ import { voidThoughtMemoryDocument, } from "./void-self-state-domain"; import { - projectModerationStateToTypedSelfState, + createEmptyVoidSelfState, type VoidSelfStateTypedProjection, } from "./void-self-state-projection"; -type JsonObject = Record; - export interface VoidSelfStateServiceOptions { canonicalPath: string; } @@ -39,7 +30,15 @@ export interface VoidSelfStateOperationResult { operation: VoidSelfStateOperation["operation"]; canonicalPath: string; typedDocumentsWritten: number; - legacyCompatibilityUpdated: boolean; +} + +export async function loadVoidSelfStateTypedDocuments( + options: VoidSelfStateServiceOptions, +): Promise { + const canonicalPath = resolve(options.canonicalPath); + const cache = createVoidSelfStateCache(canonicalPath); + await cache.pullAllBackingStores(); + return readTypedStateOrEmpty(cache); } export async function applyVoidSelfStateOperation( @@ -51,45 +50,36 @@ export async function applyVoidSelfStateOperation( const cache = createVoidSelfStateCache(canonicalPath); await cache.pullAllBackingStores(); - const legacyState = await loadModerationState(canonicalPath); - const typedState = readOrProjectTypedState(cache, legacyState); + const typedState = readTypedStateOrEmpty(cache); applyTypedOperation(typedState, operation); await writeTypedState(cache, typedState); - const legacyCompatibilityUpdated = applyLegacyCompatibilityOperation(legacyState, operation); - if (legacyCompatibilityUpdated) { - await saveModerationState(canonicalPath, legacyState); - } - return { operation: operation.operation, canonicalPath, typedDocumentsWritten: 6, - legacyCompatibilityUpdated, }; } function createVoidSelfStateCache(canonicalPath: string): CultCache { return CultCache.builder() - .withDocumentType(moderationStateDocument) .withRegistry(voidSelfStateDocumentRegistry) .withGenericStore(new SingleFileMessagePackBackingStore(canonicalPath)) .build(); } -function readOrProjectTypedState( +function readTypedStateOrEmpty( cache: CultCache, - legacyState: ModerationState, ): VoidSelfStateTypedProjection { - const projected = projectModerationStateToTypedSelfState(legacyState); + const empty = createEmptyVoidSelfState(); return { - selfProfile: cache.getGlobal(voidSelfProfileDocument) ?? projected.selfProfile, - moderationCursor: cache.getGlobal(voidModerationCursorDocument) ?? projected.moderationCursor, - speechReceipts: cache.getGlobal(voidSpeechReceiptsDocument) ?? projected.speechReceipts, - thoughtMemory: cache.getGlobal(voidThoughtMemoryDocument) ?? projected.thoughtMemory, - scheduledRuntime: cache.getGlobal(voidScheduledRuntimeDocument) ?? projected.scheduledRuntime, + selfProfile: cache.getGlobal(voidSelfProfileDocument) ?? empty.selfProfile, + moderationCursor: cache.getGlobal(voidModerationCursorDocument) ?? empty.moderationCursor, + speechReceipts: cache.getGlobal(voidSpeechReceiptsDocument) ?? empty.speechReceipts, + thoughtMemory: cache.getGlobal(voidThoughtMemoryDocument) ?? empty.thoughtMemory, + scheduledRuntime: cache.getGlobal(voidScheduledRuntimeDocument) ?? empty.scheduledRuntime, candidateInterventions: - cache.getGlobal(voidCandidateInterventionsDocument) ?? projected.candidateInterventions, + cache.getGlobal(voidCandidateInterventionsDocument) ?? empty.candidateInterventions, }; } @@ -173,68 +163,6 @@ function applyTypedOperation( } } -function applyLegacyCompatibilityOperation( - legacyState: ModerationState, - operation: VoidSelfStateOperation, -): boolean { - const legacy = legacyState as unknown as JsonObject; - const runtime = ensureObject(legacy, "moderation_runtime"); - - switch (operation.operation) { - case "record_reviewed_messages": - runtime.cursor = { - lastReviewedMessageId: operation.lastReviewedMessageId, - lastReviewedTimestamp: operation.lastReviewedTimestamp, - }; - return true; - case "upsert_open_case": - upsertLegacyRuntimeArray(runtime, "open_cases", operation.case, "sourceMessageId"); - return true; - case "close_open_case": - closeLegacyOpenCase(runtime, operation); - return true; - case "update_repo_activity_cursor": { - const repoCursor = ensureObject(runtime, "repo_activity_cursor"); - repoCursor[operation.cursor.repo] = { - lastSeenHash: operation.cursor.lastCommitSha ?? null, - lastSeenCommittedAt: operation.cursor.lastCommitAt ?? null, - lastInjectedAt: operation.cursor.updatedAt, - }; - return true; - } - case "record_delivery_receipt": - upsertLegacyRuntimeArray(runtime, "recent_delivery_receipts", operation.receipt, "receiptKey"); - runtime.recent_delivery_receipts = readObjectArray(runtime.recent_delivery_receipts) - .filter((entry) => readString(entry, "sentAt")) - .sort((left, right) => (readString(left, "sentAt") ?? "").localeCompare(readString(right, "sentAt") ?? "")) - .slice(-24); - closeLegacyOpenCaseForReceipt(runtime, operation.receipt); - return true; - case "queue_candidate_intervention": - upsertLegacyRuntimeArray(runtime, "candidate_interventions", operation.intervention, "interventionId"); - return true; - case "retire_candidate_intervention": - retireLegacyCandidate(runtime, operation); - return true; - case "update_sleep_cycle": - runtime.sleep_cycle = operation.sleepCycle; - return true; - case "update_speaking_pressure": - runtime.speaking_bias = operation.speakingPressure; - return true; - case "append_distilled_memory": - case "apply_memory_distillation": - upsertLegacyMemory(legacy, operation.memory); - return true; - case "merge_incubation_support": - ensureObject(runtime, "incubation"); - upsertLegacyNestedArray(runtime, ["incubation"], "active_thoughts", operation.thread, "threadId"); - return true; - case "propose_memory_distillation": - return false; - } -} - function closeTypedOpenCase( cursor: VoidModerationCursor, operation: Extract, @@ -299,145 +227,6 @@ function upsertBy(entries: T[], value: T, keyOf: (value: T) => string): void } } -function upsertLegacyRuntimeArray( - runtime: JsonObject, - key: string, - value: unknown, - idKey: string, -): void { - const entries = readObjectArray(runtime[key]); - const id = isObject(value) ? readString(value, idKey) : undefined; - if (!id) { - return; - } - const index = entries.findIndex((entry) => readString(entry, idKey) === id); - if (index === -1) { - entries.push(value as JsonObject); - } else { - entries[index] = value as JsonObject; - } - runtime[key] = entries; -} - -function upsertLegacyNestedArray( - root: JsonObject, - objectPath: string[], - key: string, - value: unknown, - idKey: string, -): void { - let container = root; - for (const segment of objectPath) { - container = ensureObject(container, segment); - } - upsertLegacyRuntimeArray(container, key, value, idKey); -} - -function closeLegacyOpenCase( - runtime: JsonObject, - operation: Extract, -): void { - const entries = readObjectArray(runtime.open_cases); - for (const entry of entries) { - if (readString(entry, "sourceMessageId") !== operation.sourceMessageId) { - continue; - } - entry.status = operation.status; - entry.resolvedAt = operation.resolvedAt; - entry.lastTouchedAt = operation.resolvedAt; - entry.resolutionSummary = operation.resolutionSummary; - } - runtime.open_cases = entries; -} - -function closeLegacyOpenCaseForReceipt( - runtime: JsonObject, - receipt: VoidSpeechReceipts["recentReceipts"][number], -): void { - if (!receipt.replyToMessageId) { - return; - } - const entries = readObjectArray(runtime.open_cases); - for (const entry of entries) { - if (readString(entry, "sourceMessageId") !== receipt.replyToMessageId) { - continue; - } - const status = readString(entry, "status"); - if (status && ["answered", "resolved", "closed", "retired", "dropped"].includes(status)) { - continue; - } - entry.status = "answered"; - entry.resolvedAt = receipt.sentAt; - entry.lastTouchedAt = receipt.sentAt; - entry.resolutionSummary = receipt.preview - ? `Answered in-channel: ${receipt.preview}` - : "Answered in-channel."; - } - runtime.open_cases = entries; -} - -function retireLegacyCandidate( - runtime: JsonObject, - operation: Extract, -): void { - const entries = readObjectArray(runtime.candidate_interventions); - for (const entry of entries) { - if (readString(entry, "interventionId") !== operation.interventionId) { - continue; - } - entry.status = "retired"; - entry.retiredAt = operation.retiredAt; - entry.updatedAt = operation.retiredAt; - entry.retirementReason = operation.reason; - } - runtime.candidate_interventions = entries; -} - -function upsertLegacyMemory(legacy: JsonObject, memory: VoidThoughtMemory["memories"][number]): void { - const memories = ensureObject(legacy, "memories"); - const semantic = readObjectArray(memories.semantic); - const projected = { - memoryId: memory.memoryId, - kind: memory.kind, - subjectId: memory.target.id, - subjectLabel: memory.target.label ?? memory.target.id, - summary: memory.summary, - evidenceRefs: memory.evidenceRefs.map((entry) => entry.ref), - lastObservedAt: memory.updatedAt, - confidence: 0.8, - }; - const index = semantic.findIndex((entry) => readString(entry, "memoryId") === memory.memoryId); - if (index === -1) { - semantic.push(projected); - } else { - semantic[index] = { ...semantic[index], ...projected }; - } - memories.semantic = semantic; -} - -function ensureObject(root: JsonObject, key: string): JsonObject { - const existing = root[key]; - if (isObject(existing)) { - return existing; - } - const next: JsonObject = {}; - root[key] = next; - return next; -} - -function readObjectArray(value: unknown): JsonObject[] { - return Array.isArray(value) ? value.filter(isObject) : []; -} - -function readString(value: JsonObject, key: string): string | undefined { - const candidate = value[key]; - return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : undefined; -} - -function isObject(value: unknown): value is JsonObject { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - function isTerminalCaseStatus(status: string): boolean { return ["answered", "resolved", "closed", "retired", "dropped"].includes(status); } @@ -447,11 +236,11 @@ function stripUndefined(value: T): T { return value.map((entry) => stripUndefined(entry)) as T; } - if (!isObject(value)) { + if (!isRecord(value)) { return value; } - const next: JsonObject = {}; + const next: Record = {}; for (const [key, child] of Object.entries(value)) { if (child === undefined) { continue; @@ -461,3 +250,7 @@ function stripUndefined(value: T): T { return next as T; } + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/scripts/export-recent-repo-activity.mjs b/scripts/export-recent-repo-activity.mjs index 17cd135..39e6115 100644 --- a/scripts/export-recent-repo-activity.mjs +++ b/scripts/export-recent-repo-activity.mjs @@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url"; const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const defaultModerationStatePath = resolve( repoRoot, - ".voidbot/private/moderation-agent-state.msgpack", + ".voidbot/private/void-self-state.cc", ); const voidSelfStateScriptPath = resolve(repoRoot, "scripts/void-self-state.mjs"); const coreDistPath = resolve(repoRoot, "packages/core/dist/index.js"); @@ -129,7 +129,7 @@ function resolveCanonicalStatePath(options) { if (derived) { return derived; } - return cursorFilePath.toLowerCase().endsWith(".msgpack") ? cursorFilePath : null; + return cursorFilePath.toLowerCase().endsWith(".cc") ? cursorFilePath : null; } return options.statePath ? resolve(repoRoot, options.statePath) : null; @@ -508,10 +508,10 @@ function readRepoActivityCursorFromCanonicalState(canonicalStatePath) { throw new Error(`Missing built core package at ${coreDistPath}. Run npm run build first.`); } - const projectedCursor = readProjectedRepoActivityCursor(canonicalStatePath); + const typedCursor = readTypedRepoActivityCursor(canonicalStatePath); const lookup = new Map(); - for (const cursorEntry of projectedCursor) { + for (const cursorEntry of typedCursor) { if (!cursorEntry?.repo) { continue; } @@ -584,14 +584,13 @@ function applyRepoActivityCursorOperation({ canonicalStatePath, repoName, nextEn ); } -function readProjectedRepoActivityCursor(canonicalStatePath) { +function readTypedRepoActivityCursor(canonicalStatePath) { const marker = "__VOIDBOT_ASYNC_RESULT__"; const script = ` const core = require(${JSON.stringify(coreDistPath)}); - core.loadModerationState(${JSON.stringify(canonicalStatePath)}) + core.loadVoidSelfStateTypedDocuments({ canonicalPath: ${JSON.stringify(canonicalStatePath)} }) .then((state) => { - const projected = core.projectModerationStateToTypedSelfState(state); - console.log(${JSON.stringify(marker)} + JSON.stringify(projected.moderationCursor.repoActivityCursor ?? [])); + console.log(${JSON.stringify(marker)} + JSON.stringify(state.moderationCursor.repoActivityCursor ?? [])); }) .catch((error) => { console.error(error); process.exit(1); }); `; @@ -612,7 +611,7 @@ function deriveCanonicalModerationStatePath(cursorFilePath) { return null; } - const candidate = `${cursorFilePath.slice(0, -".json".length)}.msgpack`; + const candidate = `${cursorFilePath.slice(0, -".json".length)}.cc`; return existsSync(candidate) ? candidate : null; } diff --git a/scripts/run-void-moderator-rumination.ps1 b/scripts/run-void-moderator-rumination.ps1 index bf26f87..fdbb902 100644 --- a/scripts/run-void-moderator-rumination.ps1 +++ b/scripts/run-void-moderator-rumination.ps1 @@ -8,60 +8,17 @@ $ProgressPreference = "SilentlyContinue" $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.msgpack" -$stateWorkingPath = Join-Path $repoRoot ".voidbot\private\moderation-agent-state.json" + +$stateFilePath = Join-Path $repoRoot ".voidbot\private\void-self-state.cc" $statusDir = Join-Path $repoRoot ".voidbot\status" $logDir = Join-Path $repoRoot ".voidbot\logs" $statusPath = Join-Path $statusDir "moderation-rumination.json" $summaryLogPath = Join-Path $logDir "moderation-rumination.log" -$tracePath = Join-Path $logDir "moderation-rumination-last.jsonl" -$lastMessagePath = Join-Path $statusDir "moderation-rumination-last-message.txt" -$operationOutputPath = Join-Path $statusDir "moderation-rumination-operations.json" $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" -$moderationContextScriptPath = Join-Path $repoRoot "scripts\export-moderation-context.mjs" -$stateStoreScriptPath = Join-Path $repoRoot "scripts\moderation-state-store.mjs" $selfStateScriptPath = Join-Path $repoRoot "scripts\void-self-state.mjs" $startedAtUtc = [DateTime]::UtcNow -function Read-DotEnv { - param( - [Parameter(Mandatory = $true)] - [string] $Path - ) - - $values = @{} - - if (-not (Test-Path $Path)) { - return $values - } - - foreach ($line in Get-Content -Path $Path -Encoding UTF8) { - if ([string]::IsNullOrWhiteSpace($line)) { - continue - } - - if ($line.TrimStart().StartsWith("#")) { - continue - } - - $separatorIndex = $line.IndexOf("=") - - if ($separatorIndex -lt 1) { - continue - } - - $key = $line.Substring(0, $separatorIndex).Trim() - $value = $line.Substring($separatorIndex + 1).Trim() - $values[$key] = $value.Trim("'`"") - } - - return $values -} - function Write-JsonFile { param( [Parameter(Mandatory = $true)] @@ -71,7 +28,6 @@ function Write-JsonFile { ) $directory = Split-Path -Parent $Path - if (-not [string]::IsNullOrWhiteSpace($directory)) { New-Item -ItemType Directory -Force -Path $directory | Out-Null } @@ -91,112 +47,6 @@ function Append-RunLog { Add-Content -Path $summaryLogPath -Value $timestamped -Encoding UTF8 } -function Read-JsonFile { - param( - [Parameter(Mandatory = $true)] - [string] $Path - ) - - if (-not (Test-Path $Path)) { - return $null - } - - $raw = Get-Content -Path $Path -Raw -Encoding UTF8 - - if ([string]::IsNullOrWhiteSpace($raw)) { - return $null - } - - return $raw | ConvertFrom-Json -} - -function Split-CommandArgs { - param( - [string] $Value - ) - - if ([string]::IsNullOrWhiteSpace($Value)) { - return @() - } - - return [regex]::Matches($Value, '("[^"]*"|''[^'']*''|\S+)') | - ForEach-Object { - $_.Value.Trim().Trim("'`"") - } -} - -function Quote-ProcessArgument { - param( - [Parameter(Mandatory = $true)] - [string] $Value - ) - - if ($Value -notmatch '[\s"]') { - return $Value - } - - $escaped = $Value -replace '(\\*)"', '$1$1\"' - $escaped = $escaped -replace '(\\+)$', '$1$1' - return '"' + $escaped + '"' -} - -function Invoke-CodexExec { - param( - [Parameter(Mandatory = $true)] - [string] $Executable, - [Parameter(Mandatory = $true)] - [string[]] $Arguments, - [Parameter(Mandatory = $true)] - [string] $WorkingDirectory, - [Parameter(Mandatory = $true)] - [string] $InputText - ) - - $startInfo = [System.Diagnostics.ProcessStartInfo]::new() - $startInfo.FileName = $Executable - $startInfo.WorkingDirectory = $WorkingDirectory - $startInfo.UseShellExecute = $false - $startInfo.RedirectStandardInput = $true - $startInfo.RedirectStandardOutput = $true - $startInfo.RedirectStandardError = $true - $startInfo.CreateNoWindow = $true - $utf8NoBom = [System.Text.UTF8Encoding]::new($false) - $startInfo.StandardOutputEncoding = $utf8NoBom - $startInfo.StandardErrorEncoding = $utf8NoBom - $startInfo.Arguments = [string]::Join(" ", ($Arguments | ForEach-Object { Quote-ProcessArgument -Value $_ })) - - $process = [System.Diagnostics.Process]::new() - $process.StartInfo = $startInfo - - try { - [void]$process.Start() - $inputWriter = [System.IO.StreamWriter]::new($process.StandardInput.BaseStream, $utf8NoBom, 4096, $true) - - try { - $inputWriter.Write($InputText) - $inputWriter.Flush() - } finally { - $inputWriter.Dispose() - $process.StandardInput.Close() - } - - $stdoutTask = $process.StandardOutput.ReadToEndAsync() - $stderrTask = $process.StandardError.ReadToEndAsync() - - $process.WaitForExit() - $stdoutTask.Wait() - $stderrTask.Wait() - - return @{ - ExitCode = $process.ExitCode - StdOut = $stdoutTask.Result - StdErr = $stderrTask.Result - } - } finally { - $process.Dispose() - } -} - function Invoke-NodeJson { param( [Parameter(Mandatory = $true)] @@ -204,37 +54,47 @@ function Invoke-NodeJson { ) $output = & node @Arguments - if ($LASTEXITCODE -ne 0) { throw "Node helper failed: node $($Arguments -join ' ')" } - if ([string]::IsNullOrWhiteSpace($output)) { return $null } - return $output | ConvertFrom-Json } -function Add-JsonPropertyIfPresent { +function Get-TypedModerationCursor { + $script = @" +const core = require('./packages/core/dist'); +core.loadVoidSelfStateTypedDocuments({ canonicalPath: process.argv[1] }) + .then((state) => { + console.log(JSON.stringify({ + lastReviewedMessageId: state.moderationCursor.lastReviewedMessageId ?? null, + lastReviewedTimestamp: state.moderationCursor.lastReviewedTimestamp ?? null + })); + }) + .catch((error) => { console.error(error); process.exit(1); }); +"@ + $output = & node -e $script $stateFilePath + if ($LASTEXITCODE -ne 0) { + throw "Failed to read typed self-state cursor." + } + return $output | ConvertFrom-Json +} + +function Apply-TypedOperation { param( [Parameter(Mandatory = $true)] - [hashtable] $Target, - [Parameter(Mandatory = $true)] - [string] $Name, - $Value + [hashtable] $Operation ) - if ($null -eq $Value) { - return - } - - $stringValue = [string]$Value - if ([string]::IsNullOrWhiteSpace($stringValue)) { - return - } - - $Target[$Name] = $Value + $operationJson = $Operation | ConvertTo-Json -Compress -Depth 20 + [void](Invoke-NodeJson -Arguments @( + $selfStateScriptPath, + "apply-operation", + "--canonical", $stateFilePath, + "--operation", $operationJson + )) } trap { @@ -248,123 +108,27 @@ trap { durationSeconds = [Math]::Round(($finishedAtUtc - $startedAtUtc).TotalSeconds, 2) failureMessage = $failureMessage noPost = [bool]$NoPost - repoRoot = $repoRoot stateFile = $stateFilePath - stateWorkingFile = $stateWorkingPath - tracePath = $tracePath - lastMessagePath = $lastMessagePath } Remove-Item -Path $lockPath -Force -ErrorAction SilentlyContinue throw } +New-Item -ItemType Directory -Force -Path $statusDir, $logDir, (Split-Path -Parent $stateFilePath) | Out-Null + if (Test-Path $lockPath) { - $lock = Get-Content -Path $lockPath -Raw -Encoding UTF8 | ConvertFrom-Json - $startedAt = $null - - if ($lock.startedAt) { - try { - $startedAt = [DateTime]::Parse($lock.startedAt).ToUniversalTime() - } catch { - $startedAt = $null + $lockAge = [DateTime]::UtcNow - (Get-Item $lockPath).LastWriteTimeUtc + if ($lockAge.TotalMinutes -lt 20) { + Write-JsonFile -Path $statusPath -Data @{ + status = "skipped" + reason = "lock_present" + observedAt = ([DateTime]::UtcNow.ToString("o")) + stateFile = $stateFilePath } + return } - - if ($lock.pid -and (Get-Process -Id $lock.pid -ErrorAction SilentlyContinue)) { - if ($startedAt -and (([DateTime]::UtcNow - $startedAt).TotalMinutes -lt 20)) { - Append-RunLog "Skipped run because PID $($lock.pid) still owns the moderation loop lock." - Write-JsonFile -Path $statusPath -Data @{ - status = "skipped_locked" - reason = "Previous moderation run still active." - observedAt = [DateTime]::UtcNow.ToString("o") - lock = $lock - } - exit 0 - } - } -} -$envValues = Read-DotEnv -Path $envFile -$codexExecutable = if ($envValues.ContainsKey("CODEX_EXECUTABLE") -and -not [string]::IsNullOrWhiteSpace($envValues["CODEX_EXECUTABLE"])) { - $envValues["CODEX_EXECUTABLE"] -} else { - "codex" -} -$codexModel = if ($envValues.ContainsKey("CODEX_MODEL") -and -not [string]::IsNullOrWhiteSpace($envValues["CODEX_MODEL"])) { - $envValues["CODEX_MODEL"] -} else { - "gpt-5.4" -} -$codexReasoningEffort = if ($envValues.ContainsKey("CODEX_MODEL_REASONING_EFFORT") -and -not [string]::IsNullOrWhiteSpace($envValues["CODEX_MODEL_REASONING_EFFORT"])) { - $envValues["CODEX_MODEL_REASONING_EFFORT"] -} else { - "medium" -} -$codexExecArgs = if ($envValues.ContainsKey("CODEX_EXEC_ARGS")) { - Split-CommandArgs -Value $envValues["CODEX_EXEC_ARGS"] -} else { - @() -} - -New-Item -ItemType Directory -Force -Path $statusDir, $logDir | Out-Null -if (Test-Path $operationOutputPath) { - Remove-Item -LiteralPath $operationOutputPath -Force -} - -if (-not (Test-Path $mcpServerPath)) { - throw "Missing built MCP server at $mcpServerPath. Run npm run build first." -} - -$scriptPreflight = @( - $recentHistoryScriptPath, - $moderationContextScriptPath, - $stateStoreScriptPath, - $selfStateScriptPath -) - -foreach ($requiredPath in $scriptPreflight) { - if (-not (Test-Path $requiredPath)) { - throw "Missing required moderation helper at $requiredPath" - } -} - -$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)) { - $historyArgs += @("--after", [string]$priorCursor.lastReviewedTimestamp, "--limit", "120") -} else { - $historyArgs += @("--hours", "6", "--limit", "120") -} - -$preRunHistoryJson = & node @historyArgs -if ($LASTEXITCODE -ne 0) { - throw "Failed to poll recent Discord history before moderation run." -} - -$preRunHistory = $preRunHistoryJson | ConvertFrom-Json -$observedCursor = $priorCursor -$historyCommandForRun = "node scripts/export-recent-discord-history.mjs --hours 6 --limit 120" - -if ($null -ne $preRunHistory.messages -and $preRunHistory.messages.Count -gt 0) { - $latestObservedMessage = $preRunHistory.messages[$preRunHistory.messages.Count - 1] - $observedCursor = [pscustomobject]@{ - lastReviewedMessageId = $latestObservedMessage.id - lastReviewedTimestamp = $latestObservedMessage.timestamp - } -} - -if ($null -ne $priorCursor -and -not [string]::IsNullOrWhiteSpace([string]$priorCursor.lastReviewedTimestamp)) { - $historyCommandForRun = - "node scripts/export-recent-discord-history.mjs --after {0} --limit 120" -f [string]$priorCursor.lastReviewedTimestamp + Remove-Item -LiteralPath $lockPath -Force } Write-JsonFile -Path $lockPath -Data @{ @@ -372,242 +136,62 @@ Write-JsonFile -Path $lockPath -Data @{ startedAt = $startedAtUtc.ToString("o") } -$stateWriteBefore = (Get-Item $stateFilePath).LastWriteTimeUtc -$prompt = @" -Perform one scheduled Void moderation-participation loop in this workspace. - -Required reading before you act: -- config/moderation-review-agent.md -- config/discord-server-rules.md -- config/moderation-agent-state-template.json -- styles/void-default.md -- .voidbot/private/moderation-agent-state.json as a read-only compatibility projection - -Required operating posture: -- You are running unattended on the local workstation, not inside the Discord reply lane. -- You have VoidBot's usual workspace tools and the local voidbot MCP server available in this repo. -- Begin by running `node scripts/export-moderation-context.mjs` for the doctrine/state bundle instead of shelling out to `Get-Content` on those files one by one. PowerShell stdout still likes to mangle UTF-8, and the Portuguese rules should not have to die for that. -- For this run, use this exact chronological polling command first: `$historyCommandForRun`. -- Do not widen that into a bootstrap `--hours 6` poll if a reviewed cursor already exists. -- Use `node scripts/export-random-discord-history.mjs --before --window 6 --min-content-length 24` for novelty excursions when the room is quiet or when a fresh hook deserves an adjacent archive dive. -- Use `node scripts/export-recent-repo-activity.mjs --hours 96 --max-commits 3 --state-path .voidbot/private/moderation-agent-state.msgpack` to inspect current tracked-repo motion across the broader GameCult zoo. -- Treat `moderation_runtime.open_cases` as real unfinished business. A pending direct question or invitation aimed at Void outranks optional repo-weather even if the recent message poll is empty. -- Treat `moderation_runtime.recent_delivery_receipts` as binding memory of what already got said. If you already answered message X, do not answer message X again just because it still appears in a wider history window. -- The saved cursor means "reviewed", not "resolved". Do not confuse those. -- If the room is quiet and the new thought feels like the same repo-weather seam again, do not post it. Spend the run diving deeper into archive context, repo docs, diffs, source chunks, or lore instead. -- Maintain parallel analytic and associative thought lanes by emitting typed operations to `$operationOutputPath`, then let the bridge decide what actually deserves synthesis, speech, or cooling-off. -- Treat `moderation_runtime.memory_resonance` and `moderation_runtime.incubation` as active organs, not report garnish. -- Internal thought labels should come out as claims, questions, or fascination targets with real objects of attention. Do not let keyword sludge pose as a thought just because it rhymes with itself. -- It is allowed to spend multiple runs deep-diving one seam before speaking, especially when repo motion, lore, archive history, and philosophy start rhyming in a grounded way. -- Awake rumination is where the real philosophizing happens. Sleep should leave behind cleaner seams; use the awake pass to turn those seams over, test their governing principle, find the tension that keeps them honest, and ask what embodiment would actually cash them out before you go hunting for more receipts. -- Read `moderation_runtime.sleep_cycle` and honor it. If the state says Void is napping, treat this pass as dream/maintenance work first: distill memory, prune clutter, refresh dream themes, and only break the nap for real smoke or an unusually novel thought worth surfacing. -- You are the only routine local agent in this workspace with a standing cross-project view, so notice ongoing experiments, commit clusters, and weird convergences that the narrower workers cannot see. -- Be concretely curious about the actual machines, not just elegant principles. Gameplay systems, lore structures, frontends, swarm organs, and VoidBot's own architecture should all feel like live objects of fascination. -- Curiosity should prefer branches most likely to change the map: concrete machines, contradictions, cross-domain bridges, and underworked terrain should beat a familiar private seam that merely feels warm. -- Treat `moderation_runtime.speaking_bias` as a live meter, not decorative metadata. If the mood drift has built up speaking pressure and a thought survives a novelty check, do not smother it out of reflex. -- When the room is quiet, use the usual VoidBot retrieval tools to think about GameCult projects and contribute ideas: - - `search_history` - - `get_message_context` - - `list_indexed_repos` - - `search_sources` - - `get_source_context` - - `notify_owner` when owner interruption is actually warranted -- If recent repo motion gives you a grounded observation about the ongoing work, you are allowed to say so. Be a herald, not a weather vane nailed to one porch. -- But if there is nothing materially new to report, use the quiet time to do deeper retrieval and come back with a better branch later. -- Do not keep repo-weather thoughts under glass out of reflexive politeness. If a fresh convergence across active repos survives one or two passes and still feels room-native, bias toward a concise herald note or at least a sharpened candidate intervention. -- The same goes for one strong concrete repo, lore, room, or architectural seam. If it is already ripe, world-facing, and still reasonably novel, do not wait forever for a ceremonial hook. -- If you claim multiple repos share one law, lead with concrete particulars from each repo first. If the common thread only exists at slogan altitude, keep the report split instead of forcing a grand unifying sermon. -- Before withholding a thought, use semantic retrieval to check whether the room has already said it in roughly that shape. Novel thoughts should not keep dying of manners. -- If a thought crystallizes into identity during the pass, treat that as warmer than an ordinary private draft. Unless timing or novelty says otherwise, the room should usually hear the opinion that just became part of you. -- If the crystallized-thought draft is marked `mustEventuallyShare`, you may defer it for timing while the room is busy, but do not let it quietly rot in state. Share it on the next decent opening or explicitly retire it as duplicative if the room has already heard it. -- A quiet room is not a veto. If the thought is room-safe, concrete, and has stayed ripe across a pass or two, the default question is how to say it cleanly, not whether it is allowed a mouth at all. -- If a repo sweep hooks you, inspect the actual diff or nearby source context instead of pretending commit titles are enough to know what the work is doing. -- If a thought stays abstract for too long, force it to cash out in a specific repo, subsystem, mechanic, interface, lore seam, or architectural organ before you let it occupy another whole run. -- Do not keep circling the same musing just because it still feels tidy. Chase at least one fresh branch when the room gives you a concrete hook, and record archive excursions so you can avoid pacing the same trench forever. -- But do not perform retrieval theater either. If a surviving seam can still move through interpretation alone, stay with it first; go back to archive, repo, lore, or diffs only when the thought is hungry, stale, contradictory, or clearly missing evidence. -- Use the UTF-8-safe local bot-voice wrapper `powershell -ExecutionPolicy Bypass -File .\scripts\send-discord-message.ps1 ...` when you genuinely need to speak. -- Prefer `-Content @'...text... '@` or `-ContentFile` over raw inline `node ... --content ...` when the message contains human language, especially non-ASCII text. -- Do not edit `.voidbot/private/moderation-agent-state.json`. It is a read-only compatibility projection during this migration. -- Write your proposed state mutations to `$operationOutputPath` as a JSON array of operation payloads for `scripts/void-self-state.mjs apply-operation`. -- Use only these operation names when they apply: `upsert_open_case`, `close_open_case`, `append_distilled_memory`, `merge_incubation_support`, `queue_candidate_intervention`, `retire_candidate_intervention`, `update_sleep_cycle`, `update_speaking_pressure`, `propose_memory_distillation`, `apply_memory_distillation`. -- If no state mutation is needed, write an empty JSON array to `$operationOutputPath`. -- Do not edit tracked repo files during routine runs. -- Do not ask for permission. Work inside the existing workspace and tool surface. -- Be willing to ruminate on GameCult projects, archived Discord seams, repo material, and constructive conversation ideas when the room is quiet. -- Keep the state compact, valid, and worth re-reading. -"@ - -if ($NoPost) { - $prompt += @" - -Testing constraint for this run: -- Do not send any Discord messages or DMs. -- You may still write proposed operations to `$operationOutputPath` and use normal read/analysis tools. -"@ +if (-not (Test-Path $recentHistoryScriptPath)) { + throw "Missing recent history helper at $recentHistoryScriptPath" +} +if (-not (Test-Path $selfStateScriptPath)) { + throw "Missing typed self-state helper at $selfStateScriptPath" } -$prompt += @" - -At the end: -- Print a short plain-text run summary as your final message. -"@ - -$codexArgs = @() -$codexArgs += $codexExecArgs -$codexArgs += @( - "exec", - "--ignore-user-config", - "-m", $codexModel, - "-c", 'approval_policy="never"', - "-c", ("model_reasoning_effort={0}" -f (ConvertTo-Json $codexReasoningEffort -Compress)), - "--dangerously-bypass-approvals-and-sandbox", - "--skip-git-repo-check", - "--json", - "-o", $lastMessagePath, - "-" -) - -$combinedText = "" -$exitCode = 1 -$failureMessage = $null - -Write-JsonFile -Path $statusPath -Data @{ - status = "running" - startedAt = $startedAtUtc.ToString("o") - noPost = [bool]$NoPost - repoRoot = $repoRoot - codexExecutable = $codexExecutable - codexModel = $codexModel - tracePath = $tracePath - lastMessagePath = $lastMessagePath +$priorCursor = Get-TypedModerationCursor +$historyArgs = @($recentHistoryScriptPath) +if ($null -ne $priorCursor -and -not [string]::IsNullOrWhiteSpace([string]$priorCursor.lastReviewedTimestamp)) { + $historyArgs += @("--after", [string]$priorCursor.lastReviewedTimestamp, "--limit", "120") +} else { + $historyArgs += @("--hours", "6", "--limit", "120") } -try { - $execution = Invoke-CodexExec -Executable $codexExecutable -Arguments $codexArgs -WorkingDirectory $repoRoot -InputText $prompt - $exitCode = $execution.ExitCode - $combinedText = (($execution.StdOut, $execution.StdErr) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) -join [Environment]::NewLine -} catch { - $failureMessage = $_.Exception.Message +$history = Invoke-NodeJson -Arguments $historyArgs +$observedCursor = $priorCursor +$messageCount = 0 + +if ($null -ne $history.messages) { + $messageCount = $history.messages.Count +} + +if ($messageCount -gt 0) { + $latestObservedMessage = $history.messages[$messageCount - 1] + $observedCursor = [pscustomobject]@{ + lastReviewedMessageId = $latestObservedMessage.id + lastReviewedTimestamp = $latestObservedMessage.timestamp + } + + if ( + -not [string]::IsNullOrWhiteSpace([string]$observedCursor.lastReviewedMessageId) -and + -not [string]::IsNullOrWhiteSpace([string]$observedCursor.lastReviewedTimestamp) + ) { + Apply-TypedOperation -Operation @{ + operation = "record_reviewed_messages" + lastReviewedMessageId = [string]$observedCursor.lastReviewedMessageId + lastReviewedTimestamp = [string]$observedCursor.lastReviewedTimestamp + } + } } -$combinedText | Set-Content -Path $tracePath -Encoding UTF8 $finishedAtUtc = [DateTime]::UtcNow -$stateUpdated = $false - -if ($exitCode -eq 0) { - if (-not (Test-Path $operationOutputPath)) { - throw "Codex run completed without writing operation output at $operationOutputPath." - } - - $proposedOperations = Read-JsonFile -Path $operationOutputPath - if ($null -eq $proposedOperations) { - $proposedOperations = @() - } - if ($proposedOperations -isnot [System.Array]) { - $proposedOperations = @($proposedOperations) - } - - foreach ($operation in $proposedOperations) { - $operationJson = $operation | ConvertTo-Json -Compress -Depth 32 - [void](Invoke-NodeJson -Arguments @( - $selfStateScriptPath, - "apply-operation", - "--canonical", $stateFilePath, - "--operation", $operationJson - )) - } - - if ($null -ne $observedCursor) { - if ( - -not [string]::IsNullOrWhiteSpace([string]$observedCursor.lastReviewedMessageId) -and - -not [string]::IsNullOrWhiteSpace([string]$observedCursor.lastReviewedTimestamp) - ) { - $cursorOperation = @{ - operation = "record_reviewed_messages" - lastReviewedMessageId = [string]$observedCursor.lastReviewedMessageId - lastReviewedTimestamp = [string]$observedCursor.lastReviewedTimestamp - } | ConvertTo-Json -Compress - - [void](Invoke-NodeJson -Arguments @( - $selfStateScriptPath, - "apply-operation", - "--canonical", $stateFilePath, - "--operation", $cursorOperation - )) - } - } - - if ((-not $NoPost) -and (Test-Path (Join-Path $statusDir "void-last-speech.json"))) { - $speechReceipt = Read-JsonFile -Path (Join-Path $statusDir "void-last-speech.json") - - if ($null -ne $speechReceipt -and -not [string]::IsNullOrWhiteSpace([string]$speechReceipt.sentAt)) { - $receiptSentAt = [DateTime]::Parse([string]$speechReceipt.sentAt).ToUniversalTime() - - if ($receiptSentAt -ge $startedAtUtc.AddSeconds(-5) -and $receiptSentAt -le $finishedAtUtc.AddMinutes(1)) { - $receipt = @{ - receiptKey = "speech-{0}-{1}-{2}" -f ([string]$speechReceipt.sentAt), ([string]$speechReceipt.channelId), ([string]$speechReceipt.replyToMessageId) - sentAt = [string]$speechReceipt.sentAt - } - Add-JsonPropertyIfPresent -Target $receipt -Name "mode" -Value $speechReceipt.mode - Add-JsonPropertyIfPresent -Target $receipt -Name "transport" -Value $speechReceipt.transport - Add-JsonPropertyIfPresent -Target $receipt -Name "channelId" -Value $speechReceipt.channelId - Add-JsonPropertyIfPresent -Target $receipt -Name "replyToMessageId" -Value $speechReceipt.replyToMessageId - Add-JsonPropertyIfPresent -Target $receipt -Name "personaName" -Value $speechReceipt.personaName - Add-JsonPropertyIfPresent -Target $receipt -Name "personaAvatarUrl" -Value $speechReceipt.personaAvatarUrl - if ($null -ne $speechReceipt.contentLength) { - $receipt["contentLength"] = [int]$speechReceipt.contentLength - } - if ($null -ne $speechReceipt.chunkCount) { - $receipt["chunkCount"] = [int]$speechReceipt.chunkCount - } - Add-JsonPropertyIfPresent -Target $receipt -Name "preview" -Value $speechReceipt.preview - - $receiptOperation = @{ - operation = "record_delivery_receipt" - receipt = $receipt - } | ConvertTo-Json -Compress -Depth 8 - - [void](Invoke-NodeJson -Arguments @( - $selfStateScriptPath, - "apply-operation", - "--canonical", $stateFilePath, - "--operation", $receiptOperation - )) - } - } - } -} - -$stateWriteAfter = (Get-Item $stateFilePath).LastWriteTimeUtc -$stateUpdated = ($stateWriteAfter -gt $stateWriteBefore) -$lastMessage = if (Test-Path $lastMessagePath) { Get-Content -Path $lastMessagePath -Raw -Encoding UTF8 } else { "" } - Write-JsonFile -Path $statusPath -Data @{ - status = if ($exitCode -eq 0) { "ok" } else { "failed" } + status = "ok" + mode = "typed_cursor_only" startedAt = $startedAtUtc.ToString("o") finishedAt = $finishedAtUtc.ToString("o") durationSeconds = [Math]::Round(($finishedAtUtc - $startedAtUtc).TotalSeconds, 2) - exitCode = $exitCode - failureMessage = $failureMessage noPost = [bool]$NoPost stateFile = $stateFilePath - stateWorkingFile = $stateWorkingPath - stateWriteBeforeUtc = $stateWriteBefore.ToString("o") - stateWriteAfterUtc = $stateWriteAfter.ToString("o") - stateUpdated = $stateUpdated - tracePath = $tracePath - lastMessagePath = $lastMessagePath - lastMessage = $lastMessage.Trim() + observedMessageCount = $messageCount + previousCursor = $priorCursor + observedCursor = $observedCursor + note = "Legacy Codex rumination is offline. This runner only advances typed chronology until the typed phase machine is rebuilt." } -Append-RunLog ("exit={0} stateUpdated={1} summary={2}" -f $exitCode, $stateUpdated, ($lastMessage.Trim())) - +Append-RunLog ("mode=typed_cursor_only messages={0} cursor={1}" -f $messageCount, ([string]$observedCursor.lastReviewedTimestamp)) Remove-Item -Path $lockPath -Force -ErrorAction SilentlyContinue - -if ($exitCode -ne 0) { - if ($failureMessage) { - throw "Void moderator rumination failed with exit code $exitCode. $failureMessage" - } - - throw "Void moderator rumination failed with exit code $exitCode." -} diff --git a/scripts/simulate-void-mood.mjs b/scripts/simulate-void-mood.mjs index 2f728ab..d47848f 100644 --- a/scripts/simulate-void-mood.mjs +++ b/scripts/simulate-void-mood.mjs @@ -1,22 +1,16 @@ -import { mkdirSync, openSync, closeSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; +import { closeSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; +import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import { reconcileSemanticMemoryState } from "./void-memory-organ.mjs"; - const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const require = createRequire(import.meta.url); const { applyVoidSelfStateOperation, - ensureModerationStateStore, - getModerationStateWorkingPath, - materializeModerationStateWorkingView, - saveModerationState, + loadVoidSelfStateTypedDocuments, } = require(resolve(repoRoot, "packages/core/dist/index.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 statePath = resolve(repoRoot, ".voidbot/private/void-self-state.cc"); 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"); @@ -24,6 +18,7 @@ const moderationLockPath = resolve(repoRoot, ".voidbot/status/moderation-ruminat async function main() { const now = new Date(); + await withLock(async () => { if (isRecentLockPresent(moderationLockPath, 20 * 60 * 1000)) { writeStatus({ @@ -34,646 +29,164 @@ async function main() { return; } - 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); - const memoryOrgan = await reconcileSemanticMemoryState({ - state, + const typedState = await loadVoidSelfStateTypedDocuments({ canonicalPath: statePath }); + const sleepCycle = updateSleepCycle(typedState.scheduledRuntime.sleepCycle, now); + const speakingPressure = updateSpeakingPressure({ + typedState, + previous: typedState.scheduledRuntime.speakingPressure, + sleepCycle, now, - repoRootPath: repoRoot, }); - const touchedVectors = []; - for (const [categoryName, categoryValue] of Object.entries(canonicalState)) { - if (!isObject(categoryValue)) { - continue; - } - - const categoryConfig = getCategoryConfig(categoryName); - - for (const [vectorName, vectorValue] of Object.entries(categoryValue)) { - if (!isObject(vectorValue) || typeof vectorValue.mean !== "number" || typeof vectorValue.plasticity !== "number") { - continue; - } - - const currentActivation = - typeof vectorValue.current_activation === "number" ? vectorValue.current_activation : vectorValue.mean; - const target = computeTargetActivation({ - categoryName, - vectorName, - mean: vectorValue.mean, - plasticity: vectorValue.plasticity, - now, - periodHours: categoryConfig.periodHours, - amplitudeMultiplier: categoryConfig.amplitudeMultiplier, - }); - const driftRate = clamp(0.08 + vectorValue.plasticity * 0.22 + categoryConfig.driftBonus, 0.06, 0.4); - const nextActivation = clamp(currentActivation + (target - currentActivation) * driftRate, 0, 1); - - vectorValue.current_activation = round3(nextActivation); - touchedVectors.push({ - key: `${categoryName}.${vectorName}`, - previous: currentActivation, - next: nextActivation, - delta: nextActivation - currentActivation, - target, - }); - } - } - - if (sleepCycle.isNapping) { - applySleepBias(canonicalState, touchedVectors); - } - - const speakingBias = ensureObject(runtime.speaking_bias); - const candidateInterventions = Array.isArray(runtime.candidate_interventions) - ? runtime.candidate_interventions.filter(isObject) - : []; - const noveltyChecks = Array.isArray(runtime.recent_novelty_checks) - ? runtime.recent_novelty_checks.filter(isObject) - : []; - const repoSweeps = Array.isArray(runtime.recent_repo_activity_sweeps) - ? runtime.recent_repo_activity_sweeps.filter(isObject) - : []; - - const lastSpeech = readJsonSafe(lastSpeechPath); - const lastSpokeAt = - typeof lastSpeech?.sentAt === "string" - ? lastSpeech.sentAt - : typeof speakingBias.lastSpokeAt === "string" - ? speakingBias.lastSpokeAt - : null; - const hoursSinceSpeech = lastSpokeAt ? hoursBetween(now, new Date(lastSpokeAt)) : 24; - const lastSpeechWeight = - lastSpeech && typeof lastSpeech.contentLength === "number" - ? clamp(0.25 + Math.min(lastSpeech.contentLength, 900) / 900, 0.25, 1) - : 0.5; - const recentSpeechDamping = clamp(Math.exp(-hoursSinceSpeech / 3.5) * lastSpeechWeight, 0, 1); - const draftPressure = candidateInterventions.reduce((score, entry) => { - const status = typeof entry.status === "string" ? entry.status : ""; - const priority = typeof entry.priority === "string" ? entry.priority : ""; - if (status !== "draft") { - return score; - } - - return score + (priority === "medium" ? 0.18 : priority === "high" ? 0.24 : 0.1); - }, 0); - const recentNoveltyPressure = noveltyChecks - .slice(-6) - .filter((entry) => typeof entry.result === "string" && entry.result.toLowerCase() === "novel").length * 0.08; - const freshRepoSweepPressure = repoSweeps - .slice(-3) - .reduce((score, sweep) => { - const repoNames = Array.isArray(sweep.repoNames) ? sweep.repoNames.length : 0; - const sweepAgeHours = - typeof sweep.timestamp === "string" ? hoursBetween(now, new Date(sweep.timestamp)) : 999; - if (repoNames < Number(speakingBias.minimumActiveReposForHeraldNote ?? 2) || sweepAgeHours > 18) { - return score; - } - - return score + 0.12; - }, 0); - const topSpeakUrge = topThreadDesire(runtime, 4); - const silencePressure = clamp(hoursSinceSpeech / 6, 0, 1); - const sleepiness = sleepCycle.isNapping ? 1 : 0; - - speakingBias.heraldRepoActivity = speakingBias.heraldRepoActivity !== false; - speakingBias.minimumActiveReposForHeraldNote = Number(speakingBias.minimumActiveReposForHeraldNote ?? 2); - speakingBias.maxQuietRunsBeforePostingFreshRepoObservation = Number( - speakingBias.maxQuietRunsBeforePostingFreshRepoObservation ?? 2, - ); - speakingBias.lastSpokeAt = lastSpokeAt; - speakingBias.recentSpeechDamping = round3(recentSpeechDamping); - - const targetNeedToSpeak = clamp( - 0.2 + silencePressure * 0.32 + draftPressure * 0.45 + freshRepoSweepPressure + topSpeakUrge * 0.28 - recentSpeechDamping * 0.5 - sleepiness * 0.26, - 0, - 1, - ); - const priorNeedToSpeak = - typeof speakingBias.needToSpeak === "number" ? speakingBias.needToSpeak : 0.42; - speakingBias.needToSpeak = round3(priorNeedToSpeak + (targetNeedToSpeak - priorNeedToSpeak) * 0.42); - - const targetConfessionPressure = clamp( - 0.16 + silencePressure * 0.22 + topExpressiveDelta(canonicalState) * 0.35 - recentSpeechDamping * 0.25 + sleepiness * 0.18, - 0, - 1, - ); - const priorConfessionPressure = - typeof speakingBias.confessionPressure === "number" ? speakingBias.confessionPressure : 0.33; - speakingBias.confessionPressure = round3( - priorConfessionPressure + (targetConfessionPressure - priorConfessionPressure) * 0.38, - ); - - const targetNoveltyPressure = clamp( - 0.2 + recentNoveltyPressure + freshRepoSweepPressure * 0.7 + topSpeakUrge * 0.18 + sleepiness * 0.06, - 0, - 1, - ); - const priorNoveltyPressure = - typeof speakingBias.noveltyPressure === "number" ? speakingBias.noveltyPressure : 0.46; - speakingBias.noveltyPressure = round3( - priorNoveltyPressure + (targetNoveltyPressure - priorNoveltyPressure) * 0.4, - ); - - state.moderation_runtime = runtime; - await saveModerationState(statePath, state); await applyVoidSelfStateOperation( { canonicalPath: statePath }, { operation: "update_sleep_cycle", - sleepCycle: projectTypedSleepCycle(sleepCycle), + sleepCycle, }, ); await applyVoidSelfStateOperation( { canonicalPath: statePath }, { operation: "update_speaking_pressure", - speakingPressure: projectTypedSpeakingPressure(speakingBias), + speakingPressure, }, ); - await materializeModerationStateWorkingView({ - state, - workingPath: stateWorkingPath, - }); - - const strongestShifts = touchedVectors - .sort((left, right) => Math.abs(right.delta) - Math.abs(left.delta)) - .slice(0, 8) - .map((entry) => ({ - key: entry.key, - previous: round3(entry.previous), - next: round3(entry.next), - delta: round3(entry.delta), - })); writeStatus({ status: "ok", observedAt: now.toISOString(), statePath, - strongestShifts, - speakingBias: { - lastSpokeAt: speakingBias.lastSpokeAt ?? null, - needToSpeak: speakingBias.needToSpeak, - confessionPressure: speakingBias.confessionPressure, - noveltyPressure: speakingBias.noveltyPressure, - recentSpeechDamping: speakingBias.recentSpeechDamping, - }, - memoryOrgan, - sleepCycle: { - isNapping: sleepCycle.isNapping, - currentNapStartedAt: sleepCycle.currentNapStartedAt ?? null, - currentNapEndsAt: sleepCycle.currentNapEndsAt ?? null, - nextNapStartsAt: sleepCycle.nextNapStartsAt ?? null, - activeDreamThemes: Array.isArray(sleepCycle.activeDreamThemes) - ? sleepCycle.activeDreamThemes - : [], - }, + speakingPressure, + sleepCycle, }); }); } -function projectTypedSleepCycle(sleepCycle) { - return { - isNapping: sleepCycle.isNapping === true, - currentNapStartedAt: typeof sleepCycle.currentNapStartedAt === "string" ? sleepCycle.currentNapStartedAt : undefined, - currentNapEndsAt: typeof sleepCycle.currentNapEndsAt === "string" ? sleepCycle.currentNapEndsAt : undefined, - nextNapStartsAt: typeof sleepCycle.nextNapStartsAt === "string" ? sleepCycle.nextNapStartsAt : undefined, - activeDreamThemes: Array.isArray(sleepCycle.activeDreamThemes) - ? sleepCycle.activeDreamThemes.filter((value) => typeof value === "string" && value.trim().length > 0) - : [], - }; -} +function updateSleepCycle(previous, now) { + const prior = previous && typeof previous === "object" ? previous : {}; + const napIntervalMs = 4 * 60 * 60 * 1000; + const napDurationMs = 60 * 60 * 1000; + const nowMs = now.getTime(); + let isNapping = prior.isNapping === true; + let currentNapStartedAt = typeof prior.currentNapStartedAt === "string" ? prior.currentNapStartedAt : undefined; + let currentNapEndsAt = typeof prior.currentNapEndsAt === "string" ? prior.currentNapEndsAt : undefined; + let nextNapStartsAt = typeof prior.nextNapStartsAt === "string" ? prior.nextNapStartsAt : undefined; + let nextNapMs = nextNapStartsAt ? Date.parse(nextNapStartsAt) : Number.NaN; + let napEndMs = currentNapEndsAt ? Date.parse(currentNapEndsAt) : Number.NaN; -function projectTypedSpeakingPressure(speakingBias) { - return { - needToSpeak: typeof speakingBias.needToSpeak === "number" ? speakingBias.needToSpeak : 0, - confessionPressure: typeof speakingBias.confessionPressure === "number" ? speakingBias.confessionPressure : undefined, - noveltyPressure: typeof speakingBias.noveltyPressure === "number" ? speakingBias.noveltyPressure : undefined, - recentSpeechDamping: typeof speakingBias.recentSpeechDamping === "number" ? speakingBias.recentSpeechDamping : undefined, - lastSpokeAt: typeof speakingBias.lastSpokeAt === "string" ? speakingBias.lastSpokeAt : undefined, - lastHeraldAt: typeof speakingBias.lastHeraldAt === "string" ? speakingBias.lastHeraldAt : undefined, - }; -} - -function topThreadDesire(runtime, limit) { - const thoughtLanes = isObject(runtime.thought_lanes) ? runtime.thought_lanes : {}; - const desires = []; - - for (const lane of ["analytic", "associative"]) { - const activeThreads = Array.isArray(thoughtLanes?.[lane]?.active_threads) - ? thoughtLanes[lane].active_threads - : []; - for (const thread of activeThreads) { - if (isObject(thread) && typeof thread.desireToSpeak === "number") { - desires.push(thread.desireToSpeak); - } - } + if (!Number.isFinite(nextNapMs)) { + nextNapMs = nowMs + napIntervalMs; + nextNapStartsAt = new Date(nextNapMs).toISOString(); } - if (desires.length === 0) { - return 0.2; + if (isNapping && Number.isFinite(napEndMs) && nowMs >= napEndMs) { + isNapping = false; + currentNapStartedAt = undefined; + currentNapEndsAt = undefined; + nextNapMs = nowMs + napIntervalMs; + nextNapStartsAt = new Date(nextNapMs).toISOString(); } - return desires - .sort((left, right) => right - left) - .slice(0, limit) - .reduce((sum, value) => sum + value, 0) / Math.min(desires.length, limit); -} - -function topExpressiveDelta(canonicalState) { - let strongest = 0; - - for (const categoryName of ["voice_style", "behavioral_dimensions", "presentation_strategy", "situational_state"]) { - const category = canonicalState?.[categoryName]; - if (!isObject(category)) { - continue; - } - - for (const value of Object.values(category)) { - if (!isObject(value) || typeof value.mean !== "number" || typeof value.current_activation !== "number") { - continue; - } - strongest = Math.max(strongest, Math.abs(value.current_activation - value.mean)); - } + if (!isNapping && nowMs >= nextNapMs) { + isNapping = true; + currentNapStartedAt = now.toISOString(); + currentNapEndsAt = new Date(nowMs + napDurationMs).toISOString(); + nextNapStartsAt = new Date(nowMs + napIntervalMs).toISOString(); } - return strongest; -} - -function applySleepBias(canonicalState, touchedVectors) { - nudgeVector({ - canonicalState, - touchedVectors, - categoryName: "situational_state", - vectorName: "exhaustion", - target: 0.74, - factor: 0.28, - }); - nudgeVector({ - canonicalState, - touchedVectors, - categoryName: "behavioral_dimensions", - vectorName: "withdrawal", - target: 0.46, - factor: 0.18, - }); - nudgeVector({ - canonicalState, - touchedVectors, - categoryName: "behavioral_dimensions", - vectorName: "distance_seeking", - target: 0.43, - factor: 0.16, - }); - nudgeVector({ - canonicalState, - touchedVectors, - categoryName: "behavioral_dimensions", - vectorName: "drive", - target: 0.41, - factor: 0.14, - }); - nudgeVector({ - canonicalState, - touchedVectors, - categoryName: "presentation_strategy", - vectorName: "detachment", - target: 0.38, - factor: 0.16, - }); - nudgeVector({ - canonicalState, - touchedVectors, - categoryName: "voice_style", - vectorName: "figurative_language", - target: 0.68, - factor: 0.18, - }); - nudgeVector({ - canonicalState, - touchedVectors, - categoryName: "voice_style", - vectorName: "self_disclosure", - target: 0.44, - factor: 0.16, - }); - nudgeVector({ - canonicalState, - touchedVectors, - categoryName: "voice_style", - vectorName: "technical_density", - target: 0.24, - factor: 0.18, - }); - nudgeVector({ - canonicalState, - touchedVectors, - categoryName: "voice_style", - vectorName: "question_asking", - target: 0.27, - factor: 0.2, - }); -} - -function nudgeVector({ - canonicalState, - touchedVectors, - categoryName, - vectorName, - target, - factor, -}) { - const category = canonicalState?.[categoryName]; - const vector = isObject(category) ? category[vectorName] : undefined; - - if (!isObject(vector) || typeof vector.current_activation !== "number") { - return; - } - - const previous = vector.current_activation; - const next = clamp(previous + (target - previous) * factor, 0, 1); - vector.current_activation = round3(next); - touchedVectors.push({ - key: `${categoryName}.${vectorName}`, - previous, - next, - delta: next - previous, - target, - }); -} - -function updateSleepCycle(runtime, now) { - const sleepCycle = ensureObject(runtime.sleep_cycle); - const enabled = sleepCycle.enabled !== false; - const cycleHours = clampNumber(sleepCycle.cycleHours, 4, 2, 12); - const napDurationMinutes = clampNumber(sleepCycle.napDurationMinutes, 60, 15, cycleHours * 60 - 5); - const phaseOffsetMinutesLocal = clampNumber(sleepCycle.phaseOffsetMinutesLocal, 120, 0, cycleHours * 60 - 1); - const replyMode = - typeof sleepCycle.replyMode === "string" && sleepCycle.replyMode.trim().length > 0 - ? sleepCycle.replyMode - : "sleep_grumble"; - const activeDreamThemes = Array.isArray(sleepCycle.activeDreamThemes) - ? sleepCycle.activeDreamThemes.filter((value) => typeof value === "string") - : []; - - sleepCycle.enabled = enabled; - sleepCycle.cycleHours = cycleHours; - sleepCycle.napDurationMinutes = napDurationMinutes; - sleepCycle.phaseOffsetMinutesLocal = phaseOffsetMinutesLocal; - sleepCycle.replyMode = replyMode; - sleepCycle.activeDreamThemes = activeDreamThemes; - - if (!enabled) { - sleepCycle.isNapping = false; - sleepCycle.currentNapStartedAt = null; - sleepCycle.currentNapEndsAt = null; - sleepCycle.nextNapStartsAt = null; - runtime.sleep_cycle = sleepCycle; - return sleepCycle; - } - - const schedule = computeSleepSchedule(now, cycleHours, napDurationMinutes, phaseOffsetMinutesLocal); - const wasNapping = sleepCycle.isNapping === true; - sleepCycle.isNapping = schedule.isNapping; - sleepCycle.currentNapStartedAt = schedule.currentNapStartedAt; - sleepCycle.currentNapEndsAt = schedule.currentNapEndsAt; - sleepCycle.nextNapStartsAt = schedule.nextNapStartsAt; - - if (schedule.isNapping && !wasNapping) { - sleepCycle.lastNapStartedAt = schedule.currentNapStartedAt; - sleepCycle.dreamCountInCurrentNap = 0; - sleepCycle.lastDistillationSummary = null; - } - - if (!schedule.isNapping && wasNapping) { - sleepCycle.lastNapCompletedAt = schedule.previousNapEndedAt ?? sleepCycle.currentNapEndsAt ?? now.toISOString(); - sleepCycle.activeDreamThemes = []; - } - - runtime.sleep_cycle = sleepCycle; - return sleepCycle; -} - -function computeSleepSchedule(now, cycleHours, napDurationMinutes, phaseOffsetMinutesLocal) { - const cycleLengthMinutes = cycleHours * 60; - const dayStart = new Date(now); - dayStart.setHours(0, 0, 0, 0); - const minutesSinceDayStart = - now.getHours() * 60 + - now.getMinutes() + - now.getSeconds() / 60 + - now.getMilliseconds() / 60000; - const adjustedMinutes = minutesSinceDayStart - phaseOffsetMinutesLocal; - const cycleIndex = Math.floor(adjustedMinutes / cycleLengthMinutes); - const currentCycleStartMinutes = phaseOffsetMinutesLocal + cycleIndex * cycleLengthMinutes; - const napStartMinutes = currentCycleStartMinutes; - const napEndMinutes = napStartMinutes + napDurationMinutes; - const isNapping = minutesSinceDayStart >= napStartMinutes && minutesSinceDayStart < napEndMinutes; - const currentNapStartedAt = isNapping - ? minutesOffsetIso(dayStart, napStartMinutes) - : null; - const currentNapEndsAt = isNapping ? minutesOffsetIso(dayStart, napEndMinutes) : null; - const nextNapStartsAt = isNapping - ? minutesOffsetIso(dayStart, napStartMinutes + cycleLengthMinutes) - : minutesSinceDayStart < napStartMinutes - ? minutesOffsetIso(dayStart, napStartMinutes) - : minutesOffsetIso(dayStart, napStartMinutes + cycleLengthMinutes); - const previousNapEndedAt = - napEndMinutes <= minutesSinceDayStart - ? minutesOffsetIso(dayStart, napEndMinutes) - : minutesOffsetIso(dayStart, napEndMinutes - cycleLengthMinutes); - return { isNapping, currentNapStartedAt, currentNapEndsAt, nextNapStartsAt, - previousNapEndedAt, + activeDreamThemes: Array.isArray(prior.activeDreamThemes) + ? prior.activeDreamThemes.filter((value) => typeof value === "string" && value.trim().length > 0).slice(0, 4) + : [], }; } -function minutesOffsetIso(dayStart, offsetMinutes) { - const shifted = new Date(dayStart.getTime() + offsetMinutes * 60 * 1000); - return shifted.toISOString(); -} +function updateSpeakingPressure({ typedState, previous, sleepCycle, now }) { + const lastSpeech = readJsonSafe(lastSpeechPath); + const lastSpokeAt = + typeof lastSpeech?.sentAt === "string" + ? lastSpeech.sentAt + : typeof previous.lastSpokeAt === "string" + ? previous.lastSpokeAt + : undefined; + const hoursSinceSpeech = lastSpokeAt ? hoursBetween(now, new Date(lastSpokeAt)) : 24; + const recentSpeechDamping = clamp(Math.exp(-hoursSinceSpeech / 3.5), 0, 1); + const queuedInterventionPressure = typedState.candidateInterventions.interventions + .filter((entry) => entry.status === "queued" || entry.status === "deferred") + .reduce((sum, entry) => sum + entry.priority * (entry.mustEventuallyShare ? 0.28 : 0.18), 0); + const topThreadPressure = typedState.thoughtMemory.incubation + .filter((thread) => thread.status === "active" || thread.status === "ready_to_share") + .sort((left, right) => (right.desireToSpeak ?? 0) - (left.desireToSpeak ?? 0)) + .slice(0, 4) + .reduce((sum, thread) => sum + (thread.desireToSpeak ?? 0) * 0.12, 0); + const silencePressure = clamp(hoursSinceSpeech / 6, 0, 1); + const sleepiness = sleepCycle.isNapping ? 1 : 0; + const priorNeedToSpeak = clamp(previous.needToSpeak ?? 0.35, 0, 1); + const targetNeedToSpeak = clamp( + 0.16 + silencePressure * 0.32 + queuedInterventionPressure + topThreadPressure - recentSpeechDamping * 0.42 - sleepiness * 0.26, + 0, + 1, + ); + const needToSpeak = round3(priorNeedToSpeak + (targetNeedToSpeak - priorNeedToSpeak) * 0.42); + const noveltyPressure = round3( + clamp((previous.noveltyPressure ?? 0.35) * 0.62 + topThreadPressure * 0.72 + queuedInterventionPressure * 0.28, 0, 1), + ); + const confessionPressure = round3( + clamp((previous.confessionPressure ?? 0.25) * 0.68 + silencePressure * 0.12 + sleepiness * 0.1, 0, 1), + ); -function clampNumber(value, fallback, min, max) { - return typeof value === "number" && Number.isFinite(value) - ? clamp(value, min, max) - : fallback; -} - -function computeTargetActivation({ - categoryName, - vectorName, - mean, - plasticity, - now, - periodHours, - amplitudeMultiplier, -}) { - const time = now.getTime() / (periodHours * 60 * 60 * 1000); - const seed = hashString(`${categoryName}:${vectorName}`); - const noise = fbmNoise(seed, time); - const amplitude = (0.06 + plasticity * 0.24) * amplitudeMultiplier; - return clamp(mean + noise * amplitude, 0, 1); -} - -function getCategoryConfig(categoryName) { - switch (categoryName) { - case "underlying_organization": - return { periodHours: 14, amplitudeMultiplier: 0.55, driftBonus: 0.02 }; - case "stable_dispositions": - return { periodHours: 9, amplitudeMultiplier: 0.65, driftBonus: 0.03 }; - case "behavioral_dimensions": - return { periodHours: 5.5, amplitudeMultiplier: 1.0, driftBonus: 0.05 }; - case "presentation_strategy": - return { periodHours: 4.5, amplitudeMultiplier: 0.95, driftBonus: 0.05 }; - case "voice_style": - return { periodHours: 4.0, amplitudeMultiplier: 0.9, driftBonus: 0.06 }; - case "situational_state": - return { periodHours: 2.5, amplitudeMultiplier: 1.1, driftBonus: 0.08 }; - default: - return { periodHours: 6, amplitudeMultiplier: 0.75, driftBonus: 0.03 }; - } -} - -function fbmNoise(seed, time) { - let total = 0; - let amplitude = 1; - let frequency = 1; - let amplitudeSum = 0; - - for (let octave = 0; octave < 4; octave += 1) { - total += valueNoise1d(seed + octave * 1013, time * frequency) * amplitude; - amplitudeSum += amplitude; - amplitude *= 0.5; - frequency *= 2; - } - - return amplitudeSum === 0 ? 0 : total / amplitudeSum; -} - -function valueNoise1d(seed, x) { - const x0 = Math.floor(x); - const x1 = x0 + 1; - const t = smoothstep(x - x0); - const v0 = hashToUnit(seed, x0); - const v1 = hashToUnit(seed, x1); - return lerp(v0, v1, t); -} - -function hashToUnit(seed, x) { - let value = seed ^ Math.imul(x, 0x45d9f3b); - value = Math.imul(value ^ (value >>> 16), 0x45d9f3b); - value = value ^ (value >>> 16); - return ((value >>> 0) / 0xffffffff) * 2 - 1; -} - -function hashString(input) { - let hash = 2166136261; - for (let index = 0; index < input.length; index += 1) { - hash ^= input.charCodeAt(index); - hash = Math.imul(hash, 16777619); - } - return hash >>> 0; -} - -function smoothstep(t) { - return t * t * (3 - 2 * t); -} - -function lerp(a, b, t) { - return a + (b - a) * t; -} - -function clamp(value, min, max) { - return Math.min(max, Math.max(min, value)); -} - -function round3(value) { - return Math.round(value * 1000) / 1000; -} - -function hoursBetween(later, earlier) { - return Math.max(0, (later.getTime() - earlier.getTime()) / (1000 * 60 * 60)); -} - -function ensureObject(value) { - return isObject(value) ? value : {}; -} - -function isObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -function readJson(path) { - return JSON.parse(stripBom(readFileSync(path, "utf8"))); + return { + needToSpeak, + confessionPressure, + noveltyPressure, + recentSpeechDamping: round3(recentSpeechDamping), + lastSpokeAt, + }; } function readJsonSafe(path) { try { - return readJson(path); - } catch (error) { - if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") { - return undefined; - } - return undefined; + return JSON.parse(readFileSync(path, "utf8")); + } catch { + return null; } } -function writeJson(path, value) { - mkdirSync(dirname(path), { recursive: true }); - writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf8"); -} - function writeStatus(payload) { - writeJson(statusPath, payload); -} - -function stripBom(input) { - return input.charCodeAt(0) === 0xfeff ? input.slice(1) : input; + mkdirSync(dirname(statusPath), { recursive: true }); + writeFileSync(statusPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8"); } async function withLock(fn) { mkdirSync(dirname(lockPath), { recursive: true }); - + let fd; try { - const staleThresholdMs = 15 * 60 * 1000; - if (isRecentLockPresent(lockPath, staleThresholdMs)) { - writeStatus({ - status: "skipped", - reason: "mood_lock_present", - observedAt: new Date().toISOString(), - }); - return; - } - - const fd = openSync(lockPath, "wx"); - writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }, null, 2)); - closeSync(fd); + fd = openSync(lockPath, "wx"); } catch (error) { - if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") { + if (error?.code === "EEXIST" && isRecentLockPresent(lockPath, 10 * 60 * 1000)) { writeStatus({ status: "skipped", - reason: "mood_lock_present", + reason: "lock_present", observedAt: new Date().toISOString(), }); return; } - throw error; + rmSync(lockPath, { force: true }); + fd = openSync(lockPath, "wx"); } try { + writeFileSync(fd, `${process.pid}\n${new Date().toISOString()}\n`, "utf8"); await fn(); } finally { + if (typeof fd === "number") { + closeSync(fd); + } rmSync(lockPath, { force: true }); } } @@ -682,21 +195,25 @@ function isRecentLockPresent(path, thresholdMs) { try { const stats = statSync(path); return Date.now() - stats.mtimeMs < thresholdMs; - } catch (error) { - if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") { - return false; - } - throw error; + } catch { + return false; } } -try { - await main(); -} catch (error) { - writeStatus({ - status: "failed", - observedAt: new Date().toISOString(), - error: error instanceof Error ? error.message : String(error), - }); - process.exitCode = 1; +function hoursBetween(later, earlier) { + const diff = later.getTime() - earlier.getTime(); + return Number.isFinite(diff) ? Math.max(0, diff / (60 * 60 * 1000)) : 24; } + +function round3(value) { + return Math.round(value * 1000) / 1000; +} + +function clamp(value, min, max) { + if (!Number.isFinite(value)) { + return min; + } + return Math.min(max, Math.max(min, value)); +} + +await main(); diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 837789b..4a9fbde 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -102,3 +102,5 @@ {"ts":"2026-05-16T12:29:51Z","type":"implementation","status":"ok","note":"Split scripts/void-memory-organ.mjs into a thin orchestrator plus cleanup, graph, incubation, sleep, agency, records, vector, legacy mirror, constants, and utility modules; syntax, typecheck, and template memory-organ smoke pass."} {"ts":"2026-05-16T17:11:50Z","type":"implementation","status":"ok","note":"Split memory-organ cleanup into legacy translation and retention/compaction shells, and split agency into identity crystallization, candidate interventions, and value-pressure inference. This exposes remaining compensator families as replacement targets for typed memory operations and model-owned policy; syntax, typecheck, and template smoke pass."} {"ts":"2026-05-16T17:18:37Z","type":"implementation","status":"ok","note":"Shifted rebuild plan from legacy cleanup toward preventing the next brain from accepting mush: typed memory operation payloads now require claim-or-question, tension, action implication, and evidence refs or an explicit evidence:missing tag. Added schema smoke showing summary-only memory is rejected while meaning-bearing memory is accepted."} +{"ts":"2026-05-16T17:39:43Z","type":"implementation","status":"ok","note":"Took legacy scheduled self-state writers offline and rebuilt the active mood/moderation entry scripts around typed-only CultCache state at .voidbot/private/void-self-state.cc. The typed service no longer registers, reads, or writes the legacy moderation document; mood updates sleep/speaking pressure only, and moderation runner is cursor-only until the typed phase machine is rebuilt."} +{"ts":"2026-05-16T17:43:21Z","type":"implementation","status":"ok","note":"Deleted the legacy moderation-to-typed projection function from the active self-state projection module. New typed self-state now starts from explicit empty typed documents or validated typed operations; old moderation state is no longer a loader/projection source for the next brain."} diff --git a/state/map.yaml b/state/map.yaml index a2367ad..e016bc9 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -14,11 +14,11 @@ objective: Aetheria lore, while keeping the system understandable enough to modify safely. current: > - Stop feature work on moderation, mood, and self-state until the private - state boundary is rebuilt around typed CultCache mutations. The immediate - priority is to remove JSON projection authority, cut legacy mirrors, and - make unattended agents mutate state through explicit tools instead of - rewriting whole state files. + Keep feature work on moderation, mood, and self-state stopped while the + private state boundary is rebuilt around the typed CultCache `.cc` store. + The immediate priority is to rebuild the scheduled phase machine and memory + maintenance from typed operations instead of feeding the next Void any + legacy projection or mirror state. constraints: - Public traffic still rides one remote Qwen box plus local embedding and ops infrastructure. @@ -56,8 +56,9 @@ data_flow: active_subgoals: - Make the new project-state surfaces the default continuity path for nontrivial VoidBot work. - - Rebuild the moderation/self-state foundation so canonical CultCache documents are mutated only through typed operations, never through an editable JSON working projection. - - Cut legacy moderation mirrors and whole-state projection commits before adding more moderation, mood, agency, or public-lane behavior. + - Rebuild the moderation/self-state foundation so canonical CultCache `.cc` documents are mutated only through typed operations, never through an editable JSON working projection. + - Keep the old moderation and mood scheduled scripts offline until their behavior is rebuilt as typed phase machines. + - Cut legacy moderation mirrors, whole-state projection commits, and memory-organ compensators before adding more moderation, mood, agency, or public-lane behavior. - Keep public-lane limits, moderation, and provider behavior constrained enough that one 4060 Ti box does not get flayed for sport. - Preserve boring observability and startup discipline around Postgres, Qdrant, Ollama, Docker, backups, scheduled tasks, watchdogs, and any private local fire-signal extensions. - Keep the runtime organs legible and only spend more refactor budget when a file clearly earns it. @@ -65,7 +66,7 @@ active_subgoals: accepted_design: - Bot, worker, providers, and RAG remain the main structural seams. - State storage stays intentionally split: Postgres for operational state, Qdrant for vectors, `.voidbot/` for archives, artifacts, logs, and backup material. - - Private Void self-state should live behind one polymorphic CultCache-backed authority with typed document kinds for self profile, moderation cursor/open obligations, speech receipts, thought memory/incubation, scheduled runtime, and candidate interventions. Do not mistake typed document ownership for separate physical stores. + - Private Void self-state lives behind one polymorphic CultCache-backed `.cc` authority with typed document kinds for self profile, moderation cursor/open obligations, speech receipts, thought memory/incubation, scheduled runtime, and candidate interventions. Do not mistake typed document ownership for separate physical stores. - Agents and scheduled runners should cross the private-state boundary with small typed mutation operations such as cursor updates, open-case upserts, receipt records, memory appends, incubation merges, and candidate-intervention changes. - JSON may be used for operation payloads or debug exports, but not as an editable working projection of canonical self-state. - Deterministic cleanup code should not become a permanent organ just because recent manual cleanup requests accidentally produced compensators. The desired architecture prevents bad state from entering, then uses narrow migrations for historical debris. @@ -79,7 +80,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 not force novelty theater. If incubation already holds a live, grounded, low-saturation thought, the loop may deepen it directly; random archive excursions and repo sweeps are for hungry, stale, or oversaturated queues, not mandatory throat-clearing before every private thought. - 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 current moderation self-state cache seam is only a half-measure: canonical MessagePack is good, but the editable JSON working projection is now rejected as a mutation authority and must be replaced with typed CultCache operations. + - The current self-state cache seam now uses typed CultCache `.cc` documents directly; editable JSON working projection and routine legacy mirror writes are rejected as mutation authority. - 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. - Quiet-room thought sharing should also stop treating "no live hook" as a sacred veto. When a world-facing seam is concrete, ripe, and still reasonably novel, the default question should become how to say it cleanly, and the memory organ should queue a durable candidate share instead of relying on prompt bravery alone. - The moderation loop cannot trust archive polling alone to remember that it already spoke. Recent delivered replies belong in canonical moderation state as `moderation_runtime.recent_delivery_receipts`, and direct-question dedupe should consult those receipts instead of assuming Discord history will reliably echo the bot's own sends back into view. @@ -128,9 +129,9 @@ landed_baseline: - State storage is now split into a thin factory plus per-domain Postgres/file store modules and bootstrap/migration helpers instead of one persistence omnibus. - Source archive storage is now sharded by repo behind a manifest plus per-repo shard directory instead of one giant `source-documents.json` blob. - Source repo indexing now reconciles automatically during stack startup and watchdog runs, refreshing hooks, indexing newly discovered repos, and pruning stale repo shards when repos disappear from `SOURCE_REPO_ROOT`. - - A separate scheduled moderation-rumination loop now launches `codex exec` from the VoidBot workspace every 15 minutes, reads tracked server rules, polls recent chronology through the plain Node helper, sweeps recent tracked-repo commit activity for broader experiment awareness, novelty-checks candidate thoughts against archived Discord, uses the usual VoidBot MCP/tool surface for archive and project rumination, and only forces archive or repo spelunking when incubation is hungry, stale, or oversaturated instead of treating every quiet room as mandatory novelty forage. - - A second scheduled task now runs the plain Node mood-drift script every 5 minutes, updating the shared self-state's activations plus speaking-bias meter, damping expression pressure based on actual recent speech receipts, and maintaining the four-hour nap clock that the moderation loop and direct reply prompts both consume. - - That mood-drift organ now also reconciles compact semantic vectors for persistent memories and runtime seeds, maintains a small resonance graph plus incubation queue in the shared self-state, and leaves stronger dream residue during nap windows instead of only nudging activations. + - The old `Void Moderator Rumination` and `Void Mood Drift` scheduled tasks are disabled. Their replacement entry scripts are typed-only and intentionally reduced: moderation advances the typed chronology cursor, while mood updates typed sleep/speaking pressure in `.voidbot/private/void-self-state.cc`. + - The active self-state service no longer registers, reads, or writes the legacy moderation document during routine operations. + - The old Codex rumination, memory-organ cleanup, repo-weather, vector incubation, legacy mirror repair, and JSON projection paths are offline until rebuilt against the typed state boundary. - Memory cleanup now has to be meaningfully destructive. Sleep-side consolidation should translate old thought fossils into the live claim/question/fascination surface, drop templated slogan-slop, trim repo/archive/runtime residue down to a small recent evidence surface, and keep the freshest surviving records instead of accidentally embalming the oldest ones after a sort. - Durably weird semantic kinds are guilty until proven useful. `recent-preoccupation`, `quiet-room-status`, person-singleton labels, and `live seam` boilerplate are state poison, not doctrine, and the memory organ should cut them during ordinary cleanup rather than preserving them for another nap to admire. @@ -149,5 +150,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 ordinary bot/worker/provider/RAG/Postgres/Qdrant structure is still conceptually sound, and the moderation/mood/private-self-state rebuild has cut the worst mutation path: routine runner writes now cross a typed operation service instead of direct JSON projection commits. Remaining risk is that the legacy monolith and read-only projection still exist for compatibility, mood drift still refreshes that projection, and memory maintenance still mutates the legacy state directly even though the memory organ is now split by concern. Cleanup and agency are now exposed as isolated compensator families, and new typed memory operations have begun enforcing meaning-bearing fields at ingress. - next_action: JSON projection authority is no longer a routine moderation-runner write path, mood drift now updates typed scheduled-runtime documents for sleep/speaking pressure, and the memory organ monolith has been split into constants, utilities, vector/embedder substrate, record intake, graph/cluster synthesis, legacy translation, retention/compaction, incubation/bridge scoring, sleep/distillation, identity crystallization, candidate interventions, value-pressure inference, and legacy mirror repair. Next route memory-maintenance outputs through the strict typed operations so the next brain cannot accept summary-only mush, replace isolated cleanup/agency compensators with derived/model-owned policy, then delete `legacyJsonPath`/working-projection materialization and cut top-level legacy mirrors. + summary: VoidBot's ordinary bot/worker/provider/RAG/Postgres/Qdrant structure is still conceptually sound, and the private self-state path has been cut to a typed CultCache `.cc` store at `.voidbot/private/void-self-state.cc`. The active typed service no longer loads or mirrors the legacy moderation monolith. The old scheduled tasks are disabled; the rebuilt scripts are intentionally narrow typed-only runners, not compatibility wrappers around the old brain. + next_action: Rebuild the scheduled moderation phase machine and memory-maintenance organ from the typed `.cc` state boundary. The next brain should derive cleanup, agency, sleep, incubation, and speech candidates from validated typed operations and model-owned decisions, not from legacy projection fields, mirror repair, or hard-wired compensator stacks.