@adayacas/loopbreaker 0.3.0 → 0.4.1

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.
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { t } from "./messages.js";
5
6
  export const PLUGIN_NAME = "@adayacas/loopbreaker";
6
7
  /** Versión del paquete que está ejecutando el instalador, para pinear el plugin. */
7
8
  function packageVersion() {
@@ -66,7 +67,7 @@ function stripJsonc(text) {
66
67
  }
67
68
  return out.replace(/,(\s*[}\]])/g, "$1");
68
69
  }
69
- function read(file) {
70
+ export function readJsonFile(file) {
70
71
  if (!fs.existsSync(file))
71
72
  return { data: {}, hadComments: false };
72
73
  const raw = fs.readFileSync(file, "utf8");
@@ -83,8 +84,8 @@ function read(file) {
83
84
  }
84
85
  }
85
86
  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}` };
87
+ export function manual(file, why, line) {
88
+ return { ok: false, changed: false, file, message: t("inst.manual", { why, file, line }) };
88
89
  }
89
90
  /**
90
91
  * Añade el plugin a opencode.json de forma idempotente, con copia de seguridad.
@@ -93,20 +94,20 @@ function manual(file, why, line) {
93
94
  export function install(dir, pin = true) {
94
95
  const spec = pin ? PINNED_PLUGIN : PLUGIN_NAME;
95
96
  const file = configFile(dir);
96
- const r = read(file);
97
+ const r = readJsonFile(file);
97
98
  if ("error" in r)
98
- return manual(file, `No pude leer ${file} (${r.error}).`, `"plugin": ["${spec}"]`);
99
+ return manual(file, t("inst.cantRead", { file, err: r.error }), `"plugin": ["${spec}"]`);
99
100
  if (r.hadComments) {
100
101
  // 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
+ return manual(file, t("inst.hasComments", { name: path.basename(file) }), `"plugin": [..., "${spec}"]`);
102
103
  }
103
104
  const cur = r.data.plugin;
104
105
  if (cur !== undefined && !Array.isArray(cur))
105
- return manual(file, `"plugin" en ${file} no es una lista.`, `"plugin": ["${spec}"]`);
106
+ return manual(file, t("inst.notList", { file }), `"plugin": ["${spec}"]`);
106
107
  const list = Array.isArray(cur) ? [...cur] : [];
107
108
  const idx = list.findIndex(isLoopbreaker);
108
109
  if (idx !== -1 && list[idx] === spec)
109
- return { ok: true, changed: false, file, message: `Ya estaba instalado en ${file}.` };
110
+ return { ok: true, changed: false, file, message: t("inst.already", { file }) };
110
111
  if (fs.existsSync(file))
111
112
  fs.copyFileSync(file, file + ".loopbreaker.bak");
112
113
  if (idx === -1)
@@ -120,19 +121,23 @@ export function install(dir, pin = true) {
120
121
  ok: true,
121
122
  changed: true,
122
123
  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
+ message: t(idx === -1 ? "inst.added" : "inst.updated", {
125
+ spec,
126
+ file,
127
+ backup: fs.existsSync(file + ".loopbreaker.bak") ? t("inst.backup", { name: `${path.basename(file)}.loopbreaker.bak` }) : "",
128
+ }),
124
129
  };
125
130
  }
126
131
  export function uninstall(dir) {
127
132
  const file = configFile(dir);
128
133
  if (!fs.existsSync(file))
129
- return { ok: true, changed: false, file, message: "No hay configuración que modificar." };
130
- const r = read(file);
134
+ return { ok: true, changed: false, file, message: t("inst.noConfig") };
135
+ const r = readJsonFile(file);
131
136
  if ("error" in r || r.hadComments)
132
- return manual(file, `No puedo editar ${file} automáticamente.`, `quita "${PLUGIN_NAME}" de "plugin"`);
137
+ return manual(file, t("inst.cantEdit", { file }), t("inst.removeLine", { name: PLUGIN_NAME }));
133
138
  const cur = r.data.plugin;
134
139
  if (!Array.isArray(cur) || !cur.some(isLoopbreaker))
135
- return { ok: true, changed: false, file, message: "El plugin no estaba registrado." };
140
+ return { ok: true, changed: false, file, message: t("inst.notRegistered") };
136
141
  fs.copyFileSync(file, file + ".loopbreaker.bak");
137
142
  const rest = cur.filter((p) => !isLoopbreaker(p));
138
143
  const next = { ...r.data };
@@ -141,15 +146,20 @@ export function uninstall(dir) {
141
146
  else
142
147
  delete next.plugin;
143
148
  fs.writeFileSync(file, JSON.stringify(next, null, 2) + "\n");
144
- return { ok: true, changed: true, file, message: `Plugin quitado de ${file}.` };
149
+ return { ok: true, changed: true, file, message: t("inst.removed", { file }) };
150
+ }
151
+ /** ¿El opencode.json de este directorio registra loopbreaker? */
152
+ export function isInstalled(dir) {
153
+ const r = readJsonFile(configFile(dir));
154
+ return !("error" in r) && Array.isArray(r.data.plugin) && r.data.plugin.some(isLoopbreaker);
145
155
  }
146
156
  /** Crea un .loopbreaker.json en el proyecto (no sobrescribe). */
147
157
  export function init(projectDir, config = DEFAULT_INIT) {
148
158
  const file = path.join(projectDir, ".loopbreaker.json");
149
159
  if (fs.existsSync(file))
150
- return { ok: true, changed: false, file, message: `${file} ya existe.` };
160
+ return { ok: true, changed: false, file, message: t("inst.exists", { file }) };
151
161
  fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\n");
152
- return { ok: true, changed: true, file, message: `Creado ${file}.` };
162
+ return { ok: true, changed: true, file, message: t("inst.created", { file }) };
153
163
  }
154
164
  /** Añade `.opencode/` al .gitignore del proyecto de forma idempotente. */
155
165
  export function ensureGitignore(projectDir) {
@@ -160,12 +170,12 @@ export function ensureGitignore(projectDir) {
160
170
  .split(/\r?\n/)
161
171
  .some((l) => l.trim() === GITIGNORE_ENTRY || l.trim() === GITIGNORE_ENTRY.replace(/\/$/, ""));
162
172
  if (has)
163
- return { ok: true, changed: false, file, message: `Ya estaba ${GITIGNORE_ENTRY} en ${file}.` };
173
+ return { ok: true, changed: false, file, message: t("inst.giHas", { entry: GITIGNORE_ENTRY, file }) };
164
174
  const prefix = current && !current.endsWith("\n") ? current + "\n" : current;
165
175
  fs.writeFileSync(file, prefix + GITIGNORE_ENTRY + "\n");
166
- return { ok: true, changed: true, file, message: `Añadido ${GITIGNORE_ENTRY} a ${file}.` };
176
+ return { ok: true, changed: true, file, message: t("inst.giAdded", { entry: GITIGNORE_ENTRY, file }) };
167
177
  }
168
178
  catch (e) {
169
- return { ok: false, changed: false, file, message: `No pude actualizar ${file} (${e.message}). Añade ${GITIGNORE_ENTRY} a mano.` };
179
+ return { ok: false, changed: false, file, message: t("inst.giFail", { file, err: e.message, entry: GITIGNORE_ENTRY }) };
170
180
  }
171
181
  }
@@ -0,0 +1,4 @@
1
+ export { Guard } from "./guard.js";
2
+ export { loadConfig, phaseCard } from "./config-loader.js";
3
+ export { parseFrontmatter } from "./frontmatter.js";
4
+ export type { CallEntry, LoopbreakerConfig, Mode, PhaseSpec, ResolvedConfig, ScopeRules, SessionState, Verdict, } from "./types.js";
@@ -0,0 +1,7 @@
1
+ // API programática del paquete, separada de index.ts a propósito:
2
+ // OpenCode invoca como plugin CADA export de función/clase del módulo de entrada,
3
+ // así que index.ts no puede exponer nada más. Los consumidores de librería
4
+ // importan desde acá: `import { Guard, loadConfig } from "@adayacas/loopbreaker/lib"`.
5
+ export { Guard } from "./guard.js";
6
+ export { loadConfig, phaseCard } from "./config-loader.js";
7
+ export { parseFrontmatter } from "./frontmatter.js";
@@ -17,8 +17,8 @@ export declare const hashResult: (out: unknown) => string;
17
17
  * - Ciclo: un patrón de periodo 2..K repetido N veces (A-B-A-B-A-B).
18
18
  */
19
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;
20
+ export declare function record(state: SessionState, cfg: ResolvedConfig, tool: string, sig: string, fam?: string, callID?: string): void;
21
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;
22
+ export declare function recordResult(state: SessionState, tool: string, sig: string, text: string, failed?: boolean, callID?: string): void;
23
23
  /** Mensaje de bloqueo accionable; escala a "parada dura" tras varios bloqueos. */
24
24
  export declare function blockMessage(cfg: ResolvedConfig, state: SessionState, reason: string): string;
@@ -1,3 +1,4 @@
1
+ import { t } from "./messages.js";
1
2
  import { createHash } from "node:crypto";
2
3
  /** Herramientas que cambian el estado del proyecto: una escritura exitosa "da progreso". */
3
4
  export const WRITE_TOOLS = new Set(["edit", "write", "patch", "multiedit"]);
@@ -70,7 +71,7 @@ export function check(state, cfg, tool, sig, fam = tool) {
70
71
  if (streak + 1 >= n) {
71
72
  return {
72
73
  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
+ reason: t("loop.repeat", { tool, n: streak + 1 }, cfg.locale),
74
75
  };
75
76
  }
76
77
  // 2) estancamiento: la misma familia devuelve la misma salida (aunque cambien los argumentos)
@@ -86,7 +87,9 @@ export function check(state, cfg, tool, sig, fam = tool) {
86
87
  if (same >= cfg.stagnationRepeats) {
87
88
  return {
88
89
  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
+ reason: last.snippet
91
+ ? t("loop.stagnation", { n: same, family: fam, snippet: last.snippet.replace(/\s+/g, " ") }, cfg.locale)
92
+ : t("loop.stagnationNoQuote", { n: same, family: fam }, cfg.locale),
90
93
  };
91
94
  }
92
95
  }
@@ -101,21 +104,44 @@ export function check(state, cfg, tool, sig, fam = tool) {
101
104
  if (new Set(pattern).size < 2)
102
105
  continue; // un patrón uniforme ya lo cubre la regla 1
103
106
  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` };
