@adayacas/loopbreaker 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,209 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { execFileSync } from "node:child_process";
4
+ import { LOG_FILE, STATE_FILE, loadConfig } from "./config-loader.js";
5
+ import { blockMessage, check, family, newSession, record, recordResult, resultText, signature, WRITE_TOOLS } from "./loop-detector.js";
6
+ import { bashWrites, checkPaths, gitViolations, writtenPaths } from "./scope-validator.js";
7
+ /** Un repo no confiable puede poner symlinks en .opencode: nunca escribimos a través de ellos. */
8
+ function isSymlink(f) {
9
+ try {
10
+ return fs.lstatSync(f).isSymbolicLink();
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ }
16
+ /** Núcleo del guardián: independiente de OpenCode para poder probarlo en aislamiento. */
17
+ export class Guard {
18
+ root;
19
+ cfg;
20
+ state = { sessions: {} };
21
+ constructor(root) {
22
+ this.root = root;
23
+ this.cfg = loadConfig(root);
24
+ this.load();
25
+ this.harden();
26
+ }
27
+ /** Endurece archivos existentes de versiones anteriores (0644 -> 0600). */
28
+ harden() {
29
+ for (const f of [STATE_FILE, LOG_FILE]) {
30
+ const full = path.join(this.root, f);
31
+ if (isSymlink(full))
32
+ continue;
33
+ try {
34
+ fs.chmodSync(full, 0o600);
35
+ }
36
+ catch {
37
+ /* el archivo todavía no existe */
38
+ }
39
+ }
40
+ }
41
+ /** La configuración se relee en cada llamada: cambiar de fase surte efecto sin reiniciar. */
42
+ reload() {
43
+ this.cfg = loadConfig(this.root);
44
+ }
45
+ load() {
46
+ try {
47
+ const f = path.join(this.root, STATE_FILE);
48
+ if (isSymlink(f))
49
+ return;
50
+ const raw = JSON.parse(fs.readFileSync(f, "utf8"));
51
+ if (raw && typeof raw === "object" && raw.sessions) {
52
+ this.state = raw;
53
+ // Migración: versiones anteriores guardaban los primeros 120 caracteres de cada salida.
54
+ let dirty = false;
55
+ for (const s of Object.values(this.state.sessions)) {
56
+ if (!s || !Array.isArray(s.entries))
57
+ continue;
58
+ for (const e of s.entries) {
59
+ if (e && Object.prototype.hasOwnProperty.call(e, "snippet")) {
60
+ delete e.snippet;
61
+ dirty = true;
62
+ }
63
+ }
64
+ }
65
+ if (dirty)
66
+ this.save();
67
+ }
68
+ }
69
+ catch {
70
+ /* sin estado previo o corrupto: empezamos limpio */
71
+ }
72
+ }
73
+ save() {
74
+ try {
75
+ const f = path.join(this.root, STATE_FILE);
76
+ if (isSymlink(f))
77
+ return;
78
+ fs.mkdirSync(path.dirname(f), { recursive: true, mode: 0o700 });
79
+ // El snippet se usa solo en memoria para citar la salida en el mensaje de bloqueo.
80
+ // Nunca se persiste: puede contener tokens, variables de entorno o credenciales.
81
+ const data = JSON.stringify(this.state, (k, v) => (k === "snippet" ? undefined : v));
82
+ fs.writeFileSync(f, data, { mode: 0o600 });
83
+ fs.chmodSync(f, 0o600);
84
+ }
85
+ catch {
86
+ /* el guardián nunca debe romper la sesión por no poder persistir */
87
+ }
88
+ }
89
+ log(event) {
90
+ try {
91
+ const f = path.join(this.root, LOG_FILE);
92
+ if (isSymlink(f))
93
+ return;
94
+ fs.mkdirSync(path.dirname(f), { recursive: true, mode: 0o700 });
95
+ // El motivo de estancamiento cita la salida: se redacta antes de tocar el disco.
96
+ const safe = Object.fromEntries(Object.entries(event).map(([k, v]) => [
97
+ k,
98
+ typeof v === "string" ? v.replace(/«[^»]*»/g, "«…»").slice(0, 500) : v,
99
+ ]));
100
+ fs.appendFileSync(f, JSON.stringify({ t: new Date().toISOString(), ...safe }) + "\n", { mode: 0o600 });
101
+ fs.chmodSync(f, 0o600);
102
+ }
103
+ catch {
104
+ /* idem */
105
+ }
106
+ }
107
+ session(id) {
108
+ return (this.state.sessions[id] ??= newSession());
109
+ }
110
+ /**
111
+ * Antes de ejecutar una herramienta. Devuelve el mensaje de bloqueo o undefined si puede seguir.
112
+ * En modo "warn" solo registra en el log.
113
+ */
114
+ before(sessionID, tool, args = {}) {
115
+ this.reload();
116
+ const s = this.session(sessionID);
117
+ const sig = signature(tool, args, this.root);
118
+ const fam = family(tool, args);
119
+ // 1) alcance (solo escrituras)
120
+ let reason;
121
+ let kind = "scope";
122
+ const paths = WRITE_TOOLS.has(tool)
123
+ ? writtenPaths(tool, args)
124
+ : tool === "bash" && typeof args.command === "string"
125
+ ? bashWrites(args.command)
126
+ : [];
127
+ if (paths.length) {
128
+ const v = checkPaths(this.cfg, paths);
129
+ if (v.blocked)
130
+ reason = v.reason;
131
+ }
132
+ // 2) bucles (todas las herramientas)
133
+ if (!reason) {
134
+ const v = check(s, this.cfg, tool, sig, fam);
135
+ if (v.blocked) {
136
+ reason = v.reason;
137
+ kind = "loop";
138
+ }
139
+ }
140
+ if (reason) {
141
+ s.blocks++;
142
+ this.log({ event: "violation", kind, tool, sessionID, reason, mode: this.cfg.mode, blocks: s.blocks });
143
+ if (this.cfg.mode === "block") {
144
+ // una llamada bloqueada no se ejecuta: no cuenta como progreso ni se añade al historial,
145
+ // salvo los bloqueos por bucle, que sí deben seguir sumando para escalar.
146
+ if (kind === "loop") {
147
+ s.loopBlocks = (s.loopBlocks ?? 0) + 1;
148
+ record(s, this.cfg, tool, sig, fam);
149
+ }
150
+ this.save();
151
+ return kind === "scope"
152
+ ? `🛑 [LOOPBREAKER BLOQUEADO] ${reason}. Trabaja solo dentro del alcance de la fase activa o pide al usuario que cambie de fase.`
153
+ : blockMessage(this.cfg, s, reason);
154
+ }
155
+ }
156
+ record(s, this.cfg, tool, sig, fam);
157
+ this.save();
158
+ return undefined;
159
+ }
160
+ after(sessionID, tool, args, output, failed = false) {
161
+ const s = this.session(sessionID);
162
+ recordResult(s, tool, signature(tool, args, this.root), resultText(output), failed);
163
+ this.save();
164
+ }
165
+ /** Red de seguridad fiable: archivos cambiados según git que violan el alcance. */
166
+ gitCheck() {
167
+ this.reload();
168
+ try {
169
+ const out = execFileSync("git", ["status", "--porcelain", "-uall"], { cwd: this.root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
170
+ const changed = out
171
+ .split("\n")
172
+ .filter(Boolean)
173
+ .map((l) => l.slice(3).replace(/^.* -> /, "").replace(/^"|"$/g, ""))
174
+ .filter((p) => !p.startsWith(".opencode/"));
175
+ const bad = gitViolations(this.cfg, changed);
176
+ if (bad.length)
177
+ this.log({ event: "git-violation", files: bad });
178
+ return bad;
179
+ }
180
+ catch {
181
+ return [];
182
+ }
183
+ }
184
+ reset(sessionID) {
185
+ if (sessionID)
186
+ delete this.state.sessions[sessionID];
187
+ else
188
+ this.state = { sessions: {} };
189
+ this.save();
190
+ }
191
+ status(sessionID) {
192
+ const c = this.cfg;
193
+ const lines = [
194
+ `modo: ${c.mode} | repeticiones: ${c.maxConsecutiveRepeats} | ciclos hasta periodo ${c.cycleMaxPeriod}`,
195
+ `fase: ${c.specFile ?? "(ninguna)"}`,
196
+ `allowOnly: ${c.scope.allowOnlyGlobs.join(", ") || "-"}`,
197
+ `deny: ${c.scope.denyGlobs.join(", ") || "-"}`,
198
+ ];
199
+ const ids = sessionID ? [sessionID] : Object.keys(this.state.sessions);
200
+ for (const id of ids) {
201
+ const s = this.state.sessions[id];
202
+ if (s)
203
+ lines.push(`sesión ${id}: ${s.entries.length} llamadas, ${s.blocks} bloqueos`);
204
+ }
205
+ for (const w of c.warnings)
206
+ lines.push(`⚠ ${w}`);
207
+ return lines.join("\n");
208
+ }
209
+ }
@@ -0,0 +1,45 @@
1
+ type Args = Record<string, unknown>;
2
+ type PluginCtx = {
3
+ directory?: string;
4
+ worktree?: string;
5
+ };
6
+ export declare const LoopbreakerPlugin: (ctx?: PluginCtx) => Promise<{
7
+ tool: {
8
+ loopbreaker_status: {
9
+ description: string;
10
+ args: {};
11
+ execute(_a: unknown, c: {
12
+ sessionID?: string;
13
+ }): Promise<string>;
14
+ };
15
+ };
16
+ "tool.execute.before": (input: {
17
+ tool: string;
18
+ sessionID: string;
19
+ callID: string;
20
+ }, output: {
21
+ args?: Args;
22
+ }) => Promise<void>;
23
+ "tool.execute.after": (input: {
24
+ tool: string;
25
+ sessionID: string;
26
+ callID: string;
27
+ }, output: {
28
+ output?: unknown;
29
+ metadata?: {
30
+ error?: unknown;
31
+ };
32
+ }) => Promise<void>;
33
+ "experimental.chat.system.transform": (_i: unknown, output: {
34
+ system: string[];
35
+ }) => Promise<void>;
36
+ "experimental.session.compacting": (_i: unknown, output: {
37
+ context: string[];
38
+ }) => Promise<void>;
39
+ event: ({ event }: {
40
+ event: {
41
+ type: string;
42
+ };
43
+ }) => Promise<void>;
44
+ }>;
45
+ export {};
@@ -0,0 +1,56 @@
1
+ import { Guard } from "./guard.js";
2
+ import { phaseCard } from "./config-loader.js";
3
+ export const LoopbreakerPlugin = async (ctx = {}) => {
4
+ const root = ctx.worktree || ctx.directory || process.cwd();
5
+ const guard = new Guard(root);
6
+ // Las args se guardan entre before y after por callID (el hook after no las recibe).
7
+ const pending = new Map();
8
+ // loopbreaker_status es de solo lectura. No depende de @opencode-ai/plugin:
9
+ // su helper tool() es una identidad (verificado en 1.19.5 y 0.15.31), así que
10
+ // devolver el objeto directamente evita el peer y el fallo silencioso.
11
+ return {
12
+ tool: {
13
+ loopbreaker_status: {
14
+ description: "Muestra el estado del guardián de ejecución (fase activa, alcance, bloqueos).",
15
+ args: {},
16
+ async execute(_a, c) {
17
+ return guard.status(c?.sessionID);
18
+ },
19
+ },
20
+ },
21
+ "tool.execute.before": async (input, output) => {
22
+ const args = output?.args ?? {};
23
+ pending.set(input.callID, args);
24
+ const msg = guard.before(input.sessionID, input.tool, args);
25
+ if (msg) {
26
+ pending.delete(input.callID);
27
+ throw new Error(msg);
28
+ }
29
+ },
30
+ "tool.execute.after": async (input, output) => {
31
+ const args = pending.get(input.callID);
32
+ pending.delete(input.callID);
33
+ if (!args)
34
+ return;
35
+ guard.after(input.sessionID, input.tool, args, output?.output, Boolean(output?.metadata?.error));
36
+ },
37
+ // Inyecta la tarjeta de fase en cada prompt y durante la compactación (no después).
38
+ "experimental.chat.system.transform": async (_i, output) => {
39
+ guard.reload();
40
+ const card = phaseCard(guard.cfg);
41
+ if (card)
42
+ output.system.push(card);
43
+ },
44
+ "experimental.session.compacting": async (_i, output) => {
45
+ guard.reload();
46
+ const card = phaseCard(guard.cfg);
47
+ if (card)
48
+ output.context.push(card);
49
+ },
50
+ event: async ({ event }) => {
51
+ if (event.type === "session.idle")
52
+ guard.gitCheck();
53
+ },
54
+ };
55
+ };
56
+ // Solo se exporta LoopbreakerPlugin: OpenCode invoca como plugin CADA export de función/clase del módulo.
@@ -0,0 +1,26 @@
1
+ import type { LoopbreakerConfig } from "./types.js";
2
+ export declare const PLUGIN_NAME = "@adayacas/loopbreaker";
3
+ export declare const PLUGIN_VERSION: string;
4
+ export declare const PINNED_PLUGIN: string;
5
+ export declare const GITIGNORE_ENTRY = ".opencode/";
6
+ export declare const DEFAULT_INIT: LoopbreakerConfig;
7
+ export interface InstallResult {
8
+ ok: boolean;
9
+ changed: boolean;
10
+ file: string;
11
+ message: string;
12
+ }
13
+ /** Config global de OpenCode: $XDG_CONFIG_HOME/opencode o ~/.config/opencode. */
14
+ export declare function globalConfigDir(env?: NodeJS.ProcessEnv): string;
15
+ /** Busca opencode.json (o .jsonc); si no existe ninguno, devuelve opencode.json como destino a crear. */
16
+ export declare function configFile(dir: string): string;
17
+ /**
18
+ * Añade el plugin a opencode.json de forma idempotente, con copia de seguridad.
19
+ * Por defecto fija la versión exacta; una entrada sin versión se reemplaza.
20
+ */
21
+ export declare function install(dir: string, pin?: boolean): InstallResult;
22
+ export declare function uninstall(dir: string): InstallResult;
23
+ /** Crea un .loopbreaker.json en el proyecto (no sobrescribe). */
24
+ export declare function init(projectDir: string, config?: LoopbreakerConfig): InstallResult;
25
+ /** Añade `.opencode/` al .gitignore del proyecto de forma idempotente. */
26
+ export declare function ensureGitignore(projectDir: string): InstallResult;
@@ -0,0 +1,171 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ export const PLUGIN_NAME = "@adayacas/loopbreaker";
6
+ /** Versión del paquete que está ejecutando el instalador, para pinear el plugin. */
7
+ function packageVersion() {
8
+ try {
9
+ const here = path.dirname(fileURLToPath(import.meta.url));
10
+ const pkg = JSON.parse(fs.readFileSync(path.join(here, "../../package.json"), "utf8"));
11
+ return typeof pkg.version === "string" && pkg.version ? pkg.version : "latest";
12
+ }
13
+ catch {
14
+ return "latest";
15
+ }
16
+ }
17
+ export const PLUGIN_VERSION = packageVersion();
18
+ export const PINNED_PLUGIN = `${PLUGIN_NAME}@${PLUGIN_VERSION}`;
19
+ export const GITIGNORE_ENTRY = ".opencode/";
20
+ export const DEFAULT_INIT = { mode: "block", maxConsecutiveRepeats: 3, stagnationRepeats: 3 };
21
+ /** Config global de OpenCode: $XDG_CONFIG_HOME/opencode o ~/.config/opencode. */
22
+ export function globalConfigDir(env = process.env) {
23
+ const base = env.XDG_CONFIG_HOME || path.join(env.HOME || env.USERPROFILE || os.homedir(), ".config");
24
+ return path.join(base, "opencode");
25
+ }
26
+ /** Busca opencode.json (o .jsonc); si no existe ninguno, devuelve opencode.json como destino a crear. */
27
+ export function configFile(dir) {
28
+ for (const n of ["opencode.json", "opencode.jsonc"]) {
29
+ const f = path.join(dir, n);
30
+ if (fs.existsSync(f))
31
+ return f;
32
+ }
33
+ return path.join(dir, "opencode.json");
34
+ }
35
+ /** Quita comentarios // y /* *\/ y comas finales sin tocar el contenido de las cadenas. */
36
+ function stripJsonc(text) {
37
+ let out = "";
38
+ let inStr = false;
39
+ for (let i = 0; i < text.length; i++) {
40
+ const c = text[i];
41
+ const n = text[i + 1];
42
+ if (inStr) {
43
+ out += c;
44
+ if (c === "\\")
45
+ out += text[++i] ?? "";
46
+ else if (c === '"')
47
+ inStr = false;
48
+ }
49
+ else if (c === '"') {
50
+ inStr = true;
51
+ out += c;
52
+ }
53
+ else if (c === "/" && n === "/") {
54
+ while (i < text.length && text[i] !== "\n")
55
+ i++;
56
+ out += "\n";
57
+ }
58
+ else if (c === "/" && n === "*") {
59
+ i += 2;
60
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/"))
61
+ i++;
62
+ i++;
63
+ }
64
+ else
65
+ out += c;
66
+ }
67
+ return out.replace(/,(\s*[}\]])/g, "$1");
68
+ }
69
+ function read(file) {
70
+ if (!fs.existsSync(file))
71
+ return { data: {}, hadComments: false };
72
+ const raw = fs.readFileSync(file, "utf8");
73
+ try {
74
+ return { data: raw.trim() ? JSON.parse(raw) : {}, hadComments: false };
75
+ }
76
+ catch {
77
+ try {
78
+ return { data: JSON.parse(stripJsonc(raw)), hadComments: true };
79
+ }
80
+ catch (e) {
81
+ return { error: e.message };
82
+ }
83
+ }
84
+ }
85
+ const isLoopbreaker = (p) => typeof p === "string" && (p === PLUGIN_NAME || p.startsWith(PLUGIN_NAME + "@"));
86
+ function manual(file, why, line) {
87
+ return { ok: false, changed: false, file, message: `${why}\nNo toqué tu archivo. Añade a mano en ${file}:\n ${line}` };
88
+ }
89
+ /**
90
+ * Añade el plugin a opencode.json de forma idempotente, con copia de seguridad.
91
+ * Por defecto fija la versión exacta; una entrada sin versión se reemplaza.
92
+ */
93
+ export function install(dir, pin = true) {
94
+ const spec = pin ? PINNED_PLUGIN : PLUGIN_NAME;
95
+ const file = configFile(dir);
96
+ const r = read(file);
97
+ if ("error" in r)
98
+ return manual(file, `No pude leer ${file} (${r.error}).`, `"plugin": ["${spec}"]`);
99
+ if (r.hadComments) {
100
+ // Reescribir perdería los comentarios del usuario: mejor no tocar nada.
101
+ return manual(file, `${path.basename(file)} tiene comentarios y reescribirlo los borraría.`, `"plugin": [..., "${spec}"]`);
102
+ }
103
+ const cur = r.data.plugin;
104
+ if (cur !== undefined && !Array.isArray(cur))
105
+ return manual(file, `"plugin" en ${file} no es una lista.`, `"plugin": ["${spec}"]`);
106
+ const list = Array.isArray(cur) ? [...cur] : [];
107
+ const idx = list.findIndex(isLoopbreaker);
108
+ if (idx !== -1 && list[idx] === spec)
109
+ return { ok: true, changed: false, file, message: `Ya estaba instalado en ${file}.` };
110
+ if (fs.existsSync(file))
111
+ fs.copyFileSync(file, file + ".loopbreaker.bak");
112
+ if (idx === -1)
113
+ list.push(spec);
114
+ else
115
+ list[idx] = spec;
116
+ const next = { ...(fs.existsSync(file) ? r.data : { $schema: "https://opencode.ai/config.json" }), plugin: list };
117
+ fs.mkdirSync(dir, { recursive: true });
118
+ fs.writeFileSync(file, JSON.stringify(next, null, 2) + "\n");
119
+ return {
120
+ ok: true,
121
+ changed: true,
122
+ file,
123
+ message: `Plugin ${idx === -1 ? "añadido" : `actualizado a ${spec}`} en ${file}${fs.existsSync(file + ".loopbreaker.bak") ? ` (copia: ${path.basename(file)}.loopbreaker.bak)` : ""}.`,
124
+ };
125
+ }
126
+ export function uninstall(dir) {
127
+ const file = configFile(dir);
128
+ if (!fs.existsSync(file))
129
+ return { ok: true, changed: false, file, message: "No hay configuración que modificar." };
130
+ const r = read(file);
131
+ if ("error" in r || r.hadComments)
132
+ return manual(file, `No puedo editar ${file} automáticamente.`, `quita "${PLUGIN_NAME}" de "plugin"`);
133
+ const cur = r.data.plugin;
134
+ if (!Array.isArray(cur) || !cur.some(isLoopbreaker))
135
+ return { ok: true, changed: false, file, message: "El plugin no estaba registrado." };
136
+ fs.copyFileSync(file, file + ".loopbreaker.bak");
137
+ const rest = cur.filter((p) => !isLoopbreaker(p));
138
+ const next = { ...r.data };
139
+ if (rest.length)
140
+ next.plugin = rest;
141
+ else
142
+ delete next.plugin;
143
+ fs.writeFileSync(file, JSON.stringify(next, null, 2) + "\n");
144
+ return { ok: true, changed: true, file, message: `Plugin quitado de ${file}.` };
145
+ }
146
+ /** Crea un .loopbreaker.json en el proyecto (no sobrescribe). */
147
+ export function init(projectDir, config = DEFAULT_INIT) {
148
+ const file = path.join(projectDir, ".loopbreaker.json");
149
+ if (fs.existsSync(file))
150
+ return { ok: true, changed: false, file, message: `${file} ya existe.` };
151
+ fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\n");
152
+ return { ok: true, changed: true, file, message: `Creado ${file}.` };
153
+ }
154
+ /** Añade `.opencode/` al .gitignore del proyecto de forma idempotente. */
155
+ export function ensureGitignore(projectDir) {
156
+ const file = path.join(projectDir, ".gitignore");
157
+ try {
158
+ const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
159
+ const has = current
160
+ .split(/\r?\n/)
161
+ .some((l) => l.trim() === GITIGNORE_ENTRY || l.trim() === GITIGNORE_ENTRY.replace(/\/$/, ""));
162
+ if (has)
163
+ return { ok: true, changed: false, file, message: `Ya estaba ${GITIGNORE_ENTRY} en ${file}.` };
164
+ const prefix = current && !current.endsWith("\n") ? current + "\n" : current;
165
+ fs.writeFileSync(file, prefix + GITIGNORE_ENTRY + "\n");
166
+ return { ok: true, changed: true, file, message: `Añadido ${GITIGNORE_ENTRY} a ${file}.` };
167
+ }
168
+ catch (e) {
169
+ return { ok: false, changed: false, file, message: `No pude actualizar ${file} (${e.message}). Añade ${GITIGNORE_ENTRY} a mano.` };
170
+ }
171
+ }
@@ -0,0 +1,24 @@
1
+ import type { ResolvedConfig, SessionState, Verdict } from "./types.js";
2
+ /** Herramientas que cambian el estado del proyecto: una escritura exitosa "da progreso". */
3
+ export declare const WRITE_TOOLS: Set<string>;
4
+ export declare const newSession: () => SessionState;
5
+ /** Firma estable: mismo tool + mismos argumentos (orden de claves y espacios normalizados). */
6
+ export declare function signature(tool: string, args: unknown, root?: string): string;
7
+ /** Salidas más cortas que esto ("", "ok", "done") son demasiado genéricas para indicar estancamiento. */
8
+ export declare const MIN_STAGNANT_LEN = 40;
9
+ /** Familia: la herramienta y, en bash, el programa principal (ignora `cd x &&` y VAR=valor). */
10
+ export declare function family(tool: string, args: Record<string, unknown>): string;
11
+ export declare const resultText: (out: unknown) => string;
12
+ export declare const hashResult: (out: unknown) => string;
13
+ /**
14
+ * Evalúa una llamada ANTES de ejecutarla (no la registra).
15
+ * - Repetición: la misma firma N veces seguidas, con resultados idénticos o desconocidos.
16
+ * Si el resultado cambia entre repeticiones, hay progreso y el contador se reinicia.
17
+ * - Ciclo: un patrón de periodo 2..K repetido N veces (A-B-A-B-A-B).
18
+ */
19
+ export declare function check(state: SessionState, cfg: ResolvedConfig, tool: string, sig: string, fam?: string): Verdict;
20
+ export declare function record(state: SessionState, cfg: ResolvedConfig, tool: string, sig: string, fam?: string): void;
21
+ /** Después de ejecutar: guarda el hash del resultado y sube la época si hubo escritura. */
22
+ export declare function recordResult(state: SessionState, tool: string, sig: string, text: string, failed?: boolean): void;
23
+ /** Mensaje de bloqueo accionable; escala a "parada dura" tras varios bloqueos. */
24
+ export declare function blockMessage(cfg: ResolvedConfig, state: SessionState, reason: string): string;
@@ -0,0 +1,136 @@
1
+ import { createHash } from "node:crypto";
2
+ /** Herramientas que cambian el estado del proyecto: una escritura exitosa "da progreso". */
3
+ export const WRITE_TOOLS = new Set(["edit", "write", "patch", "multiedit"]);
4
+ export const newSession = () => ({ epoch: 0, blocks: 0, entries: [] });
5
+ const sha = (s) => createHash("sha1").update(s).digest("hex").slice(0, 16);
6
+ function canonical(v) {
7
+ if (Array.isArray(v))
8
+ return v.map(canonical);
9
+ if (v && typeof v === "object") {
10
+ return Object.fromEntries(Object.entries(v)
11
+ .sort(([a], [b]) => (a < b ? -1 : 1))
12
+ .map(([k, val]) => [k, canonical(val)]));
13
+ }
14
+ if (typeof v === "string")
15
+ return v.replace(/\s+/g, " ").trim();
16
+ return v;
17
+ }
18
+ /** Firma estable: mismo tool + mismos argumentos (orden de claves y espacios normalizados). */
19
+ export function signature(tool, args, root) {
20
+ let a = canonical(args);
21
+ if (root) {
22
+ // rutas absolutas dentro del proyecto == relativas
23
+ a = JSON.parse(JSON.stringify(a).split(root.replace(/\/$/, "") + "/").join(""));
24
+ }
25
+ return `${tool}:${sha(JSON.stringify(a))}`;
26
+ }
27
+ /** Salidas más cortas que esto ("", "ok", "done") son demasiado genéricas para indicar estancamiento. */
28
+ export const MIN_STAGNANT_LEN = 40;
29
+ /** Familia: la herramienta y, en bash, el programa principal (ignora `cd x &&` y VAR=valor). */
30
+ export function family(tool, args) {
31
+ if (tool === "bash" && typeof args.command === "string") {
32
+ const cmd = args.command.trim().replace(/^(?:cd\s+\S+\s*(?:&&|;)\s*)+/, "").replace(/^(?:\w+=\S+\s+)+/, "");
33
+ return `bash:${cmd.split(/\s+/)[0] ?? ""}`;
34
+ }
35
+ return tool;
36
+ }
37
+ export const resultText = (out) => (typeof out === "string" ? out : JSON.stringify(out ?? ""));
38
+ export const hashResult = (out) => sha(resultText(out));
39
+ const thresholdFor = (cfg, tool) => cfg.toolThresholds[tool] ?? cfg.maxConsecutiveRepeats;
40
+ /** Entradas de la época actual (sin escrituras exitosas en medio). */
41
+ function currentRun(state) {
42
+ const out = [];
43
+ for (let i = state.entries.length - 1; i >= 0; i--) {
44
+ if (state.entries[i].epoch !== state.epoch)
45
+ break;
46
+ out.unshift(state.entries[i]);
47
+ }
48
+ return out;
49
+ }
50
+ /**
51
+ * Evalúa una llamada ANTES de ejecutarla (no la registra).
52
+ * - Repetición: la misma firma N veces seguidas, con resultados idénticos o desconocidos.
53
+ * Si el resultado cambia entre repeticiones, hay progreso y el contador se reinicia.
54
+ * - Ciclo: un patrón de periodo 2..K repetido N veces (A-B-A-B-A-B).
55
+ */
56
+ export function check(state, cfg, tool, sig, fam = tool) {
57
+ const n = thresholdFor(cfg, tool);
58
+ const run = currentRun(state);
59
+ // 1) repetición idéntica
60
+ let streak = 0;
61
+ for (let i = run.length - 1; i >= 0; i--) {
62
+ const e = run[i];
63
+ if (e.sig !== sig)
64
+ break;
65
+ const next = run[i + 1];
66
+ if (next && e.resultHash && next.resultHash && e.resultHash !== next.resultHash)
67
+ break;
68
+ streak++;
69
+ }
70
+ if (streak + 1 >= n) {
71
+ return {
72
+ blocked: true,
73
+ reason: `la llamada "${tool}" se repitió ${streak + 1} veces seguidas con los mismos argumentos y sin cambios en el proyecto ni en su salida`,
74
+ };
75
+ }
76
+ // 2) estancamiento: la misma familia devuelve la misma salida (aunque cambien los argumentos)
77
+ const last = run[run.length - 1];
78
+ if (last?.resultHash && last.family === fam && (last.resultLen ?? 0) >= MIN_STAGNANT_LEN) {
79
+ let same = 0;
80
+ for (let i = run.length - 1; i >= 0; i--) {
81
+ const e = run[i];
82
+ if (e.family !== fam || e.resultHash !== last.resultHash)
83
+ break;
84
+ same++;
85
+ }
86
+ if (same >= cfg.stagnationRepeats) {
87
+ return {
88
+ blocked: true,
89
+ reason: `las últimas ${same} llamadas de "${fam}" devolvieron EXACTAMENTE la misma salida («${(last.snippet ?? "").replace(/\s+/g, " ")}») aunque cambiaste los argumentos: el problema no está en el comando, algo se quedó pegado en la herramienta o el entorno`,
90
+ };
91
+ }
92
+ }
93
+ // 3) ciclos de periodo p >= 2
94
+ const seq = [...run.map((e) => e.sig), sig];
95
+ for (let p = 2; p <= cfg.cycleMaxPeriod; p++) {
96
+ const need = p * n;
97
+ if (seq.length < need)
98
+ continue;
99
+ const tail = seq.slice(-need);
100
+ const pattern = tail.slice(0, p);
101
+ if (new Set(pattern).size < 2)
102
+ continue; // un patrón uniforme ya lo cubre la regla 1
103
+ if (tail.every((s, i) => s === pattern[i % p])) {
104
+ return { blocked: true, reason: `se detectó un ciclo de ${p} llamadas repetido ${n} veces sin progreso` };
105
+ }
106
+ }
107
+ return { blocked: false };
108
+ }
109
+ export function record(state, cfg, tool, sig, fam = tool) {
110
+ state.entries.push({ sig, tool, family: fam, epoch: state.epoch });
111
+ if (state.entries.length > cfg.window)
112
+ state.entries.splice(0, state.entries.length - cfg.window);
113
+ }
114
+ /** Después de ejecutar: guarda el hash del resultado y sube la época si hubo escritura. */
115
+ export function recordResult(state, tool, sig, text, failed = false) {
116
+ for (let i = state.entries.length - 1; i >= 0; i--) {
117
+ const e = state.entries[i];
118
+ if (e.sig === sig && e.resultHash === undefined) {
119
+ e.resultHash = hashResult(text);
120
+ e.resultLen = text.length;
121
+ e.snippet = text.slice(0, 120);
122
+ break;
123
+ }
124
+ }
125
+ if (WRITE_TOOLS.has(tool) && !failed)
126
+ state.epoch++;
127
+ }
128
+ /** Mensaje de bloqueo accionable; escala a "parada dura" tras varios bloqueos. */
129
+ export function blockMessage(cfg, state, reason) {
130
+ const hard = (state.loopBlocks ?? 0) >= cfg.hardStopAfter;
131
+ const head = hard ? "🛑 [LOOPBREAKER PARADA DURA]" : "🛑 [LOOPBREAKER BLOQUEADO]";
132
+ const todo = hard
133
+ ? "Has insistido tras varios bloqueos. DETENTE ahora: explica al usuario qué intentas lograr, qué falla y pídele instrucciones. No sigas llamando herramientas."
134
+ : "No repitas esta acción ni variantes de ella. Lee el error o la salida anterior, cambia de enfoque (otro comando, otro archivo, otra hipótesis) o pide ayuda al usuario.";
135
+ return `${head} ${reason}. ${todo}`;
136
+ }