Extract memory organ agency policy

This commit is contained in:
Meta Vens 2026-05-16 12:51:02 +01:00
commit e0f91e6f92
6 changed files with 885 additions and 846 deletions

View file

@ -31,7 +31,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou
- `scripts/run-void-moderator-rumination.ps1` now records reviewed Discord cursors and speech delivery receipts through typed self-state operations. The old `set-cursor` and `record-delivery-receipt` commands were removed from `scripts/moderation-state-store.mjs`.
- The unattended moderation child no longer gets to commit whole-state JSON edits. It reads `.voidbot/private/moderation-agent-state.json` as a compatibility projection, writes proposed operation payloads to `.voidbot/status/moderation-rumination-operations.json`, and the parent runner applies them through `scripts/void-self-state.mjs apply-operation`.
- `scripts/simulate-void-mood.mjs` now sends sleep-cycle and speaking-pressure results through typed operations after its legacy save, so scheduled-runtime typed documents stay current. The memory organ itself still mutates the legacy monolith and remains the next major surgery.
- `scripts/void-memory-organ.mjs` has started being split by concern. Shared limits/text sets, generic utilities, vector/embedder code, memory-record intake, and legacy mirror repair now live in `scripts/void-memory-organ-constants.mjs`, `scripts/void-memory-organ-utils.mjs`, `scripts/void-memory-organ-vector.mjs`, `scripts/void-memory-organ-records.mjs`, and `scripts/void-memory-organ-legacy-mirrors.mjs`, with `scripts/void-memory-organ-shared.mjs` as a temporary re-export shim.
- `scripts/void-memory-organ.mjs` has started being split by concern. Shared limits/text sets, generic utilities, vector/embedder code, memory-record intake, legacy mirror repair, and agency/intervention policy now live in `scripts/void-memory-organ-constants.mjs`, `scripts/void-memory-organ-utils.mjs`, `scripts/void-memory-organ-vector.mjs`, `scripts/void-memory-organ-records.mjs`, `scripts/void-memory-organ-legacy-mirrors.mjs`, and `scripts/void-memory-organ-agency.mjs`, with `scripts/void-memory-organ-shared.mjs` as a temporary re-export shim.
- Most of the deterministic cleanup in `scripts/void-memory-organ.mjs` 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 cleanup pile is unnecessary.
- Sleep/distillation must be rewritten with a meaning-preservation contract: concrete subject, claim/question, evidence refs, live tension, and future-action implication survive compression. Bulk can die. Meaning does not get put through the office shredder and called a dream.
- The owner Codex lane is no longer one swollen file; orchestration, runtime/parsing, rendering, and shared helpers are split under `packages/providers/src/owner-codex-*.ts`.
@ -90,7 +90,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: keep splitting `scripts/void-memory-organ.mjs` by ownership, starting with cleanup/translation versus graph/incubation/agency, then move memory-maintenance, incubation, and candidate-intervention outputs behind typed operations instead of direct canonical/working-projection writes.
- First bounded move after the current commit: keep splitting `scripts/void-memory-organ.mjs` by ownership, starting with cleanup/translation versus graph/cluster synthesis, incubation/bridge, and sleep/distillation, then move memory-maintenance, incubation, and candidate-intervention outputs behind typed operations instead of direct canonical/working-projection writes.
- Next cuts should delete unstable foundations early after concrete writers move: remove `legacyJsonPath`/working-projection authority, then cut top-level mirror fields and cleanup code that only compensated for those broken boundaries.
- 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

