Volver al índice

src/main/java/ar/com/companeros/runtime/AgentKnowledge.java

package ar.com.companeros.runtime;

import ar.com.companeros.memory.*;
import ar.com.companeros.identity.AgentRegistry;
import ar.com.companeros.social.AgentInbox;
import java.util.*;
import net.minecraft.core.*;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.*;
import net.minecraft.resources.*;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.saveddata.SavedData;
import net.minecraftforge.registries.ForgeRegistries;

/** Contexto de trabajo pequeño y persistente; separado del historial de cientos de acciones. */
public final class AgentKnowledge extends SavedData {
    public record Place(String name, GlobalPos location, String purpose, long verifiedAt) { }
    public enum MapScope {
        OWN, FACTION, GLOBAL, ALL;
        public static MapScope parse(String text) {
            if (text == null || text.isBlank()) return OWN;
            return switch (text.strip().toLowerCase(Locale.ROOT)) {
                case "own", "individual", "private" -> OWN;
                case "faction", "team" -> FACTION;
                case "global" -> GLOBAL;
                case "all" -> ALL;
                default -> throw new IllegalArgumentException("Alcance de mapa inválido: own, faction, global o all");
            };
        }
        public String id() { return name().toLowerCase(Locale.ROOT); }
    }
    /** El equipo es el nombre real de scoreboard al compartir; nunca un argumento de la IA. */
    public record SharedPlace(Place place, UUID author, String authorName, MapScope scope, String team) { }
    private static final class Entry {
        final LinkedHashMap<String, Place> places = new LinkedHashMap<>();
        final ArrayDeque<String> conversation = new ArrayDeque<>();
        final WorkedRoutes routes = new WorkedRoutes();
        final RiskDecisions risks = new RiskDecisions();
        final ArrayDeque<String> overheard = new ArrayDeque<>();
        String project = "", projectStatus = "none", progress = "";
        final LinkedHashMap<String, String> workBlocks = new LinkedHashMap<>();
        GlobalPos furnaceWorksite;
        String furnaceProduct = "";
        int furnaceRemaining;
        GlobalPos death;
        long deathAt;
        Map<String, Integer> lostItems = Map.of();
        int failedRecoveryAttempts;
    }
    private final Map<UUID, Entry> entries = new HashMap<>();
    private final LinkedHashMap<String, SharedPlace> sharedPlaces = new LinkedHashMap<>();
    public static AgentKnowledge get(MinecraftServer server) {
        if (!server.isSameThread()) throw new IllegalStateException("Conocimiento exige hilo servidor");
        return server.overworld().getDataStorage().computeIfAbsent(AgentKnowledge::load, AgentKnowledge::new, "raps_conocimiento");
    }
    private Entry entry(UUID id) {
        if (entries.size() >= 256 && !entries.containsKey(id)) throw new IllegalStateException("Conocimiento lleno");
        return entries.computeIfAbsent(id, ignored -> new Entry());
    }

