Volver al índice
src/main/java/ar/com/companeros/runtime/MessageAttentionTests.java
package ar.com.companeros.runtime;
import ar.com.companeros.body.PlayerSessions;
import ar.com.companeros.identity.AgentRegistry;
import ar.com.companeros.identity.AgentState;
import ar.com.companeros.social.AgentInbox;
import ar.com.companeros.tools.ToolExecution;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.minecraft.core.BlockPos;
import net.minecraft.core.GlobalPos;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.gametest.GameTestHolder;
import net.minecraftforge.gametest.PrefixGameTestTemplate;
/** Respuestas pendientes: las órdenes nuevas invalidan, el contexto ajeno no. Sin transporte ni consultas. */
@GameTestHolder("rapsreview")
@PrefixGameTestTemplate(false)
public final class MessageAttentionTests {
@GameTest(batch = "review_pending_messages", template = "empty")
public void directedMessagesInvalidatePendingDecisionOnceAndStayInInbox(GameTestHelper helper) throws Exception {
MinecraftServer server = helper.getLevel().getServer();
UUID id = UUID.randomUUID();
try {
fixture(helper, id);
helper.assertTrue(AgentRuntime.runTool(console(server), name(id), "inspect", "{}") == 1,
"El runtime inicializa la mente del fixture sin pedir una decisión");
AgentRuntime runtime = runtime(server);
Object mind = ((Map<?, ?>) field(runtime, "minds").get(runtime)).get(id);
ToolExecution execution = (ToolExecution) field(mind, "execution").get(mind);
execution.cancel(); field(mind, "execution").set(mind, null);
AgentInbox inbox = AgentInbox.get(server);
UUID human = UUID.randomUUID();
// El mensaje que ya formaba parte del snapshot no vuelve a cancelar su propia consulta.
helper.assertTrue(inbox.deliver(id, human, "Visitante", AgentInbox.Kind.HUMAN, "Revisá el entorno."),
"Se entrega la orden observada antes de enviar la consulta");
Method observe = AgentRuntime.class.getDeclaredMethod("observeMessageOrders", UUID.class, mind.getClass(), List.class);
observe.setAccessible(true); observe.invoke(runtime, id, mind, inbox.pending(id, 8));
field(mind, "pending").setBoolean(mind, true);
long initialEpoch = field(mind, "epoch").getLong(mind);
helper.assertTrue(!reconsider(runtime, id, mind), "Una orden ya observada no cancela la respuesta pendiente");
helper.assertTrue(inbox.deliver(id, human, "Visitante", AgentInbox.Kind.HUMAN_CONTEXT, "Ese comentario era para otra persona."),
"El fixture también oye una conversación ajena");
helper.assertTrue(!reconsider(runtime, id, mind) && field(mind, "pending").getBoolean(mind)
&& field(mind, "epoch").getLong(mind) == initialEpoch,
"La conversación ajena conserva la consulta en vuelo y no genera un despertar");
// Se usa la misma comprobación que corre antes de aceptar una respuesta, entre sondeos del tick.
for (AgentInbox.Kind kind : List.of(AgentInbox.Kind.HUMAN, AgentInbox.Kind.HUMAN_PRIVATE, AgentInbox.Kind.ADMIN)) {
field(mind, "pending").setBoolean(mind, true);
long oldEpoch = field(mind, "epoch").getLong(mind);
helper.assertTrue(inbox.deliver(id, human, "Visitante", kind, "Detené el plan anterior: " + kind),
"La orden dirigida llega mientras la respuesta anterior sigue pendiente");
int pendingMessages = inbox.pending(id, 64).size();
helper.assertTrue(reconsider(runtime, id, mind) && !field(mind, "pending").getBoolean(mind)
&& field(mind, "epoch").getLong(mind) == oldEpoch + 1,
"La nueva orden cambia la sesión para impedir que se acepte la respuesta anterior: " + kind);
helper.assertTrue(!reconsider(runtime, id, mind) && field(mind, "epoch").getLong(mind) == oldEpoch + 1
&& inbox.pending(id, 64).size() == pendingMessages,
"La misma orden no causa consultas repetidas ni se confirma antes de observarla: " + kind);
}
helper.assertTrue(inbox.pending(id, 64).size() == 5,
"Los mensajes originales, el contexto y las tres órdenes nuevas siguen disponibles para el próximo snapshot");
helper.succeed();
} finally { cleanup(server, id); }
}
@GameTest(batch = "review_pending_survival", template = "empty")
public void survivalChangesDuringPendingDecisionRequireOneRevision(GameTestHelper helper) throws Exception {
MinecraftServer server = helper.getLevel().getServer();
UUID id = UUID.randomUUID();
try {
ServerPlayer body = fixture(helper, id);
helper.assertTrue(AgentRuntime.runTool(console(server), name(id), "inspect", "{}") == 1,
"El fixture inicializa su controlador sin transporte remoto");
AgentRuntime runtime = runtime(server);
Object mind = ((Map<?, ?>) field(runtime, "minds").get(runtime)).get(id);
((ToolExecution) field(mind, "execution").get(mind)).cancel();
field(mind, "execution").set(mind, null);
field(mind, "observedHunger").setInt(mind, 20);
body.getFoodData().setFoodLevel(11);
field(mind, "pending").setBoolean(mind, true);
field(mind, "lastDecisionTick").setLong(mind, server.getTickCount());
long epoch = field(mind, "epoch").getLong(mind);
long decisionTick = field(mind, "lastDecisionTick").getLong(mind);
// La detección real de hambre y varias señales más llegan durante una sola consulta.
Method observe = AgentRuntime.class.getDeclaredMethod("observeSurvivalSignals", UUID.class, ServerPlayer.class, mind.getClass(), long.class);
observe.setAccessible(true); observe.invoke(runtime, id, body, mind, (long) server.getTickCount());
Method signal = AgentRuntime.class.getDeclaredMethod("reconsiderSurvival", UUID.class, mind.getClass(), String.class);
signal.setAccessible(true);
signal.invoke(runtime, id, mind, "DAMAGED_RECONSIDER");
signal.invoke(runtime, id, mind, "THREAT_APPROACHING_RECONSIDER");
signal.invoke(runtime, id, mind, "DAMAGED_RECONSIDER");
helper.assertTrue(field(mind, "pending").getBoolean(mind) && field(mind, "epoch").getLong(mind) == epoch
&& field(mind, "lastDecisionTick").getLong(mind) == decisionTick
&& !((String) field(mind, "pendingReplanReason").get(mind)).isEmpty(),
"Hambre, peligro y golpes se acumulan sin cancelar la llamada ni adelantar el cupo de consultas");
Method resolve = AgentRuntime.class.getDeclaredMethod("resolvePendingReplan", UUID.class, mind.getClass());
resolve.setAccessible(true);
helper.assertTrue((boolean) resolve.invoke(runtime, id, mind) && !field(mind, "pending").getBoolean(mind)
&& field(mind, "epoch").getLong(mind) == epoch + 1
&& ((String) field(mind, "pendingReplanReason").get(mind)).isEmpty(),
"Resolver la respuesta anterior invalida una vez su sesión y borra la revisión acumulada");
helper.assertTrue(!(boolean) resolve.invoke(runtime, id, mind) && field(mind, "epoch").getLong(mind) == epoch + 1,
"Resolver otra vez no dispara una segunda revisión");
// Una percepción nueva ya conoce el hambre actual: mantenerla no invalida su propia respuesta.
field(mind, "pending").setBoolean(mind, true);
observe.invoke(runtime, id, body, mind, (long) server.getTickCount());
helper.assertTrue(!(boolean) resolve.invoke(runtime, id, mind) && field(mind, "pending").getBoolean(mind),
"La siguiente decisión no hereda una señal vieja cuyo estado ya fue observado");
helper.succeed();
} finally { cleanup(server, id); }
}
// Fixture quieto: aunque el operador tenga una clave configurada, esta prueba nunca llama al proveedor.
private static ServerPlayer fixture(GameTestHelper helper, UUID id) {
PlayerSessions.install(); AgentRuntime.install();
for (int x = 0; x <= 13; x++) for (int z = 0; z <= 13; z++)
helper.setBlock(new BlockPos(x, 1, z), Blocks.DIRT);
BlockPos position = helper.absolutePos(new BlockPos(3, 2, 3));
MinecraftServer server = helper.getLevel().getServer();
AgentRegistry.get(server).register(id, name(id), null, GlobalPos.of(helper.getLevel().dimension(), position), "quieto");
AgentRegistry.get(server).markState(id, AgentState.ACTIVE);
return PlayerSessions.create(server, id, name(id), helper.getLevel(), position);
}
private static String name(UUID id) { return "Msg_" + id.toString().substring(0, 8); }
private static net.minecraft.commands.CommandSourceStack console(MinecraftServer server) {
return server.createCommandSourceStack().withPermission(4).withSuppressedOutput();
}
// Acceso a la frontera privada del runtime: simula una consulta pendiente, sin fabricar respuestas HTTP.
private static AgentRuntime runtime(MinecraftServer server) throws Exception {
Method get = AgentRuntime.class.getDeclaredMethod("get", MinecraftServer.class);
get.setAccessible(true); return (AgentRuntime) get.invoke(null, server);
}
private static Field field(Object target, String name) throws Exception {
Field field = target.getClass().getDeclaredField(name); field.setAccessible(true); return field;
}
private static boolean reconsider(AgentRuntime runtime, UUID id, Object mind) throws Exception {
Method reconsider = AgentRuntime.class.getDeclaredMethod("reconsiderMessages", UUID.class, mind.getClass());
reconsider.setAccessible(true); return (boolean) reconsider.invoke(runtime, id, mind);
}
private static void cleanup(MinecraftServer server, UUID id) {
var identity = AgentRegistry.get(server).find(id).orElse(null);
try {
if (identity != null && identity.state() != AgentState.RETIRED)
AgentRuntime.retire(console(server), identity.name());
} finally {
PlayerSessions.remove(server, id);
if (identity != null) AgentRegistry.get(server).markState(id, AgentState.RETIRED);
AgentInbox inbox = AgentInbox.get(server);
for (AgentInbox.Message message : inbox.pending(id, 64)) inbox.acknowledge(id, message.id());
}
}
}