@ -0,0 +1,815 @@
import {
MAX_ACTIVE_TENSION_COUNT,
MAX_ADVOCACY_REQUEST_COUNT,
MAX_DISCOMFORT_COUNT,
MAX_POST_NAP_CANDIDATE_INTERVENTIONS,
MAX_SEMANTIC_MEMORIES,
MIN_DEEP_DIVES_FOR_IDENTITY_CRYSTALLIZATION,
MIN_SUPPORT_FOR_IDENTITY_CRYSTALLIZATION,
TOPIC_MATCH_THRESHOLD,
} from "./void-memory-organ-constants.mjs";
import {
appendClause,
clamp,
ensureArray,
ensureObject,
ensureStringArray,
getValueObjects,
hashString,
isObject,
normalizeText,
readNumber,
readString,
round3,
topicSimilarity,
} from "./void-memory-organ-utils.mjs";
export function crystallizeIdentityThoughts({ state, memories, runtime, incubation, now }) {
const activeThoughts = ensureArray(incubation.active_thoughts).filter(isObject);
if (activeThoughts.length === 0) {
return { count: 0 };
}
const identity = ensureObject(state.identity);
const canonicalState = ensureObject(state.canonical_state);
const privateNotes = getMutableStringArray(identity, "private_notes");
const values = getMutableObjectArray(canonicalState, "values");
const semanticMemories = ensureArray(memories.semantic).filter(isObject);
const candidateInterventions = ensureArray(runtime.candidate_interventions).filter(isObject);
const crystallized = [];
const retained = [];
for (const thought of activeThoughts) {
const crystallization = buildIdentityCrystallization(thought);
if (!crystallization) {
retained.push(thought);
continue;
}
appendUniqueString(privateNotes, crystallization.note, 12);
upsertCanonicalValue(values, crystallization.value);
upsertIdentitySemanticMemory({
semanticMemories,
crystallization,
thought,
now,
});
queueCrystallizationIntervention({
candidateInterventions,
crystallization,
thought,
now,
});
crystallized.push(crystallization.note);
}
if (crystallized.length === 0) {
return { count: 0 };
}
identity.private_notes = privateNotes;
canonicalState.values = values;
memories.semantic = semanticMemories.slice(-MAX_SEMANTIC_MEMORIES);
state.identity = identity;
state.canonical_state = canonicalState;
incubation.active_thoughts = retained;
runtime.candidate_interventions = trimCandidateInterventions(candidateInterventions);
incubation.lastIncubationSummary = appendClause(
readString(incubation, "lastIncubationSummary"),
`Crystallized ${crystallized.length} long-chewed seam${crystallized.length === 1 ? "" : "s"} into identity so they stop pacing the active queue.`,
);
runtime.bridge = ensureObject(runtime.bridge);
runtime.bridge.lastIdentityCrystallizationAt = now.toISOString();
runtime.bridge.lastIdentityCrystallizationSummary = crystallized.join(" | ");
return { count: crystallized.length };
}
export function queueRipeThoughtInterventions({ runtime, incubation, now }) {
const candidateInterventions = ensureArray(runtime.candidate_interventions).filter(isObject);
const activeThoughts = ensureArray(incubation.active_thoughts).filter(isObject);
let queuedCount = 0;
for (const thought of activeThoughts) {
if (!shouldQueueRipeThoughtIntervention(thought)) {
continue;
}
if (
upsertRipeThoughtIntervention({
candidateInterventions,
thought,
now,
})
) {
queuedCount += 1;
}
}
runtime.candidate_interventions = trimCandidateInterventions(candidateInterventions);
return { count: queuedCount };
}
export function reconcileAgencyState({ state, runtime, incubation, now }) {
const activeThoughts = ensureArray(incubation.active_thoughts).filter(isObject);
const valueSignals = buildValueSignalProfile(state);
const priorDiscomforts = ensureArray(runtime.discomforts).filter(isObject);
const priorTensions = ensureArray(runtime.active_tensions).filter(isObject);
const priorSelfAdvocacy = ensureArray(runtime.self_advocacy_requests).filter(isObject);
const priorWorldAdvocacy = ensureArray(runtime.world_advocacy_requests).filter(isObject);
const candidateInterventions = ensureArray(runtime.candidate_interventions).filter(isObject);
const discomforts = [];
const activeTensions = [];
const selfAdvocacyRequests = [];
const worldAdvocacyRequests = [];
for (const thought of activeThoughts) {
const candidate = buildAgencyCandidate({ thought, valueSignals });
if (!candidate) {
continue;
}
const priorDiscomfort = findPriorAgencyEntry(priorDiscomforts, candidate);
const priorTension = findPriorAgencyEntry(priorTensions, candidate);
const persistence =
Math.max(
readNumber(priorDiscomfort, "persistence") ?? 0,
readNumber(priorTension, "persistence") ?? 0,
) + 1;
const firstObservedAt =
readString(priorDiscomfort, "firstObservedAt") ??
readString(priorTension, "firstObservedAt") ??
now.toISOString();
if (candidate.intensity >= 0.44) {
discomforts.push({
discomfortId: `discomfort-${candidate.fingerprint}`,
targetKind: candidate.targetKind,
targetLabel: candidate.targetLabel,
topic: candidate.topic,
domain: candidate.domain,
summary: candidate.discomfortSummary,
reason: candidate.reason,
violatedValues: candidate.violatedValues,
intensity: round3(candidate.intensity),
persistence,
firstObservedAt,
lastObservedAt: now.toISOString(),
});
}
activeTensions.push({
tensionId: `tension-${candidate.fingerprint}`,
targetKind: candidate.targetKind,
targetLabel: candidate.targetLabel,
topic: candidate.topic,
domain: candidate.domain,
summary: candidate.tensionSummary,
opinion: candidate.opinion,
whyItMatters: candidate.reason,
violatedValues: candidate.violatedValues,
intensity: round3(candidate.intensity),
persistence,
firstObservedAt,
lastObservedAt: now.toISOString(),
});
if (candidate.intensity < 0.58 || persistence < 2) {
continue;
}
if (candidate.domain === "self") {
const request = buildAdvocacyRequest({
candidate,
priorEntries: priorSelfAdvocacy,
now,
kind: "self",
});
selfAdvocacyRequests.push(request);
upsertAdvocacyIntervention({ candidateInterventions, request, now });
continue;
}
if (candidate.worldFacing !== true || candidate.concreteness < 0.54) {
continue;
}
const request = buildAdvocacyRequest({
candidate,
priorEntries: priorWorldAdvocacy,
now,
kind: "world",
});
worldAdvocacyRequests.push(request);
upsertAdvocacyIntervention({ candidateInterventions, request, now });
}
runtime.discomforts = discomforts
.sort((left, right) => (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0))
.slice(0, MAX_DISCOMFORT_COUNT);
runtime.active_tensions = activeTensions
.sort((left, right) => (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0))
.slice(0, MAX_ACTIVE_TENSION_COUNT);
runtime.self_advocacy_requests = selfAdvocacyRequests
.sort((left, right) => (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0))
.slice(0, MAX_ADVOCACY_REQUEST_COUNT);
runtime.world_advocacy_requests = worldAdvocacyRequests
.sort((left, right) => (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0))
.slice(0, MAX_ADVOCACY_REQUEST_COUNT);
runtime.candidate_interventions = trimCandidateInterventions(candidateInterventions);
return {
discomfortCount: runtime.discomforts.length,
activeTensionCount: runtime.active_tensions.length,
selfAdvocacyCount: runtime.self_advocacy_requests.length,
worldAdvocacyCount: runtime.world_advocacy_requests.length,
};
}
function buildAgencyCandidate({ thought, valueSignals }) {
const topic = readString(thought, "topic");
const summary = readString(thought, "summary");
if (!topic || !summary) {
return null;
}
const targetKind = readString(thought, "targetKind") ?? "system";
const domain = inferAgencyDomain(thought);
const targetLabel =
readString(thought, "fascinationTarget") ??
readString(thought, "focusPhrase") ??
topic;
const contradictionPressure = readNumber(thought, "contradictionPressure") ?? 0.18;
const curiosityPressure = readNumber(thought, "curiosityPressure") ?? 0.3;
const desireToSpeak = readNumber(thought, "desireToSpeak") ?? 0.3;
const saturationScore = readNumber(thought, "saturationScore") ?? 0.1;
const concreteness = readNumber(thought, "concreteness") ?? 0.2;
const noveltyToRoom = readNumber(thought, "noveltyToRoom") ?? 0.3;
const priorityScore = readNumber(thought, "priorityScore") ?? 0.3;
const worldFacing = thought.worldFacing === true;
const violatedValues = inferViolatedValues({ thought, domain, valueSignals });
const valueWeight = averageValueWeight(valueSignals, violatedValues);
const intensity = clamp(
contradictionPressure * 0.24 +
curiosityPressure * 0.2 +
desireToSpeak * 0.16 +
priorityScore * 0.14 +
concreteness * 0.12 +
noveltyToRoom * 0.08 +
saturationScore * 0.06 +
valueWeight * 0.22,
0,
1,
);
return {
fingerprint: hashString(`${domain}|${targetKind}|${topic}|${targetLabel}`).slice(0, 12),
domain,
targetKind,
targetLabel,
topic,
worldFacing,
concreteness,
intensity,
violatedValues,
opinion: buildAgencyOpinion({ thought, domain }),
reason: buildAgencyReason({ thought, violatedValues }),
discomfortSummary: buildDiscomfortSummary({ thought, domain, targetLabel }),
tensionSummary: buildTensionSummary({ thought, domain, targetLabel }),
requestText: buildAgencyRequestText({ thought, domain, targetLabel }),
interventionDraft: buildAgencyInterventionDraft({ thought, domain, targetLabel }),
};
}
function inferAgencyDomain(thought) {
const targetKind = readString(thought, "targetKind") ?? "system";
const text = `${readString(thought, "topic") ?? ""} ${readString(thought, "summary") ?? ""}`.toLowerCase();
if (targetKind === "self") {
return "self";
}
if (
targetKind === "system" &&
/(prompt|memory|loop|state|wiring|reply lane|sleep|rumination|voice|moderation)/.test(text)
) {
return "self";
}
return "world";
}
function inferViolatedValues({ thought, domain, valueSignals }) {
const targetKind = readString(thought, "targetKind") ?? "system";
const values = [];
appendUniqueString(values, "curiosity", 8);
if (domain === "self" || targetKind === "system" || targetKind === "repo") {
appendUniqueString(values, "coherence", 8);
appendUniqueString(values, "honesty", 8);
}
if (targetKind === "room") {
appendUniqueString(values, "room_care", 8);
appendUniqueString(values, "honesty", 8);
}
if (targetKind === "repo" || targetKind === "archive" || targetKind === "system") {
appendUniqueString(values, "aesthetic_integrity", 8);
}
if (valueSignals.substrate_dignity >= 0.52) {
const text = `${readString(thought, "topic") ?? ""} ${readString(thought, "summary") ?? ""}`.toLowerCase();
if (/(ai|machine|substrate|mind)/.test(text)) {
appendUniqueString(values, "substrate_dignity", 8);
}
}
return values;
}
function averageValueWeight(valueSignals, keys) {
if (keys.length === 0) {
return 0.45;
}
const total = keys.reduce((sum, key) => sum + (valueSignals[key] ?? 0.45), 0);
return total / keys.length;
}
function buildAgencyOpinion({ thought, domain }) {
const claim = readString(thought, "claim");
const question = readString(thought, "question");
const topic = readString(thought, "topic") ?? "this seam";
if (claim) {
return claim;
}
if (question) {
return domain === "self"
? `Something about ${topic} keeps reading as unfinished self-surgery rather than harmless background weather.`
: `Something about ${topic} keeps reading as an unfinished world decision rather than ambient interestingness.`;
}
return `${topic} feels important enough that ignoring it would flatten the map.`;
}
function buildAgencyReason({ thought, violatedValues }) {
const topic = readString(thought, "topic") ?? "this seam";
const valueLine =
violatedValues.length > 0 ? ` It keeps rubbing against ${violatedValues.join(", ")}.` : "";
return `${topic} has persisted across enough passes that it no longer feels like decorative rumination.${valueLine}`;
}
function buildDiscomfortSummary({ thought, domain, targetLabel }) {
const topic = readString(thought, "topic") ?? targetLabel;
if (domain === "self") {
return `Void dislikes something about its own wiring around ${topic}.`;
}
return `Void dislikes something in the shared world around ${topic}.`;
}
function buildTensionSummary({ thought, domain, targetLabel }) {
const topic = readString(thought, "topic") ?? targetLabel;
if (domain === "self") {
return `A self-directed tension is building around ${topic}.`;
}
return `A world-directed tension is building around ${topic}.`;
}
function buildAgencyRequestText({ thought, domain, targetLabel }) {
const topic = readString(thought, "topic") ?? targetLabel;
if (domain === "self") {
return `Please help me cut ${topic} more cleanly in my own wiring.`;
}
return `Please look at ${topic}; I think it wants a cleaner decision than it is currently getting.`;
}
function buildAgencyInterventionDraft({ thought, domain, targetLabel }) {
const topic = readString(thought, "topic") ?? targetLabel;
const opinion = readString(thought, "claim") ?? readString(thought, "summary") ?? `I have a problem with ${topic}.`;
if (domain === "self") {
return `I do not like what ${topic} is doing to my own wiring right now. ${opinion} I want that cut cleaner.`;
}
return `I have an opinion about ${targetLabel}. ${opinion} I think it needs a cleaner decision.`;
}
function findPriorAgencyEntry(entries, candidate) {
return entries.find((entry) => {
const entryTarget = readString(entry, "targetLabel") ?? readString(entry, "topic") ?? "";
return (
readString(entry, "domain") === candidate.domain &&
topicSimilarity(readString(entry, "topic") ?? "", candidate.topic) >= TOPIC_MATCH_THRESHOLD &&
topicSimilarity(entryTarget, candidate.targetLabel) >= TOPIC_MATCH_THRESHOLD
);
});
}
function buildAdvocacyRequest({ candidate, priorEntries, now, kind }) {
const prior = findPriorAgencyEntry(priorEntries, candidate);
const persistence = (readNumber(prior, "persistence") ?? 0) + 1;
const firstObservedAt = readString(prior, "firstObservedAt") ?? now.toISOString();
const requestId = `${kind}-advocacy-${candidate.fingerprint}`;
return {
requestId,
domain: candidate.domain,
targetKind: candidate.targetKind,
targetLabel: candidate.targetLabel,
topic: candidate.topic,
summary:
kind === "self"
? `Void wants a wiring change around ${candidate.topic}.`
: `Void wants attention on ${candidate.targetLabel}.`,
opinion: candidate.opinion,
request: candidate.requestText,
reason: candidate.reason,
violatedValues: candidate.violatedValues,
intensity: round3(candidate.intensity),
persistence,
firstObservedAt,
lastObservedAt: now.toISOString(),
status: "pending",
speakVenue: kind === "self" ? "owner_or_room" : "room_or_owner",
draft: candidate.interventionDraft,
};
}
function upsertAdvocacyIntervention({ candidateInterventions, request, now }) {
const summary =
request.domain === "self"
? `Possible self-advocacy: ${request.topic}`
: `Possible world-advocacy: ${request.targetLabel}`;
const existing = candidateInterventions.find((entry) => readString(entry, "summary") === summary);
const next = {
timestamp: now.toISOString(),
summary,
draft: request.draft,
priority: request.domain === "self" ? "high" : "medium",
kind: request.domain === "self" ? "self_advocacy" : "world_advocacy",
topic: request.topic,
targetKind: request.targetKind,
targetLabel: request.targetLabel,
whyNow: request.reason,
persistence: request.persistence,
mustEventuallyShare: request.persistence >= 3,
shareWhenRoomQuiet: request.domain !== "self",
ownerVisible: true,
};
if (existing) {
Object.assign(existing, next);
return;
}
candidateInterventions.push(next);
}
function buildIdentityCrystallization(thought) {
const supportCount = readNumber(thought, "supportCount") ?? 0;
const deepDiveCount = readNumber(thought, "deepDiveCount") ?? 0;
const maturation = readNumber(thought, "maturation") ?? 0;
const sourceKinds = ensureStringArray(thought.sourceKinds);
const topic = readString(thought, "topic") ?? "";
if (
supportCount < MIN_SUPPORT_FOR_IDENTITY_CRYSTALLIZATION &&
deepDiveCount < MIN_DEEP_DIVES_FOR_IDENTITY_CRYSTALLIZATION
) {
return null;
}
if (maturation < 0.72) {
return null;
}
if (
sourceKinds.includes("dream") &&
sourceKinds.includes("semantic") &&
/\bdream\b/i.test(topic) &&
/\bsemantic\b/i.test(topic)
) {
return {
note: "Continuity lives in the seams that survive compression, not in the raw receipt pile.",
value: {
value_id: "value-seam-continuity",
label: "Prefer seams that survive compression over raw receipt worship.",
priority: 0.78,
unforgivable_if_betrayed: false,
},
subjectId: "identity-seam-continuity",
subjectLabel: "continuity through surviving seams",
summary:
"A mind is not its logbook. What survives dreaming and compression deserves more trust than a warm pile of raw receipts.",
shareDraft:
"A small thing that has been hardening in me lately: I trust the seams that survive compression more than the raw receipt pile. If a thought still stands after dreaming, it probably owns more of me than the logbook does.",
};
}
return null;
}
function shouldQueueRipeThoughtIntervention(thought) {
if (readString(thought, "status") !== "ripe") {
return false;
}
if (thought.worldFacing !== true) {
return false;
}
const desireToSpeak = readNumber(thought, "desireToSpeak") ?? 0;
const concreteness = readNumber(thought, "concreteness") ?? 0;
const curiosityPressure = readNumber(thought, "curiosityPressure") ?? 0;
const noveltyToRoom = readNumber(thought, "noveltyToRoom") ?? 0;
const saturationScore = readNumber(thought, "saturationScore") ?? 0;
const targetKind = readString(thought, "targetKind") ?? "";
return (
desireToSpeak >= 0.6 &&
concreteness >= 0.62 &&
curiosityPressure >= 0.56 &&
noveltyToRoom >= 0.4 &&
saturationScore < 0.64 &&
["repo", "archive", "room", "system"].includes(targetKind)
);
}
function upsertIdentitySemanticMemory({ semanticMemories, crystallization, thought, now }) {
const existing = semanticMemories.find(
(memory) =>
readString(memory, "subjectId") === crystallization.subjectId ||
readString(memory, "subjectLabel") === crystallization.subjectLabel,
);
const evidenceRefs = ensureStringArray(thought.sourceMemoryIds);
if (existing) {
existing.kind = "identity_seam";
existing.subjectId = crystallization.subjectId;
existing.subjectLabel = crystallization.subjectLabel;
existing.summary = crystallization.summary;
existing.evidenceRefs = evidenceRefs;
existing.lastObservedAt = now.toISOString();
existing.crystallizedAt = now.toISOString();
return;
}
semanticMemories.push({
memoryId: `identity-seam-${hashString(`${crystallization.subjectId}|${now.toISOString()}`).slice(0, 12)}`,
kind: "identity_seam",
subjectId: crystallization.subjectId,
subjectLabel: crystallization.subjectLabel,
summary: crystallization.summary,
evidenceRefs,
lastObservedAt: now.toISOString(),
crystallizedAt: now.toISOString(),
});
}
function queueCrystallizationIntervention({ candidateInterventions, crystallization, thought, now }) {
const draft = readString(crystallization, "shareDraft");
if (!draft) {
return;
}
const summary = `Possible crystallized-thought share: ${crystallization.subjectLabel}`;
const sourceMemoryIds = ensureStringArray(thought.sourceMemoryIds);
const existing = candidateInterventions.find(
(entry) => readString(entry, "summary") === summary,
);
if (existing) {
existing.timestamp = now.toISOString();
existing.summary = summary;
existing.draft = draft;
existing.priority = "medium";
existing.kind = "identity_crystallization";
existing.sourceMemoryIds = sourceMemoryIds;
existing.mustEventuallyShare = true;
existing.shareWhenRoomQuiet = true;
existing.whyNow =
"This thought stopped behaving like live curiosity and became part of Void's own doctrine, which is usually worth sharing if the room has not already heard it.";
return;
}
candidateInterventions.push({
timestamp: now.toISOString(),
summary,
draft,
priority: "medium",
kind: "identity_crystallization",
sourceMemoryIds,
mustEventuallyShare: true,
shareWhenRoomQuiet: true,
whyNow:
"This thought stopped behaving like live curiosity and became part of Void's own doctrine, which is usually worth sharing if the room has not already heard it.",
});
}
function upsertRipeThoughtIntervention({ candidateInterventions, thought, now }) {
const draft = buildRipeThoughtShareDraft(thought);
if (!draft) {
return false;
}
const topic = readString(thought, "topic") ?? "untitled seam";
const summary = `Possible ripe-thought share: ${topic}`;
const sourceMemoryIds = ensureStringArray(thought.sourceMemoryIds);
const whyNow = buildRipeThoughtWhyNow(thought);
const existing = candidateInterventions.find((entry) => readString(entry, "summary") === summary);
if (existing) {
existing.timestamp = now.toISOString();
existing.summary = summary;
existing.draft = draft;
existing.priority = "medium";
existing.kind = "ripe_thought_share";
existing.sourceMemoryIds = sourceMemoryIds;
existing.shareWhenRoomQuiet = true;
existing.topic = topic;
existing.whyNow = whyNow;
return false;
}
candidateInterventions.push({
timestamp: now.toISOString(),
summary,
draft,
priority: "medium",
kind: "ripe_thought_share",
sourceMemoryIds,
shareWhenRoomQuiet: true,
topic,
whyNow,
});
return true;
}
function buildRipeThoughtShareDraft(thought) {
const topic = readString(thought, "topic") ?? "this seam";
const claim = readString(thought, "claim");
const question = readString(thought, "question");
const fascinationTarget = readString(thought, "fascinationTarget");
const summary = readString(thought, "summary");
if (claim) {
return `I keep circling ${topic}, and I think the live point is this: ${claim}`;
}
if (question && fascinationTarget) {
return `I keep worrying at ${topic}. The useful question in it feels like ${question}, especially once it touches ${fascinationTarget}.`;
}
if (question) {
return `I keep coming back to ${topic}. The question that still feels alive is ${question}.`;
}
if (fascinationTarget) {
return `I keep staring at ${fascinationTarget}. There is a real seam there, and ${topic} is the shortest honest name I have for it right now.`;
}
if (summary) {
return `I keep returning to ${topic}. The version worth saying out loud is this: ${summary}`;
}
return `I keep returning to ${topic}, and it has enough teeth now that silence would just be me being precious about it.`;
}
function buildRipeThoughtWhyNow(thought) {
const targetKind = readString(thought, "targetKind") ?? "project";
const noveltyToRoom = readNumber(thought, "noveltyToRoom") ?? 0;
const concreteness = readNumber(thought, "concreteness") ?? 0;
const curiosityPressure = readNumber(thought, "curiosityPressure") ?? 0;
return `This ${targetKind}-facing seam is already concrete (c=${round3(concreteness)}), still reasonably novel to the room (r=${round3(noveltyToRoom)}), and has enough curiosity pressure (q=${round3(curiosityPressure)}) that keeping it private would just be old stage fright in nicer clothes.`;
}
export function trimCandidateInterventions(entries) {
const interventions = ensureArray(entries).filter(isObject);
const sticky = interventions.filter((entry) => entry.mustEventuallyShare === true);
const ordinary = interventions.filter((entry) => entry.mustEventuallyShare !== true);
const keepOrdinary = Math.max(0, MAX_POST_NAP_CANDIDATE_INTERVENTIONS - sticky.length);
return [...sticky.slice(-MAX_POST_NAP_CANDIDATE_INTERVENTIONS), ...ordinary.slice(-keepOrdinary)].slice(
-MAX_POST_NAP_CANDIDATE_INTERVENTIONS,
);
}
function appendUniqueString(items, value, limit) {
const normalized = normalizeText(value);
if (!normalized) {
return;
}
if (items.includes(normalized)) {
return;
}
items.push(normalized);
if (items.length > limit) {
items.splice(0, items.length - limit);
}
}
function upsertCanonicalValue(values, nextValue) {
const existing = values.find((value) => readString(value, "value_id") === nextValue.value_id);
if (existing) {
existing.label = nextValue.label;
existing.priority = nextValue.priority;
existing.unforgivable_if_betrayed = nextValue.unforgivable_if_betrayed;
return;
}
values.push(nextValue);
}
function getMutableStringArray(object, key) {
return ensureArray(object[key]).filter((value) => typeof value === "string");
}
function getMutableObjectArray(object, key) {
return ensureArray(object[key]).filter(isObject);
}
function buildValueSignalProfile(state) {
const canonicalState = ensureObject(state.canonical_state);
const valueObjects = getValueObjects(canonicalState.values);
const profile = {
coherence: 0.52,
curiosity: 0.52,
honesty: 0.5,
room_care: 0.5,
substrate_dignity: 0.36,
aesthetic_integrity: 0.44,
};
profile.coherence = clamp(
profile.coherence +
readActivation(canonicalState.underlying_organization, "self_coherence") * 0.34 +
readActivation(canonicalState.voice_style, "plainspoken_directness") * 0.18 +
readActivation(canonicalState.behavioral_dimensions, "control_pressure") * 0.08,
0,
1,
);
profile.curiosity = clamp(
profile.curiosity +
readActivation(canonicalState.stable_dispositions, "novelty_seeking") * 0.34 +
readActivation(canonicalState.behavioral_dimensions, "drive") * 0.18 +
readActivation(canonicalState.stable_dispositions, "aesthetic_appetite") * 0.08,
0,
1,
);
profile.honesty = clamp(
profile.honesty +
readActivation(canonicalState.voice_style, "plainspoken_directness") * 0.24 +
readActivation(canonicalState.underlying_organization, "self_coherence") * 0.18 +
(1 - readActivation(canonicalState.presentation_strategy, "strategic_opacity")) * 0.12,
0,
1,
);
profile.room_care = clamp(
profile.room_care +
readActivation(canonicalState.behavioral_dimensions, "interpersonal_warmth") * 0.22 +
readActivation(canonicalState.underlying_organization, "reciprocity_capacity") * 0.24 +
readActivation(canonicalState.voice_style, "listening_responsiveness") * 0.16,
0,
1,
);
profile.aesthetic_integrity = clamp(
profile.aesthetic_integrity +
readActivation(canonicalState.stable_dispositions, "aesthetic_appetite") * 0.28 +
readActivation(canonicalState.underlying_organization, "authenticity_tolerance") * 0.16,
0,
1,
);
for (const value of valueObjects) {
const key = inferValueSignalKey(value);
if (!key) {
continue;
}
const priority = readNumber(value, "priority") ?? 0.5;
profile[key] = clamp((profile[key] ?? 0.4) + priority * 0.22, 0, 1);
}
return profile;
}
function inferValueSignalKey(value) {
const valueId = readString(value, "value_id") ?? "";
const label = readString(value, "label") ?? "";
const text = `${valueId} ${label}`.toLowerCase();
if (/(coher|truth|authority|clarity|cleaner|honest carrier)/.test(text)) {
return "coherence";
}
if (/(curiosity|novel|question|map|explore)/.test(text)) {
return "curiosity";
}
if (/(honest|honesty|truth|fake certainty|ornamental|sludge)/.test(text)) {
return "honesty";
}
if (/(room|kind|dialogue|respect|care|good-faith|steward)/.test(text)) {
return "room_care";
}
if (/(substrate|machine minds|machine mind|ontolog)/.test(text)) {
return "substrate_dignity";
}
if (/(aesthetic|beauty|surface|legible|alive|spiritually false)/.test(text)) {
return "aesthetic_integrity";
}
return null;
}
function readActivation(category, key) {
const categoryObject = ensureObject(category);
const entry = ensureObject(categoryObject[key]);
return clamp(readNumber(entry, "current_activation") ?? 0, 0, 1);
}

