Restore typed rumination prompt surface

This commit is contained in:
Meta Vens 2026-05-16 19:13:07 +01:00
commit cb63ef45e9
8 changed files with 574 additions and 65 deletions

View file

@ -29,7 +29,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou
- 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 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/run-void-moderator-rumination.ps1` has been rebuilt as a typed rumination runner. It builds a typed context packet, loads `prompts/void-moderator-rumination.md`, runs Codex rumination, and applies only the JSON operation payloads that come back through `scripts/void-self-state.mjs`. Cursor and receipt bookkeeping remain parent-owned.
- `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.
@ -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.
- 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.
- The old 15-minute local scheduled task `Void Moderator Rumination` is disabled. Its replacement script restores rumination against `.voidbot/private/void-self-state.cc` without reviving the legacy projection path. The prompt lives in `prompts/void-moderator-rumination.md`; treat that file as a sensitive behavior surface, not incidental script text.
- 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`.
@ -92,7 +92,7 @@ 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: rebuild the scheduled moderation phase machine against typed `.cc` documents, then rebuild memory maintenance/sleep as typed operations with the existing meaning-preservation gate.
- First bounded move after the current commit: harden the typed scheduled rumination phase machine, 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.

View file

@ -111,7 +111,7 @@ 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`
- 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.
- typed rumination runner. It builds a bounded context packet from `.voidbot/private/void-self-state.cc`, recent Discord chronology, and read-only repo activity; loads `prompts/void-moderator-rumination.md`; runs Codex rumination; applies returned typed operations through `scripts/void-self-state.mjs`; then records parent-owned cursor and speech receipts.
- `scripts/moderation-state-store.mjs`
- legacy moderation-state wrapper. It is not part of the active typed self-state path.
- `scripts/void-self-state.mjs`
@ -166,12 +166,16 @@ 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 Rebuild Stub
## Flow 5: Scheduled Moderation Rumination
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.
2. `scripts/run-void-moderator-rumination.ps1` reads `.voidbot/private/void-self-state.cc`, polls `node scripts/export-recent-discord-history.mjs`, and gathers read-only repo activity with `node scripts/export-recent-repo-activity.mjs --read-only`.
3. The runner writes a bounded context packet at `.voidbot/status/moderation-rumination-context.json`.
4. The runner loads `prompts/void-moderator-rumination.md`, substitutes the context/state/output paths, and sends that prompt to Codex.
5. Codex may use retrieval and analysis tools, but its durable state output is restricted to `.voidbot/status/moderation-rumination-operations.json`.
6. The parent runner applies those typed operations through `scripts/void-self-state.mjs`, then records reviewed-message cursor and any speech receipt itself.
7. The runner writes `.voidbot/status/moderation-rumination.json` and `.voidbot/logs/moderation-rumination.log`.
8. It intentionally does not materialize `.json`, load `.msgpack`, read the legacy moderation monolith, or let the child edit state directly.
## Flow 6: Mood Rebuild Stub

View file