    // El mensaje original permanece disponible después de confirmar su recepción; no lo parafrasea otro modelo.
    public void conversation(UUID id, AgentInbox.Message message) {
        Entry e = entry(id);
        String text = "chat_context kind=" + message.kind() + " sender=" + message.senderName()
            + " utc=" + message.createdAtUtc() + " body=" + message.body();
        if (message.kind() == AgentInbox.Kind.HUMAN_CONTEXT) {
            String heard = text.replace("chat_context", "overheard_context");
            if (!e.overheard.contains(heard)) e.overheard.addLast(limit(heard, 2048));
            while (e.overheard.size() > 2) e.overheard.removeFirst();
            setDirty(); return;
        }
        if (!e.conversation.contains(text)) e.conversation.addLast(limit(text, 2048));
        while (e.conversation.size() > 4) e.conversation.removeFirst();
        setDirty();
    }
    public void project(UUID id, String goal, String status, String progress) {
        if (!Set.of("active", "done", "abandoned").contains(status)) throw new IllegalArgumentException("Estado de proyecto inválido");
        Entry e = entry(id); e.project = checked(goal, 512); e.projectStatus = status; e.progress = limit(progress, 256); setDirty();
    }
    public String project(UUID id) {
        Entry e = entries.get(id);
        return e == null || !e.projectStatus.equals("active") ? "" : e.project;
    }
    // Sólo el ejecutor llama esto tras pisar cada peldaño completado.
    public void excavation(ServerPlayer player, BlockPos origin, net.minecraft.core.Direction direction, int slope, int completed) {
        if (completed <= 0) return;
        entry(player.getUUID()).routes.record(new WorkedRoutes.Route(player.level().dimension().location().toString(),
            origin.getX(), origin.getY(), origin.getZ(), direction.getStepX(), direction.getStepZ(), slope, completed, System.currentTimeMillis()));
        setDirty();
    }
    // Cada bot conserva sus propios criterios; nunca autoriza a otro agente.
    public void decideRisk(ServerPlayer player, String action, String risk, BlockPos target, String decision) {
        entry(player.getUUID()).risks.decide(player.level().dimension().location().toString(), action, risk,
            target.asLong(), decision, System.currentTimeMillis()); setDirty();
    }
    public RiskDecisions.Verdict risk(ServerPlayer player, String action, String risk, BlockPos target) {
        return entry(player.getUUID()).risks.consume(player.level().dimension().location().toString(), action, risk,
            target.asLong(), System.currentTimeMillis());
    }
    public long riskRevision(UUID id, String action) {
        Entry e = entries.get(id); return e == null ? 0 : e.risks.revision(action);
    }
    // Sólo se registra después de depositar realmente una tanda del inventario propio.
    public void workBlock(ServerPlayer player, BlockPos pos) {
        if (player.level().getBlockEntity(pos) == null) return;
        Entry e = entry(player.getUUID()); String key = player.level().dimension().location() + ":" + pos.asLong();
        e.workBlocks.remove(key);
        e.workBlocks.put(key, "known_work_block dimension=" + player.level().dimension().location()
            + " pos=" + pos.toShortString() + " block=" + ForgeRegistries.BLOCKS.getKey(player.level().getBlockState(pos).getBlock())
            + " verified_utc=" + System.currentTimeMillis() + "; owner_and_current_safety_not_assumed");
        while (e.workBlocks.size() > 8) e.workBlocks.remove(e.workBlocks.keySet().iterator().next()); setDirty();
    }
    public void furnaceLoaded(ServerPlayer player, BlockPos pos, String output, int expected) {
        Entry e = entry(player.getUUID()); e.furnaceWorksite = GlobalPos.of(player.level().dimension(), pos.immutable());
        e.furnaceProduct = checked(output, 128); e.furnaceRemaining = Math.max(0, expected); setDirty();
    }
    public void furnaceCollected(ServerPlayer player, BlockPos pos, String item, int count) {
        Entry e = entries.get(player.getUUID());
        if (e != null && e.furnaceWorksite != null && e.furnaceWorksite.dimension().equals(player.level().dimension())
                && e.furnaceWorksite.pos().equals(pos) && e.furnaceProduct.equals(item)) {
            e.furnaceRemaining = Math.max(0, e.furnaceRemaining - Math.max(0, count)); setDirty();
        }
    }
    public List<String> context(UUID id) {
        Entry e = entries.get(id); if (e == null) return List.of();
        List<String> facts = new ArrayList<>();
        if (e.furnaceWorksite != null && e.furnaceRemaining > 0) facts.add("own_furnace_worksite dimension="
            + e.furnaceWorksite.dimension().location() + " pos=" + e.furnaceWorksite.pos().toShortString()
            + " product=" + e.furnaceProduct + " expected_remaining=" + e.furnaceRemaining
            + "; deposited_your_input=true; contents_require_verification; not_the_base_waypoint; use_container_take_for_ready_output");
        if (!e.project.isBlank()) facts.add("persistent_project status=" + e.projectStatus + " goal=" + e.project + " progress=" + e.progress);
        facts.addAll(e.workBlocks.values());
        facts.addAll(e.routes.facts());
        facts.addAll(e.conversation); facts.addAll(e.overheard); return List.copyOf(facts);
    }