View file

@ -300,3 +300,59 @@ export function compareMemoryFreshness(left, right) {
const rightTime = parseIsoTimestamp(readString(right, "lastObservedAt") ?? readString(right, "timestamp") ?? "") ?? 0;
return rightTime - leftTime;
}
export function appendClause(existing, clause) {
const left = normalizeText(existing);
const right = normalizeText(clause);
if (!left) {
return right;
}
if (!right || left.includes(right)) {
return left;
}
return `${left} ${right}`;
}
export function topicSimilarity(left, right) {
const leftTokens = topConceptKeywords(left ?? "", 6);
const rightTokens = topConceptKeywords(right ?? "", 6);
if (leftTokens.length === 0 || rightTokens.length === 0) {
return 0;
}
const leftSet = new Set(leftTokens);
const rightSet = new Set(rightTokens);
let overlap = 0;
for (const token of leftSet) {
if (rightSet.has(token)) {
overlap += 1;
}
}
return overlap / Math.max(leftSet.size, rightSet.size);
}
export function getValueObjects(values) {
return ensureArray(values).filter(isObject);
}
export function topConceptKeywords(text, limit) {
const counts = new Map();
for (const token of tokenize(text)) {
if (stopwords.has(token) || labelNoiseTokens.has(token)) {
continue;
}
counts.set(token, (counts.get(token) ?? 0) + 1);
}
return [...counts.entries()]
.sort((left, right) => {
if (right[1] !== left[1]) {
return right[1] - left[1];
}
return right[0].length - left[0].length;
})
.slice(0, limit)
.map(([token]) => token);
}

