From 10413141afd6639756d5b2b71c44c986d392ae2b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:11:19 +0100 Subject: [PATCH] Remove dead scripts, disabled persona-feedback ingress, and source-grep safety theater --- tests/persona-feedback-cli.test.mjs | 130 ------------------ tests/persona-feedback-idunn-health.test.mjs | 40 ------ tests/persona-matrix-mouth-fetch.test.mjs | 14 +- tests/persona-matrix-mouth.test.mjs | 27 ---- tools/bifrost-discord-persona-ingress.mjs | 107 -------------- tools/bifrost-feedback-identity.mjs | 50 ------- tools/merge-saga-mutants.py | 83 ----------- tools/persona-feedback-documents.mjs | 45 ------ tools/persona-feedback-idunn-health.mjs | 70 ---------- tools/persona-feedback.mjs | 114 --------------- tools/persona-matrix-mouth.mjs | 2 +- ...ify-persona-feedback-release-authority.mjs | 23 ---- 12 files changed, 3 insertions(+), 702 deletions(-) delete mode 100644 tests/persona-feedback-cli.test.mjs delete mode 100644 tests/persona-feedback-idunn-health.test.mjs delete mode 100644 tools/bifrost-discord-persona-ingress.mjs delete mode 100644 tools/bifrost-feedback-identity.mjs delete mode 100644 tools/merge-saga-mutants.py delete mode 100644 tools/persona-feedback-documents.mjs delete mode 100644 tools/persona-feedback-idunn-health.mjs delete mode 100644 tools/persona-feedback.mjs delete mode 100644 tools/verify-persona-feedback-release-authority.mjs diff --git a/tests/persona-feedback-cli.test.mjs b/tests/persona-feedback-cli.test.mjs deleted file mode 100644 index 704d587..0000000 --- a/tests/persona-feedback-cli.test.mjs +++ /dev/null @@ -1,130 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { spawnSync } from "node:child_process"; -import { createHash, createPublicKey, verify } from "node:crypto"; -import { createRequire } from "node:module"; -import { mkdtemp, stat, readFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { resolve } from "node:path"; -import { buildFeedbackDefinitions } from "../tools/persona-feedback-documents.mjs"; -import { conversationFromDiscordMessage, discordGatewayReady } from "../tools/bifrost-discord-persona-ingress.mjs"; - -import { cultLibRoot } from "./cultlib-root.mjs"; -const root=resolve(import.meta.dirname,".."), cult=cultLibRoot; -const cr=createRequire(resolve(cult,"packages","cultcache-ts","package.json")); -const mr=createRequire(resolve(cult,"packages","cultmesh-ts","package.json")); -const {defineDocumentType}=cr("@gamecult/cultcache-ts"), {CultMesh}=mr("@gamecult/cultmesh-ts"), defs=buildFeedbackDefinitions(defineDocumentType); -const nr=createRequire(resolve(cult,"packages","cultnet-ts","package.json")),{decode,encode}=nr("@msgpack/msgpack"); - -test("Bifrost admits bound feedback as pressure only and exports CultNet",async()=>{ - const dir=await mkdtemp(resolve(tmpdir(),"bifrost-feedback-")), store=resolve(dir,"provider.cc"), observationStore=resolve(dir,"observations.cc"), deliveryStore=resolve(dir,"delivery.cc"), unusedDeliveryDefault=resolve(dir,"unused-delivery.cc"), out=resolve(dir,"feedback.msgpack"), key=resolve(dir,"identity.seed"), anchor=resolve(dir,"anchor.msgpack"),providerAnchor=resolve(dir,"provider-health-anchor.msgpack"); - cliNoStore("enroll-identity","--private-key",key,"--trust-anchor-out",anchor); - cliNoStore("export-provider-health-anchor","--private-key",key,"--trust-anchor-out",providerAnchor); - cli("bind-target",store,"--guild-id","g","--channel-id","c","--persona-id","epiphany","--repo","GameCult/Epiphany","--runtime-id","epiphany-yggdrasil","--producer-runtime-id","bifrost-discord-yggdrasil","--source-visibility","organization","--data-classification","organization_feedback","--delivery-store",deliveryStore); - await putEvent(observationStore,event("one","human-one")); - const sourceBefore=await readEvent(observationStore,"one"); - const served=cli("serve",store,"--observation-store",observationStore,"--once","true","--private-key",key,"--delivery-store",unusedDeliveryDefault,"--interval-ms","1"); - assert.equal(served.scanned,1);assert.equal(served.results[0].ok,true); - assert.deepEqual(await readEvent(observationStore,"one"),sourceBefore); - const n=await CultMesh.createNode(store,{documents:[defs.binding,defs.actorLink,defs.receipt,defs.delivery]});await n.cache?.pullAllBackingStores?.(); - const first={delivery:(await n.get(defs.delivery,"one"))?.value??await n.get(defs.delivery,"one"),receipt:(await n.get(defs.receipt,"one"))?.value??await n.get(defs.receipt,"one")}; - assert.equal(first.receipt.classification,"unlinked_social_feedback"); - assert.equal(first.delivery.authority,"feedback_only"); - assert.equal(first.delivery.packet.privateStateIncluded,false); - assert.equal(first.delivery.packet.sourceVisibility,"organization"); - assert.equal(first.delivery.packet.dataClassification,"organization_feedback"); - assert.match(first.delivery.packetSha256,/^sha256-[a-f0-9]{64}$/); - assert.equal(Object.keys(first.delivery.providerSignature).length,64); - const signed=(await n.get(defs.delivery,"one"))?.value??await n.get(defs.delivery,"one"), trust=decode(await readFile(anchor)); - assert.equal(signed.packetSha256,`sha256-${createHash("sha256").update(encode(packetTuple(signed.packet))).digest("hex")}`); - assert.equal(signed.sourceObserverId,"bifrost-discord");assert.equal(signed.provider,"bifrost"); - const payload=encode([signed.schemaVersion,signed.admissionId,packetTuple(signed.packet),signed.packetSha256,signed.sourceObserverId,signed.sourceObserverRuntimeId,signed.provider,signed.bifrostAdmissionReceiptId,signed.authority,signed.providerIdentityId]); - const purpose=Buffer.from("bifrost.persona-feedback.delivery.v0"),domain=Buffer.from("epiphany.host-incarnation.signature.v0\0"),message=Buffer.concat([domain,u64(purpose.length),purpose,u64(payload.length),payload]); - assert.equal(trust.length,6); assert.equal(trust[0],"epiphany.host_identity_trust_anchor.v0"); assert.equal(trust[1],signed.providerIdentityId); - const providerTrust=decode(await readFile(providerAnchor));assert.equal(providerTrust.length,6);assert.equal(providerTrust[0],"gamecult.provider_health_identity.trust_anchor.v1");assert.equal(providerTrust[1],createHash("sha256").update(Buffer.from("gamecult.provider-health.identity.v1\0")).update(providerTrust[2]).digest("hex"));assert.notEqual(providerTrust[1],trust[1]);assert.deepEqual(providerTrust[2],trust[2]); - const overwrite=spawnSync(process.execPath,[resolve(root,"tools","persona-feedback.mjs"),"export-provider-health-anchor","--private-key",key,"--trust-anchor-out",providerAnchor],{cwd:root,encoding:"utf8"});assert.notEqual(overwrite.status,0);assert.match(overwrite.stderr,/already exists|EEXIST/); - const publicKey=createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),Buffer.from(trust[2])]),format:"der",type:"spki"}); - assert.equal(verify(null,message,publicKey,Buffer.from(signed.providerSignature)),true); - assert.equal(first.receipt.grantsWorkAuthority,false); - cli("link-actor",store,"--guild-id","g","--discord-author-id","human-two","--bifrost-actor-id","member:42","--heimdall-actor-ref","heimdall:42"); - await putEvent(observationStore,event("two","human-two")); - assert.equal(cli("process",store,"--observation-store",observationStore,"--event-id","two","--private-key",key,"--delivery-store",deliveryStore).receipt.classification,"linked_governance_feedback"); - const replay=cli("process",store,"--observation-store",observationStore,"--event-id","two","--private-key",key,"--delivery-store",deliveryStore); - assert.equal(replay.receiptId,"two"); - const exported=cli("export",store,"--out",out); - assert.ok(exported.documentCount>=4); assert.ok((await stat(out)).size>0); - const deliveryCache=cr("@gamecult/cultcache-ts").CultCache.builder().withDocumentType(defs.delivery).withGenericStore(new (cr("@gamecult/cultcache-ts").SingleFileMessagePackBackingStore)(deliveryStore)).build();await deliveryCache.pullAllBackingStores();assert.equal(deliveryCache.getAll(defs.delivery).length,2); - const beforeStatus=await Promise.all([store,observationStore,deliveryStore,key].map(path=>readFile(path))); - const readiness=cli("status",store,"--observation-store",observationStore,"--private-key",key); - assert.equal(readiness.schemaVersion,"bifrost.persona_feedback.readiness.v0");assert.equal(readiness.status,"ready");assert.equal(readiness.bindingCount,1);assert.equal(readiness.pendingFailedCount,0);assert.equal(readiness.privateStateExposed,false); - const staged=cli("status",store,"--observation-store",observationStore,"--private-key",key); - assert.equal(staged.ingressReady,true);assert.deepEqual(staged.ingressReasons,[]);assert.equal(staged.personaDelivery,undefined);assert.equal(staged.status,"ready"); - const afterStatus=await Promise.all([store,observationStore,deliveryStore,key].map(path=>readFile(path)));assert.deepEqual(afterStatus,beforeStatus); - const Store=cr("@gamecult/cultcache-ts").SingleFileMessagePackBackingStore; - assert.deepEqual([...new Set((await new Store(observationStore).pullAll()).map(entry=>entry.type))],["bifrost.discord.persona_conversation_event"]); - assert.equal((await new Store(store).pullAll()).some(entry=>entry.type==="bifrost.discord.persona_conversation_event"),false); - assert.deepEqual([...new Set((await new Store(deliveryStore).pullAll()).map(entry=>entry.type))],["bifrost.persona_feedback.delivery"]); - await assert.rejects(stat(unusedDeliveryDefault)); -}); - -test("Bifrost rejects an event without exact target binding",async()=>{const dir=await mkdtemp(resolve(tmpdir(),"bifrost-feedback-")),store=resolve(dir,"provider.cc"),observationStore=resolve(dir,"observations.cc");await putEvent(observationStore,event("wrong","human","other-runtime"));const r=raw("process",store,"--observation-store",observationStore,"--event-id","wrong");assert.notEqual(r.status,0);assert.match(r.stderr,/No exact Bifrost target binding/);assert.equal((await readEvent(observationStore,"wrong")).status,"pending");}); - -test("Bifrost rejects aliased observation, private, and delivery stores",async()=>{const dir=await mkdtemp(resolve(tmpdir(),"bifrost-feedback-")),store=resolve(dir,"provider.cc"),observations=resolve(dir,"observations.cc");await putEvent(observations,event("alias","human"));const r=raw("bind-target",store,"--observation-store",observations,"--guild-id","g","--channel-id","c","--persona-id","epiphany","--repo","GameCult/Epiphany","--runtime-id","epiphany-yggdrasil","--producer-runtime-id","bifrost-discord-yggdrasil","--source-visibility","organization","--data-classification","organization_feedback","--delivery-store",store);assert.notEqual(r.status,0);assert.match(r.stderr,/distinct canonical paths/);}); - -test("Bifrost rejects mismatched classification and malformed observations",async()=>{const dir=await mkdtemp(resolve(tmpdir(),"bifrost-feedback-")),store=resolve(dir,"provider.cc"),observations=resolve(dir,"observations.cc"),delivery=resolve(dir,"delivery.cc");const mismatch=raw("bind-target",store,"--observation-store",observations,"--guild-id","g","--channel-id","c","--persona-id","epiphany","--repo","GameCult/Epiphany","--runtime-id","epiphany-yggdrasil","--producer-runtime-id","bifrost-discord-yggdrasil","--source-visibility","private","--data-classification","public_feedback","--delivery-store",delivery);assert.notEqual(mismatch.status,0);assert.match(mismatch.stderr,/exact admitted pair/);for(const malformed of [{observedAt:"yesterday"},{addressingMode:"ambient"},{authorityClass:"work"},{status:"admitted"},{payloadHash:"not-a-digest"},{producerId:"voidbot"}])await assert.rejects(putEvent(observations,{...event(`bad-${Object.keys(malformed)[0]}`,"human"),...malformed}));}); - -test("native Discord ingress admits only direct human address",()=>{ - const base={id:"m1",guild_id:"g",channel_id:"c",timestamp:"2026-07-21T20:00:00.000Z",author:{id:"human",username:"Human",bot:false},content:"<@42> hello Epiphany",mentions:[{id:"42"}]}; - const admitted=conversationFromDiscordMessage(base,"42");assert.equal(admitted.content,"hello Epiphany");assert.equal(admitted.addressingMode,"text");assert.match(admitted.payloadHash,/^[a-f0-9]{64}$/); - assert.equal(conversationFromDiscordMessage({...base,author:{id:"bot",bot:true}},"42"),null); - assert.equal(conversationFromDiscordMessage({...base,mentions:[],content:"ambient chatter"},"42"),null); - assert.equal(conversationFromDiscordMessage({...base,mentions:[{id:"42"}],content:"<@42> "},"42"),null); - assert.equal(conversationFromDiscordMessage({...base,content:`<@42> ${"x".repeat(1201)}`},"42"),null); - assert.equal(conversationFromDiscordMessage({...base,content:`<@42> ${"x".repeat(1200)}`},"42").content.length,1200); - assert.equal(Buffer.byteLength(conversationFromDiscordMessage({...base,content:`<@42> ${"😀".repeat(300)}`},"42").content,"utf8"),1200); - assert.equal(conversationFromDiscordMessage({...base,content:`<@42> ${"😀".repeat(301)}`},"42"),null); - assert.equal(conversationFromDiscordMessage({...base,timestamp:"not-a-time"},"42"),null); - const reply=conversationFromDiscordMessage({...base,mentions:[],content:"following up",referenced_message:{author:{id:"42"}}},"42");assert.equal(reply.addressingMode,"reply"); - const commandShaped=conversationFromDiscordMessage({...base,content:"<@42> /epiphany wake"},"42");assert.equal(commandShaped.content,"/epiphany wake");assert.equal(commandShaped.addressingMode,"text"); -}); - -test("Discord gateway health fails closed while disconnected or heartbeat-stale",()=>{ - const now=1_000_000; - assert.equal(discordGatewayReady({connected:false,sessionId:"s",lastHeartbeatAckAtMillis:now},now),false); - assert.equal(discordGatewayReady({connected:true,sessionId:"",lastHeartbeatAckAtMillis:now},now),false); - assert.equal(discordGatewayReady({connected:true,sessionId:"s",lastHeartbeatAckAtMillis:0},now),false); - assert.equal(discordGatewayReady({connected:true,sessionId:"s",lastHeartbeatAckAtMillis:now-120001},now),false); - assert.equal(discordGatewayReady({connected:true,sessionId:"s",lastHeartbeatAckAtMillis:now-120000},now),true); -}); - -test("serve drains a persisted observation left by a failed prior process",async()=>{ - const dir=await mkdtemp(resolve(tmpdir(),"bifrost-feedback-recovery-")),store=resolve(dir,"provider.cc"),observations=resolve(dir,"observations.cc"),delivery=resolve(dir,"delivery.cc"),key=resolve(dir,"identity.seed"),anchor=resolve(dir,"anchor.msgpack"); - cli("bind-target",store,"--guild-id","g","--channel-id","c","--persona-id","epiphany","--repo","GameCult/Epiphany","--runtime-id","epiphany-yggdrasil","--producer-runtime-id","bifrost-discord-yggdrasil","--source-visibility","organization","--data-classification","organization_feedback","--delivery-store",delivery); - await putEvent(observations,event("crash-recovery","human")); - const failed=raw("process",store,"--observation-store",observations,"--event-id","crash-recovery","--private-key",key,"--delivery-store",delivery);assert.notEqual(failed.status,0); - cliNoStore("enroll-identity","--private-key",key,"--trust-anchor-out",anchor); - const recovered=cli("serve",store,"--observation-store",observations,"--once","true","--private-key",key,"--delivery-store",delivery,"--interval-ms","1");assert.equal(recovered.scanned,1);assert.equal(recovered.results[0].ok,true); - const n=await CultMesh.createNode(store,{documents:[defs.binding,defs.actorLink,defs.receipt,defs.delivery]});await n.cache?.pullAllBackingStores?.();assert.ok((await n.get(defs.receipt,"crash-recovery"))); -}); - -test("serve durably accounts for failed pending observations and clears them after admission",async()=>{ - const dir=await mkdtemp(resolve(tmpdir(),"bifrost-feedback-failure-")),store=resolve(dir,"provider.cc"),observations=resolve(dir,"observations.cc"),delivery=resolve(dir,"delivery.cc"),key=resolve(dir,"identity.seed"),anchor=resolve(dir,"anchor.msgpack"); - cli("bind-target",store,"--guild-id","g","--channel-id","c","--persona-id","epiphany","--repo","GameCult/Epiphany","--runtime-id","epiphany-yggdrasil","--producer-runtime-id","bifrost-discord-yggdrasil","--source-visibility","organization","--data-classification","organization_feedback","--delivery-store",delivery); - await putEvent(observations,event("retry-evidence","human")); - const failed=cli("serve",store,"--observation-store",observations,"--once","true","--private-key",key,"--delivery-store",delivery,"--interval-ms","1"); - assert.equal(failed.results[0].ok,false);assert.equal(failed.readiness.status,"degraded");assert.equal(failed.readiness.pendingFailedCount,1);assert.match(failed.readiness.reasons[0],/identity|pendingFailures/); - let n=await CultMesh.createNode(store,{documents:[defs.binding,defs.actorLink,defs.receipt,defs.delivery,defs.pendingFailure]});await n.cache?.pullAllBackingStores?.(); - const evidence=(await n.get(defs.pendingFailure,"retry-evidence"))?.value??await n.get(defs.pendingFailure,"retry-evidence");assert.equal(evidence.attemptCount,1);assert.equal(evidence.privateStateExposed,false);assert.ok(Buffer.byteLength(evidence.lastError,"utf8")<=512); - cliNoStore("enroll-identity","--private-key",key,"--trust-anchor-out",anchor); - const recovered=cli("serve",store,"--observation-store",observations,"--once","true","--private-key",key,"--delivery-store",delivery,"--interval-ms","1");assert.equal(recovered.results[0].ok,true);assert.equal(recovered.readiness.pendingFailedCount,0);assert.equal(recovered.readiness.status,"ready"); - n=await CultMesh.createNode(store,{documents:[defs.binding,defs.actorLink,defs.receipt,defs.delivery,defs.pendingFailure]});await n.cache?.pullAllBackingStores?.();assert.equal(await n.get(defs.pendingFailure,"retry-evidence"),undefined); -}); - -function event(id,author,targetRuntimeId="epiphany-yggdrasil"){const content=`feedback ${id}`;return {schemaName:"bifrost.discord.persona_conversation_event",schemaVersion:"bifrost.discord.persona_conversation_event.v0",eventId:id,observedAt:new Date().toISOString(),guildId:"g",channelId:"c",messageId:`m-${id}`,authorId:author,authorName:author,addressingMode:"role",targetPersonaId:"epiphany",targetRepoName:"GameCult/Epiphany",targetRuntimeId,content,payloadHash:createHash("sha256").update(content).digest("hex"),producerId:"bifrost-discord",producerRuntimeId:"bifrost-discord-yggdrasil",authorityClass:"feedback_only",status:"pending"};} -async function putEvent(store,value){const n=await CultMesh.createNode(store,{documents:[defs.event]});await n.put(defs.event,value.eventId,value);await n.flush?.();} -async function readEvent(store,id){const n=await CultMesh.createNode(store,{documents:[defs.event]});await n.cache?.pullAllBackingStores?.();return (await n.get(defs.event,id))?.value??await n.get(defs.event,id);} -function raw(command,store,...args){return spawnSync(process.execPath,[resolve(root,"tools","persona-feedback.mjs"),command,"--store",store,...args],{cwd:root,encoding:"utf8"});} -function cli(command,store,...args){const r=raw(command,store,...args);assert.equal(r.status,0,r.stderr||r.stdout);return JSON.parse(r.stdout);} -function cliNoStore(command,...args){const r=spawnSync(process.execPath,[resolve(root,"tools","persona-feedback.mjs"),command,...args],{cwd:root,encoding:"utf8"});assert.equal(r.status,0,r.stderr||r.stdout);return JSON.parse(r.stdout);} -function packetTuple(p){return [p.feedbackId,p.sourceEventId,p.sourceActorId,p.actorClassification,p.actorLinkRefs,p.discordGuildId,p.discordChannelId,p.discordMessageId,p.targetRuntimeId,p.targetRepository,p.targetPersonaId,p.sourceRoomId,p.feedbackText,p.contentSha256,p.sourceDiscussionRefs,p.sourceVisibility,p.dataClassification,p.privateStateIncluded];} -function u64(v){const b=Buffer.alloc(8);b.writeBigUInt64BE(BigInt(v));return b;} diff --git a/tests/persona-feedback-idunn-health.test.mjs b/tests/persona-feedback-idunn-health.test.mjs deleted file mode 100644 index 80c3a0f..0000000 --- a/tests/persona-feedback-idunn-health.test.mjs +++ /dev/null @@ -1,40 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { createHash, createPublicKey, verify } from "node:crypto"; -import { createRequire } from "node:module"; -import { mkdtemp } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { resolve } from "node:path"; -import { enrollBifrostFeedbackIdentity, providerHealthIdentity, signFeedbackAdmission } from "../tools/bifrost-feedback-identity.mjs"; -import { createPersonaFeedbackHealthPublisher, createSignedHealthRawPut, createSignedPersonaFeedbackHealth, signedHealthSourceRole } from "../tools/persona-feedback-idunn-health.mjs"; - -import { cultLibRoot } from "./cultlib-root.mjs"; -const root=resolve(import.meta.dirname,".."),cult=cultLibRoot,require=createRequire(resolve(cult,"packages","cultnet-ts","package.json")),{encode,decode}=require("@msgpack/msgpack"); -const idDomain=Buffer.from("gamecult.provider-health.identity.v1\0"),signatureDomain=Buffer.from("gamecult.provider-health.signature.v1\0"),purpose=Buffer.from("idunn.signed_daemon_health.v1"); - -test("Persona-feedback emits the exact canonical signed daemon-health tuple",async()=>{ - assert.equal(signedHealthSourceRole,"daemon-health-publisher"); - const identity=await identityFixture(),incarnation="019f523f-f650-7001-be75-b4428985652b",signed=createSignedPersonaFeedbackHealth({daemonId:"yggdrasil-bifrost-persona-feedback",healthContract:"bifrost.cultnet-rudp-persona-feedback-health",state:"active",detail:"ready",identity,publisherIncarnationId:incarnation,publisherSequence:7,observedAtUnixMillis:1773950400123}),record=decode(signed.payload,{useBigInt64:true}); - assert.equal(record.length,17);assert.deepEqual(record.slice(0,10),["idunn.signed_daemon_health.v1","yggdrasil-bifrost-persona-feedback","bifrost.cultnet-rudp-persona-feedback-health","bifrost-persona-feedback","active","ready",signed.providerIdentityId,incarnation,7,1773950400123n]);assert.deepEqual(record.slice(10,14),[null,null,null,null]);assert.ok(record[15] instanceof Uint8Array);assert.equal(record[14],"ed25519");assert.equal(record[15].length,64);assert.equal(record[16],false); - const put=createSignedHealthRawPut("yggdrasil-bifrost-persona-feedback",signed);assert.equal(put.document.recordKey,"yggdrasil-bifrost-persona-feedback");assert.equal(put.document.sourceRuntimeId,"bifrost-persona-feedback");assert.equal(put.document.sourceRole,"daemon-health-publisher");assert.equal(put.document.schemaId,"idunn.signed_daemon_health");assert.deepEqual(put.document.payload,signed.payload); - const canonical=[...record];canonical[15]=new Uint8Array();assert.equal(verifyProvider(identity,encode(canonical,{useBigInt64:true}),record[15]),true); - assert.equal(signed.providerIdentityId,createHash("sha256").update(idDomain).update(identity.publicKey).digest("hex"));assert.notEqual(signed.providerIdentityId,identity.identityId); -}); - -test("provider-health signature rejects purpose, key, and payload substitution",async()=>{ - const identity=await identityFixture(),other=await identityFixture(),signed=createSignedPersonaFeedbackHealth({daemonId:"daemon",healthContract:"contract",state:"degraded",detail:"readiness-degraded",identity,publisherIncarnationId:"019f523f-f650-7001-be75-b4428985652b",publisherSequence:1,observedAtUnixMillis:1773950400123}),record=decode(signed.payload,{useBigInt64:true}),canonical=[...record];canonical[15]=new Uint8Array(); - const canonicalPayload=encode(canonical,{useBigInt64:true});assert.equal(verifyProvider(identity,canonicalPayload,record[15]),true);assert.equal(verifyProvider(other,canonicalPayload,record[15]),false); - const mutated=[...canonical];mutated[4]="active";assert.equal(verifyProvider(identity,encode(mutated,{useBigInt64:true}),record[15]),false); - const oldDomainSignature=signFeedbackAdmission(identity,canonicalPayload);assert.equal(verifyProvider(identity,canonicalPayload,oldDomainSignature),false); - const unsignedDiagnostic=[record[1],record[4],record[5],new Date(Number(record[9])).toISOString(),record[2],"diagnostic-only","cultnet.transport.rudp.v0"];assert.equal(verifyProvider(identity,encode(unsignedDiagnostic),record[15]),false); -}); - -test("publisher sequence and process incarnation are mandatory protocol state",async()=>{ - const identity=await identityFixture(),base={daemonId:"daemon",healthContract:"contract",state:"warming",detail:"starting",identity,publisherIncarnationId:"019f523f-f650-7001-be75-b4428985652b",publisherSequence:1,observedAtUnixMillis:1773950400123}; - for(const bad of [{publisherSequence:0},{publisherSequence:1.5},{publisherIncarnationId:"process-1"},{state:"healthy"},{detail:"private database error"}])assert.throws(()=>createSignedPersonaFeedbackHealth({...base,...bad})); - const publisher=createPersonaFeedbackHealthPublisher(identity,base.publisherIncarnationId),first=publisher.next({daemonId:base.daemonId,healthContract:base.healthContract,state:base.state,detail:base.detail,observedAtUnixMillis:base.observedAtUnixMillis}),second=publisher.next({daemonId:base.daemonId,healthContract:base.healthContract,state:base.state,detail:base.detail,observedAtUnixMillis:base.observedAtUnixMillis+1});assert.equal(decode(first.payload)[7],decode(second.payload)[7]);assert.equal(decode(second.payload)[8],decode(first.payload)[8]+1); -}); - -async function identityFixture(){const dir=await mkdtemp(resolve(tmpdir(),"bifrost-provider-health-"));return enrollBifrostFeedbackIdentity(resolve(dir,"feedback.seed"));} -function verifyProvider(identity,payload,signature){const key=createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),Buffer.from(identity.publicKey)]),format:"der",type:"spki"}),message=Buffer.concat([signatureDomain,u64(purpose.length),purpose,u64(payload.length),Buffer.from(payload)]);return verify(null,message,key,Buffer.from(signature));} -function u64(value){const out=Buffer.alloc(8);out.writeBigUInt64BE(BigInt(value));return out;} diff --git a/tests/persona-matrix-mouth-fetch.test.mjs b/tests/persona-matrix-mouth-fetch.test.mjs index 2d2ed01..faf8a39 100644 --- a/tests/persona-matrix-mouth-fetch.test.mjs +++ b/tests/persona-matrix-mouth-fetch.test.mjs @@ -5,7 +5,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; -import { readFileSync, readdirSync } from "node:fs"; +import { readdirSync } from "node:fs"; import { resolve } from "node:path"; import { createMouth, createRoomGate, fetchFromEnv } from "../tools/persona-matrix-mouth.mjs"; import { createImageStore, MAX_BYTES } from "../tools/persona-chat-images.mjs"; @@ -22,7 +22,7 @@ const FILE = "$file1"; const ROOT = "$album1"; const TOKEN = "tok-secret-eureka"; const sha = bytes => createHash("sha256").update(bytes).digest("hex"); -const PLATFORM = ["disc", "ord"].join(""); +const PLATFORM = "discord"; const IMG = png(8, 8); const IMG_SHA = sha(IMG); const thread = { rel_type: "m.thread", event_id: ROOT }; @@ -568,16 +568,6 @@ test("the flag is exactly one", () => { assert.equal(fetchFromEnv({ CHAT_FETCH: "1" }), true); }); -test("images.put has exactly two call sites in the mouth and the fetch's comes after the hash decision; no second media fetcher", () => { - const source = readFileSync(resolve(import.meta.dirname, "..", "tools", "persona-matrix-mouth.mjs"), "utf8"); - assert.equal(source.match(/images\.put\(/g).length, 2); - const fetchBody = source.slice(source.indexOf("async function fetchAttachment"), source.indexOf("async function postFileReceipt")); - assert.ok(fetchBody.indexOf("HashMismatch") < fetchBody.indexOf("images.put("), "the hash decision precedes the put"); - assert.ok(fetchBody.indexOf("throwIfAborted", fetchBody.indexOf("HashMismatch")) < fetchBody.indexOf("images.put("), "the deadline is checked right before the put"); - assert.ok(!/media\/download/.test(source), "no media GET outside fetchImage"); - assert.equal([...source.matchAll(/\/state\/(m\.|uk\.)|event_type=/g)].length, 0); -}); - test("the receipt names the event the GET resolved: reference and content.event_id both carry the returned id, in a thread file and a plain one", async () => { const answered = { type: "m.room.message", event_id: "$resolved", room_id: ROOM, sender: OTHER }; const plain = synapse({ events: { [FILE]: { ...answered, content: plainFile(undefined)[FILE].content } } }); diff --git a/tests/persona-matrix-mouth.test.mjs b/tests/persona-matrix-mouth.test.mjs index 958b684..73a57ea 100644 --- a/tests/persona-matrix-mouth.test.mjs +++ b/tests/persona-matrix-mouth.test.mjs @@ -1,7 +1,6 @@ import test from "node:test"; import assert from "node:assert/strict"; import { EventEmitter } from "node:events"; -import { readFileSync, readdirSync, statSync } from "node:fs"; import { resolve, join } from "node:path"; import { existsSync, mkdtempSync, statSync as stat } from "node:fs"; import { tmpdir } from "node:os"; @@ -333,27 +332,6 @@ test("a homeserver error is reported with its status and none of its body", asyn } finally { await hs.close(); } }); -function walk(dir, out = []) { - for (const name of readdirSync(dir)) { - if (name === ".git" || name === "node_modules" || name === "bin" || name === "obj") continue; - const full = join(dir, name); - statSync(full).isDirectory() ? walk(full, out) : out.push(full); - } - return out; -} - -test("the Discord posting actuator is gone and the Matrix path names no Discord", () => { - const root = resolve(import.meta.dirname, ".."); - for (const file of ["tools/persona-matrix-mouth.mjs", "tools/persona-chat-documents.mjs"]) { - assert.ok(!/discord/i.test(readFileSync(resolve(root, file), "utf8")), `${file} mentions Discord`); - } - const survivors = walk(root).filter(f => /\.(mjs|cs|json|ya?ml|ps1|sh)$/.test(f) && /persona-discord-delivery/.test(readFileSync(f, "utf8")) && !/persona-matrix-mouth\.test\.mjs$/.test(f)); - assert.deepEqual(survivors, []); - for (const gone of ["persona-discord-delivery.mjs", "persona-discord-rudp.mjs", "persona-discord-delivery-documents.mjs", "persona-discord-permit.mjs"]) { - assert.throws(() => statSync(resolve(root, "tools", gone))); - } -}); - // ---- one mouth, many Personas ---------------------------------------------------- const NOVA = `@nova:${HS_NAME}`; @@ -506,11 +484,6 @@ test("guarded: a failure leaves with every secret redacted, however many tokens assert.equal(await guarded([TOKEN], async () => 5), 5); }); -test("the ring is gone: the mouth names no unit manager and spawns no child", () => { - const source = readFileSync(resolve(import.meta.dirname, "..", "tools", "persona-matrix-mouth.mjs"), "utf8"); - assert.ok(!/systemctl|child_process|execFile|mind-persona@/.test(source)); -}); - test("delivery_poison_pill: a non-string display name or malformed event fields never reach a delivery; the sender falls back to its localpart", async () => { const hs = await fakeHomeserver({ sync: since => since === null ? { next_batch: "b0" } : { next_batch: "b1", ...joined({ "!swarm:gamecult.test": { diff --git a/tools/bifrost-discord-persona-ingress.mjs b/tools/bifrost-discord-persona-ingress.mjs deleted file mode 100644 index 3c08602..0000000 --- a/tools/bifrost-discord-persona-ingress.mjs +++ /dev/null @@ -1,107 +0,0 @@ -import { createHash } from "node:crypto"; - -const GATEWAY_VERSION = 10; -const GATEWAY_INTENTS = (1 << 0) | (1 << 9) | (1 << 15); - -export function conversationFromDiscordMessage(message, botUserId) { - if (!message || typeof message !== "object" || message.author?.bot === true) return null; - const guildId = text(message.guild_id); - const channelId = text(message.channel_id); - const messageId = text(message.id); - const authorId = text(message.author?.id); - const observedAt = Date.parse(String(message.timestamp ?? "")); - if (!guildId || !channelId || !messageId || !authorId || !botUserId || !Number.isFinite(observedAt)) return null; - const mentioned = Array.isArray(message.mentions) - && message.mentions.some((mention) => String(mention?.id ?? "") === botUserId); - const replied = String(message.referenced_message?.author?.id ?? "") === botUserId; - if (!mentioned && !replied) return null; - const content = String(message.content ?? "") - .replace(new RegExp(`<@!?${escapeRegex(botUserId)}>`, "g"), " ") - .replace(/\s+/g, " ") - .trim(); - if (!content || Buffer.byteLength(content, "utf8") > 1200) return null; - return { - guildId, - channelId, - messageId, - authorId, - authorName: text(message.member?.nick) || text(message.author?.global_name) || text(message.author?.username) || authorId, - content, - addressingMode: mentioned ? "text" : "reply", - observedAt: new Date(observedAt).toISOString(), - payloadHash: createHash("sha256").update(content, "utf8").digest("hex"), - }; -} - -export function discordGatewayReady(state, nowMillis = Date.now(), maxAckAgeMillis = 120000) { - return state?.connected === true - && text(state.sessionId) !== "" - && Number.isFinite(state.lastHeartbeatAckAtMillis) - && state.lastHeartbeatAckAtMillis > 0 - && nowMillis >= state.lastHeartbeatAckAtMillis - && nowMillis - state.lastHeartbeatAckAtMillis <= maxAckAgeMillis; -} - -export async function serveDiscordPersonaIngress({ token, runtimeId, onConversation, onReady = () => {}, onDisconnect = () => {}, onState = () => {} }) { - if (!text(token)) throw new Error("Bifrost Discord Persona ingress requires a bot token."); - if (!text(runtimeId)) throw new Error("Bifrost Discord Persona ingress requires a runtime id."); - if (typeof onConversation !== "function") throw new Error("Bifrost Discord Persona ingress requires a conversation sink."); - onState({connected:false,sessionId:"",lastHeartbeatAckAtMillis:0,phase:"discovering"}); - const gateway = await discordJson("https://discord.com/api/v10/gateway/bot", token); - if (!text(gateway?.url)) throw new Error("Discord gateway discovery returned no URL."); - onState({connected:false,sessionId:"",lastHeartbeatAckAtMillis:0,phase:"discovered"}); - let sequence = null, sessionId = "", resumeUrl = gateway.url, botUserId = "", stopped = false; - while (!stopped) { - try { - const result = await gatewaySession({ token, runtimeId, url: resumeUrl, sequence, sessionId, botUserId, onConversation, onReady, onState }); - sequence = result.sequence; sessionId = result.sessionId; resumeUrl = result.resumeUrl; botUserId = result.botUserId; - stopped = result.stopped; - } catch (error) { - if (error?.fatal === true) throw error; - onState({connected:false,sessionId,botUserId,lastHeartbeatAckAtMillis:0,phase:"disconnected"}); - onDisconnect(error); - await delay(2000); - } - } -} - -async function gatewaySession(state) { - const socket = new WebSocket(`${state.url}/?v=${GATEWAY_VERSION}&encoding=json`); - let sequence=state.sequence,sessionId=state.sessionId,resumeUrl=state.url,botUserId=state.botUserId,heartbeatTimer=null,heartbeatAck=true,stopped=false; - await new Promise((resolve, reject) => { - const cleanup=()=>{if(heartbeatTimer)clearInterval(heartbeatTimer);}; - socket.addEventListener("error",()=>{cleanup();reject(new Error("Discord gateway socket failed."));},{once:true}); - socket.addEventListener("close",(event)=>{cleanup();state.onState({connected:false,sessionId,botUserId,lastHeartbeatAckAtMillis:0,phase:"disconnected"});if([4004,4013,4014].includes(event.code)){stopped=true;const error=new Error(`Discord permanently rejected the Bifrost gateway session (close ${event.code}).`);error.fatal=true;reject(error);return;}resolve();},{once:true}); - socket.addEventListener("message",async event=>{ - try { - const frame=JSON.parse(String(event.data)); - if(Number.isInteger(frame.s))sequence=frame.s; - if(frame.op===10){ - const interval=Number(frame.d?.heartbeat_interval);if(!Number.isFinite(interval)||interval<1000)throw new Error("Discord gateway supplied an invalid heartbeat interval."); - const heartbeat=()=>{if(!heartbeatAck){socket.close(4000,"heartbeat timeout");return;}heartbeatAck=false;socket.send(JSON.stringify({op:1,d:sequence}));}; - heartbeatTimer=setInterval(heartbeat,interval);heartbeat(); - if(sessionId&&sequence!==null)socket.send(JSON.stringify({op:6,d:{token:state.token,session_id:sessionId,seq:sequence}})); - else socket.send(JSON.stringify({op:2,d:{token:state.token,intents:GATEWAY_INTENTS,properties:{os:process.platform,browser:"bifrost",device:"bifrost"}}})); - } else if(frame.op===11){heartbeatAck=true;state.onState({connected:true,sessionId,botUserId,lastHeartbeatAckAtMillis:Date.now(),phase:"heartbeat-acknowledged"});} - else if(frame.op===7)socket.close(4000,"server reconnect"); - else if(frame.op===9){sessionId="";sequence=null;socket.close(4000,"invalid session");} - else if(frame.op===0&&frame.t==="READY"){ - sessionId=text(frame.d?.session_id);resumeUrl=text(frame.d?.resume_gateway_url)||state.url;botUserId=text(frame.d?.user?.id);if(!sessionId||!botUserId)throw new Error("Discord READY omitted session or bot identity.");state.onState({connected:true,sessionId,botUserId,lastHeartbeatAckAtMillis:0,phase:"ready-awaiting-heartbeat-ack"});await state.onReady({runtimeId:state.runtimeId,botUserId,sessionId}); - } else if(frame.op===0&&frame.t==="RESUMED"){state.onState({connected:true,sessionId,botUserId,lastHeartbeatAckAtMillis:0,phase:"resumed-awaiting-heartbeat-ack"});await state.onReady({runtimeId:state.runtimeId,botUserId,sessionId});} - else if(frame.op===0&&frame.t==="MESSAGE_CREATE"){ - const conversation=conversationFromDiscordMessage(frame.d,botUserId);if(conversation)await state.onConversation(conversation); - } - } catch(error){socket.close(4000,"ingress failure");reject(error);} - }); - }); - return {sequence,sessionId,resumeUrl,botUserId,stopped}; -} - -async function discordJson(url, token) { - const response=await fetch(url,{headers:{authorization:`Bot ${token}`},redirect:"error",signal:AbortSignal.timeout(15000)}); - if(!response.ok)throw new Error(`Discord gateway discovery failed with HTTP ${response.status}.`); - return response.json(); -} -function text(value){return typeof value==="string"?value.trim():"";} -function escapeRegex(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");} -function delay(ms){return new Promise(resolve=>setTimeout(resolve,ms));} diff --git a/tools/bifrost-feedback-identity.mjs b/tools/bifrost-feedback-identity.mjs deleted file mode 100644 index 1dbab9e..0000000 --- a/tools/bifrost-feedback-identity.mjs +++ /dev/null @@ -1,50 +0,0 @@ -import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign as ed25519Sign } from "node:crypto"; -import { chmod, mkdir, open, readFile, stat } from "node:fs/promises"; -import { dirname, resolve } from "node:path"; - -const ID_DOMAIN=Buffer.from("epiphany.host-incarnation.identity.v0\0","utf8"); -const SIGNATURE_DOMAIN=Buffer.from("epiphany.host-incarnation.signature.v0\0","utf8"); -const PROVIDER_HEALTH_ID_DOMAIN=Buffer.from("gamecult.provider-health.identity.v1\0","utf8"); -const PROVIDER_HEALTH_SIGNATURE_DOMAIN=Buffer.from("gamecult.provider-health.signature.v1\0","utf8"); -export const FEEDBACK_SIGNING_PURPOSE="bifrost.persona-feedback.delivery.v0"; -export const IDUNN_SIGNED_DAEMON_HEALTH_PURPOSE="idunn.signed_daemon_health.v1"; -export const PROVIDER_HEALTH_TRUST_ANCHOR_SCHEMA="gamecult.provider_health_identity.trust_anchor.v1"; - -export async function enrollBifrostFeedbackIdentity(privateKeyPath){ - await mkdir(dirname(privateKeyPath),{recursive:true}); - const {privateKey}=generateKeyPairSync("ed25519"), jwk=privateKey.export({format:"jwk"}); - const seed=Buffer.from(jwk.d,"base64url"); - const handle=await open(privateKeyPath,"wx",0o600); - try{await handle.writeFile(seed);await handle.sync();}finally{await handle.close();} - await chmod(privateKeyPath,0o600); - return loadBifrostFeedbackIdentity(privateKeyPath); -} -export async function loadBifrostFeedbackIdentity(privateKeyPath){ - const info=await stat(privateKeyPath); - if(!info.isFile())throw new Error("Bifrost feedback identity must be a regular file."); - if(process.platform!=="win32"&&(info.mode&0o077)!==0)throw new Error("Bifrost feedback identity private key must have mode 0600."); - if(process.platform!=="win32"&&typeof process.geteuid==="function"&&info.uid!==process.geteuid())throw new Error("Bifrost feedback identity private key must be owned by the service user."); - const seed=await readFile(privateKeyPath);if(seed.length!==32)throw new Error("Bifrost feedback identity seed must be exactly 32 bytes."); - const key=createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),seed]),format:"der",type:"pkcs8"}); - const publicKey=createPublicKey(key).export({format:"der",type:"spki"}).subarray(-32); - const identityId=createHash("sha256").update(ID_DOMAIN).update(publicKey).digest("hex"); - return {identityId,publicKey,key}; -} -export function signFeedbackAdmission(identity,payload){ - const purpose=Buffer.from(FEEDBACK_SIGNING_PURPOSE,"utf8"), message=Buffer.concat([SIGNATURE_DOMAIN,u64(purpose.length),purpose,u64(payload.length),payload]); - return ed25519Sign(null,message,identity.key); -} -export function providerHealthIdentity(identity){ - return {...identity,identityId:createHash("sha256").update(PROVIDER_HEALTH_ID_DOMAIN).update(identity.publicKey).digest("hex")}; -} -export function signProviderHealth(identity,payload){ - const provider=providerHealthIdentity(identity),purpose=Buffer.from(IDUNN_SIGNED_DAEMON_HEALTH_PURPOSE,"utf8"),message=Buffer.concat([PROVIDER_HEALTH_SIGNATURE_DOMAIN,u64(purpose.length),purpose,u64(payload.length),payload]); - return {identityId:provider.identityId,signature:ed25519Sign(null,message,identity.key)}; -} -export function providerHealthTrustAnchor(identity,createdAt){ - const provider=providerHealthIdentity(identity); - return {schemaVersion:PROVIDER_HEALTH_TRUST_ANCHOR_SCHEMA,identityId:provider.identityId,publicKey:new Uint8Array(identity.publicKey),assurance:"os_service_file_bound",identityCreatedAt:createdAt,sourceIdentityRecordSha256:`sha256-${createHash("sha256").update(PROVIDER_HEALTH_ID_DOMAIN).update(identity.publicKey).digest("hex")}`}; -} -export function trustAnchor(identity,createdAt){return {schemaVersion:"epiphany.host_identity_trust_anchor.v0",identityId:identity.identityId,publicKey:new Uint8Array(identity.publicKey),assurance:"os_service_file_bound",identityCreatedAt:createdAt,sourceIdentityRecordSha256:`sha256-${createHash("sha256").update(identity.publicKey).digest("hex")}`};} -export function defaultFeedbackIdentityPath(){return process.env.BIFROST_PERSONA_FEEDBACK_PRIVATE_KEY??(process.platform==="win32"?resolve(".bifrost","private","persona-feedback-ed25519.seed"):"/var/lib/gamecult/bifrost/persona-feedback/persona-feedback-ed25519.seed");} -function u64(value){const b=Buffer.alloc(8);b.writeBigUInt64BE(BigInt(value));return b;} diff --git a/tools/merge-saga-mutants.py b/tools/merge-saga-mutants.py deleted file mode 100644 index 1b8da0b..0000000 --- a/tools/merge-saga-mutants.py +++ /dev/null @@ -1,83 +0,0 @@ -"""One-off mutation probe for the account merge saga (not a gate; survivors are triaged by name). -Usage, from any directory with BIFROST_TEST_PG and the dotnet environment set: - python3 tools/merge-saga-mutants.py [mutant-name ...] # no names: all -Each mutant is one exact text edit, applied, run against the merge tests (and again alone if it fails), then restored. -Logs go to $MUTANT_LOGS (default ./mutant-logs). Expected: every mutant KILLED. -""" -import subprocess, re, sys, os, json -WT=subprocess.run(['git','rev-parse','--show-toplevel'],capture_output=True,text=True,check=True,cwd=os.path.dirname(os.path.abspath(__file__))).stdout.strip() -LOGS=os.environ.get('MUTANT_LOGS','./mutant-logs'); os.makedirs(LOGS,exist_ok=True) -SAGA='src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs' -LEDGER='src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs' -FILTER='FullyQualifiedName~AccountMergeSaga|FullyQualifiedName~AccountMergePostgres' -M=[ -('derive-move-id', SAGA, [(" var merge = new AccountMerge\n {\n State = AccountMergeState.Confirmed,"," var fixedId = Guid.NewGuid();\n var merge = new AccountMerge\n {\n Id = fixedId,\n State = AccountMergeState.Confirmed,"),('HeimdallMoveId = Guid.NewGuid().ToString("N"),','HeimdallMoveId = fixedId.ToString("N"),')], None), -('no-wipe-on-moved', SAGA, " merge.SealedProofs = null;\n if (moved.Receipt.AccountId != destination)", " if (moved.Receipt.AccountId != destination)"), -('no-wipe-on-refused', SAGA, " // Heimdall applied nothing before a 4xx. A forward refusal ends the merge; a refused undo leaves it as it was.\n merge.SealedProofs = null;", " // Heimdall applied nothing before a 4xx. A forward refusal ends the merge; a refused undo leaves it as it was."), -('refused-stays-confirmed', SAGA, "merge.State = AccountMergeState.Failed;", "merge.State = AccountMergeState.Confirmed;"), -('unknown-no-attempt', SAGA, " merge.Attempts++;\n", ""), -('unknown-no-backoff', SAGA, "merge.NextAttemptUtc = now + Backoff[Math.Min(merge.Attempts, Backoff.Length) - 1];", "merge.NextAttemptUtc = null;"), -('no-digest-check', SAGA, "if (!string.Equals(plan.Digest(request.SurvivorUserAccountId, request.FoldedUserAccountId), request.PreviewDigest, StringComparison.Ordinal))", "if (false)"), -('no-proof-account-check', SAGA, "if (request.SurvivorProof.HeimdallAccountId != survivorHeimdall || request.FoldedProofs.Any(x => x.HeimdallAccountId != foldedHeimdall))", "if (false)"), -('no-notparty', SAGA, "if (request.ActorUserAccountId != request.SurvivorUserAccountId && request.ActorUserAccountId != request.FoldedUserAccountId)", "if (false)"), -('no-block-check', SAGA, "if (plan.Blocks.Count > 0)", "if (false)"), -('no-grace-check', SAGA, "if (merge.GraceEndsUtc is not { } graceEnds || now >= graceEnds)", "if (merge.GraceEndsUtc is not { } graceEnds)"), -('no-notsurvivor', SAGA, "if (actorUserAccountId != merge.SurvivorUserAccountId)", "if (false)"), -('no-undo-proof-check', SAGA, "if (survivorProofs.Any(x => x.HeimdallAccountId != survivorHeimdall))", "if (false)"), -('no-final-graceover', SAGA, "if (merge.State == AccountMergeState.Final || merge.FinalizedUtc is not null)", "if (false)"), -('no-receipt-check', SAGA, "if (moved.Receipt.AccountId != destination)", "if (false)"), -('no-concurrency-retry', SAGA, "catch (DbUpdateConcurrencyException) when (lost < 2)", "catch (DbUpdateConcurrencyException) when (false)"), -('no-live-violation-catch', SAGA, "catch (DbUpdateException error) when (IsLiveMergeViolation(error))", "catch (DbUpdateException error) when (false)"), -('undo-refused-fails', SAGA, " merge.State = AccountMergeState.Committed;\n merge.LastOutcome = \"undo_\" + code;", " merge.State = AccountMergeState.Failed;\n merge.LastOutcome = \"undo_\" + code;"), -('unreadable-no-delay', SAGA, "merge.NextAttemptUtc = now + UnreadableRetry;", "merge.NextAttemptUtc = null;"), -('due-ignores-next-attempt', SAGA, "&& (x.NextAttemptUtc == null || x.NextAttemptUtc <= now)", ""), -('mismatch-retries', SAGA, " if (merge.LastOutcome == ReceiptMismatch)\n {\n return merge;", " if (false)\n {\n return merge;"), -('reverse-id-forward', SAGA, "new HeimdallMoveRequest(merge.HeimdallReverseMoveId!, proofs.From, ReversesMoveId: merge.HeimdallMoveId)", "new HeimdallMoveRequest(merge.HeimdallMoveId!, proofs.From, ReversesMoveId: merge.HeimdallMoveId)"), -('log-token', SAGA, 'logger.LogInformation("Account merge {MergeId} {State}: {Outcome} {Code}", merge.Id, merge.State, outcome.GetType().Name, code);', 'logger.LogInformation("Account merge {MergeId} {State}: {Outcome} {Code} {Req}", merge.Id, merge.State, outcome.GetType().Name, code, proofs.From[0]);'), -('seal-plain', SAGA, "private string Seal(IEnumerable from, string? to) => _seal.Protect(JsonSerializer.Serialize(new ProofSeal([.. from], to)));", "private string Seal(IEnumerable from, string? to) => JsonSerializer.Serialize(new ProofSeal([.. from], to));"), -('sweeper-no-advance', LEDGER, " await scope.ServiceProvider.GetRequiredService().AdvanceDueAsync(now, stoppingToken);\n", ""), -('sweeper-no-finalize', LEDGER, " await scope.ServiceProvider.GetRequiredService().FinalizeDueAsync(now, stoppingToken);\n", ""), -('no-writegate-confirm', SAGA, "return await AccountMergeLedger.WriteAsAsync(dbContext, request.ActorUserAccountId, _ => InsertConfirmedAsync(request, cancellationToken), cancellationToken);", "return await InsertConfirmedAsync(request, cancellationToken);"), -('digest-no-entries', LEDGER, " foreach (var entry in Entries)\n {\n Field(entry.Kind.ToString());", " foreach (var entry in Entries.Take(0))\n {\n Field(entry.Kind.ToString());"), -('tier-swapped', SAGA, "merge.ProofFromTier = Tier(moved.Receipt.ProofFrom);", "merge.ProofFromTier = \"strong\";"), -('wipe-missing-on-reversed', SAGA, " merge.State = AccountMergeState.HeimdallReversed;\n merge.ReversedUtc = now;", " merge.State = AccountMergeState.HeimdallReversed;\n merge.ReversedUtc = now;\n merge.SealedProofs = \"kept\";"), -('grace-boundary', SAGA, "now >= graceEnds", "now > graceEnds"), -('move-id-not-unique', 'src/Bifrost.Web/Data/Migrations/20261114130000_AddAccountMergeSaga.cs', 'column: "HeimdallMoveId",\n unique: true,', 'column: "HeimdallMoveId",\n unique: false,'), -('reverse-id-not-unique', 'src/Bifrost.Web/Data/Migrations/20261114130000_AddAccountMergeSaga.cs', 'column: "HeimdallReverseMoveId",\n unique: true,', 'column: "HeimdallReverseMoveId",\n unique: false,'), -('digest-includes-created-id', LEDGER, 'entry.Action == AccountMergeEntryAction.Created ? null : entry.RecordId.ToString("N")', 'entry.RecordId.ToString("N")'), -('proofseal-prints-bearer', SAGA, 'builder.Append($"From = {From?.Count}, To = {(To is null ? "none" : "present")}");', 'builder.Append($"From = {string.Join(",", From)}, To = {To}");'), -] -only=sys.argv[1:] -def run(filt,log): - env=dict(os.environ,DOTNET_USE_POLLING_FILE_WATCHER='1') - r=subprocess.run([*os.environ.get('DOTNET','dotnet').split(),'test','tests/Bifrost.Web.Tests','--filter',filt],cwd=WT,env=env,capture_output=True,text=True) - open(log,'w').write(r.stdout+r.stderr) - out=r.stdout+r.stderr - fails=sorted(set(re.findall(r'^\s*Failed (Bifrost\.\S+)',out,re.M))) - built='Build FAILED' not in out and 'error CS' not in out - return built,fails,out -res={} -for name,path,old,new in M: - if only and name not in only: continue - full=os.path.join(WT,path) - src=open(full).read() - pairs=old if isinstance(old,list) else [(old,new)] - if any(src.count(o)!=1 for o,_ in pairs): - print(name,'ANCHOR',flush=True); res[name]='anchor-miss'; continue - mutated=src - for o,n in pairs: mutated=mutated.replace(o,n) - open(full,'w').write(mutated) - try: - built,fails,out=run(FILTER,f'{LOGS}/{name}.log') - if not built: res[name]='BUILD-FAIL' - elif not fails: res[name]='SURVIVED' - else: - # rerun the first failing test in isolation - t=fails[0]; method=t.split('.')[-1].split('(')[0] - built2,fails2,_=run('FullyQualifiedName~'+method,f'{LOGS}/{name}.iso.log') - res[name]=('KILLED x%d; isolated %s: %s'%(len(fails),method,'still fails' if fails2 else 'PASSES ALONE (order-dependent)')) - finally: - open(full,'w').write(src) - print(name,res[name],flush=True) -json.dump(res,open(LOGS+'/result.json','w'),indent=1) -print('MUT-DONE',flush=True) diff --git a/tools/persona-feedback-documents.mjs b/tools/persona-feedback-documents.mjs deleted file mode 100644 index b183c90..0000000 --- a/tools/persona-feedback-documents.mjs +++ /dev/null @@ -1,45 +0,0 @@ -export const feedbackEventType = "bifrost.discord.persona_conversation_event"; -export const feedbackEventSchema = "bifrost.discord.persona_conversation_event.v0"; -export const feedbackBindingType = "bifrost.persona_feedback.target_binding"; -export const feedbackBindingSchema = "bifrost.persona_feedback.target_binding.v0"; -export const actorLinkType = "bifrost.discord.actor_link"; -export const actorLinkSchema = "bifrost.discord.actor_link.v0"; -export const feedbackReceiptType = "bifrost.persona_feedback.admission_receipt"; -export const feedbackReceiptSchema = "bifrost.persona_feedback.admission_receipt.v0"; -export const feedbackDeliveryType = "bifrost.persona_feedback.delivery"; -export const feedbackDeliverySchema = "bifrost.persona_feedback.delivery.v0"; -export const feedbackPendingFailureType = "bifrost.persona_feedback.pending_failure"; -export const feedbackPendingFailureSchema = "bifrost.persona_feedback.pending_failure.v0"; - -// Kept as explicit constructors because CultCache document metadata is part of the wire contract. -export function buildFeedbackDefinitions(defineDocumentType) { - const make = (type, schemaId, name, parse) => defineDocumentType({ type, schemaName: type, schemaId, schemaVersion: schemaId, contentHash: schemaId, global: false, name, schema: { parse } }); - return { - event: make(feedbackEventType, feedbackEventSchema, "eventId", parseEvent), - binding: make(feedbackBindingType, feedbackBindingSchema, "bindingId", parseBinding), - actorLink: make(actorLinkType, actorLinkSchema, "linkId", parseActorLink), - receipt: make(feedbackReceiptType, feedbackReceiptSchema, "receiptId", parseReceipt), - delivery: make(feedbackDeliveryType, feedbackDeliverySchema, "admissionId", parseDelivery), - pendingFailure: make(feedbackPendingFailureType, feedbackPendingFailureSchema, "failureId", parsePendingFailure), - }; -} - -export function parseEvent(value) { - const v = record(value, "feedback event"); - exact(v.schemaVersion, feedbackEventSchema, "event schema"); - for (const key of ["eventId","guildId","channelId","messageId","authorId","addressingMode","targetPersonaId","targetRepoName","targetRuntimeId","content","payloadHash","producerId","producerRuntimeId"]) text(v[key], key); - exact(v.producerId, "bifrost-discord", "producer"); exact(v.authorityClass, "feedback_only", "authorityClass"); - exact(v.status, "pending", "status"); - if(!["role","text","reply","broadcast"].includes(v.addressingMode))throw new Error("addressingMode is invalid."); - if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(v.observedAt)||Number.isNaN(Date.parse(v.observedAt)))throw new Error("observedAt must be RFC3339."); - if (!/^[a-f0-9]{64}$/.test(v.payloadHash)) throw new Error("payloadHash must be sha256 hex."); - return v; -} -export function parseBinding(value) { const v = record(value,"target binding"); exact(v.schemaVersion,feedbackBindingSchema,"binding schema"); for (const k of ["bindingId","guildId","channelId","targetPersonaId","targetRepoName","targetRuntimeId","producerId","producerRuntimeId","sourceVisibility","dataClassification","deliveryStorePath"]) text(v[k],k); const expected={public:"public_feedback",organization:"organization_feedback",private:"private_feedback"}[v.sourceVisibility];if(!expected||v.dataClassification!==expected)throw new Error("sourceVisibility and dataClassification must be the exact admitted pair."); return v; } -export function parseActorLink(value) { const v=record(value,"actor link"); exact(v.schemaVersion,actorLinkSchema,"actor link schema"); for(const k of ["linkId","guildId","discordAuthorId","bifrostActorId","heimdallActorRef"]) text(v[k],k); return v; } -export function parseReceipt(value) { const v=record(value,"receipt"); exact(v.schemaVersion,feedbackReceiptSchema,"receipt schema"); for(const k of ["receiptId","eventId","status","classification","payloadHash","bindingId","recordedAt"]) text(v[k],k); return v; } -export function parseDelivery(value) { const v=record(value,"delivery"); exact(v.schemaVersion,feedbackDeliverySchema,"delivery schema"); for(const k of ["admissionId","packetSha256","sourceObserverId","sourceObserverRuntimeId","provider","bifrostAdmissionReceiptId","authority","providerIdentityId"]) text(v[k],k); exact(v.sourceObserverId,"bifrost-discord","sourceObserverId"); exact(v.provider,"bifrost","provider"); exact(v.authority,"feedback_only","authority"); if(!(v.providerSignature instanceof Uint8Array)||v.providerSignature.length!==64)throw new Error("providerSignature must be 64 bytes."); const p=record(v.packet,"packet"); for(const k of ["feedbackId","sourceEventId","sourceActorId","actorClassification","discordGuildId","discordChannelId","discordMessageId","targetRuntimeId","targetRepository","targetPersonaId","sourceRoomId","feedbackText","contentSha256","sourceVisibility","dataClassification"])text(p[k],k);if(!Array.isArray(p.sourceDiscussionRefs)||p.sourceDiscussionRefs.length===0)throw new Error("sourceDiscussionRefs are required.");if(p.privateStateIncluded!==false)throw new Error("privateStateIncluded describes embedded private machine state and must be false.");return v; } -export function parsePendingFailure(value) { const v=record(value,"pending failure"); exact(v.schemaVersion,feedbackPendingFailureSchema,"pending failure schema"); for(const k of ["failureId","eventId","lastError","lastAttemptAt"])text(v[k],k); if(v.failureId!==v.eventId)throw new Error("failureId must equal eventId."); if(!Number.isSafeInteger(v.attemptCount)||v.attemptCount<1||v.attemptCount>1_000_000)throw new Error("attemptCount is invalid."); if(Buffer.byteLength(v.lastError,"utf8")>512)throw new Error("lastError exceeds 512 UTF-8 bytes."); if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(v.lastAttemptAt)||Number.isNaN(Date.parse(v.lastAttemptAt)))throw new Error("lastAttemptAt must be RFC3339."); if(v.privateStateExposed!==false)throw new Error("privateStateExposed must be false."); return v; } -function record(value,label){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error(`${label} must be an object.`);return value;} -function text(value,label){if(typeof value!=="string"||!value.trim())throw new Error(`${label} is required.`);return value;} -function exact(value,expected,label){if(value!==expected)throw new Error(`${label} must be ${expected}.`);} diff --git a/tools/persona-feedback-idunn-health.mjs b/tools/persona-feedback-idunn-health.mjs deleted file mode 100644 index 646bcfc..0000000 --- a/tools/persona-feedback-idunn-health.mjs +++ /dev/null @@ -1,70 +0,0 @@ -import dgram from "node:dgram"; -import { randomUUID } from "node:crypto"; -import { createRequire } from "node:module"; -import { resolve } from "node:path"; -import { providerHealthIdentity, signProviderHealth } from "./bifrost-feedback-identity.mjs"; - -const root=resolve(import.meta.dirname,".."),projects=resolve(root,".."),cult=resolve(process.env.VOIDBOT_CULTLIB_ROOT||resolve(projects,"CultLib")); -const require=createRequire(resolve(cult,"packages","cultnet-ts","package.json")); -const {encodeCultNetMessageForWire,encodeRudpPacket}=require("@gamecult/cultnet-ts"),{encode}=require("@msgpack/msgpack"); -const protocol="cultnet.transport.rudp.v0",schema="idunn.signed_daemon_health.v1",sourceRuntimeId="bifrost-persona-feedback"; -export const signedHealthSourceRole="daemon-health-publisher"; -const states=new Set(["active","warming","degraded","failed"]),reasons=new Set(["ready","starting","readiness-degraded","unavailable"]); - -export function createPersonaFeedbackHealthPublisher(identity,publisherIncarnationId=randomUUID()){ - if(!identity)throw new Error("Bifrost Persona-feedback provider-health identity is required."); - if(!isUuid(publisherIncarnationId))throw new Error("Bifrost Persona-feedback publisher incarnation must be a UUID."); - let publisherSequence=0; - return {identity,publisherIncarnationId,next(input){return createSignedPersonaFeedbackHealth({...input,identity,publisherIncarnationId,publisherSequence:++publisherSequence});}}; -} - -export function createSignedPersonaFeedbackHealth(input){ - requireText(input.daemonId,"daemon id");requireText(input.healthContract,"health contract"); - if(!states.has(input.state))throw new Error(`Bifrost Persona-feedback health state is invalid: ${input.state}`); - if(!reasons.has(input.detail))throw new Error("Bifrost Persona-feedback health detail must be a bounded generic reason."); - if(!input.identity)throw new Error("Bifrost Persona-feedback provider-health identity is required."); - if(!isUuid(input.publisherIncarnationId))throw new Error("Bifrost Persona-feedback publisher incarnation must be a UUID."); - if(!Number.isSafeInteger(input.publisherSequence)||input.publisherSequence<=0)throw new Error("Bifrost Persona-feedback publisher sequence must be a positive safe integer."); - const observed=Number(input.observedAtUnixMillis??Date.now());if(!Number.isSafeInteger(observed)||observed<=0)throw new Error("Bifrost Persona-feedback observation time must be positive Unix milliseconds."); - // The shared CultNet contract marks signatures as portable bytes, so both - // Rust and JavaScript lower this field as MessagePack binary. - // Safe JavaScript numbers above u32 lower as float64. Rust's u64 lowers as - // uint64, so retain the timestamp as BigInt on this signed wire surface. - const provider=providerHealthIdentity(input.identity),record=[schema,input.daemonId,input.healthContract,sourceRuntimeId,input.state,input.detail,provider.identityId,input.publisherIncarnationId,input.publisherSequence,BigInt(observed),null,null,null,null,"ed25519",new Uint8Array(),false]; - const proof=signProviderHealth(input.identity,canonicalHealthEncode(record));if(proof.identityId!==provider.identityId)throw new Error("Provider-health signer identity derivation disagrees with the packet.");record[15]=new Uint8Array(proof.signature); - return {record,payload:canonicalHealthEncode(record),providerIdentityId:provider.identityId,observedAtUnixMillis:observed}; -} - -export function createSignedHealthRawPut(daemonId,signed){ - requireText(daemonId,"daemon id"); - const incarnation=signed.record[7],sequence=signed.record[8],storedAt=new Date(signed.observedAtUnixMillis).toISOString(); - return rawPut(`bifrost-feedback-signed-health:${incarnation}:${sequence}`,"idunn.signed_daemon_health",daemonId,storedAt,signed.payload,signedHealthSourceRole); -} - -function canonicalHealthEncode(value){return encode(value,{useBigInt64:true});} - -export async function publishPersonaFeedbackHealth(input){ - if(!input.endpoint)throw new Error("Bifrost Persona-feedback Idunn health endpoint is required."); - if(!input.publisher||typeof input.publisher.next!=="function")throw new Error("Bifrost Persona-feedback process-scoped health publisher is required."); - const endpoint=parseEndpoint(input.endpoint),signed=input.publisher.next(input),socket=dgram.createSocket(endpoint.host.includes(":")?"udp6":"udp4"); - try{ - await new Promise((ok,fail)=>{socket.once("error",fail);socket.bind(0,endpoint.host.includes(":")?"::":"0.0.0.0",()=>{socket.off("error",fail);ok();});}); - await send(socket,endpoint,packet("connect",1,new Uint8Array(),"control"));await delay(300); - const incarnation=signed.record[7],sequence=signed.record[8],storedAt=new Date(signed.observedAtUnixMillis).toISOString(),signedMessage=createSignedHealthRawPut(input.daemonId,signed); - await send(socket,endpoint,packet("data",2,encode(encodeCultNetMessageForWire(signedMessage,"cultnet.schema.v0")),"schema")); - if(input.publishUnsignedDiagnostic===true){ - const diagnosticPayload=encode([input.daemonId,input.state,input.detail,storedAt,input.healthContract,"diagnostic-only",protocol]),diagnosticMessage=rawPut(`bifrost-feedback-unsigned-diagnostic:${incarnation}:${sequence}`,"idunn.daemon_health",input.daemonId,storedAt,diagnosticPayload,"unsigned-health-diagnostic"); - await send(socket,endpoint,packet("data",3,encode(encodeCultNetMessageForWire(diagnosticMessage,"cultnet.schema.v0")),"schema")); - } - await delay(1000); - }finally{socket.close();} -} - -function rawPut(messageId,schemaId,recordKey,storedAt,payload,sourceRole){return {schemaVersion:"cultnet.document_put_raw.v0",messageId,document:{schemaId,recordKey,storedAt,payloadEncoding:"messagepack",payload,sourceRuntimeId,sourceRole,tags:[protocol]}};} -export function parseEndpoint(value){const text=String(value||"").trim(),ipv6=text.match(/^\[([^\]]+)\]:(\d+)$/);if(ipv6)return {host:ipv6[1],port:port(ipv6[2])};const split=text.lastIndexOf(":");if(split<=0)throw new Error(`Idunn RUDP endpoint must be host:port, got "${value}".`);return {host:text.slice(0,split),port:port(text.slice(split+1))};} -function port(value){const result=Number(value);if(!Number.isInteger(result)||result<=0||result>65535)throw new Error(`Idunn RUDP endpoint port is invalid: ${value}`);return result;} -function packet(packetType,sequence,payload,channelId){return {packetType,connectionId:0x1d0d0001,sequence,ack:0,ackMask:0,channelId,reliable:true,ordered:true,sequenced:false,payload};} -async function send(socket,endpoint,value){const wire=encodeRudpPacket(value);await new Promise((ok,fail)=>socket.send(wire,endpoint.port,endpoint.host,error=>error?fail(error):ok()));} -function delay(ms){return new Promise(ok=>setTimeout(ok,ms));} -function requireText(value,label){if(typeof value!=="string"||!value.trim()||value.length>256||/[\u0000-\u001f\u007f]/.test(value))throw new Error(`Bifrost Persona-feedback ${label} is invalid.`);} -function isUuid(value){return typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);} diff --git a/tools/persona-feedback.mjs b/tools/persona-feedback.mjs deleted file mode 100644 index a49c1f4..0000000 --- a/tools/persona-feedback.mjs +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env node -import { createHash, randomUUID } from "node:crypto"; -import { createRequire } from "node:module"; -import { constants } from "node:fs"; -import { access, mkdir, realpath, rm, stat, writeFile } from "node:fs/promises"; -import { dirname, resolve } from "node:path"; -import { buildFeedbackDefinitions, actorLinkSchema, feedbackBindingSchema, feedbackDeliverySchema, feedbackReceiptSchema, feedbackPendingFailureSchema } from "./persona-feedback-documents.mjs"; -import { defaultFeedbackIdentityPath, enrollBifrostFeedbackIdentity, loadBifrostFeedbackIdentity, providerHealthTrustAnchor, signFeedbackAdmission, trustAnchor } from "./bifrost-feedback-identity.mjs"; -import { createPersonaFeedbackHealthPublisher, publishPersonaFeedbackHealth } from "./persona-feedback-idunn-health.mjs"; -import { discordGatewayReady, serveDiscordPersonaIngress } from "./bifrost-discord-persona-ingress.mjs"; - -const root=resolve(import.meta.dirname,".."),projects=resolve(root,".."),cult=resolve(process.env.VOIDBOT_CULTLIB_ROOT||resolve(projects,"CultLib")); -const [command,...rawArgs]=process.argv.slice(2),options=parseArgs(rawArgs); -const privateStorePath=resolve(options.store||(process.platform==="win32"?resolve(root,".bifrost","provider-store.cc"):"/var/lib/gamecult/bifrost/persona-feedback/provider.cc")); -const observationStorePath=resolve(options["observation-store"]||(process.platform==="win32"?resolve(root,".bifrost","persona-conversation-observations.cc"):"/srv/bifrost/persona-feedback/observations.cc")); -const deliveryStorePath=resolve(options["delivery-store"]||(process.platform==="win32"?resolve(root,".bifrost","epiphany-persona-feedback.cc"):"/srv/bifrost/persona-feedback/deliveries.cc")); -const runtime=loadRuntime(),defs=buildFeedbackDefinitions(runtime.defineDocumentType); - -try{await main();}catch(error){console.error(error instanceof Error?error.message:String(error));process.exitCode=1;} - -async function main(){ - if(command==="bind-target")return bindTarget(); - if(command==="link-actor")return linkActor(); - if(command==="process")return processEvent(requireOption("event-id")); - if(command==="serve")return serve(); - if(command==="serve-discord")return serveDiscord(); - if(command==="export")return exportSnapshot(); - if(command==="enroll-identity")return enrollIdentity(); - if(command==="export-provider-health-anchor")return exportProviderHealthAnchor(); - if(command==="status")return status(); - throw new Error("Usage: persona-feedback.mjs bind-target|link-actor|process|serve|serve-discord|status|export|enroll-identity|export-provider-health-anchor"); -} -async function privateNode(){return runtime.CultMesh.createNode(privateStorePath,{documents:[defs.binding,defs.actorLink,defs.receipt,defs.delivery,defs.pendingFailure]});} -async function observationNode(){return runtime.CultMesh.createNode(observationStorePath,{documents:[defs.event]});} - -async function bindTarget(){const n=await privateNode(),binding={schemaName:"bifrost.persona_feedback.target_binding",schemaVersion:feedbackBindingSchema,bindingId:bindingId(options),guildId:requireOption("guild-id"),channelId:requireOption("channel-id"),targetPersonaId:requireOption("persona-id"),targetRepoName:requireOption("repo"),targetRuntimeId:requireOption("runtime-id"),producerId:options["producer-id"]||"bifrost-discord",producerRuntimeId:requireOption("producer-runtime-id"),sourceVisibility:requireOption("source-visibility"),dataClassification:requireOption("data-classification"),deliveryStorePath:resolve(options["delivery-store"]||deliveryStorePath),createdAt:new Date().toISOString()};await assertStoreSeparation(binding.deliveryStorePath);await n.put(defs.binding,binding.bindingId,binding);await n.flush?.();print(binding);} -async function linkActor(){const n=await privateNode(),link={schemaName:"bifrost.discord.actor_link",schemaVersion:actorLinkSchema,linkId:`${requireOption("guild-id")}:${requireOption("discord-author-id")}`,guildId:requireOption("guild-id"),discordAuthorId:requireOption("discord-author-id"),bifrostActorId:requireOption("bifrost-actor-id"),heimdallActorRef:requireOption("heimdall-actor-ref"),linkedAt:new Date().toISOString()};await n.put(defs.actorLink,link.linkId,link);await n.flush?.();print(link);} - -async function processEvent(id,emit=true){ - await assertStoreSeparation(deliveryStorePath); - const observations=await observationNode(),privateNodeValue=await privateNode();await observations.cache?.pullAllBackingStores?.();await privateNodeValue.cache?.pullAllBackingStores?.(); - const event=unwrap(await observations.get(defs.event,id));if(!event)throw new Error(`Unknown feedback event ${id}.`); - const existing=unwrap(await privateNodeValue.get(defs.receipt,id));if(existing){await republishExisting(privateNodeValue,id);if(emit)print(existing);return;} - if(shaText(event.content)!==event.payloadHash)throw new Error("Feedback payload hash mismatch."); - const binding=unwrap(await privateNodeValue.get(defs.binding,bindingId({"guild-id":event.guildId,"channel-id":event.channelId,"persona-id":event.targetPersonaId,repo:event.targetRepoName,"runtime-id":event.targetRuntimeId,"producer-id":event.producerId,"producer-runtime-id":event.producerRuntimeId}))); - if(!binding)throw new Error("No exact Bifrost target binding admits this feedback event."); - const link=unwrap(await privateNodeValue.get(defs.actorLink,`${event.guildId}:${event.authorId}`)),classification=link?"linked_governance_feedback":"unlinked_social_feedback",sourceActorId=link?.bifrostActorId||`discord:${event.guildId}:${event.authorId}`; - const packet={feedbackId:id,sourceEventId:id,sourceActorId,actorClassification:classification,actorLinkRefs:link?[link.heimdallActorRef]:[],discordGuildId:event.guildId,discordChannelId:event.channelId,discordMessageId:event.messageId,targetRuntimeId:event.targetRuntimeId,targetRepository:event.targetRepoName,targetPersonaId:event.targetPersonaId,sourceRoomId:`discord:${event.guildId}:${event.channelId}`,feedbackText:event.content,contentSha256:`sha256-${event.payloadHash}`,sourceDiscussionRefs:[`discord:${event.guildId}:${event.channelId}:${event.messageId}`],sourceVisibility:binding.sourceVisibility,dataClassification:binding.dataClassification,privateStateIncluded:false}; - const identity=await loadBifrostFeedbackIdentity(resolve(options["private-key"]||defaultFeedbackIdentityPath())); - const admission={schemaName:"bifrost.persona_feedback.delivery",schemaVersion:feedbackDeliverySchema,admissionId:id,packet,packetSha256:`sha256-${shaBytes(runtime.encode(packetTuple(packet)))}`,sourceObserverId:"bifrost-discord",sourceObserverRuntimeId:event.producerRuntimeId,provider:"bifrost",bifrostAdmissionReceiptId:id,authority:"feedback_only",providerIdentityId:identity.identityId,providerSignature:new Uint8Array()}; - admission.providerSignature=new Uint8Array(signFeedbackAdmission(identity,runtime.encode(admissionSigningTuple(admission)))); - const receipt={schemaName:"bifrost.persona_feedback.admission_receipt",schemaVersion:feedbackReceiptSchema,receiptId:id,eventId:id,status:"admitted",classification,payloadHash:event.payloadHash,bindingId:binding.bindingId,deliveryId:id,recordedAt:new Date().toISOString(),immutable:true,grantsWorkAuthority:false,grantsAdoptionAuthority:false}; - await publishAdmission(admission,binding.deliveryStorePath);await privateNodeValue.put(defs.delivery,id,admission);await privateNodeValue.put(defs.receipt,id,receipt);await privateNodeValue.flush?.();if(emit)print({receipt,delivery:admission,deliveryStore:binding.deliveryStorePath}); -} -async function republishExisting(n,id){const admission=unwrap(await n.get(defs.delivery,id));if(!admission)throw new Error(`Feedback receipt ${id} has no signed admission.`);const binding=unwrap(await n.get(defs.binding,bindingIdFromAdmission(admission)));if(!binding)throw new Error(`Feedback admission ${id} has no target binding.`);await publishAdmission(admission,binding.deliveryStorePath);} -async function publishAdmission(admission,path){await assertStoreSeparation(path);await mkdir(dirname(path),{recursive:true});const cache=runtime.CultCache.builder().withDocumentType(defs.delivery).withGenericStore(new runtime.SingleFileMessagePackBackingStore(path)).build();await cache.pullAllBackingStores();const current=cache.get(defs.delivery,admission.admissionId);if(current&&stable(current)!==stable(admission))throw new Error(`Signed admission ${admission.admissionId} already exists with different immutable content.`);if(!current)await cache.put(defs.delivery,admission.admissionId,admission);} - -async function serve(){const interval=positiveInteger(options["interval-ms"]||"5000","interval-ms"),once=options.once==="true",healthEndpoint=options["idunn-rudp-health"]||process.env.BIFROST_IDUNN_RUDP_HEALTH;if(!healthEndpoint&&!once)throw new Error("Persona-feedback serve requires --idunn-rudp-health or BIFROST_IDUNN_RUDP_HEALTH; no localhost default is assumed.");const healthPublisher=healthEndpoint?createPersonaFeedbackHealthPublisher(await loadBifrostFeedbackIdentity(resolve(options["private-key"]||defaultFeedbackIdentityPath()))):null;do{const results=await drainPendingObservations(),readinessState=await readiness();if(healthEndpoint)await publishPersonaFeedbackHealth({endpoint:healthEndpoint,daemonId:"yggdrasil-bifrost-persona-feedback",healthContract:"bifrost.cultnet-rudp-persona-feedback-health",state:readinessState.status==="ready"?"active":"degraded",detail:readinessState.status==="ready"?"ready":"readiness-degraded",publisher:healthPublisher,publishUnsignedDiagnostic:true});if(once){print({ok:results.every(value=>value.ok)&&readinessState.status==="ready",scanned:results.length,results,readiness:readinessState});return;}await new Promise(done=>setTimeout(done,interval));}while(true);} - -async function drainPendingObservations(){const observations=await observationNode(),privateNodeValue=await privateNode();await observations.cache?.pullAllBackingStores?.();await privateNodeValue.cache?.pullAllBackingStores?.();const admitted=new Set(privateNodeValue.cache.getAll(defs.receipt).map(value=>value.eventId));const pending=observations.cache.getAll(defs.event).filter(event=>!admitted.has(event.eventId)).sort((a,b)=>String(a.observedAt).localeCompare(String(b.observedAt)));const results=[];for(const event of pending){try{await processEvent(event.eventId,false);await privateNodeValue.cache.pullAllBackingStores();await privateNodeValue.cache.delete(defs.pendingFailure,event.eventId);results.push({eventId:event.eventId,ok:true,error:""});}catch(error){const message=boundedError(error),previous=unwrap(await privateNodeValue.get(defs.pendingFailure,event.eventId)),failure={schemaName:"bifrost.persona_feedback.pending_failure",schemaVersion:feedbackPendingFailureSchema,failureId:event.eventId,eventId:event.eventId,attemptCount:Math.min((previous?.attemptCount??0)+1,1_000_000),lastError:message,lastAttemptAt:new Date().toISOString(),privateStateExposed:false};await privateNodeValue.put(defs.pendingFailure,event.eventId,failure);results.push({eventId:event.eventId,ok:false,error:message});}}await privateNodeValue.flush?.();return results;} - -async function serveDiscord(){ - const token=process.env.BIFROST_DISCORD_BOT_TOKEN; - const producerRuntimeId=options["producer-runtime-id"]||process.env.BIFROST_DISCORD_RUNTIME_ID||"bifrost-discord-yggdrasil"; - const healthEndpoint=options["idunn-rudp-health"]||process.env.BIFROST_IDUNN_RUDP_HEALTH;if(!healthEndpoint)throw new Error("Bifrost Discord Persona ingress requires --idunn-rudp-health or BIFROST_IDUNN_RUDP_HEALTH."); - const healthPublisher=createPersonaFeedbackHealthPublisher(await loadBifrostFeedbackIdentity(resolve(options["private-key"]||defaultFeedbackIdentityPath()))); - let gatewayState={connected:false,sessionId:"",lastHeartbeatAckAtMillis:0,phase:"starting"}; - const publishHealth=async()=>{const value=await readiness(),gatewayReady=discordGatewayReady(gatewayState),active=value.status==="ready"&&gatewayReady;await publishPersonaFeedbackHealth({endpoint:healthEndpoint,daemonId:"yggdrasil-bifrost-persona-feedback",healthContract:"bifrost.cultnet-rudp-persona-feedback-health",state:active?"active":"degraded",detail:active?"ready":"readiness-degraded",publisher:healthPublisher,publishUnsignedDiagnostic:true});return {...value,gatewayReady,gatewayState};}; - const initial=await readiness();if(!initial.ingressReady)throw new Error(`Bifrost Discord Persona ingress is not ready: ${initial.ingressReasons.join("; ")}`); - const recovered=await drainPendingObservations();if(recovered.some(value=>!value.ok))console.error(`Bifrost Persona ingress startup recovery retained ${recovered.filter(value=>!value.ok).length} failed observation(s) for reconnect retry.`); - await publishHealth(); - const healthTimer=setInterval(()=>publishHealth().catch(error=>console.error(`Bifrost Persona-feedback health publication failed: ${error instanceof Error?error.message:String(error)}`)),10000); - let observationBusy=false;const observationTimer=setInterval(async()=>{if(observationBusy)return;observationBusy=true;try{const retried=await drainPendingObservations();if(retried.some(value=>!value.ok))console.error(`Bifrost Persona ingress retained ${retried.filter(value=>!value.ok).length} failed pending observation(s).`);}catch(error){console.error(`Bifrost Persona observation reconciliation failed: ${error instanceof Error?error.message:String(error)}`);}finally{observationBusy=false;}},positiveInteger(options["observation-retry-interval-ms"]||"5000","observation-retry-interval-ms")); - try{await serveDiscordPersonaIngress({token,runtimeId:producerRuntimeId,onConversation:conversation=>admitDiscordConversation(conversation,producerRuntimeId),onReady:async state=>{const drained=await drainPendingObservations();print({schemaVersion:"bifrost.discord.persona_ingress_status.v0",status:drained.every(value=>value.ok)?"ready":"degraded",runtimeId:state.runtimeId,botUserId:state.botUserId,recoveredObservationCount:drained.length,privateStateExposed:false});},onState:state=>{gatewayState=state;},onDisconnect:error=>console.error(`Bifrost Discord Persona ingress reconnecting: ${error instanceof Error?error.message:String(error)}`)});}finally{gatewayState={connected:false,sessionId:"",lastHeartbeatAckAtMillis:0,phase:"stopped"};await publishHealth().catch(()=>{});clearInterval(healthTimer);clearInterval(observationTimer);} -} - - - - -async function admitDiscordConversation(conversation,producerRuntimeId){ - const privateNodeValue=await privateNode();await privateNodeValue.cache?.pullAllBackingStores?.(); - const bindings=privateNodeValue.cache.getAll(defs.binding).filter(binding=>binding.guildId===conversation.guildId&&binding.channelId===conversation.channelId&&binding.producerId==="bifrost-discord"&&binding.producerRuntimeId===producerRuntimeId); - if(bindings.length===0)return; - if(bindings.length!==1)throw new Error("Discord channel has multiple Bifrost Persona targets; addressed conversation is ambiguous."); - const binding=bindings[0],eventId=`discord:${conversation.guildId}:${conversation.channelId}:${conversation.messageId}`,event={schemaName:"bifrost.discord.persona_conversation_event",schemaVersion:"bifrost.discord.persona_conversation_event.v0",eventId,observedAt:conversation.observedAt,guildId:conversation.guildId,channelId:conversation.channelId,messageId:conversation.messageId,authorId:conversation.authorId,authorName:conversation.authorName,addressingMode:conversation.addressingMode,targetPersonaId:binding.targetPersonaId,targetRepoName:binding.targetRepoName,targetRuntimeId:binding.targetRuntimeId,content:conversation.content,payloadHash:conversation.payloadHash,producerId:"bifrost-discord",producerRuntimeId,authorityClass:"feedback_only",status:"pending"}; - const observations=await observationNode();await observations.cache?.pullAllBackingStores?.();const existing=unwrap(await observations.get(defs.event,eventId)); - if(existing&&stable(existing)!==stable(event))throw new Error("Discord conversation event identity collision."); - if(!existing){await observations.put(defs.event,eventId,event);await observations.flush?.();} - await processEvent(eventId,false); -} - -async function enrollIdentity(){const keyPath=resolve(options["private-key"]||defaultFeedbackIdentityPath()),identity=await enrollBifrostFeedbackIdentity(keyPath),createdAt=new Date().toISOString(),anchor=trustAnchor(identity,createdAt),out=resolve(requireOption("trust-anchor-out")),providerOut=options["provider-health-trust-anchor-out"]?resolve(options["provider-health-trust-anchor-out"]):null;await mkdir(dirname(out),{recursive:true});await writeFile(out,runtime.encode(anchorTuple(anchor)));if(providerOut){if(providerOut===out)throw new Error("Feedback and provider-health trust anchors must use distinct paths.");const providerAnchor=providerHealthTrustAnchor(identity,createdAt);await mkdir(dirname(providerOut),{recursive:true});await writeFile(providerOut,runtime.encode(anchorTuple(providerAnchor)));}print({privateKey:keyPath,trustAnchor:out,identityId:identity.identityId,providerHealthTrustAnchor:providerOut??""});} -async function exportProviderHealthAnchor(){const keyPath=resolve(options["private-key"]||defaultFeedbackIdentityPath()),identity=await loadBifrostFeedbackIdentity(keyPath),out=resolve(requireOption("trust-anchor-out")),anchor=providerHealthTrustAnchor(identity,new Date().toISOString());await mkdir(dirname(out),{recursive:true});await writeFile(out,runtime.encode(anchorTuple(anchor)),{flag:"wx",mode:0o640});print({privateKey:keyPath,trustAnchor:out,identityId:anchor.identityId});} -async function exportSnapshot(){const n=await privateNode();await n.cache?.pullAllBackingStores?.();const out=resolve(requireOption("out")),scratch=`${out}.scratch.cc`,cache=runtime.CultCache.builder().withDocumentType(defs.delivery).withDocumentType(defs.receipt).withGenericStore(new runtime.SingleFileMessagePackBackingStore(scratch)).build();for(const value of n.cache.getAll(defs.delivery))await cache.put(defs.delivery,value.admissionId,value);for(const value of n.cache.getAll(defs.receipt))await cache.put(defs.receipt,value.receiptId,value);const registry=new runtime.CultNetDocumentRegistry([runtime.defineCultNetDocumentBinding({definition:defs.delivery,payloadSchemaVersion:feedbackDeliverySchema}),runtime.defineCultNetDocumentBinding({definition:defs.receipt,payloadSchemaVersion:feedbackReceiptSchema})]),message=registry.createRawSnapshotResponse(cache,options["message-id"]||`persona-feedback-${randomUUID()}`);await mkdir(dirname(out),{recursive:true});await writeFile(out,runtime.encode(message));await rm(scratch,{force:true});print({schemaVersion:message.schemaVersion,messageId:message.messageId,documentCount:message.documents.length,out});} -async function readiness(){const ingressReasons=[];let identity,bindingCount=0,pendingFailedCount=0;try{identity=await loadBifrostFeedbackIdentity(resolve(options["private-key"]||defaultFeedbackIdentityPath()));}catch(error){ingressReasons.push(`identity:${error instanceof Error?error.message:String(error)}`);}let bindings=[];try{const info=await stat(privateStorePath);if(!info.isFile())throw new Error("private provider store is not a regular file");const cache=runtime.CultCache.builder().withDocumentType(defs.binding).withDocumentType(defs.actorLink).withDocumentType(defs.receipt).withDocumentType(defs.delivery).withDocumentType(defs.pendingFailure).withGenericStore(new runtime.SingleFileMessagePackBackingStore(privateStorePath)).build();await cache.pullAllBackingStores();bindings=cache.getAll(defs.binding);bindingCount=bindings.length;const admitted=new Set(cache.getAll(defs.receipt).map(value=>value.eventId));pendingFailedCount=cache.getAll(defs.pendingFailure).filter(value=>!admitted.has(value.eventId)).length;if(pendingFailedCount>0)ingressReasons.push(`pendingFailures:${pendingFailedCount}`);if(bindingCount===0)ingressReasons.push("bindings:none");}catch(error){ingressReasons.push(`privateStore:${error instanceof Error?error.message:String(error)}`);}for(const binding of bindings){try{await assertStoreSeparation(binding.deliveryStorePath);try{const info=await stat(binding.deliveryStorePath);if(!info.isFile())throw new Error("delivery path is not a regular file");await access(binding.deliveryStorePath,constants.W_OK);}catch(error){if(!error||typeof error!=="object"||error.code!=="ENOENT")throw error;await access(dirname(binding.deliveryStorePath),constants.W_OK);}}catch(error){ingressReasons.push(`binding:${binding.bindingId}:${error instanceof Error?error.message:String(error)}`);}}const reasons=[...ingressReasons],ingressReady=ingressReasons.length===0;return {schemaVersion:"bifrost.persona_feedback.readiness.v0",providerIdentityId:identity?.identityId??"",bindingCount,pendingFailedCount,ingressReady,ingressReasons,status:ingressReady?"ready":"degraded",reasons,privateStateExposed:false};} -async function status(){print(await readiness());} - -function loadRuntime(){const cr=createRequire(resolve(cult,"packages","cultcache-ts","package.json")),mr=createRequire(resolve(cult,"packages","cultmesh-ts","package.json")),nr=createRequire(resolve(cult,"packages","cultnet-ts","package.json")),cc=cr("@gamecult/cultcache-ts"),cn=nr("@gamecult/cultnet-ts"),mp=nr("@msgpack/msgpack");return {CultMesh:mr("@gamecult/cultmesh-ts").CultMesh,CultCache:cc.CultCache,SingleFileMessagePackBackingStore:cc.SingleFileMessagePackBackingStore,defineDocumentType:cc.defineDocumentType,CultNetDocumentRegistry:cn.CultNetDocumentRegistry,defineCultNetDocumentBinding:cn.defineCultNetDocumentBinding,cultnet:cn,msgpack:mp,encode:mp.encode,decode:mp.decode};} -function bindingId(o){return `feedback:${o["guild-id"]}:${o["channel-id"]}:${o["runtime-id"]}:${o.repo}:${o["persona-id"]}:${o["producer-id"]||"bifrost-discord"}:${o["producer-runtime-id"]}`;} -function bindingIdFromAdmission(admission){const p=admission.packet;return bindingId({"guild-id":p.discordGuildId,"channel-id":p.discordChannelId,"runtime-id":p.targetRuntimeId,repo:p.targetRepository,"persona-id":p.targetPersonaId,"producer-id":admission.sourceObserverId,"producer-runtime-id":admission.sourceObserverRuntimeId});} -function packetTuple(p){return [p.feedbackId,p.sourceEventId,p.sourceActorId,p.actorClassification,p.actorLinkRefs,p.discordGuildId,p.discordChannelId,p.discordMessageId,p.targetRuntimeId,p.targetRepository,p.targetPersonaId,p.sourceRoomId,p.feedbackText,p.contentSha256,p.sourceDiscussionRefs,p.sourceVisibility,p.dataClassification,p.privateStateIncluded];} -function admissionSigningTuple(a){return [a.schemaVersion,a.admissionId,packetTuple(a.packet),a.packetSha256,a.sourceObserverId,a.sourceObserverRuntimeId,a.provider,a.bifrostAdmissionReceiptId,a.authority,a.providerIdentityId];} -function anchorTuple(a){return [a.schemaVersion,a.identityId,a.publicKey,a.assurance,a.identityCreatedAt,a.sourceIdentityRecordSha256];} -function parseArgs(args){const result={};for(let i=0;i0&&(bytes[end]&0xc0)===0x80)end--;return bytes.subarray(0,end).toString("utf8");} -function stable(value){return JSON.stringify(value,(_key,current)=>current instanceof Uint8Array?Buffer.from(current).toString("hex"):current);} -function positiveInteger(value,label){const parsed=Number(value);if(!Number.isSafeInteger(parsed)||parsed<=0)throw new Error(`${label} must be a positive integer.`);return parsed;} -async function assertStoreSeparation(targetDeliveryStore){const paths=[observationStorePath,privateStorePath,resolve(targetDeliveryStore)],seenPaths=new Set(),seenFiles=new Set();for(const path of paths){const canonical=await canonicalPath(path);const key=process.platform==="win32"?canonical.toLowerCase():canonical;if(seenPaths.has(key))throw new Error("Persona feedback observation inbox, Bifrost private state, and delivery export must use distinct canonical paths.");seenPaths.add(key);try{const info=await stat(path),fileKey=`${info.dev}:${info.ino}`;if(seenFiles.has(fileKey))throw new Error("Persona feedback stores must not alias the same physical file.");seenFiles.add(fileKey);}catch(error){if(!error||typeof error!=="object"||error.code!=="ENOENT")throw error;}}} -async function canonicalPath(path){try{return await realpath(path);}catch(error){if(!error||typeof error!=="object"||error.code!=="ENOENT")throw error;return resolve(path);}} -function print(value){process.stdout.write(`${JSON.stringify(value,null,2)}\n`);} diff --git a/tools/persona-matrix-mouth.mjs b/tools/persona-matrix-mouth.mjs index 8f889a2..e976c1a 100644 --- a/tools/persona-matrix-mouth.mjs +++ b/tools/persona-matrix-mouth.mjs @@ -80,7 +80,7 @@ const TAIL_TTL_MS = 15 * 1000; const FETCH_DEADLINE_MS = 15000; // one fetch, whole: it ends before Huginn's 20 s wait const FETCH_PER_HOUR = 30; // fetches one Persona may ask in an hour const RELATION_PAGES = 3; // pages of a receipt target's relations read before the answer is called unproven -const PLATFORM = ["disc", "ord"].join(""); // the bridged platform's name, as Huginn's room_scope spells it: never written out whole +const PLATFORM = "discord"; // the bridged platform's name, as Huginn's room_scope spells it const FOLLOW_WINDOW_MS = 10 * 60 * 1000; // W: an engagement lasts this long from the Mind's own post; a follow never extends it const FOLLOW_PER_HOUR = 3; // K: follow bases given per (Mind, peer, room) in an hour; past it the message keeps the basis it had const FOLLOW_ROOM_TTL_MS = 5 * 60 * 1000; // how long a room's public verdict (not encrypted, not bridged) is kept diff --git a/tools/verify-persona-feedback-release-authority.mjs b/tools/verify-persona-feedback-release-authority.mjs deleted file mode 100644 index 0e96cd0..0000000 --- a/tools/verify-persona-feedback-release-authority.mjs +++ /dev/null @@ -1,23 +0,0 @@ -import { openRepositoryReleaseAuthorityStore } from "./bifrost-repository-release-authority.mjs"; - -const storePath = process.argv[2]; -const authorityId = requiredEnvironment("EXPECTED_AUTHORITY_ID"); -const commitSha = requiredEnvironment("EXPECTED_COMMIT"); -if (!storePath) throw new Error("Pass the repository release-authority CultCache path."); - -const store = await openRepositoryReleaseAuthorityStore(storePath); -const authority = store.get(authorityId); -if (!authority) throw new Error(`Bifrost release authority ${authorityId} is absent.`); -if (authority.repositoryFullName !== "GameCult/Bifrost") throw new Error("Release authority does not own GameCult/Bifrost."); -if (authority.upstreamRef !== "refs/heads/main") throw new Error("Release authority does not own refs/heads/main."); -if (authority.commitSha !== commitSha) throw new Error("Release authority does not bind the frozen Bifrost commit."); -if (authority.status !== "authorized" || authority.decision !== "authorize") throw new Error("Release authority is not authorized."); -if (authority.expiresAt && Date.parse(authority.expiresAt) <= Date.now()) throw new Error("Release authority has expired."); - -process.stdout.write(`${authority.authorityId}\n`); - -function requiredEnvironment(name) { - const value = process.env[name]?.trim(); - if (!value) throw new Error(`Missing ${name}.`); - return value; -}