107
+ // Salidas que cambian entre repeticiones del mismo elemento = progreso:
108
+ // el agente avanza aunque alterne, no es un bucle pegado.
109
+ let progress = false;
110
+ const firstHash = new Map();
111
+ for (const e of run.slice(-(need - 1))) {
112
+ if (!e.resultHash)
113
+ continue;
114
+ const first = firstHash.get(e.sig);
115
+ if (first === undefined)
116
+ firstHash.set(e.sig, e.resultHash);
117
+ else if (first !== e.resultHash) {
118
+ progress = true;
119
+ break;
120
+ }
121
+ }
122
+ if (!progress) {
123
+ return { blocked: true, reason: t("loop.cycle", { p, n }, cfg.locale) };
124
+ }
105
125
  }
106
126
  }
107
127
  return { blocked: false };
108
128
  }
109
- export function record(state, cfg, tool, sig, fam = tool) {
110
- state.entries.push({ sig, tool, family: fam, epoch: state.epoch });
129
+ export function record(state, cfg, tool, sig, fam = tool, callID) {
130
+ state.entries.push({ sig, tool, family: fam, epoch: state.epoch, ...(callID ? { callID } : {}) });
111
131
  if (state.entries.length > cfg.window)
112
132
  state.entries.splice(0, state.entries.length - cfg.window);
113
133
  }
114
134
  /** 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) {
135
+ export function recordResult(state, tool, sig, text, failed = false, callID) {
136
+ // Con id de llamada: si ese id ya tiene resultado, es una invocación duplicada (el mismo hook registrado dos veces).
137
+ if (callID) {
138
+ const dup = state.entries.find((e) => e.callID === callID);
139
+ if (dup?.resultHash !== undefined)
140
+ return;
141
+ }
116
142
  for (let i = state.entries.length - 1; i >= 0; i--) {
117
143
  const e = state.entries[i];
118
- if (e.sig === sig && e.resultHash === undefined) {
144
+ if (callID ? e.callID === callID : e.sig === sig && e.resultHash === undefined) {
119
145
  e.resultHash = hashResult(text);
120
146
  e.resultLen = text.length;
121
147
  e.snippet = text.slice(0, 120);
@@ -128,9 +154,8 @@ export function recordResult(state, tool, sig, text, failed = false) {
128
154
  /** Mensaje de bloqueo accionable; escala a "parada dura" tras varios bloqueos. */
129
155
  export function blockMessage(cfg, state, reason) {
130
156
  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.";
157
+ const L = cfg.locale;
158
+ const head = t(hard ? "loop.headHard" : "loop.headBlocked", {}, L);
159
+ const todo = t(hard ? "loop.todoHard" : "loop.todoBlocked", {}, L);
135
160
  return `${head} ${reason}. ${todo}`;
136
161
  }