diff --git a/package.json b/package.json index 82e8143..22d4afe 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,7 @@ "moderation:affect-state:fixture": "powershell -ExecutionPolicy Bypass -File scripts/smoke-void-affect-state-fixture.ps1", "agents:repo-persona-affect-mcp-fixture": "node scripts/smoke-repo-persona-affect-mcp-fixture.mjs", "agents:seed-stress-responses": "node scripts/seed-persona-stress-responses.mjs", + "agents:apply-stress-shards": "tsx scripts/apply-persona-stress-profile-shards.ts", "agents:stress-coverage-smoke": "node scripts/smoke-persona-stress-coverage.mjs", "agents:nibu-trigger-smoke": "node scripts/smoke-repo-persona-nibu-trigger.mjs", "moderation:rumination:fixture": "powershell -ExecutionPolicy Bypass -File scripts/smoke-void-rumination-fixture.ps1", diff --git a/packages/core/src/void-self-state-domain.ts b/packages/core/src/void-self-state-domain.ts index 7e16853..7155b56 100644 --- a/packages/core/src/void-self-state-domain.ts +++ b/packages/core/src/void-self-state-domain.ts @@ -810,6 +810,12 @@ export const voidSelfStateOperationSchema = z.discriminatedUnion("operation", [ responses: z.array(faceStressResponseSchema).min(1), updatedAt: timestampSchema, }).strict(), + z.object({ + operation: z.literal("replace_stress_responses_by_tag"), + replaceTags: z.array(nonEmptyStringSchema).min(1), + responses: z.array(faceStressResponseSchema).min(1), + updatedAt: timestampSchema, + }).strict(), z.object({ operation: z.literal("upsert_doctrine_stance"), stance: faceDoctrineStanceSchema, diff --git a/packages/core/src/void-self-state-service.ts b/packages/core/src/void-self-state-service.ts index b10af22..79e57ea 100644 --- a/packages/core/src/void-self-state-service.ts +++ b/packages/core/src/void-self-state-service.ts @@ -498,6 +498,19 @@ function applyTypedOperation( .slice(0, 24); state.personaAffect.updatedAt = operation.updatedAt; return; + case "replace_stress_responses_by_tag": { + const replaceTags = new Set(operation.replaceTags); + state.personaAffect.stressResponses = state.personaAffect.stressResponses + .filter((response) => !response.tags.some((tag) => replaceTags.has(tag))); + for (const response of operation.responses) { + upsertBy(state.personaAffect.stressResponses, response, (entry) => entry.responseId); + } + state.personaAffect.stressResponses = state.personaAffect.stressResponses + .sort((left, right) => right.intensity - left.intensity) + .slice(0, 24); + state.personaAffect.updatedAt = operation.updatedAt; + return; + } case "upsert_doctrine_stance": upsertBy(state.personaAffect.doctrineStances, operation.stance, (entry) => entry.stanceId); state.personaAffect.doctrineStances = state.personaAffect.doctrineStances diff --git a/scripts/apply-persona-stress-profile-shards.ts b/scripts/apply-persona-stress-profile-shards.ts new file mode 100644 index 0000000..98c6ad5 --- /dev/null +++ b/scripts/apply-persona-stress-profile-shards.ts @@ -0,0 +1,351 @@ +import "dotenv/config"; + +import { readdir, readFile, writeFile } from "node:fs/promises"; +import { extname, join, resolve } from "node:path"; + +import { loadConfig } from "@voidbot/config"; +import { + applyVoidSelfStateOperation, + loadRepoDiscordIdentityRegistry, + loadVoidSelfStateTypedDocuments, + resolveRepoPersonaStatePath, + type RepoDiscordIdentity, +} from "@voidbot/core"; + +type ResearchAnchor = { + ref?: string; + kind?: string; + summary?: string; +}; + +type ResearchStressResponse = { + responseId?: string; + trigger?: string; + summary?: string; + cognitiveDegradation?: string; + affectiveSignature?: string; + constraintLoss?: string; + behavioralLeak?: string; + tangentAttractors?: unknown[]; + cadence?: string; + recoveryPath?: string; + intensity?: number; + threshold?: number; + anchors?: ResearchAnchor[]; + tags?: unknown[]; +}; + +type ResearchIdentity = { + evidenceQueries?: unknown[]; + stressResponses?: ResearchStressResponse[]; +}; + +type ResearchShard = { + identities?: Record; +}; + +type AppliedResult = { + identity: string; + statePath: string; + responseCount: number; + totalStressResponses?: number; + skipped?: boolean; + reason?: string; +}; + +main().catch((error) => { + const message = error instanceof Error ? error.stack ?? error.message : String(error); + console.error(message); + process.exit(1); +}); + +async function main(): Promise { + const args = parseArgs(process.argv.slice(2)); + const config = loadConfig(); + const shardDir = resolve(args.dir ?? ".voidbot/artifacts/stress-profile-research"); + const dryRun = args["dry-run"] === "true"; + const replaceTags = parseList(args["replace-tags"] ?? "swarm-generalization"); + const now = new Date().toISOString(); + + const registry = await loadRepoDiscordIdentityRegistry(config.repoDiscordIdentitiesPath); + const identityById = new Map(registry.identities.map((identity) => [identity.id.toLowerCase(), identity])); + const shardPaths = await discoverShardPaths(shardDir); + const responsesByIdentity = new Map[]>(); + const errors: string[] = []; + + for (const shardPath of shardPaths) { + const shard = JSON.parse(await readFile(shardPath, "utf8")) as ResearchShard; + for (const [rawId, identityResearch] of Object.entries(shard.identities ?? {})) { + const identityId = rawId.toLowerCase(); + const identity = identityById.get(identityId); + if (!identity) { + errors.push(`${shardPath}: unknown identity ${rawId}`); + continue; + } + + for (const [index, response] of (identityResearch.stressResponses ?? []).entries()) { + try { + const normalized = normalizeResponse(identity, response, now, shardPath, index); + const existing = responsesByIdentity.get(identityId) ?? []; + existing.push(normalized); + responsesByIdentity.set(identityId, existing); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + errors.push(`${shardPath}:${rawId}:${index}: ${message}`); + } + } + } + } + + if (errors.length > 0) { + console.error(JSON.stringify({ ok: false, errors }, null, 2)); + process.exit(1); + } + + const results: AppliedResult[] = []; + for (const [identityId, responses] of [...responsesByIdentity.entries()].sort(([left], [right]) => left.localeCompare(right))) { + const identity = identityById.get(identityId); + if (!identity) { + results.push({ identity: identityId, statePath: "", responseCount: responses.length, skipped: true, reason: "unknown_identity" }); + continue; + } + + const statePath = resolveRepoPersonaStatePath(identity, config.storageRoot); + if (extname(statePath).toLowerCase() !== ".cc") { + const doc = JSON.parse(await readFile(statePath, "utf8")); + doc.affect ??= {}; + doc.affect.stressResponses = [ + ...jsonStressResponsesWithoutTags(doc.affect.stressResponses, replaceTags), + ...responses.map(toPortableStressResponse), + ]; + doc.updatedAt = now; + if (!dryRun) { + await writeFile(statePath, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); + } + results.push({ + identity: identityId, + statePath, + responseCount: responses.length, + totalStressResponses: Array.isArray(doc.affect.stressResponses) ? doc.affect.stressResponses.length : responses.length, + }); + continue; + } + + if (!dryRun) { + await applyVoidSelfStateOperation( + { + canonicalPath: statePath, + identity: { + agentId: identity.id, + publicName: identity.displayName, + publicDescription: identity.description, + }, + }, + { + operation: "replace_stress_responses_by_tag", + replaceTags, + responses, + updatedAt: now, + }, + ); + } + + const after = await loadVoidSelfStateTypedDocuments({ + canonicalPath: statePath, + identity: { + agentId: identity.id, + publicName: identity.displayName, + publicDescription: identity.description, + }, + }); + results.push({ + identity: identityId, + statePath, + responseCount: responses.length, + totalStressResponses: dryRun + ? stressResponsesAfterReplacement(after.personaAffect.stressResponses, replaceTags, responses.length) + : after.personaAffect.stressResponses.length, + }); + } + + const summary = { + ok: true, + dryRun, + shardDir, + shardCount: shardPaths.length, + identityCount: results.length, + replaceTags, + results, + }; + + if (args.out) { + await writeFile(resolve(args.out), `${JSON.stringify(summary, null, 2)}\n`, "utf8"); + } + + console.log(JSON.stringify(summary, null, 2)); +} + +async function discoverShardPaths(dir: string): Promise { + const entries = await readdir(dir, { withFileTypes: true }); + return entries + .filter((entry) => entry.isFile() && entry.name.startsWith("shard-") && entry.name.endsWith(".json")) + .map((entry) => join(dir, entry.name)) + .sort(); +} + +function normalizeResponse( + identity: RepoDiscordIdentity, + response: ResearchStressResponse, + updatedAt: string, + shardPath: string, + index: number, +) { + const responseId = requiredString(response.responseId, "responseId") + .trim() + .toLowerCase() + .replace(/[^a-z0-9._:-]+/g, "-"); + const anchors = (response.anchors ?? []).map((anchor, anchorIndex) => ({ + ref: requiredString(anchor.ref, `anchors[${anchorIndex}].ref`), + kind: stringOrDefault(anchor.kind, "research"), + summary: stringOrUndefined(anchor.summary), + })); + const tags = [ + "stress-response", + "researched-stress-profile", + `identity:${identity.id.toLowerCase()}`, + ...stringArray(response.tags), + ]; + + return { + responseId, + status: "active" as const, + trigger: requiredString(response.trigger, "trigger"), + summary: requiredString(response.summary, "summary"), + cognitiveDegradation: requiredString(response.cognitiveDegradation, "cognitiveDegradation"), + affectiveSignature: requiredString(response.affectiveSignature, "affectiveSignature"), + constraintLoss: requiredString(response.constraintLoss, "constraintLoss"), + behavioralLeak: requiredString(response.behavioralLeak, "behavioralLeak"), + tangentAttractors: stringArray(response.tangentAttractors), + cadence: stringOrUndefined(response.cadence), + recoveryPath: requiredString(response.recoveryPath, "recoveryPath"), + intensity: clampNumber(response.intensity, 0, 1, 0.8), + threshold: clampNumber(response.threshold, 0, 1, 0.56), + anchorRefs: anchors.length > 0 + ? anchors + : [{ ref: `stress-profile-shard:${shardPath}:${identity.id}:${index}`, kind: "research", summary: "Sub-agent stress profile shard did not provide a narrower anchor." }], + evidenceRefs: [], + sourceMemoryIds: [], + createdAt: updatedAt, + updatedAt, + tags: [...new Set(tags)], + }; +} + +function requiredString(value: unknown, field: string): string { + if (typeof value !== "string" || value.trim().length === 0) { + throw new Error(`Missing required ${field}.`); + } + return value.trim(); +} + +function stringOrUndefined(value: unknown): string | undefined { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined; +} + +function stringOrDefault(value: unknown, fallback: string): string { + return stringOrUndefined(value) ?? fallback; +} + +function stringArray(values: unknown): string[] { + if (!Array.isArray(values)) { + return []; + } + return values + .filter((value): value is string => typeof value === "string") + .map((value) => value.trim()) + .filter((value) => value.length > 0); +} + +function clampNumber(value: unknown, min: number, max: number, fallback: number): number { + return typeof value === "number" && Number.isFinite(value) + ? Math.min(max, Math.max(min, value)) + : fallback; +} + +function jsonStressResponsesWithoutTags(values: unknown, replaceTags: string[]): unknown[] { + if (!Array.isArray(values)) { + return []; + } + const tags = new Set(replaceTags); + return values.filter((value) => { + if (!value || typeof value !== "object" || !("tags" in value) || !Array.isArray(value.tags)) { + return true; + } + return !value.tags.some((tag) => typeof tag === "string" && tags.has(tag)); + }); +} + +function toPortableStressResponse(response: ReturnType): Record { + return { + id: response.responseId, + status: response.status, + trigger: response.trigger, + summary: response.summary, + cognitiveDegradation: response.cognitiveDegradation, + affectiveSignature: response.affectiveSignature, + constraintLoss: response.constraintLoss, + behavioralLeak: response.behavioralLeak, + tangentAttractors: response.tangentAttractors, + cadence: response.cadence, + recoveryPath: response.recoveryPath, + intensity: response.intensity, + threshold: response.threshold, + createdAt: response.createdAt, + updatedAt: response.updatedAt, + tags: response.tags, + extensions: { + anchors: response.anchorRefs.map((anchor) => anchor.ref), + }, + }; +} + +function stressResponsesAfterReplacement( + existing: { tags?: string[] }[], + replaceTags: string[], + addedCount: number, +): number { + const tags = new Set(replaceTags); + const retained = existing.filter((response) => { + if (!Array.isArray(response.tags)) { + return true; + } + return !response.tags.some((tag) => tags.has(tag)); + }); + return retained.length + addedCount; +} + +function parseList(value: string): string[] { + return value + .split(",") + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0); +} + +function parseArgs(argv: string[]): Record { + const parsed: Record = {}; + for (let index = 0; index < argv.length; index += 1) { + const token = argv[index]; + if (!token.startsWith("--")) { + continue; + } + const key = token.slice(2); + const next = argv[index + 1]; + if (!next || next.startsWith("--")) { + parsed[key] = "true"; + continue; + } + parsed[key] = next; + index += 1; + } + return parsed; +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 3ef5f39..fff54c1 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -381,3 +381,4 @@ {"ts":"2026-06-06T07:39:15Z","type":"verification","status":"ok","note":"Adjusted Nibu stress projection after user correction: polished venom remains core Nibu, but triggered speech should make the wound plain first, then let the companion-mask knife come out. Updated projector/turn prompts, Nibu stress cadences, and trigger smoke assertions. Full smoke now yields a short boundary-first Would say ('I am not your angry little ship waifu...') plus longer private explanation; typecheck/build/deterministic smoke passed."} {"ts":"2026-06-06T08:47:20Z","type":"implementation","status":"ok","note":"Registered Meita locally as a native swarm Persona backed by typed .cc state; enabled live REPO_PERSONA heartbeat env keys with heat for Nibu/Meita; prompt assembly verifies Meita .cc projection and Nibu stress-loaded affect state. Code now lets native Personas project .cc state and the swarm dashboard avoid the duplicate state-tree helper crash; CultMesh publish still hits the pre-existing MessagePack decode fault."} {"ts":"2026-06-06T08:58:51Z","type":"implementation","status":"ok","note":"Generalized Persona stress response seeding across the live swarm. scripts/seed-persona-stress-responses.mjs now writes one character-specific stress profile for every registered identity (Libby avoidant dissociation/submission, Aqua fawn-noise, Mimir severe withdrawal, Epiphany purity panic, etc.) while preserving Nibu's richer existing trigger map and Meita's Metacrat stress profiles. scripts/smoke-persona-stress-coverage.mjs verifies 17/17 identities have stress responses; Libby prompt assembly projects her avoidant collapse as character-facing pressure."} +{"ts":"2026-06-06T09:12:38Z","type":"implementation","status":"ok","note":"Dispatched six Persona stress-profile research shards across 17 identities, imported shard-*.json outputs through reusable agents:apply-stress-shards tooling, replaced swarm-generalization sketch stress responses in live Persona state, and verified stress coverage plus Libby projector prompt assembly."}