@ -158,7 +158,7 @@ The runner can hand these to a CLI/MCP tool. The store decides what survives.
- 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
- the scheduled moderation runner has a typed rumination contract again: bounded context in, reviewed prompt template, typed operation payloads out, parent-owned cursor/receipt recording
- 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 implementation in the active runner, so it remains offline until rebuilt
@ -203,7 +203,7 @@ Verdict: stop feature work and rebuild this foundation. The rest of the machine
### Commit 6: Delete JSON Projection Authority
- 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/run-void-moderator-rumination.ps1` restores rumination through `prompts/void-moderator-rumination.md` and typed operation output; it 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.
@ -213,9 +213,9 @@ Verdict: stop feature work and rebuild this foundation. The rest of the machine
- 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
### Commit 7: Harden Scheduled Runner As A Phase Machine
- Replace the cursor-only moderation stub with explicit phases:
- Continue hardening the typed rumination runner's explicit phases:
- poll chronology
- read typed state summary
- collect evidence from Discord/source/lore only when a phase asks for it

View file

@ -0,0 +1,64 @@
# Void Moderator Rumination
Perform one scheduled Void rumination pass in this workspace.
## Required Reading
- `{{CONTEXT_PATH}}`
- `config/moderation-review-agent.md`
- `config/discord-server-rules.md`
- `styles/void-default.md`
## State Boundary
- The canonical private self-state is `{{STATE_FILE_PATH}}`.
- The private self-state is a typed CultCache `.cc` store.
- Do not read or write `.voidbot/private/moderation-agent-state.json`.
- Do not read or write `.voidbot/private/moderation-agent-state.msgpack`.
- Do not edit tracked repo files.
- Do not mutate self-state directly.
- Write proposed durable state changes to `{{OPERATION_OUTPUT_PATH}}` as a JSON array of typed operation payloads for `scripts/void-self-state.mjs apply-operation`.
## Rumination Phases
1. Read the typed summary, recent chronology, open cases, candidate interventions, incubation, sleep/speaking pressure, and repo activity from the context file.
2. If a direct room obligation exists, decide whether it needs an open-case operation, a close-case operation, or a candidate intervention.
3. If the room is quiet, ruminate on a concrete seam from typed memory, recent repo activity, archived Discord history, indexed source, or lore.
4. Use VoidBot MCP retrieval tools when a claim depends on Discord history, indexed repos, or lore.
5. Preserve meaning. Any memory operation must include a target, a claim or question, a tension, an action implication, and evidence refs unless it explicitly includes the tag `evidence:missing`.
6. Queue candidate interventions only when the thought has a plausible future speech path. Keep drafts concise and room-safe.
7. If speaking is warranted, use `scripts/send-discord-message.ps1` or `scripts/send-discord-message.mjs`. If `{{NO_POST}}` is true, do not send; queue a candidate instead.
8. Write `{{OPERATION_OUTPUT_PATH}}`. If nothing deserves persistence, write `[]`.
## Allowed Operations
- `upsert_open_case`
- `close_open_case`
- `append_distilled_memory`
- `merge_incubation_support`
- `queue_candidate_intervention`
- `retire_candidate_intervention`
- `propose_memory_distillation`
- `apply_memory_distillation`
## Parent-Owned Operations
Do not emit these operations from rumination:
- `record_reviewed_messages`
- `record_delivery_receipt`
- `update_sleep_cycle`
- `update_speaking_pressure`
The parent runner owns cursor and receipt recording. Mood maintenance owns sleep and speaking-pressure updates.
## Test Constraint
When `{{NO_POST}}` is true:
- Do not send Discord messages or DMs.
- You may still use read-only retrieval and write operation proposals.
## Completion
At the end, print a short run summary.

View file

@ -39,6 +39,7 @@ function main() {
canonicalStatePath,
repos,
generatedAt,
readOnly: options.readOnly,
})
: { mode: "stateless", updated: false, repoCount: 0 };
@ -72,6 +73,7 @@ function parseArgs(args) {
repoNames: undefined,
statePath: defaultModerationStatePath,
cursorFile: undefined,
readOnly: false,
};
for (let index = 0; index < args.length; index += 1) {
@ -102,6 +104,9 @@ function parseArgs(args) {
options.statePath = null;
options.cursorFile = null;
break;
case "--read-only":
options.readOnly = true;
break;
default:
throw new Error(`Unknown argument: ${argument}`);
}
@ -525,10 +530,18 @@ function readRepoActivityCursorFromCanonicalState(canonicalStatePath) {
return lookup;
}
function writeRepoActivityCursor({ canonicalStatePath, repos, generatedAt }) {
function writeRepoActivityCursor({ canonicalStatePath, repos, generatedAt, readOnly }) {
let updated = false;
let repoCount = 0;
if (readOnly) {
return {
mode: "incremental_read_only",
updated: false,
repoCount: repos.filter((repo) => repo.status === "ok" && repo.recentCommitCount > 0).length,
};
}
for (const repo of repos) {
if (repo.status !== "ok" || !repo.latestCommit?.hash || repo.recentCommitCount <= 0) {
continue;

View file

@ -1,5 +1,6 @@
param(
[switch] $NoPost
[switch] $NoPost,
[switch] $SkipModel
)
Set-StrictMode -Version Latest
@ -14,8 +15,14 @@ $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"
$contextPath = Join-Path $statusDir "moderation-rumination-context.json"
$lockPath = Join-Path $statusDir "moderation-rumination.lock"
$promptTemplatePath = Join-Path $repoRoot "prompts\void-moderator-rumination.md"
$recentHistoryScriptPath = Join-Path $repoRoot "scripts\export-recent-discord-history.mjs"
$repoActivityScriptPath = Join-Path $repoRoot "scripts\export-recent-repo-activity.mjs"
$selfStateScriptPath = Join-Path $repoRoot "scripts\void-self-state.mjs"
$startedAtUtc = [DateTime]::UtcNow
@ -32,11 +39,42 @@ function Write-JsonFile {
New-Item -ItemType Directory -Force -Path $directory | Out-Null
}
$json = $Data | ConvertTo-Json -Depth 12
$json = if ($Data -is [System.Array] -and $Data.Count -eq 0) {
"[]"
} else {
$Data | ConvertTo-Json -Depth 32
}
$utf8NoBom = [System.Text.UTF8Encoding]::new($false)
[System.IO.File]::WriteAllText($Path, $json, $utf8NoBom)
}
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 Read-TextFile {
param(
[Parameter(Mandatory = $true)]
[string] $Path
)
return Get-Content -Path $Path -Raw -Encoding UTF8
}
function Append-RunLog {
param(
[Parameter(Mandatory = $true)]
@ -47,6 +85,124 @@ function Append-RunLog {
Add-Content -Path $summaryLogPath -Value $timestamped -Encoding UTF8
}
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) {
$trimmed = $line.Trim()
if ($trimmed.Length -eq 0 -or $trimmed.StartsWith("#")) {
continue
}
$separator = $trimmed.IndexOf("=")
if ($separator -lt 0) {
continue
}
$key = $trimmed.Substring(0, $separator).Trim()
$value = $trimmed.Substring($separator + 1).Trim()
if ($value.Length -ge 2 -and (($value.StartsWith('"') -and $value.EndsWith('"')) -or ($value.StartsWith("'") -and $value.EndsWith("'")))) {
$value = $value.Substring(1, $value.Length - 2)
}
$values[$key] = $value
}
return $values
}
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)]
@ -63,21 +219,22 @@ function Invoke-NodeJson {
return $output | ConvertFrom-Json
}
function Get-TypedModerationCursor {
function Get-TypedSelfState {
$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); });
Promise.all([
core.loadVoidSelfStateTypedDocuments({ canonicalPath: process.argv[1] }),
core.loadVoidSelfState(process.argv[1]),
]).then(([typedState, context]) => {
console.log(JSON.stringify({
typedState,
summary: context?.summary ?? ''
}));
}).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."
throw "Failed to read typed self-state."
}
return $output | ConvertFrom-Json
}
@ -85,16 +242,128 @@ core.loadVoidSelfStateTypedDocuments({ canonicalPath: process.argv[1] })
function Apply-TypedOperation {
param(
[Parameter(Mandatory = $true)]
[hashtable] $Operation
$Operation
)
$operationJson = $Operation | ConvertTo-Json -Compress -Depth 20
[void](Invoke-NodeJson -Arguments @(
$operationJson = $Operation | ConvertTo-Json -Compress -Depth 32
return Invoke-NodeJson -Arguments @(
$selfStateScriptPath,
"apply-operation",
"--canonical", $stateFilePath,
"--operation", $operationJson
))
)
}
function Convert-ToOperationArray {
param($Value)
if ($null -eq $Value) {
return @()
}
if ($Value -is [System.Array]) {
return @($Value)
}
return @($Value)
}
function Get-ObjectPropertyString {
param(
$Value,
[Parameter(Mandatory = $true)]
[string] $Name
)
if ($null -eq $Value) {
return $null
}
$property = $Value.PSObject.Properties[$Name]
if ($null -eq $property -or $null -eq $property.Value) {
return $null
}
$text = [string]$property.Value
if ([string]::IsNullOrWhiteSpace($text)) {
return $null
}
return $text
}
function Convert-LastSpeechToReceiptOperation {
param($Speech)
$sentAt = Get-ObjectPropertyString -Value $Speech -Name "sentAt"
if ($null -eq $Speech -or $null -eq $sentAt) {
return $null
}
$receiptKeyParts = @(
"speech",
$sentAt,
(Get-ObjectPropertyString -Value $Speech -Name "channelId"),
(Get-ObjectPropertyString -Value $Speech -Name "replyToMessageId"),
(Get-ObjectPropertyString -Value $Speech -Name "preview")
)
$receiptKey = ($receiptKeyParts -join "|").ToLowerInvariant() -replace '[^a-z0-9]+', '-'
$receiptKey = $receiptKey.Trim("-")
if ([string]::IsNullOrWhiteSpace($receiptKey)) {
$receiptKey = "speech-" + ([Guid]::NewGuid().ToString("n"))
}
$receipt = @{
receiptKey = $receiptKey.Substring(0, [Math]::Min(96, $receiptKey.Length))
sentAt = $sentAt
mode = if (Get-ObjectPropertyString -Value $Speech -Name "mode") { Get-ObjectPropertyString -Value $Speech -Name "mode" } else { "channel" }
transport = if (Get-ObjectPropertyString -Value $Speech -Name "transport") { Get-ObjectPropertyString -Value $Speech -Name "transport" } else { "bot" }
}
foreach ($key in @("channelId", "replyToMessageId", "personaName", "personaAvatarUrl", "preview", "previewHash")) {
$propertyValue = Get-ObjectPropertyString -Value $Speech -Name $key
if ($null -ne $propertyValue) {
$receipt[$key] = $propertyValue
}
}
foreach ($key in @("contentLength", "chunkCount")) {
$property = if ($null -ne $Speech) { $Speech.PSObject.Properties[$key] } else { $null }
if ($null -ne $property -and $null -ne $property.Value) {
$receipt[$key] = [int]$property.Value
}
}
return @{
operation = "record_delivery_receipt"
receipt = $receipt
}
}
function Select-RuminationRepoActivity {
param($RepoActivity)
if ($null -eq $RepoActivity) {
return $null
}
$reposProperty = $RepoActivity.PSObject.Properties["repos"]
$repos = if ($null -ne $reposProperty -and $null -ne $reposProperty.Value) { @($reposProperty.Value) } else { @() }
$freshRepos = @(
$repos |
Where-Object {
$recent = $_.PSObject.Properties["recentCommitCount"]
$status = $_.PSObject.Properties["status"]
$null -ne $recent -and $null -ne $status -and [string]$status.Value -eq "ok" -and [int]$recent.Value -gt 0
} |
Select-Object -First 8
)
return @{
generatedAt = Get-ObjectPropertyString -Value $RepoActivity -Name "generatedAt"
cursorMode = Get-ObjectPropertyString -Value $RepoActivity -Name "cursorMode"
digest = Get-ObjectPropertyString -Value $RepoActivity -Name "digest"
freshRepos = $freshRepos
}
}
trap {
@ -108,7 +377,11 @@ trap {
durationSeconds = [Math]::Round(($finishedAtUtc - $startedAtUtc).TotalSeconds, 2)
failureMessage = $failureMessage
noPost = [bool]$NoPost
skipModel = [bool]$SkipModel
stateFile = $stateFilePath
contextPath = $contextPath
operationOutputPath = $operationOutputPath
tracePath = $tracePath
}
Remove-Item -Path $lockPath -Force -ErrorAction SilentlyContinue
@ -136,17 +409,33 @@ Write-JsonFile -Path $lockPath -Data @{
startedAt = $startedAtUtc.ToString("o")
}
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"
if (Test-Path $operationOutputPath) {
Remove-Item -LiteralPath $operationOutputPath -Force
}
$priorCursor = Get-TypedModerationCursor
foreach ($requiredPath in @($recentHistoryScriptPath, $repoActivityScriptPath, $selfStateScriptPath)) {
if (-not (Test-Path $requiredPath)) {
throw "Missing required helper at $requiredPath"
}
}
if (-not (Test-Path $promptTemplatePath)) {
throw "Missing rumination prompt template at $promptTemplatePath"
}
$envValues = Read-DotEnv -Path (Join-Path $repoRoot ".env")
$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 { @() }
$typedContext = Get-TypedSelfState
$typedState = $typedContext.typedState
$priorCursor = $typedState.moderationCursor
$historyArgs = @($recentHistoryScriptPath)
if ($null -ne $priorCursor -and -not [string]::IsNullOrWhiteSpace([string]$priorCursor.lastReviewedTimestamp)) {
$historyArgs += @("--after", [string]$priorCursor.lastReviewedTimestamp, "--limit", "120")
$priorCursorTimestamp = Get-ObjectPropertyString -Value $priorCursor -Name "lastReviewedTimestamp"
if ($null -ne $priorCursor -and $null -ne $priorCursorTimestamp) {
$historyArgs += @("--after", $priorCursorTimestamp, "--limit", "120")
} else {
$historyArgs += @("--hours", "6", "--limit", "120")
}
@ -154,44 +443,182 @@ if ($null -ne $priorCursor -and -not [string]::IsNullOrWhiteSpace([string]$prior
$history = Invoke-NodeJson -Arguments $historyArgs
$observedCursor = $priorCursor
$messageCount = 0
if ($null -ne $history.messages) {
$messageCount = $history.messages.Count
$historyMessagesProperty = if ($null -ne $history) { $history.PSObject.Properties["messages"] } else { $null }
if ($null -ne $historyMessagesProperty -and $null -ne $historyMessagesProperty.Value) {
$messageCount = $historyMessagesProperty.Value.Count
}
if ($messageCount -gt 0) {
$latestObservedMessage = $history.messages[$messageCount - 1]
$latestObservedMessage = $historyMessagesProperty.Value[$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
}
lastReviewedMessageId = Get-ObjectPropertyString -Value $latestObservedMessage -Name "id"
lastReviewedTimestamp = Get-ObjectPropertyString -Value $latestObservedMessage -Name "timestamp"
}
}
$finishedAtUtc = [DateTime]::UtcNow
$repoActivity = $null
try {
$repoActivity = Invoke-NodeJson -Arguments @(
$repoActivityScriptPath,
"--hours", "96",
"--max-commits", "3",
"--read-only",
"--state-path", $stateFilePath
)
} catch {
$repoActivity = @{
status = "failed"
error = $_.Exception.Message
}
}
Write-JsonFile -Path $contextPath -Data @{
generatedAt = [DateTime]::UtcNow.ToString("o")
stateFile = $stateFilePath
noPost = [bool]$NoPost
selfStateSummary = $typedContext.summary
openCases = $typedState.moderationCursor.openCases
speechReceipts = $typedState.speechReceipts.recentReceipts
memories = $typedState.thoughtMemory.memories
incubation = $typedState.thoughtMemory.incubation
candidateInterventions = $typedState.candidateInterventions.interventions
scheduledRuntime = $typedState.scheduledRuntime
priorCursor = @{
lastReviewedMessageId = Get-ObjectPropertyString -Value $priorCursor -Name "lastReviewedMessageId"
lastReviewedTimestamp = Get-ObjectPropertyString -Value $priorCursor -Name "lastReviewedTimestamp"
}
observedCursor = @{
lastReviewedMessageId = Get-ObjectPropertyString -Value $observedCursor -Name "lastReviewedMessageId"
lastReviewedTimestamp = Get-ObjectPropertyString -Value $observedCursor -Name "lastReviewedTimestamp"
}
recentHistory = $history
repoActivity = Select-RuminationRepoActivity -RepoActivity $repoActivity
}
$stateWriteBefore = if (Test-Path $stateFilePath) { (Get-Item $stateFilePath).LastWriteTimeUtc } else { [DateTime]::MinValue }
$prompt = Read-TextFile -Path $promptTemplatePath
$prompt = $prompt.Replace("{{CONTEXT_PATH}}", $contextPath)
$prompt = $prompt.Replace("{{STATE_FILE_PATH}}", $stateFilePath)
$prompt = $prompt.Replace("{{OPERATION_OUTPUT_PATH}}", $operationOutputPath)
$prompt = $prompt.Replace("{{NO_POST}}", ([bool]$NoPost).ToString().ToLowerInvariant())
$exitCode = 0
$failureMessage = $null
$combinedText = ""
Write-JsonFile -Path $statusPath -Data @{
status = if ($SkipModel) { "running_skip_model" } else { "running" }
startedAt = $startedAtUtc.ToString("o")
noPost = [bool]$NoPost
skipModel = [bool]$SkipModel
stateFile = $stateFilePath
contextPath = $contextPath
operationOutputPath = $operationOutputPath
codexExecutable = $codexExecutable
codexModel = $codexModel
tracePath = $tracePath
}
if ($SkipModel) {
Append-RunLog "skip-model: writing empty operation proposal."
Write-JsonFile -Path $operationOutputPath -Data @()
$combinedText = "Skipped model rumination by explicit -SkipModel smoke mode."
} else {
$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,
"-"
)
$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
}
if ($exitCode -ne 0) {
$failureMessage = if ([string]::IsNullOrWhiteSpace($combinedText)) { "Codex rumination failed with exit code $exitCode." } else { $combinedText }
throw $failureMessage
}
if (-not (Test-Path $operationOutputPath)) {
throw "Rumination completed without writing operation output at $operationOutputPath."
}
Append-RunLog "reading proposed operation output."
$proposedOperations = @(Convert-ToOperationArray -Value (Read-JsonFile -Path $operationOutputPath))
$appliedOperations = @()
Append-RunLog ("applying proposed operations: {0}" -f @($proposedOperations).Count)
foreach ($operation in $proposedOperations) {
$operationName = Get-ObjectPropertyString -Value $operation -Name "operation"
if ($null -eq $operation -or $null -eq $operationName) {
continue
}
$appliedOperations += Apply-TypedOperation -Operation $operation
}
$observedCursorMessageId = Get-ObjectPropertyString -Value $observedCursor -Name "lastReviewedMessageId"
$observedCursorTimestamp = Get-ObjectPropertyString -Value $observedCursor -Name "lastReviewedTimestamp"
if (
$messageCount -gt 0 -and
$null -ne $observedCursorMessageId -and
$null -ne $observedCursorTimestamp
) {
Append-RunLog "recording reviewed message cursor."
$appliedOperations += Apply-TypedOperation -Operation @{
operation = "record_reviewed_messages"
lastReviewedMessageId = $observedCursorMessageId
lastReviewedTimestamp = $observedCursorTimestamp
}
}
$lastSpeechPath = Join-Path $statusDir "void-last-speech.json"
if ((-not $NoPost) -and (Test-Path $lastSpeechPath)) {
$speech = Read-JsonFile -Path $lastSpeechPath
$receiptOperation = Convert-LastSpeechToReceiptOperation -Speech $speech
if ($null -ne $receiptOperation) {
$appliedOperations += Apply-TypedOperation -Operation $receiptOperation
}
}
Append-RunLog "writing final rumination status."
$finishedAtUtc = [DateTime]::UtcNow
Append-RunLog "final status timestamp captured."
$lastMessage = if (Test-Path $lastMessagePath) { Get-Content -Path $lastMessagePath -Raw -Encoding UTF8 } else { "" }
Append-RunLog "final status last message loaded."
$finalStatus = [ordered]@{
status = "ok"
mode = "typed_cursor_only"
mode = if ($SkipModel) { "typed_rumination_skip_model" } else { "typed_rumination" }
startedAt = $startedAtUtc.ToString("o")
finishedAt = $finishedAtUtc.ToString("o")
durationSeconds = [Math]::Round(($finishedAtUtc - $startedAtUtc).TotalSeconds, 2)
exitCode = [int]$exitCode
noPost = [bool]$NoPost
stateFile = $stateFilePath
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."
skipModel = [bool]$SkipModel
stateFile = [string]$stateFilePath
contextPath = [string]$contextPath
operationOutputPath = [string]$operationOutputPath
observedMessageCount = [int]$messageCount
previousCursorTimestamp = [string](Get-ObjectPropertyString -Value $priorCursor -Name "lastReviewedTimestamp")
observedCursorTimestamp = [string]$observedCursorTimestamp
proposedOperationCount = [int]@($proposedOperations).Count
appliedOperationCount = [int]@($appliedOperations).Count
stateUpdated = [bool](@($appliedOperations).Count -gt 0)
tracePath = [string]$tracePath
lastMessagePath = [string]$lastMessagePath
}
Write-JsonFile -Path $statusPath -Data $finalStatus
Append-RunLog ("mode=typed_cursor_only messages={0} cursor={1}" -f $messageCount, ([string]$observedCursor.lastReviewedTimestamp))
Append-RunLog ("mode=typed_rumination messages={0} proposed={1} applied={2} cursor={3}" -f $messageCount, @($proposedOperations).Count, @($appliedOperations).Count, $observedCursorTimestamp)
Remove-Item -Path $lockPath -Force -ErrorAction SilentlyContinue

View file

@ -104,3 +104,4 @@
{"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."}
{"ts":"2026-05-16T18:12:51Z","type":"implementation","status":"ok","note":"Restored scheduled moderation as typed rumination instead of cursor-only bookkeeping. The runner now loads prompts/void-moderator-rumination.md, builds a bounded typed context packet from .voidbot/private/void-self-state.cc, accepts only typed operation output, and leaves cursor/receipt writes parent-owned."}

View file

@ -57,7 +57,7 @@ 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 `.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.
- Keep the old moderation and mood scheduled tasks offline until their typed replacements are deliberately reinstalled; typed rumination exists as a direct runner again, but not as an enabled legacy task.
- 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.
@ -129,7 +129,7 @@ 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`.
- 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 old `Void Moderator Rumination` and `Void Mood Drift` scheduled tasks are disabled. Their replacement entry scripts are typed-only: moderation now builds a bounded context packet, runs the reviewed rumination prompt from `prompts/void-moderator-rumination.md`, and applies typed operation payloads; 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.
@ -150,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 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.
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 moderation replacement has real rumination again through a reviewed prompt file plus typed operation output.
next_action: Harden the scheduled moderation phase machine and rebuild the 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.