    // Se marca un lugar observado, con una finalidad elegida por el agente. No se concede seguridad absoluta.
    public Place remember(ServerPlayer player, String name, String purpose) {
        return remember(player, name, purpose, MapScope.OWN);
    }
    public Place remember(ServerPlayer player, String name, String purpose, MapScope scope) {
        String label = checked(name, 64), note = checked(purpose, 220);
        Objects.requireNonNull(scope);
        if (scope == MapScope.ALL) throw new IllegalArgumentException("Elegí un alcance concreto para guardar");
        Place p = new Place(label, GlobalPos.of(player.level().dimension(), player.blockPosition()), note, System.currentTimeMillis());
        if (scope == MapScope.OWN) {
            Entry e = entry(player.getUUID()); String key = label.toLowerCase(Locale.ROOT);
            if (e.places.size() >= 16 && !e.places.containsKey(key)) throw new IllegalArgumentException("Mapa lleno: reutilizá una marca");
            e.places.put(key, p);
        } else {
            requireAgent(player);
            String team = scope == MapScope.FACTION ? requireTeam(player) : "";
            SharedPlace shared = new SharedPlace(p, player.getUUID(), player.getScoreboardName(), scope, team);
            String key = sharedKey(shared);
            if (!sharedPlaces.containsKey(key)) {
                long ownCount = sharedPlaces.values().stream().filter(s -> s.author().equals(player.getUUID())).count();
                if (sharedPlaces.size() >= 256 || ownCount >= 32)
                    throw new IllegalArgumentException("Mapa compartido lleno: reutilizá una de tus marcas");
            }
            sharedPlaces.put(key, shared);
        }
        setDirty();
        MemoryStore store = MemoryStore.get(player.server); long now = System.currentTimeMillis();
        store.record(new MemoryRecord(UUID.randomUUID(), player.getUUID(), store.worldId(), p.location(), now,
            player.serverLevel().getGameTime(), MemoryType.PLACE, .85, 1, now, player.serverLevel().getGameTime(),
            MemoryOrigin.OBSERVED, "map:" + label, List.of(), "Lugar " + label + ": " + note,
            Set.of("place", "map", "map_scope:" + scope.id()), Set.of(), null, true));
        return p;
    }
    public List<Place> places(UUID id) {
        Entry e = entries.get(id); return e == null ? List.of() : List.copyOf(e.places.values());
    }
    public List<String> mapFacts(UUID id) {
        return places(id).stream().map(p -> placeFact(p, MapScope.OWN, id, "")).toList();
    }

