asyncfunctionrepublishExisting(n,id){constadmission=unwrap(awaitn.get(defs.delivery,id));if(!admission)thrownewError(`Feedback receipt ${id} has no signed admission.`);constbinding=unwrap(awaitn.get(defs.binding,bindingIdFromAdmission(admission)));if(!binding)thrownewError(`Feedback admission ${id} has no target binding.`);awaitpublishAdmission(admission,binding.deliveryStorePath);}
asyncfunctionpublishAdmission(admission,path){awaitassertStoreSeparation(path);awaitmkdir(dirname(path),{recursive:true});constcache=runtime.CultCache.builder().withDocumentType(defs.delivery).withGenericStore(newruntime.SingleFileMessagePackBackingStore(path)).build();awaitcache.pullAllBackingStores();constcurrent=cache.get(defs.delivery,admission.admissionId);if(current&&stable(current)!==stable(admission))thrownewError(`Signed admission ${admission.admissionId} already exists with different immutable content.`);if(!current)awaitcache.put(defs.delivery,admission.admissionId,admission);}
asyncfunctionserve(){constinterval=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)thrownewError("Persona-feedback serve requires --idunn-rudp-health or BIFROST_IDUNN_RUDP_HEALTH; no localhost default is assumed.");consthealthPublisher=healthEndpoint?createPersonaFeedbackHealthPublisher(awaitloadBifrostFeedbackIdentity(resolve(options["private-key"]||defaultFeedbackIdentityPath()))):null;do{constresults=awaitdrainPendingObservations(),readinessState=awaitreadiness();if(healthEndpoint)awaitpublishPersonaFeedbackHealth({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;}awaitnewPromise(done=>setTimeout(done,interval));}while(true);}
consthealthEndpoint=options["idunn-rudp-health"]||process.env.BIFROST_IDUNN_RUDP_HEALTH;if(!healthEndpoint)thrownewError("Bifrost Discord Persona ingress requires --idunn-rudp-health or BIFROST_IDUNN_RUDP_HEALTH.");
constinitial=awaitreadiness();if(!initial.ingressReady)thrownewError(`Bifrost Discord Persona ingress is not ready: ${initial.ingressReasons.join("; ")}`);
constrecovered=awaitdrainPendingObservations();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.`);
awaitpublishHealth();
consthealthTimer=setInterval(()=>publishHealth().catch(error=>console.error(`Bifrost Persona-feedback health publication failed: ${errorinstanceofError?error.message:String(error)}`)),10000);
letobservationBusy=false;constobservationTimer=setInterval(async()=>{if(observationBusy)return;observationBusy=true;try{constretried=awaitdrainPendingObservations();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: ${errorinstanceofError?error.message:String(error)}`);}finally{observationBusy=false;}},positiveInteger(options["observation-retry-interval-ms"]||"5000","observation-retry-interval-ms"));
asyncfunctionenrollIdentity(){constkeyPath=resolve(options["private-key"]||defaultFeedbackIdentityPath()),identity=awaitenrollBifrostFeedbackIdentity(keyPath),createdAt=newDate().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;awaitmkdir(dirname(out),{recursive:true});awaitwriteFile(out,runtime.encode(anchorTuple(anchor)));if(providerOut){if(providerOut===out)thrownewError("Feedback and provider-health trust anchors must use distinct paths.");constproviderAnchor=providerHealthTrustAnchor(identity,createdAt);awaitmkdir(dirname(providerOut),{recursive:true});awaitwriteFile(providerOut,runtime.encode(anchorTuple(providerAnchor)));}print({privateKey:keyPath,trustAnchor:out,identityId:identity.identityId,providerHealthTrustAnchor:providerOut??""});}
asyncfunctionreadiness(){constingressReasons=[];letidentity,bindingCount=0,pendingFailedCount=0;try{identity=awaitloadBifrostFeedbackIdentity(resolve(options["private-key"]||defaultFeedbackIdentityPath()));}catch(error){ingressReasons.push(`identity:${errorinstanceofError?error.message:String(error)}`);}letbindings=[];try{constinfo=awaitstat(privateStorePath);if(!info.isFile())thrownewError("private provider store is not a regular file");constcache=runtime.CultCache.builder().withDocumentType(defs.binding).withDocumentType(defs.actorLink).withDocumentType(defs.receipt).withDocumentType(defs.delivery).withDocumentType(defs.pendingFailure).withGenericStore(newruntime.SingleFileMessagePackBackingStore(privateStorePath)).build();awaitcache.pullAllBackingStores();bindings=cache.getAll(defs.binding);bindingCount=bindings.length;constadmitted=newSet(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:${errorinstanceofError?error.message:String(error)}`);}for(constbindingofbindings){try{awaitassertStoreSeparation(binding.deliveryStorePath);try{constinfo=awaitstat(binding.deliveryStorePath);if(!info.isFile())thrownewError("delivery path is not a regular file");awaitaccess(binding.deliveryStorePath,constants.W_OK);}catch(error){if(!error||typeoferror!=="object"||error.code!=="ENOENT")throwerror;awaitaccess(dirname(binding.deliveryStorePath),constants.W_OK);}}catch(error){ingressReasons.push(`binding:${binding.bindingId}:${errorinstanceofError?error.message:String(error)}`);}}constreasons=[...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};}
functionpositiveInteger(value,label){constparsed=Number(value);if(!Number.isSafeInteger(parsed)||parsed<=0)thrownewError(`${label} must be a positive integer.`);returnparsed;}
asyncfunctionassertStoreSeparation(targetDeliveryStore){constpaths=[observationStorePath,privateStorePath,resolve(targetDeliveryStore)],seenPaths=newSet(),seenFiles=newSet();for(constpathofpaths){constcanonical=awaitcanonicalPath(path);constkey=process.platform==="win32"?canonical.toLowerCase():canonical;if(seenPaths.has(key))thrownewError("Persona feedback observation inbox, Bifrost private state, and delivery export must use distinct canonical paths.");seenPaths.add(key);try{constinfo=awaitstat(path),fileKey=`${info.dev}:${info.ino}`;if(seenFiles.has(fileKey))thrownewError("Persona feedback stores must not alias the same physical file.");seenFiles.add(fileKey);}catch(error){if(!error||typeoferror!=="object"||error.code!=="ENOENT")throwerror;}}}