package ar.com.companeros.memory; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; /** Cuaderno individual exterior al mundo: texto, búsqueda y edición; nunca código ejecutable. */ public final class AgentNotebook { public static final int MAX_BYTES = 16 * 1024 * 1024; private static final int PAGE_CHARS = 600; private final Path root; private final String fileName; public record Page(int offset, int nextOffset, boolean more, String text) { } public record Match(int offset, String text) { } public record Search(int nextOffset, boolean more, List matches) { public Search { matches = List.copyOf(matches); } } public AgentNotebook(Path root) { this(root, "README.md"); } public AgentNotebook(Path root, String fileName) { if (!Set.of("README.md", "BASE.md", "KNOWLEDGE.md").contains(fileName)) throw new IllegalArgumentException("Cuaderno desconocido"); this.root = root.toAbsolutePath().normalize(); this.fileName = fileName; } // Sólo un UUID real determina la carpeta: ninguna ruta procede de la IA. public synchronized Path ensure(UUID actor, String name) throws IOException { if (!name.matches("[A-Za-z0-9_]{1,16}")) throw new IllegalArgumentException("Nombre inválido"); Files.createDirectories(root); if (Files.isSymbolicLink(root)) throw new IOException("Raíz de cuadernos enlazada"); Path folder = root.resolve(actor.toString()); if (Files.exists(folder, LinkOption.NOFOLLOW_LINKS) && Files.isSymbolicLink(folder)) throw new IOException("Cuaderno enlazado"); Files.createDirectories(folder); if (!folder.toRealPath().startsWith(root.toRealPath())) throw new IOException("Cuaderno fuera de su carpeta"); Path file = folder.resolve(fileName); if (Files.isSymbolicLink(file)) throw new IOException("Archivo enlazado"); if (!Files.exists(file, LinkOption.NOFOLLOW_LINKS)) Files.writeString(file, fileName.equals("BASE.md") ? "# Estado de la base\n\n## Facción y titularidad\nPor confirmar.\n\n## Ubicación y accesos\nSin verificar.\n\n## Cobertura, seguridad y peligros\nDesconocidos; un waypoint no prueba refugio.\n\n## Inventarios, hornos y producción pendiente\nSin registrar.\n\n## Obras y prioridades\nPor definir.\n\n## Coordinación y acuerdos\nSin líder acordado.\n\n## Observaciones fechadas\n\n" : "# Contexto de " + name + "\n\nUUID: " + actor + "\n\n## Resumen actual\n\n### Objetivo y plan en curso\nPor definir.\n\n### Recursos y lugares verificados\nSin registrar.\n\n### Relaciones y compromisos\nSin registrar.\n\n### Aprendizajes y errores que evitar\nSin registrar.\n\n### Pendientes y próxima acción\nPor definir.\n\n## Notas de experiencia\n\n", StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS) || Files.size(file) > MAX_BYTES) throw new IOException("Cuaderno inválido o lleno"); return file; } public synchronized void append(UUID actor, String name, String text) throws IOException { checked(text); Path file = ensure(actor, name); byte[] addition = ("\n" + text + "\n").getBytes(StandardCharsets.UTF_8); if (Files.size(file) + addition.length > MAX_BYTES) throw new IOException("Cuaderno lleno"); Files.write(file, addition, StandardOpenOption.APPEND); } public synchronized Page read(UUID actor, String name, int offset) throws IOException { checkOffset(offset); Path file = ensure(actor, name); try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { int actual = skip(reader, offset); char[] page = new char[PAGE_CHARS]; int used = 0, count; while (used < page.length && (count = reader.read(page, used, page.length - used)) > 0) used += count; // No separar un par UTF-16 entre páginas: el próximo offset vuelve a ese carácter. if (used > 0 && Character.isHighSurrogate(page[used - 1])) used--; boolean more = reader.read() != -1; return new Page(actual, actual + used, more, new String(page, 0, used)); } } // Una búsqueda recorre como máximo 256 Ki caracteres; se continúa con nextOffset. public synchronized Search search(UUID actor, String name, String query, int offset) throws IOException { checked(query); if (query.length() > 220) throw new IllegalArgumentException("Consulta larga"); checkOffset(offset); Path file = ensure(actor, name); try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { int actual = skip(reader, offset); char[] buffer = new char[262144 + query.length()]; int used = 0, count; while (used < buffer.length && (count = reader.read(buffer, used, buffer.length - used)) > 0) used += count; String text = new String(buffer, 0, used); List matches = new ArrayList<>(); int from = 0, hit; while (matches.size() < 2 && (hit = text.indexOf(query, from)) >= 0) { int start = Math.max(0, hit - 60), end = Math.min(text.length(), Math.max(hit + query.length(), hit + 180)); matches.add(new Match(actual + hit, text.substring(start, end))); from = hit + Math.max(1, query.length()); } int advance = matches.size() == 2 ? from : Math.max(0, used - query.length() + 1); boolean more = matches.size() == 2 && from < used || reader.read() != -1; return new Search(actual + (more ? advance : used), more, matches); } } // Reemplazar un fragmento exige una coincidencia única y conserva la versión previa. public synchronized void replace(UUID actor, String name, String oldText, String newText) throws IOException { checked(oldText); checked(newText); Path file = ensure(actor, name); String previous = Files.readString(file, StandardCharsets.UTF_8); int at = previous.indexOf(oldText); if (at < 0 || previous.indexOf(oldText, at + 1) >= 0) throw new IOException("Fragmento ausente o ambiguo"); String next = previous.substring(0, at) + newText + previous.substring(at + oldText.length()); if (next.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) throw new IOException("Cuaderno lleno"); Path backup = file.resolveSibling(fileName + ".bak"); if (Files.isSymbolicLink(backup)) throw new IOException("Respaldo enlazado"); Files.copy(file, backup, StandardCopyOption.REPLACE_EXISTING); Path temporary = Files.createTempFile(file.getParent(), "anotacion-", ".tmp"); try { Files.writeString(temporary, next, StandardCharsets.UTF_8); try { Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (AtomicMoveNotSupportedException unsupported) { Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING); } } finally { Files.deleteIfExists(temporary); } } private static int skip(Reader reader, int offset) throws IOException { int skipped = 0; long next; while (skipped < offset && (next = reader.skip(offset - skipped)) > 0) skipped += (int) next; return skipped; } private static void checked(String text) { if (text == null || text.isBlank() || text.length() > 2048 || text.indexOf(0) >= 0) throw new IllegalArgumentException("Anotación inválida"); } private static void checkOffset(int offset) { if (offset < 0 || offset > MAX_BYTES) throw new IllegalArgumentException("Offset inválido"); } }