    // Los mapas compartidos se consultan con el cuerpo actual: cambiar de facción revoca el acceso inmediato.
    public List<SharedPlace> sharedPlaces(ServerPlayer player, MapScope scope) {
        if (scope == MapScope.OWN) return List.of();
        requireAgent(player);
        String team = player.getTeam() == null ? "" : player.getTeam().getName();
        return sharedPlaces.values().stream().filter(s ->
            (scope == MapScope.ALL || scope == s.scope())
                && (s.scope() == MapScope.GLOBAL || !team.isBlank() && team.equals(s.team())))
            .sorted(Comparator.comparingLong((SharedPlace s) -> s.place().verifiedAt()).reversed()
                .thenComparing(s -> s.author().toString()).thenComparing(s -> s.place().name()))
            .toList();
    }
    public List<String> mapFacts(ServerPlayer player, MapScope scope) {
        List<String> facts = new ArrayList<>();
        if (scope == MapScope.OWN || scope == MapScope.ALL) facts.addAll(mapFacts(player.getUUID()));
        for (SharedPlace p : sharedPlaces(player, scope)) facts.add(placeFact(p.place(), p.scope(), p.author(), p.team()));
        return List.copyOf(facts);
    }
    public Optional<Place> findPlace(ServerPlayer player, String name, MapScope scope) {
        String label = checked(name, 64);
        List<Place> matches = new ArrayList<>();
        if (scope == MapScope.OWN || scope == MapScope.ALL)
            places(player.getUUID()).stream().filter(p -> p.name().equalsIgnoreCase(label)).forEach(matches::add);
        sharedPlaces(player, scope).stream().map(SharedPlace::place)
            .filter(p -> p.name().equalsIgnoreCase(label)).forEach(matches::add);
        if (matches.size() > 1) throw new IllegalArgumentException("Nombre ambiguo: elegí un alcance o una marca con nombre único");
        return matches.stream().findFirst();
    }
    private static String placeFact(Place p, MapScope scope, UUID author, String team) {
        return limit("known_place scope=" + scope.id() + " author=" + author + (team.isBlank() ? "" : " team=" + team)
            + " name=" + p.name() + " dimension=" + p.location().dimension().location() + " pos=" + p.location().pos().toShortString()
            + " purpose=" + p.purpose() + " verified_utc=" + p.verifiedAt() + " current_route_requires_observation=true", 640);
    }
    private static void requireAgent(ServerPlayer player) {
        if (!AgentRegistry.get(player.server).isAgent(player.getUUID())) throw new IllegalArgumentException("Mapa interno reservado a agentes registrados");
    }
    private static String requireTeam(ServerPlayer player) {
        if (player.getTeam() == null) throw new IllegalArgumentException("El bot no pertenece a un equipo de scoreboard");
        return checked(player.getTeam().getName(), 64);
    }
    private static String sharedKey(SharedPlace p) {
        return p.scope().id() + ":" + p.team() + ":" + p.author() + ":" + p.place().name().toLowerCase(Locale.ROOT);
    }

    // Inventario real al morir, incluidos equipo y mano secundaria: tierra barata no equivale a un pico valioso.
    public void death(ServerPlayer player) {
        Entry e = entry(player.getUUID()); e.death = GlobalPos.of(player.level().dimension(), player.blockPosition());
        e.deathAt = player.serverLevel().getGameTime(); e.failedRecoveryAttempts = 0;
        Map<String, Integer> items = new TreeMap<>();
        for (int i = 0; i < player.getInventory().getContainerSize(); i++) {
            var stack = player.getInventory().getItem(i);
            if (!stack.isEmpty()) items.merge(ForgeRegistries.ITEMS.getKey(stack.getItem()).toString(), stack.getCount(), Integer::sum);
        }
        e.lostItems = Map.copyOf(items); setDirty();
    }
    public void recoveryAttempt(ServerPlayer player, Map<String, Integer> inventoryDelta) {
        Entry e = entries.get(player.getUUID());
        if (e == null || e.death == null || !e.death.dimension().equals(player.level().dimension())
                || e.death.pos().distSqr(player.blockPosition()) > 64) return;
        // Una recuperación parcial no borra la armadura o herramientas que todavía faltan.
        Map<String, Integer> remaining = new TreeMap<>(e.lostItems);
        boolean recovered = false;
        for (var gain : inventoryDelta.entrySet()) {
            if (gain.getValue() <= 0 || !remaining.containsKey(gain.getKey())) continue;
            int left = Math.max(0, remaining.get(gain.getKey()) - gain.getValue());
            if (left == 0) remaining.remove(gain.getKey()); else remaining.put(gain.getKey(), left);
            recovered = true;
        }
        e.lostItems = Map.copyOf(remaining);
        if (!recovered) e.failedRecoveryAttempts = Math.min(100, e.failedRecoveryAttempts + 1);
        setDirty();
    }
    public String deathFact(UUID id) {
        Entry e = entries.get(id); if (e == null || e.death == null) return "";
        return limit("death_inventory pos=" + e.death.pos().toShortString() + " dimension=" + e.death.dimension().location()
            + " game_tick=" + e.deathAt + " lost=" + e.lostItems + " unsuccessful_interactions=" + e.failedRecoveryAttempts
            + " current_grave_contents_unknown=true; weigh_value_travel_night_threats_and_repeated_failures", 512);
    }