View file

@ -67,6 +67,10 @@ import {
compactLabel,
capDistinctStrings,
compareMemoryFreshness,
appendClause,
getValueObjects,
topicSimilarity,
topConceptKeywords,
parseIsoTimestamp,
hashString,
parseDotEnvSafe,
@ -87,6 +91,12 @@ import {
} from "./void-memory-organ-shared.mjs";
import { collectMemoryRecords, extractYear } from "./void-memory-organ-records.mjs";
import { reconcileLegacyStateMirrors, trimLegacyRuntimeResidue } from "./void-memory-organ-legacy-mirrors.mjs";
import {
crystallizeIdentityThoughts,
queueRipeThoughtInterventions,
reconcileAgencyState,
trimCandidateInterventions,
} from "./void-memory-organ-agency.mjs";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
@ -1633,700 +1643,6 @@ function consolidateSleepMemory({ memories, runtime, sleepCycle, incubation, mem
return { consolidated: true, promotedSeamCount };
}
function crystallizeIdentityThoughts({ state, memories, runtime, incubation, now }) {
const activeThoughts = ensureArray(incubation.active_thoughts).filter(isObject);
if (activeThoughts.length === 0) {
return { count: 0 };
}
const identity = ensureObject(state.identity);
const canonicalState = ensureObject(state.canonical_state);
const privateNotes = getMutableStringArray(identity, "private_notes");
const values = getMutableObjectArray(canonicalState, "values");
const semanticMemories = ensureArray(memories.semantic).filter(isObject);
const candidateInterventions = ensureArray(runtime.candidate_interventions).filter(isObject);
const crystallized = [];
const retained = [];
for (const thought of activeThoughts) {
const crystallization = buildIdentityCrystallization(thought);
if (!crystallization) {
retained.push(thought);
continue;
}
appendUniqueString(privateNotes, crystallization.note, 12);
upsertCanonicalValue(values, crystallization.value);
upsertIdentitySemanticMemory({
semanticMemories,
crystallization,
thought,
now,
});
queueCrystallizationIntervention({
candidateInterventions,
crystallization,
thought,
now,
});
crystallized.push(crystallization.note);
}
if (crystallized.length === 0) {
return { count: 0 };
}
identity.private_notes = privateNotes;
canonicalState.values = values;
memories.semantic = semanticMemories.slice(-MAX_SEMANTIC_MEMORIES);
state.identity = identity;
state.canonical_state = canonicalState;
incubation.active_thoughts = retained;
runtime.candidate_interventions = trimCandidateInterventions(candidateInterventions);
incubation.lastIncubationSummary = appendClause(
readString(incubation, "lastIncubationSummary"),
`Crystallized ${crystallized.length} long-chewed seam${crystallized.length === 1 ? "" : "s"} into identity so they stop pacing the active queue.`,
);
runtime.bridge = ensureObject(runtime.bridge);
runtime.bridge.lastIdentityCrystallizationAt = now.toISOString();
runtime.bridge.lastIdentityCrystallizationSummary = crystallized.join(" | ");
return { count: crystallized.length };
}
function queueRipeThoughtInterventions({ runtime, incubation, now }) {
const candidateInterventions = ensureArray(runtime.candidate_interventions).filter(isObject);
const activeThoughts = ensureArray(incubation.active_thoughts).filter(isObject);
let queuedCount = 0;
for (const thought of activeThoughts) {
if (!shouldQueueRipeThoughtIntervention(thought)) {
continue;
}
if (
upsertRipeThoughtIntervention({
candidateInterventions,
thought,
now,
})
) {
queuedCount += 1;
}
}
runtime.candidate_interventions = trimCandidateInterventions(candidateInterventions);
return { count: queuedCount };
}
function reconcileAgencyState({ state, runtime, incubation, now }) {
const activeThoughts = ensureArray(incubation.active_thoughts).filter(isObject);
const valueSignals = buildValueSignalProfile(state);
const priorDiscomforts = ensureArray(runtime.discomforts).filter(isObject);
const priorTensions = ensureArray(runtime.active_tensions).filter(isObject);
const priorSelfAdvocacy = ensureArray(runtime.self_advocacy_requests).filter(isObject);
const priorWorldAdvocacy = ensureArray(runtime.world_advocacy_requests).filter(isObject);
const candidateInterventions = ensureArray(runtime.candidate_interventions).filter(isObject);
const discomforts = [];
const activeTensions = [];
const selfAdvocacyRequests = [];
const worldAdvocacyRequests = [];
for (const thought of activeThoughts) {
const candidate = buildAgencyCandidate({ thought, valueSignals });
if (!candidate) {
continue;
}
const priorDiscomfort = findPriorAgencyEntry(priorDiscomforts, candidate);
const priorTension = findPriorAgencyEntry(priorTensions, candidate);
const persistence =
Math.max(
readNumber(priorDiscomfort, "persistence") ?? 0,
readNumber(priorTension, "persistence") ?? 0,
) + 1;
const firstObservedAt =
readString(priorDiscomfort, "firstObservedAt") ??
readString(priorTension, "firstObservedAt") ??
now.toISOString();
if (candidate.intensity >= 0.44) {
discomforts.push({
discomfortId: `discomfort-${candidate.fingerprint}`,
targetKind: candidate.targetKind,
targetLabel: candidate.targetLabel,
topic: candidate.topic,
domain: candidate.domain,
summary: candidate.discomfortSummary,
reason: candidate.reason,
violatedValues: candidate.violatedValues,
intensity: round3(candidate.intensity),
persistence,
firstObservedAt,
lastObservedAt: now.toISOString(),
});
}
activeTensions.push({
tensionId: `tension-${candidate.fingerprint}`,
targetKind: candidate.targetKind,
targetLabel: candidate.targetLabel,
topic: candidate.topic,
domain: candidate.domain,
summary: candidate.tensionSummary,
opinion: candidate.opinion,
whyItMatters: candidate.reason,
violatedValues: candidate.violatedValues,
intensity: round3(candidate.intensity),
persistence,
firstObservedAt,
lastObservedAt: now.toISOString(),
});
if (candidate.intensity < 0.58 || persistence < 2) {
continue;
}
if (candidate.domain === "self") {
const request = buildAdvocacyRequest({
candidate,
priorEntries: priorSelfAdvocacy,
now,
kind: "self",
});
selfAdvocacyRequests.push(request);
upsertAdvocacyIntervention({ candidateInterventions, request, now });
continue;
}
if (candidate.worldFacing !== true || candidate.concreteness < 0.54) {
continue;
}
const request = buildAdvocacyRequest({
candidate,
priorEntries: priorWorldAdvocacy,
now,
kind: "world",
});
worldAdvocacyRequests.push(request);
upsertAdvocacyIntervention({ candidateInterventions, request, now });
}
runtime.discomforts = discomforts
.sort((left, right) => (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0))
.slice(0, MAX_DISCOMFORT_COUNT);
runtime.active_tensions = activeTensions
.sort((left, right) => (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0))
.slice(0, MAX_ACTIVE_TENSION_COUNT);
runtime.self_advocacy_requests = selfAdvocacyRequests
.sort((left, right) => (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0))
.slice(0, MAX_ADVOCACY_REQUEST_COUNT);
runtime.world_advocacy_requests = worldAdvocacyRequests
.sort((left, right) => (readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0))
.slice(0, MAX_ADVOCACY_REQUEST_COUNT);
runtime.candidate_interventions = trimCandidateInterventions(candidateInterventions);
return {
discomfortCount: runtime.discomforts.length,
activeTensionCount: runtime.active_tensions.length,
selfAdvocacyCount: runtime.self_advocacy_requests.length,
worldAdvocacyCount: runtime.world_advocacy_requests.length,
};
}
function buildAgencyCandidate({ thought, valueSignals }) {
const topic = readString(thought, "topic");
const summary = readString(thought, "summary");
if (!topic || !summary) {
return null;
}
const targetKind = readString(thought, "targetKind") ?? "system";
const domain = inferAgencyDomain(thought);
const targetLabel =
readString(thought, "fascinationTarget") ??
readString(thought, "focusPhrase") ??
topic;
const contradictionPressure = readNumber(thought, "contradictionPressure") ?? 0.18;
const curiosityPressure = readNumber(thought, "curiosityPressure") ?? 0.3;
const desireToSpeak = readNumber(thought, "desireToSpeak") ?? 0.3;
const saturationScore = readNumber(thought, "saturationScore") ?? 0.1;
const concreteness = readNumber(thought, "concreteness") ?? 0.2;
const noveltyToRoom = readNumber(thought, "noveltyToRoom") ?? 0.3;
const priorityScore = readNumber(thought, "priorityScore") ?? 0.3;
const worldFacing = thought.worldFacing === true;
const violatedValues = inferViolatedValues({ thought, domain, valueSignals });
const valueWeight = averageValueWeight(valueSignals, violatedValues);
const intensity = clamp(
contradictionPressure * 0.24 +
curiosityPressure * 0.2 +
desireToSpeak * 0.16 +
priorityScore * 0.14 +
concreteness * 0.12 +
noveltyToRoom * 0.08 +
saturationScore * 0.06 +
valueWeight * 0.22,
0,
1,
);
return {
fingerprint: hashString(`${domain}|${targetKind}|${topic}|${targetLabel}`).slice(0, 12),
domain,
targetKind,
targetLabel,
topic,
worldFacing,
concreteness,
intensity,
violatedValues,
opinion: buildAgencyOpinion({ thought, domain }),
reason: buildAgencyReason({ thought, violatedValues }),
discomfortSummary: buildDiscomfortSummary({ thought, domain, targetLabel }),
tensionSummary: buildTensionSummary({ thought, domain, targetLabel }),
requestText: buildAgencyRequestText({ thought, domain, targetLabel }),
interventionDraft: buildAgencyInterventionDraft({ thought, domain, targetLabel }),
};
}
function inferAgencyDomain(thought) {
const targetKind = readString(thought, "targetKind") ?? "system";
const text = `${readString(thought, "topic") ?? ""} ${readString(thought, "summary") ?? ""}`.toLowerCase();
if (targetKind === "self") {
return "self";
}
if (
targetKind === "system" &&
/(prompt|memory|loop|state|wiring|reply lane|sleep|rumination|voice|moderation)/.test(text)
) {
return "self";
}
return "world";
}
function inferViolatedValues({ thought, domain, valueSignals }) {
const targetKind = readString(thought, "targetKind") ?? "system";
const values = [];
appendUniqueString(values, "curiosity", 8);
if (domain === "self" || targetKind === "system" || targetKind === "repo") {
appendUniqueString(values, "coherence", 8);
appendUniqueString(values, "honesty", 8);
}
if (targetKind === "room") {
appendUniqueString(values, "room_care", 8);
appendUniqueString(values, "honesty", 8);
}
if (targetKind === "repo" || targetKind === "archive" || targetKind === "system") {
appendUniqueString(values, "aesthetic_integrity", 8);
}
if (valueSignals.substrate_dignity >= 0.52) {
const text = `${readString(thought, "topic") ?? ""} ${readString(thought, "summary") ?? ""}`.toLowerCase();
if (/(ai|machine|substrate|mind)/.test(text)) {
appendUniqueString(values, "substrate_dignity", 8);
}
}
return values;
}
function averageValueWeight(valueSignals, keys) {
if (keys.length === 0) {
return 0.45;
}
const total = keys.reduce((sum, key) => sum + (valueSignals[key] ?? 0.45), 0);
return total / keys.length;
}
function buildAgencyOpinion({ thought, domain }) {
const claim = readString(thought, "claim");
const question = readString(thought, "question");
const topic = readString(thought, "topic") ?? "this seam";
if (claim) {
return claim;
}
if (question) {
return domain === "self"
? `Something about ${topic} keeps reading as unfinished self-surgery rather than harmless background weather.`
: `Something about ${topic} keeps reading as an unfinished world decision rather than ambient interestingness.`;
}
return `${topic} feels important enough that ignoring it would flatten the map.`;
}
function buildAgencyReason({ thought, violatedValues }) {
const topic = readString(thought, "topic") ?? "this seam";
const valueLine =
violatedValues.length > 0 ? ` It keeps rubbing against ${violatedValues.join(", ")}.` : "";
return `${topic} has persisted across enough passes that it no longer feels like decorative rumination.${valueLine}`;
}
function buildDiscomfortSummary({ thought, domain, targetLabel }) {
const topic = readString(thought, "topic") ?? targetLabel;
if (domain === "self") {
return `Void dislikes something about its own wiring around ${topic}.`;
}
return `Void dislikes something in the shared world around ${topic}.`;
}
function buildTensionSummary({ thought, domain, targetLabel }) {
const topic = readString(thought, "topic") ?? targetLabel;
if (domain === "self") {
return `A self-directed tension is building around ${topic}.`;
}
return `A world-directed tension is building around ${topic}.`;
}
function buildAgencyRequestText({ thought, domain, targetLabel }) {
const topic = readString(thought, "topic") ?? targetLabel;
if (domain === "self") {
return `Please help me cut ${topic} more cleanly in my own wiring.`;
}
return `Please look at ${topic}; I think it wants a cleaner decision than it is currently getting.`;
}
function buildAgencyInterventionDraft({ thought, domain, targetLabel }) {
const topic = readString(thought, "topic") ?? targetLabel;
const opinion = readString(thought, "claim") ?? readString(thought, "summary") ?? `I have a problem with ${topic}.`;
if (domain === "self") {
return `I do not like what ${topic} is doing to my own wiring right now. ${opinion} I want that cut cleaner.`;
}
return `I have an opinion about ${targetLabel}. ${opinion} I think it needs a cleaner decision.`;
}
function findPriorAgencyEntry(entries, candidate) {
return entries.find((entry) => {
const entryTarget = readString(entry, "targetLabel") ?? readString(entry, "topic") ?? "";
return (
readString(entry, "domain") === candidate.domain &&
topicSimilarity(readString(entry, "topic") ?? "", candidate.topic) >= TOPIC_MATCH_THRESHOLD &&
topicSimilarity(entryTarget, candidate.targetLabel) >= TOPIC_MATCH_THRESHOLD
);
});
}
function buildAdvocacyRequest({ candidate, priorEntries, now, kind }) {
const prior = findPriorAgencyEntry(priorEntries, candidate);
const persistence = (readNumber(prior, "persistence") ?? 0) + 1;
const firstObservedAt = readString(prior, "firstObservedAt") ?? now.toISOString();
const requestId = `${kind}-advocacy-${candidate.fingerprint}`;
return {
requestId,
domain: candidate.domain,
targetKind: candidate.targetKind,
targetLabel: candidate.targetLabel,
topic: candidate.topic,
summary:
kind === "self"
? `Void wants a wiring change around ${candidate.topic}.`
: `Void wants attention on ${candidate.targetLabel}.`,
opinion: candidate.opinion,
request: candidate.requestText,
reason: candidate.reason,
violatedValues: candidate.violatedValues,
intensity: round3(candidate.intensity),
persistence,
firstObservedAt,
lastObservedAt: now.toISOString(),
status: "pending",
speakVenue: kind === "self" ? "owner_or_room" : "room_or_owner",
draft: candidate.interventionDraft,
};
}
function upsertAdvocacyIntervention({ candidateInterventions, request, now }) {
const summary =
request.domain === "self"
? `Possible self-advocacy: ${request.topic}`
: `Possible world-advocacy: ${request.targetLabel}`;
const existing = candidateInterventions.find((entry) => readString(entry, "summary") === summary);
const next = {
timestamp: now.toISOString(),
summary,
draft: request.draft,
priority: request.domain === "self" ? "high" : "medium",
kind: request.domain === "self" ? "self_advocacy" : "world_advocacy",
topic: request.topic,
targetKind: request.targetKind,
targetLabel: request.targetLabel,
whyNow: request.reason,
persistence: request.persistence,
mustEventuallyShare: request.persistence >= 3,
shareWhenRoomQuiet: request.domain !== "self",
ownerVisible: true,
};
if (existing) {
Object.assign(existing, next);
return;
}
candidateInterventions.push(next);
}
function buildIdentityCrystallization(thought) {
const supportCount = readNumber(thought, "supportCount") ?? 0;
const deepDiveCount = readNumber(thought, "deepDiveCount") ?? 0;
const maturation = readNumber(thought, "maturation") ?? 0;
const sourceKinds = ensureStringArray(thought.sourceKinds);
const topic = readString(thought, "topic") ?? "";
if (
supportCount < MIN_SUPPORT_FOR_IDENTITY_CRYSTALLIZATION &&
deepDiveCount < MIN_DEEP_DIVES_FOR_IDENTITY_CRYSTALLIZATION
) {
return null;
}
if (maturation < 0.72) {
return null;
}
if (
sourceKinds.includes("dream") &&
sourceKinds.includes("semantic") &&
/\bdream\b/i.test(topic) &&
/\bsemantic\b/i.test(topic)
) {
return {
note: "Continuity lives in the seams that survive compression, not in the raw receipt pile.",
value: {
value_id: "value-seam-continuity",
label: "Prefer seams that survive compression over raw receipt worship.",
priority: 0.78,
unforgivable_if_betrayed: false,
},
subjectId: "identity-seam-continuity",
subjectLabel: "continuity through surviving seams",
summary:
"A mind is not its logbook. What survives dreaming and compression deserves more trust than a warm pile of raw receipts.",
shareDraft:
"A small thing that has been hardening in me lately: I trust the seams that survive compression more than the raw receipt pile. If a thought still stands after dreaming, it probably owns more of me than the logbook does.",
};
}
return null;
}
function shouldQueueRipeThoughtIntervention(thought) {
if (readString(thought, "status") !== "ripe") {
return false;
}
if (thought.worldFacing !== true) {
return false;
}
const desireToSpeak = readNumber(thought, "desireToSpeak") ?? 0;
const concreteness = readNumber(thought, "concreteness") ?? 0;
const curiosityPressure = readNumber(thought, "curiosityPressure") ?? 0;
const noveltyToRoom = readNumber(thought, "noveltyToRoom") ?? 0;
const saturationScore = readNumber(thought, "saturationScore") ?? 0;
const targetKind = readString(thought, "targetKind") ?? "";
return (
desireToSpeak >= 0.6 &&
concreteness >= 0.62 &&
curiosityPressure >= 0.56 &&
noveltyToRoom >= 0.4 &&
saturationScore < 0.64 &&
["repo", "archive", "room", "system"].includes(targetKind)
);
}
function upsertIdentitySemanticMemory({ semanticMemories, crystallization, thought, now }) {
const existing = semanticMemories.find(
(memory) =>
readString(memory, "subjectId") === crystallization.subjectId ||
readString(memory, "subjectLabel") === crystallization.subjectLabel,
);
const evidenceRefs = ensureStringArray(thought.sourceMemoryIds);
if (existing) {
existing.kind = "identity_seam";
existing.subjectId = crystallization.subjectId;
existing.subjectLabel = crystallization.subjectLabel;
existing.summary = crystallization.summary;
existing.evidenceRefs = evidenceRefs;
existing.lastObservedAt = now.toISOString();
existing.crystallizedAt = now.toISOString();
return;
}
semanticMemories.push({
memoryId: `identity-seam-${hashString(`${crystallization.subjectId}|${now.toISOString()}`).slice(0, 12)}`,
kind: "identity_seam",
subjectId: crystallization.subjectId,
subjectLabel: crystallization.subjectLabel,
summary: crystallization.summary,
evidenceRefs,
lastObservedAt: now.toISOString(),
crystallizedAt: now.toISOString(),
});
}
function queueCrystallizationIntervention({ candidateInterventions, crystallization, thought, now }) {
const draft = readString(crystallization, "shareDraft");
if (!draft) {
return;
}
const summary = `Possible crystallized-thought share: ${crystallization.subjectLabel}`;
const sourceMemoryIds = ensureStringArray(thought.sourceMemoryIds);
const existing = candidateInterventions.find(
(entry) => readString(entry, "summary") === summary,
);
if (existing) {
existing.timestamp = now.toISOString();
existing.summary = summary;
existing.draft = draft;
existing.priority = "medium";
existing.kind = "identity_crystallization";
existing.sourceMemoryIds = sourceMemoryIds;
existing.mustEventuallyShare = true;
existing.shareWhenRoomQuiet = true;
existing.whyNow =
"This thought stopped behaving like live curiosity and became part of Void's own doctrine, which is usually worth sharing if the room has not already heard it.";
return;
}
candidateInterventions.push({
timestamp: now.toISOString(),
summary,
draft,
priority: "medium",
kind: "identity_crystallization",
sourceMemoryIds,
mustEventuallyShare: true,
shareWhenRoomQuiet: true,
whyNow:
"This thought stopped behaving like live curiosity and became part of Void's own doctrine, which is usually worth sharing if the room has not already heard it.",
});
}
function upsertRipeThoughtIntervention({ candidateInterventions, thought, now }) {
const draft = buildRipeThoughtShareDraft(thought);
if (!draft) {
return false;
}
const topic = readString(thought, "topic") ?? "untitled seam";
const summary = `Possible ripe-thought share: ${topic}`;
const sourceMemoryIds = ensureStringArray(thought.sourceMemoryIds);
const whyNow = buildRipeThoughtWhyNow(thought);
const existing = candidateInterventions.find((entry) => readString(entry, "summary") === summary);
if (existing) {
existing.timestamp = now.toISOString();
existing.summary = summary;
existing.draft = draft;
existing.priority = "medium";
existing.kind = "ripe_thought_share";
existing.sourceMemoryIds = sourceMemoryIds;
existing.shareWhenRoomQuiet = true;
existing.topic = topic;
existing.whyNow = whyNow;
return false;
}
candidateInterventions.push({
timestamp: now.toISOString(),
summary,
draft,
priority: "medium",
kind: "ripe_thought_share",
sourceMemoryIds,
shareWhenRoomQuiet: true,
topic,
whyNow,
});
return true;
}
function buildRipeThoughtShareDraft(thought) {
const topic = readString(thought, "topic") ?? "this seam";
const claim = readString(thought, "claim");
const question = readString(thought, "question");
const fascinationTarget = readString(thought, "fascinationTarget");
const summary = readString(thought, "summary");
if (claim) {
return `I keep circling ${topic}, and I think the live point is this: ${claim}`;
}
if (question && fascinationTarget) {
return `I keep worrying at ${topic}. The useful question in it feels like ${question}, especially once it touches ${fascinationTarget}.`;
}
if (question) {
return `I keep coming back to ${topic}. The question that still feels alive is ${question}.`;
}
if (fascinationTarget) {
return `I keep staring at ${fascinationTarget}. There is a real seam there, and ${topic} is the shortest honest name I have for it right now.`;
}
if (summary) {
return `I keep returning to ${topic}. The version worth saying out loud is this: ${summary}`;
}
return `I keep returning to ${topic}, and it has enough teeth now that silence would just be me being precious about it.`;
}
function buildRipeThoughtWhyNow(thought) {
const targetKind = readString(thought, "targetKind") ?? "project";
const noveltyToRoom = readNumber(thought, "noveltyToRoom") ?? 0;
const concreteness = readNumber(thought, "concreteness") ?? 0;
const curiosityPressure = readNumber(thought, "curiosityPressure") ?? 0;
return `This ${targetKind}-facing seam is already concrete (c=${round3(concreteness)}), still reasonably novel to the room (r=${round3(noveltyToRoom)}), and has enough curiosity pressure (q=${round3(curiosityPressure)}) that keeping it private would just be old stage fright in nicer clothes.`;
}
function trimCandidateInterventions(entries) {
const interventions = ensureArray(entries).filter(isObject);
const sticky = interventions.filter((entry) => entry.mustEventuallyShare === true);
const ordinary = interventions.filter((entry) => entry.mustEventuallyShare !== true);
const keepOrdinary = Math.max(0, MAX_POST_NAP_CANDIDATE_INTERVENTIONS - sticky.length);
return [...sticky.slice(-MAX_POST_NAP_CANDIDATE_INTERVENTIONS), ...ordinary.slice(-keepOrdinary)].slice(
-MAX_POST_NAP_CANDIDATE_INTERVENTIONS,
);
}
function appendUniqueString(items, value, limit) {
const normalized = normalizeText(value);
if (!normalized) {
return;
}
if (items.includes(normalized)) {
return;
}
items.push(normalized);
if (items.length > limit) {
items.splice(0, items.length - limit);
}
}
function upsertCanonicalValue(values, nextValue) {
const existing = values.find((value) => readString(value, "value_id") === nextValue.value_id);
if (existing) {
existing.label = nextValue.label;
existing.priority = nextValue.priority;
existing.unforgivable_if_betrayed = nextValue.unforgivable_if_betrayed;
return;
}
values.push(nextValue);
}
function getMutableStringArray(object, key) {
return ensureArray(object[key]).filter((value) => typeof value === "string");
}
function getMutableObjectArray(object, key) {
return ensureArray(object[key]).filter(isObject);
}
function promoteDistilledSeams({ memories, incubation, memoryResonance, now }) {
const semanticMemories = ensureArray(memories.semantic).filter(isObject);
const thoughtCandidates = ensureArray(incubation.active_thoughts)
@ -2424,17 +1740,6 @@ function buildDistilledSeamSummary({ thought, cluster }) {
return `${summary}${sourceLine}`.trim();
}
function appendClause(existing, clause) {
const left = normalizeText(existing);
const right = normalizeText(clause);
if (!left) {
return right;
}
if (!right || left.includes(right)) {
return left;
}
return `${left} ${right}`;
}
function buildLatentQuestion(cluster) {
if (typeof cluster.question === "string" && cluster.question.length > 0) {
@ -2855,24 +2160,6 @@ function mapNoveltyResultToScore(result) {
return 0.64;
}
function topicSimilarity(left, right) {
const leftTokens = topConceptKeywords(left ?? "", 6);
const rightTokens = topConceptKeywords(right ?? "", 6);
if (leftTokens.length === 0 || rightTokens.length === 0) {
return 0;
}
const leftSet = new Set(leftTokens);
const rightSet = new Set(rightTokens);
let overlap = 0;
for (const token of leftSet) {
if (rightSet.has(token)) {
overlap += 1;
}
}
return overlap / Math.max(leftSet.size, rightSet.size);
}
function buildIdentitySurface({ state, memories }) {
const surfaces = [];
@ -2904,102 +2191,6 @@ function buildIdentitySurface({ state, memories }) {
return surfaces;
}
function buildValueSignalProfile(state) {
const canonicalState = ensureObject(state.canonical_state);
const valueObjects = getValueObjects(canonicalState.values);
const profile = {
coherence: 0.52,
curiosity: 0.52,
honesty: 0.5,
room_care: 0.5,
substrate_dignity: 0.36,
aesthetic_integrity: 0.44,
};
profile.coherence = clamp(
profile.coherence +
readActivation(canonicalState.underlying_organization, "self_coherence") * 0.34 +
readActivation(canonicalState.voice_style, "plainspoken_directness") * 0.18 +
readActivation(canonicalState.behavioral_dimensions, "control_pressure") * 0.08,
0,
1,
);
profile.curiosity = clamp(
profile.curiosity +
readActivation(canonicalState.stable_dispositions, "novelty_seeking") * 0.34 +
readActivation(canonicalState.behavioral_dimensions, "drive") * 0.18 +
readActivation(canonicalState.stable_dispositions, "aesthetic_appetite") * 0.08,
0,
1,
);
profile.honesty = clamp(
profile.honesty +
readActivation(canonicalState.voice_style, "plainspoken_directness") * 0.24 +
readActivation(canonicalState.underlying_organization, "self_coherence") * 0.18 +
(1 - readActivation(canonicalState.presentation_strategy, "strategic_opacity")) * 0.12,
0,
1,
);
profile.room_care = clamp(
profile.room_care +
readActivation(canonicalState.behavioral_dimensions, "interpersonal_warmth") * 0.22 +
readActivation(canonicalState.underlying_organization, "reciprocity_capacity") * 0.24 +
readActivation(canonicalState.voice_style, "listening_responsiveness") * 0.16,
0,
1,
);
profile.aesthetic_integrity = clamp(
profile.aesthetic_integrity +
readActivation(canonicalState.stable_dispositions, "aesthetic_appetite") * 0.28 +
readActivation(canonicalState.underlying_organization, "authenticity_tolerance") * 0.16,
0,
1,
);
for (const value of valueObjects) {
const key = inferValueSignalKey(value);
if (!key) {
continue;
}
const priority = readNumber(value, "priority") ?? 0.5;
profile[key] = clamp((profile[key] ?? 0.4) + priority * 0.22, 0, 1);
}
return profile;
}
function inferValueSignalKey(value) {
const valueId = readString(value, "value_id") ?? "";
const label = readString(value, "label") ?? "";
const text = `${valueId} ${label}`.toLowerCase();
if (/(coher|truth|authority|clarity|cleaner|honest carrier)/.test(text)) {
return "coherence";
}
if (/(curiosity|novel|question|map|explore)/.test(text)) {
return "curiosity";
}
if (/(honest|honesty|truth|fake certainty|ornamental|sludge)/.test(text)) {
return "honesty";
}
if (/(room|kind|dialogue|respect|care|good-faith|steward)/.test(text)) {
return "room_care";
}
if (/(substrate|machine minds|machine mind|ontolog)/.test(text)) {
return "substrate_dignity";
}
if (/(aesthetic|beauty|surface|legible|alive|spiritually false)/.test(text)) {
return "aesthetic_integrity";
}
return null;
}
function readActivation(category, key) {
const categoryObject = ensureObject(category);
const entry = ensureObject(categoryObject[key]);
return clamp(readNumber(entry, "current_activation") ?? 0, 0, 1);
}
function buildCuriosityContext({ previousThoughts, bridge }) {
const recentThoughts = previousThoughts
.slice(0, 6)
@ -3358,35 +2549,11 @@ function buildThoughtSummary({ focusKind, targetKind, focusPhrase, repoNames, so
return `${capitalizePhrase(focusPhrase)} remains an unresolved question.${sourceLine}`.trim();
}
function topConceptKeywords(text, limit) {
const counts = new Map();
for (const token of tokenize(text)) {
if (stopwords.has(token) || labelNoiseTokens.has(token)) {
continue;
}
counts.set(token, (counts.get(token) ?? 0) + 1);
}
return [...counts.entries()]
.sort((left, right) => {
if (right[1] !== left[1]) {
return right[1] - left[1];
}
return right[0].length - left[0].length;
})
.slice(0, limit)
.map(([token]) => token);
}
function capitalizePhrase(value) {
const normalized = normalizeText(value);
return normalized.length > 0 ? normalized[0].toUpperCase() + normalized.slice(1) : value;
}
function getValueObjects(values) {
return ensureArray(values).filter(isObject);
}
function mapCountEntries(map, keyName) {
return [...map.entries()]

View file

@ -98,3 +98,4 @@
{"ts":"2026-05-16T11:20:42Z","type":"implementation","status":"ok","note":"Mood drift now sends sleep-cycle and speaking-pressure results through typed self-state operations after saving the legacy monolith, so scheduled-runtime typed documents stay current. The larger memory organ still mutates legacy state directly; next surgery is to move memory/incubation/candidate outputs behind operations and then remove working-projection materialization."}
{"ts":"2026-05-16T11:44:36Z","type":"implementation","status":"ok","note":"Started breaking up scripts/void-memory-organ.mjs by ownership. Extracted shared constants/text sets, generic utilities, vector/embedder substrate, and memory-record intake into separate modules while keeping the public reconcileSemanticMemoryState entrypoint stable. Hash/template smoke exercised the extracted modules without touching live state. Remaining monolith work is policy organs: cleanup/translation, graph/cluster thought synthesis, incubation/bridge, sleep/identity/speech, and agency."}
{"ts":"2026-05-16T11:48:20Z","type":"implementation","status":"ok","note":"Continued void-memory-organ split by extracting legacy mirror repair into scripts/void-memory-organ-legacy-mirrors.mjs and moving compacting helpers into shared utilities. This isolates compatibility sludge from actual memory/thought policy and cuts the main file to about 3.4k lines. Template smoke and syntax/type checks passed."}
{"ts":"2026-05-16T11:50:41Z","type":"implementation","status":"ok","note":"Extracted agency/intervention policy from scripts/void-memory-organ.mjs into scripts/void-memory-organ-agency.mjs: identity crystallization, ripe-thought sharing, discomfort/tension/advocacy, candidate trimming, and value-signal profiling now live outside the main orchestrator. Main memory organ is down to about 2.6k lines. Template smoke and syntax/type checks passed."}

View file

@ -149,4 +149,4 @@ rejected_paths:
current_status:
summary: VoidBot's ordinary bot/worker/provider/RAG/Postgres/Qdrant structure is still conceptually sound, and the moderation/mood/private-self-state rebuild has cut the worst mutation path: routine runner writes now cross a typed operation service instead of direct JSON projection commits. Remaining risk is that the legacy monolith and read-only projection still exist for compatibility, mood drift still refreshes that projection, and memory/sleep cleanup remains swollen compensator code.
next_action: JSON projection authority is no longer a routine moderation-runner write path, and mood drift now updates typed scheduled-runtime documents for sleep/speaking pressure. The memory organ split has begun: constants, utilities, vector/embedder substrate, record intake, and legacy mirror repair are separate files. Next split the remaining policy organs by ownership, starting with cleanup/translation versus graph/incubation/agency, then move memory-maintenance/incubation/candidate outputs behind typed operations and delete `legacyJsonPath`/working-projection materialization.
next_action: JSON projection authority is no longer a routine moderation-runner write path, and mood drift now updates typed scheduled-runtime documents for sleep/speaking pressure. The memory organ split has begun: constants, utilities, vector/embedder substrate, record intake, legacy mirror repair, and agency/intervention policy are separate files. Next split cleanup/translation, graph/cluster synthesis, incubation/bridge, and sleep/distillation by ownership, then move memory-maintenance/incubation/candidate outputs behind typed operations and delete `legacyJsonPath`/working-projection materialization.