Rebuild self-state runners on typed store

This commit is contained in:
Meta Vens 2026-05-16 18:43:53 +01:00
commit a10e7e9171
12 changed files with 448 additions and 2518 deletions

View file

@ -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;
}

View file

@ -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 <timestamp-or-now> --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."
}

View file

@ -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();