    // NBT acotado: mundo nuevo no hereda coordenadas, pero los recuerdos PLACE se archivan por separado.
    @Override public CompoundTag save(CompoundTag root) {
        root.putInt("Schema", 1); ListTag list = new ListTag();
        for (var pair : entries.entrySet()) {
            Entry e = pair.getValue(); CompoundTag tag = new CompoundTag(); tag.putUUID("Id", pair.getKey());
            if (e.furnaceWorksite != null) { CompoundTag f = new CompoundTag(); putPos(f, e.furnaceWorksite);
                f.putString("Product", e.furnaceProduct); f.putInt("Remaining", e.furnaceRemaining); tag.put("FurnaceWorksite", f); }
            tag.putString("Project", e.project); tag.putString("Status", e.projectStatus); tag.putString("Progress", e.progress);
            CompoundTag sites = new CompoundTag(); e.workBlocks.forEach(sites::putString); tag.put("WorkBlocks", sites);
            ListTag preferences = new ListTag(); e.risks.saved().forEach(t -> preferences.add(StringTag.valueOf(t))); tag.put("RiskChoices", preferences);
            ListTag routes = new ListTag(); e.routes.saved().forEach(t -> routes.add(StringTag.valueOf(t))); tag.put("WorkedRoutes", routes);
            ListTag heard = new ListTag(); e.overheard.forEach(t -> heard.add(StringTag.valueOf(t))); tag.put("Overheard", heard);
            ListTag chat = new ListTag(); e.conversation.forEach(t -> chat.add(StringTag.valueOf(t))); tag.put("Chat", chat);
            ListTag marks = new ListTag();
            for (Place p : e.places.values()) {
                CompoundTag m = new CompoundTag(); m.putString("Name", p.name()); m.putString("Purpose", p.purpose());
                putPos(m, p.location()); m.putLong("Verified", p.verifiedAt()); marks.add(m);
            }
            tag.put("Places", marks);
            if (e.death != null) { CompoundTag d = new CompoundTag(); putPos(d, e.death); d.putLong("Tick", e.deathAt);
                d.putInt("Attempts", e.failedRecoveryAttempts); CompoundTag items = new CompoundTag();
                e.lostItems.forEach(items::putInt); d.put("Items", items); tag.put("Death", d); }
            list.add(tag);
        }
        root.put("Entries", list);
        ListTag shared = new ListTag();
        for (SharedPlace p : sharedPlaces.values()) {
            CompoundTag m = new CompoundTag(); m.putString("Name", p.place().name()); m.putString("Purpose", p.place().purpose());
            putPos(m, p.place().location()); m.putLong("Verified", p.place().verifiedAt());
            m.putUUID("Author", p.author()); m.putString("AuthorName", p.authorName());
            m.putString("Scope", p.scope().id()); m.putString("Team", p.team()); shared.add(m);
        }
        root.put("SharedPlaces", shared); return root;
    }
    public static AgentKnowledge load(CompoundTag root) {
        if (root.getInt("Schema") > 1) throw new IllegalArgumentException("Conocimiento de versión posterior");
        AgentKnowledge data = new AgentKnowledge(); ListTag list = root.getList("Entries", 10);
        if (list.size() > 256) throw new IllegalArgumentException("Conocimiento fuera de límite");
        for (int i = 0; i < list.size(); i++) {
            CompoundTag tag = list.getCompound(i); Entry e = data.entry(tag.getUUID("Id"));
            if (tag.contains("FurnaceWorksite", 10)) { CompoundTag f = tag.getCompound("FurnaceWorksite");
                e.furnaceWorksite = readPos(f); e.furnaceProduct = checked(f.getString("Product"), 128);
                e.furnaceRemaining = Math.max(0, Math.min(4096, f.getInt("Remaining"))); }
            e.project = limit(tag.getString("Project"), 512); e.projectStatus = tag.getString("Status"); e.progress = limit(tag.getString("Progress"), 256);
            CompoundTag sites = tag.getCompound("WorkBlocks"); sites.getAllKeys().stream().sorted().limit(8)
                .forEach(k -> e.workBlocks.put(limit(k, 128), limit(sites.getString(k), 384)));
            ListTag heard = tag.getList("Overheard", 8);
            for (int n = Math.max(0, heard.size() - 2); n < heard.size(); n++) e.overheard.add(limit(heard.getString(n), 2048));
            ListTag preferences = tag.getList("RiskChoices", 8);
            if (preferences.size() > 64) throw new IllegalArgumentException("Preferencias de riesgo fuera de límite");
            for (int n = 0; n < preferences.size(); n++) e.risks.restore(preferences.getString(n));
            ListTag routes = tag.getList("WorkedRoutes", 8);
            for (int n = Math.max(0, routes.size() - 8); n < routes.size(); n++) e.routes.restore(routes.getString(n));
            ListTag chat = tag.getList("Chat", 8); for (int n = Math.max(0, chat.size() - 4); n < chat.size(); n++) e.conversation.add(limit(chat.getString(n), 2048));
            ListTag marks = tag.getList("Places", 10);
            for (int n = 0; n < Math.min(16, marks.size()); n++) { CompoundTag m = marks.getCompound(n);
                Place p = new Place(checked(m.getString("Name"), 64), readPos(m), checked(m.getString("Purpose"), 220), Math.max(0, m.getLong("Verified")));
                e.places.put(p.name().toLowerCase(Locale.ROOT), p); }
            if (tag.contains("Death", 10)) { CompoundTag d = tag.getCompound("Death"); e.death = readPos(d); e.deathAt = Math.max(0, d.getLong("Tick"));
                e.failedRecoveryAttempts = Math.max(0, Math.min(100, d.getInt("Attempts"))); Map<String, Integer> items = new TreeMap<>();
                CompoundTag saved = d.getCompound("Items"); saved.getAllKeys().stream().limit(128).forEach(k -> { if (saved.getInt(k) > 0) items.put(k, saved.getInt(k)); }); e.lostItems = Map.copyOf(items); }
        }
        ListTag shared = root.getList("SharedPlaces", 10);
        if (shared.size() > 256) throw new IllegalArgumentException("Mapa compartido fuera de límite");
        Map<UUID, Integer> perAuthor = new HashMap<>();
        for (int n = 0; n < shared.size(); n++) {
            CompoundTag m = shared.getCompound(n); MapScope scope = MapScope.parse(m.getString("Scope"));
            if (scope != MapScope.FACTION && scope != MapScope.GLOBAL) throw new IllegalArgumentException("Alcance compartido inválido");
            String team = scope == MapScope.FACTION ? checked(m.getString("Team"), 64) : "";
            Place p = new Place(checked(m.getString("Name"), 64), readPos(m), checked(m.getString("Purpose"), 220), Math.max(0, m.getLong("Verified")));
            SharedPlace saved = new SharedPlace(p, m.getUUID("Author"), checked(m.getString("AuthorName"), 64), scope, team);
            if (perAuthor.merge(saved.author(), 1, Integer::sum) > 32) throw new IllegalArgumentException("Mapa de autor fuera de límite");
            if (data.sharedPlaces.putIfAbsent(sharedKey(saved), saved) != null) throw new IllegalArgumentException("Marca compartida duplicada");
        }
        return data;
    }
    private static void putPos(CompoundTag tag, GlobalPos pos) { tag.putString("Dimension", pos.dimension().location().toString()); tag.putLong("Pos", pos.pos().asLong()); }
    private static GlobalPos readPos(CompoundTag tag) { return GlobalPos.of(ResourceKey.create(Registries.DIMENSION, new ResourceLocation(tag.getString("Dimension"))), BlockPos.of(tag.getLong("Pos"))); }
    private static String checked(String s, int max) { if (s == null || s.isBlank() || s.length() > max || s.chars().anyMatch(Character::isISOControl)) throw new IllegalArgumentException("Texto fuera de límite"); return s.strip(); }
    private static String limit(String s, int max) { return s.length() <= max ? s : s.substring(0, max); }
}