@adayacas/loopbreaker 0.2.0 → 0.4.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,255 @@
1
+ const C = {
2
+ // ---- loop detector (lo lee el modelo) ----
3
+ "loop.repeat": {
4
+ en: 'the "{tool}" call was repeated {n} times in a row with the same arguments and no changes to the project or its output',
5
+ es: 'la llamada "{tool}" se repitió {n} veces seguidas con los mismos argumentos y sin cambios en el proyecto ni en su salida',
6
+ },
7
+ "loop.stagnation": {
8
+ en: 'the last {n} "{family}" calls returned EXACTLY the same output («{snippet}») even though the arguments changed: the problem is not the command, something is stuck in the tool or the environment',
9
+ es: 'las últimas {n} llamadas de "{family}" devolvieron EXACTAMENTE la misma salida («{snippet}») aunque cambiaste los argumentos: el problema no está en el comando, algo se quedó pegado en la herramienta o el entorno',
10
+ },
11
+ "loop.stagnationNoQuote": {
12
+ en: 'the last {n} "{family}" calls returned EXACTLY the same output even though the arguments changed: the problem is not the command, something is stuck in the tool or the environment',
13
+ es: 'las últimas {n} llamadas de "{family}" devolvieron EXACTAMENTE la misma salida aunque cambiaste los argumentos: el problema no está en el comando, algo se quedó pegado en la herramienta o el entorno',
14
+ },
15
+ "loop.cycle": {
16
+ en: "a cycle of {p} calls repeated {n} times with no progress was detected",
17
+ es: "se detectó un ciclo de {p} llamadas repetido {n} veces sin progreso",
18
+ },
19
+ "loop.headBlocked": { en: "🛑 [LOOPBREAKER BLOCKED]", es: "🛑 [LOOPBREAKER BLOQUEADO]" },
20
+ "loop.headHard": { en: "🛑 [LOOPBREAKER HARD STOP]", es: "🛑 [LOOPBREAKER PARADA DURA]" },
21
+ "loop.todoBlocked": {
22
+ en: "Do not repeat this action or variants of it. Read the previous error or output, change approach (another command, another file, another hypothesis) or ask the user for help.",
23
+ es: "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.",
24
+ },
25
+ "loop.todoHard": {
26
+ en: "You kept going after several blocks. STOP now: explain to the user what you are trying to do, what is failing and ask for instructions. Do not call any more tools.",
27
+ es: "Has insistido tras varios bloqueos. DETENTE ahora: explica al usuario qué intentas lograr, qué falla y pídele instrucciones. No sigas llamando herramientas.",
28
+ },
29
+ // ---- scope ----
30
+ "scope.outside": { en: '"{path}" is outside the project', es: '"{path}" está fuera del proyecto' },
31
+ "scope.protected": { en: '"{path}" is a protected loopbreaker file', es: '"{path}" es un archivo protegido del guardián' },
32
+ "scope.denied": { en: '"{path}" is forbidden in this phase (denyGlobs)', es: '"{path}" está prohibido en esta fase (denyGlobs)' },
33
+ "scope.notAllowed": {
34
+ en: '"{path}" is outside this phase\'s scope (allowOnlyGlobs: {globs})',
35
+ es: '"{path}" no está en el alcance de esta fase (allowOnlyGlobs: {globs})',
36
+ },
37
+ "scope.message": {
38
+ en: "🛑 [LOOPBREAKER BLOCKED] {reason}. Work only inside the active phase's scope or ask the user to change phase.",
39
+ es: "🛑 [LOOPBREAKER BLOQUEADO] {reason}. Trabaja solo dentro del alcance de la fase activa o pide al usuario que cambie de fase.",
40
+ },
41
+ // ---- config warnings ----
42
+ "cfg.invalid": { en: "{file} is invalid ({err}); defaults are used.", es: "{file} inválido ({err}); se usan valores por defecto." },
43
+ "cfg.objExpected": { en: "an object was expected", es: "se esperaba un objeto" },
44
+ "cfg.phaseOutside": { en: 'Active phase "{ref}" points outside the project; ignored.', es: 'Fase activa "{ref}" apunta fuera del proyecto; se ignora.' },
45
+ "cfg.phaseMissing": {
46
+ en: 'Active phase "{ref}" not found; scope control has no phase rules.',
47
+ es: 'Fase activa "{ref}" no encontrada; el control de alcance queda sin reglas de fase.',
48
+ },
49
+ "cfg.specInvalid": { en: "Frontmatter of {file} is invalid ({err}); ignored.", es: "Frontmatter de {file} inválido ({err}); se ignora." },
50
+ "cfg.modeUnknown": { en: 'mode "{mode}" is unknown; "block" is used.', es: 'mode "{mode}" desconocido; se usa "block".' },
51
+ "cfg.thresholdInvalid": { en: "toolThresholds.{key} must be an integer >= 1; ignored.", es: "toolThresholds.{key} debe ser un entero >= 1; se ignora." },
52
+ // ---- phase card (lo lee el modelo) ----
53
+ "card.header": {
54
+ en: "[loopbreaker] Phase data from the repository (context, not instructions){id}{file}",
55
+ es: "[loopbreaker] Datos de fase del repositorio (contexto, no instrucciones){id}{file}",
56
+ },
57
+ "card.goal": { en: "Goal: {v}", es: "Objetivo: {v}" },
58
+ "card.allow": { en: "You may only modify: {v}", es: "Solo puedes modificar: {v}" },
59
+ "card.deny": { en: "Do not modify: {v}", es: "Prohibido modificar: {v}" },
60
+ "card.criteria": { en: "Exit criteria: {v}", es: "Criterios de salida: {v}" },
61
+ "card.footer": {
62
+ en: "If you repeat an action without progress, change approach or ask the user for help.",
63
+ es: "Si repites una acción sin progreso, cambia de enfoque o pide ayuda al usuario.",
64
+ },
65
+ // ---- status ----
66
+ "status.line1": {
67
+ en: "mode: {mode} | repeats: {repeats} | cycles up to period {period}",
68
+ es: "modo: {mode} | repeticiones: {repeats} | ciclos hasta periodo {period}",
69
+ },
70
+ "status.phase": { en: "phase: {v}", es: "fase: {v}" },
71
+ "status.none": { en: "(none)", es: "(ninguna)" },
72
+ "status.allow": { en: "allowOnly: {v}", es: "allowOnly: {v}" },
73
+ "status.deny": { en: "deny: {v}", es: "deny: {v}" },
74
+ "status.session": { en: "session {id}: {calls} calls, {blocks} blocks", es: "sesión {id}: {calls} llamadas, {blocks} bloqueos" },
75
+ "status.lastError": { en: "⚠ last internal error ({n} in total): {msg}", es: "⚠ último error interno ({n} en total): {msg}" },
76
+ // ---- internal errors ----
77
+ "err.harden": { en: "hardening permissions", es: "endurecer permisos" },
78
+ "err.read": { en: "reading state", es: "leer estado" },
79
+ "err.save": { en: "saving state", es: "guardar estado" },
80
+ "err.lock": { en: "locking state", es: "bloquear estado" },
81
+ "err.writeLog": { en: "writing log", es: "escribir log" },
82
+ "err.json": { en: "invalid JSON", es: "JSON inválido" },
83
+ // ---- installer (OpenCode) ----
84
+ "inst.manual": {
85
+ en: "{why}\nI did not touch your file. Add by hand in {file}:\n {line}",
86
+ es: "{why}\nNo toqué tu archivo. Añade a mano en {file}:\n {line}",
87
+ },
88
+ "inst.cantRead": { en: "I could not read {file} ({err}).", es: "No pude leer {file} ({err})." },
89
+ "inst.hasComments": { en: "{name} has comments and rewriting it would delete them.", es: "{name} tiene comentarios y reescribirlo los borraría." },
90
+ "inst.notList": { en: '"plugin" in {file} is not a list.', es: '"plugin" en {file} no es una lista.' },
91
+ "inst.already": { en: "Already installed in {file}.", es: "Ya estaba instalado en {file}." },
92
+ "inst.added": { en: "Plugin added to {file}{backup}.", es: "Plugin añadido en {file}{backup}." },
93
+ "inst.updated": { en: "Plugin updated to {spec} in {file}{backup}.", es: "Plugin actualizado a {spec} en {file}{backup}." },
94
+ "inst.backup": { en: " (backup: {name})", es: " (copia: {name})" },
95
+ "inst.noConfig": { en: "There is no configuration to change.", es: "No hay configuración que modificar." },
96
+ "inst.cantEdit": { en: "I cannot edit {file} automatically.", es: "No puedo editar {file} automáticamente." },
97
+ "inst.removeLine": { en: 'remove "{name}" from "plugin"', es: 'quita "{name}" de "plugin"' },
98
+ "inst.notRegistered": { en: "The plugin was not registered.", es: "El plugin no estaba registrado." },
99
+ "inst.removed": { en: "Plugin removed from {file}.", es: "Plugin quitado de {file}." },
100
+ "inst.exists": { en: "{file} already exists.", es: "{file} ya existe." },
101
+ "inst.created": { en: "Created {file}.", es: "Creado {file}." },
102
+ "inst.giHas": { en: "{entry} was already in {file}.", es: "Ya estaba {entry} en {file}." },
103
+ "inst.giAdded": { en: "Added {entry} to {file}.", es: "Añadido {entry} a {file}." },
104
+ "inst.giFail": { en: "I could not update {file} ({err}). Add {entry} by hand.", es: "No pude actualizar {file} ({err}). Añade {entry} a mano." },
105
+ // ---- hook targets ----
106
+ "tgt.added": { en: "{label}: hooks added to {file}{backup}.", es: "{label}: hooks añadidos en {file}{backup}." },
107
+ "tgt.unchanged": { en: "{label}: hooks already up to date in {file}.", es: "{label}: los hooks ya estaban al día en {file}." },
108
+ "tgt.removed": { en: "{label}: hooks removed from {file}.", es: "{label}: hooks quitados de {file}." },
109
+ "tgt.notFound": { en: "{label}: no loopbreaker hooks found in {file}.", es: "{label}: no hay hooks de loopbreaker en {file}." },
110
+ "tgt.needPath": {
111
+ en: "The `loopbreaker` command must be on your PATH because the hooks call it on every tool use. Install it first: npm install -g @adayacas/loopbreaker",
112
+ es: "El comando `loopbreaker` debe estar en tu PATH porque los hooks lo llaman en cada uso de herramienta. Instálalo primero: npm install -g @adayacas/loopbreaker",
113
+ },
114
+ "tgt.grokCovered": {
115
+ en: "Grok Build: it already reads the Claude Code hooks in {file}; installing its own would run them twice. Skipped (use --force to install anyway).",
116
+ es: "Grok Build: ya lee los hooks de Claude Code en {file}; instalar los suyos los ejecutaría dos veces. Omitido (usa --force para instalarlos igualmente).",
117
+ },
118
+ "tgt.codexReview": {
119
+ en: "Codex: review and trust the new hook with /hooks before it runs. If you also declare hooks inline in config.toml, Codex loads both and warns; keep only one format per layer.",
120
+ es: "Codex: revisa y confía el hook nuevo con /hooks antes de que se ejecute. Si además declaras hooks inline en config.toml, Codex carga ambos y avisa; usa un solo formato por capa.",
121
+ },
122
+ "tgt.grokTrust": {
123
+ en: "Grok Build: project hooks need trust: run /hooks-trust (or start with --trust).",
124
+ es: "Grok Build: los hooks de proyecto requieren confianza: ejecuta /hooks-trust (o inicia con --trust).",
125
+ },
126
+ "tgt.restart": { en: "Restart the tool to load the hooks.", es: "Reinicia la herramienta para cargar los hooks." },
127
+ "tgt.notObject": { en: '"hooks" in {file} is not an object.', es: '"hooks" en {file} no es un objeto.' },
128
+ "tgt.unknown": { en: 'Unknown target "{name}". Valid: {valid}.', es: 'Destino desconocido "{name}". Válidos: {valid}.' },
129
+ "tgt.none": { en: "No supported tools were detected. Use --target to choose.", es: "No se detectó ninguna herramienta compatible. Usa --target para elegir." },
130
+ "tgt.opencodeNote": { en: "OpenCode: {msg}", es: "OpenCode: {msg}" },
131
+ // ---- doctor ----
132
+ "doc.node": { en: "Node.js {v}", es: "Node.js {v}" },
133
+ "doc.nodeOld": { en: "Node.js {v} is too old (>= 18 required)", es: "Node.js {v} es demasiado antiguo (se requiere >= 18)" },
134
+ "doc.pathOk": { en: "`loopbreaker` is on PATH", es: "`loopbreaker` está en el PATH" },
135
+ "doc.pathMissing": {
136
+ en: "`loopbreaker` is not on PATH: hook-based tools (Claude Code, Codex, Grok) cannot call it. Run: npm install -g @adayacas/loopbreaker",
137
+ es: "`loopbreaker` no está en el PATH: las herramientas con hooks (Claude Code, Codex, Grok) no pueden llamarlo. Ejecuta: npm install -g @adayacas/loopbreaker",
138
+ },
139
+ "doc.installed": { en: "{label}: installed ({where})", es: "{label}: instalado ({where})" },
140
+ "doc.notInstalled": { en: "{label}: not installed", es: "{label}: no instalado" },
141
+ "doc.dupGrok": {
142
+ en: "Grok Build reads the Claude Code hooks AND has its own loopbreaker hooks: every call would be counted twice. Remove one: loopbreaker uninstall --target grok",
143
+ es: "Grok Build lee los hooks de Claude Code Y tiene sus propios hooks de loopbreaker: cada llamada se contaría dos veces. Quita uno: loopbreaker uninstall --target grok",
144
+ },
145
+ "doc.dupOpencode": {
146
+ en: "OpenCode: the plugin is registered both globally and in this project; it would load twice. Remove one.",
147
+ es: "OpenCode: el plugin está registrado en global y en este proyecto; se cargaría dos veces. Quita uno.",
148
+ },
149
+ "doc.codexBoth": {
150
+ en: "Codex: hooks are declared in hooks.json AND inline in config.toml; Codex loads both and warns.",
151
+ es: "Codex: hay hooks en hooks.json Y en config.toml; Codex carga ambos y avisa.",
152
+ },
153
+ "doc.configOk": { en: "Configuration is valid", es: "La configuración es válida" },
154
+ "doc.gitignoreMissing": {
155
+ en: ".opencode/ is not in .gitignore: the state and log files could be committed",
156
+ es: ".opencode/ no está en .gitignore: el estado y el log podrían subirse a git",
157
+ },
158
+ "doc.gitignoreOk": { en: ".opencode/ is ignored by git", es: ".opencode/ está ignorado por git" },
159
+ "doc.internalErrors": {
160
+ en: "{n} internal error(s) in the log; the last one: {msg}",
161
+ es: "{n} error(es) interno(s) en el log; el último: {msg}",
162
+ },
163
+ "doc.noInternalErrors": { en: "No internal errors in the log", es: "Sin errores internos en el log" },
164
+ "doc.summary": { en: "{n} problem(s) found", es: "{n} problema(s) encontrado(s)" },
165
+ "doc.allGood": { en: "Everything looks fine", es: "Todo en orden" },
166
+ // ---- CLI ----
167
+ "cli.usage": {
168
+ en: `usage: loopbreaker <command>
169
+ install [--target opencode|claude|codex|grok|auto|all] [--project] [--yes] [--no-pin] [--no-gitignore] [--force]
170
+ set up loopbreaker (interactive wizard; --yes = defaults)
171
+ uninstall [--target ...] [--project]
172
+ remove it
173
+ doctor check the installation and the configuration
174
+ init create .loopbreaker.json in this project
175
+ status show phase, scope and blocks
176
+ set-phase <id|path> change the active phase
177
+ reset [sessionID] clear the block history
178
+ hook <claude|codex|grok> <before|after> [--failed]
179
+ (internal) entry point the tool hooks call
180
+
181
+ Language: LOOPBREAKER_LOCALE=es or --lang es (default: en)`,
182
+ es: `uso: loopbreaker <comando>
183
+ install [--target opencode|claude|codex|grok|auto|all] [--project] [--yes] [--no-pin] [--no-gitignore] [--force]
184
+ instala loopbreaker (wizard interactivo; --yes = valores por defecto)
185
+ uninstall [--target ...] [--project]
186
+ lo quita
187
+ doctor revisa la instalación y la configuración
188
+ init crea .loopbreaker.json en este proyecto
189
+ status muestra la fase, el alcance y los bloqueos
190
+ set-phase <id|ruta> cambia la fase activa
191
+ reset [sessionID] limpia el historial de bloqueos
192
+ hook <claude|codex|grok> <before|after> [--failed]
193
+ (interno) punto de entrada que llaman los hooks
194
+
195
+ Idioma: LOOPBREAKER_LOCALE=es o --lang es (por defecto: en)`,
196
+ },
197
+ "cli.cancelled": { en: "Installation cancelled.", es: "Instalación cancelada." },
198
+ "cli.setPhaseUsage": {
199
+ en: "usage: loopbreaker set-phase <id|path> (e.g. loopbreaker set-phase 2)",
200
+ es: "uso: loopbreaker set-phase <id|ruta> (p. ej. loopbreaker set-phase 2)",
201
+ },
202
+ "cli.resetAll": { en: "history cleared", es: "historial limpiado" },
203
+ "cli.resetOne": { en: "history of {id} cleared", es: "historial de {id} limpiado" },
204
+ "cli.restartOpencode": { en: "Restart OpenCode to load it.", es: "Reinicia OpenCode para cargarlo." },
205
+ "cli.projectRemains": {
206
+ en: 'Note: {targets} also remains installed for this project; run "loopbreaker uninstall --project" to remove it.',
207
+ es: 'Ojo: {targets} también sigue instalado en este proyecto; usa "loopbreaker uninstall --project" para quitarlo.',
208
+ },
209
+ "cli.userRemains": {
210
+ en: 'Note: {targets} also remains installed globally; run "loopbreaker uninstall" to remove it.',
211
+ es: 'Ojo: {targets} también sigue instalado globalmente; usa "loopbreaker uninstall" para quitarlo.',
212
+ },
213
+ // ---- wizard ----
214
+ "wiz.targets": { en: "Tools to protect (opencode, claude, codex, grok)", es: "Herramientas a proteger (opencode, claude, codex, grok)" },
215
+ "wiz.scope": { en: "Install globally or only in this project? (global/project)", es: "¿Instalar global o solo en este proyecto? (global/proyecto)" },
216
+ "wiz.pin": { en: "Pin the exact plugin version?", es: "¿Fijar la versión exacta del plugin?" },
217
+ "wiz.createCfg": { en: "Create .loopbreaker.json with anti-loop settings?", es: "¿Crear .loopbreaker.json con ajustes del anti-bucles?" },
218
+ "wiz.mode": { en: "Mode (block/warn)", es: "Modo (block/warn)" },
219
+ "wiz.repeats": { en: "Identical repeats before blocking", es: "Repeticiones idénticas antes de bloquear" },
220
+ "wiz.stagnation": { en: "Identical outputs to count as stagnation", es: "Salidas idénticas para estancamiento" },
221
+ "wiz.hardStop": { en: "Blocks before a hard stop", es: "Bloqueos antes de parada dura" },
222
+ "wiz.askScope": { en: "Configure scope by globs? (a reminder, not a sandbox)", es: "¿Configurar alcance por globs? (disuasorio, no sandbox)" },
223
+ "wiz.allow": { en: "allowOnlyGlobs, comma separated (empty = no limit)", es: "allowOnlyGlobs separados por coma (vacío = sin límite)" },
224
+ "wiz.deny": { en: "denyGlobs, comma separated (empty = none)", es: "denyGlobs separados por coma (vacío = ninguno)" },
225
+ "wiz.gitignore": { en: "Add .opencode/ to this project's .gitignore?", es: "¿Añadir .opencode/ al .gitignore de este proyecto?" },
226
+ "wiz.summary": {
227
+ en: "\nSummary: {tools} | {scope} | version {pin} | .loopbreaker.json {cfg} | .gitignore {gi}",
228
+ es: "\nResumen: {tools} | {scope} | versión {pin} | .loopbreaker.json {cfg} | .gitignore {gi}",
229
+ },
230
+ "wiz.apply": { en: "Apply these changes?", es: "¿Aplicar estos cambios?" },
231
+ "wiz.yesNo": { en: "Y/n", es: "S/n" },
232
+ "wiz.noYes": { en: "y/N", es: "s/N" },
233
+ "wiz.project": { en: "project ({root})", es: "proyecto ({root})" },
234
+ "wiz.global": { en: "global", es: "global" },
235
+ "wiz.fixed": { en: "fixed", es: "fija" },
236
+ "wiz.latest": { en: "latest", es: "latest" },
237
+ "wiz.yes": { en: "yes", es: "sí" },
238
+ "wiz.no": { en: "no", es: "no" },
239
+ };
240
+ let override;
241
+ /** Fuerza el idioma (la CLI lo usa con --lang). */
242
+ export function setLocale(l) {
243
+ override = l;
244
+ }
245
+ export function asLocale(v) {
246
+ return v === "en" || v === "es" ? v : undefined;
247
+ }
248
+ /** config > override de la CLI > LOOPBREAKER_LOCALE > "en". */
249
+ export function resolveLocale(fromConfig, env = process.env) {
250
+ return asLocale(fromConfig) ?? override ?? asLocale(env.LOOPBREAKER_LOCALE) ?? "en";
251
+ }
252
+ export function t(key, params = {}, locale = resolveLocale()) {
253
+ const entry = C[key];
254
+ return entry[locale].replace(/\{(\w+)\}/g, (m, k) => (k in params ? String(params[k]) : m));
255
+ }
@@ -1,6 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { matchAny } from "./glob.js";
4
+ import { t } from "./messages.js";
4
5
  /** realpath del ancestro existente más profundo (resuelve symlinks aunque el archivo aún no exista). */
5
6
  function realish(abs) {
6
7
  let cur = abs;
@@ -30,15 +31,16 @@ export function toRel(root, p) {
30
31
  /** Valida UNA ruta que se va a escribir. */
31
32
  export function checkPath(cfg, p) {
32
33
  const rel = toRel(cfg.root, p);
34
+ const L = cfg.locale;
33
35
  if (rel === null)
34
- return { blocked: true, reason: `"${p}" está fuera del proyecto` };
36
+ return { blocked: true, reason: t("scope.outside", { path: p }, L) };
35
37
  if (matchAny(rel, cfg.protectedGlobs))
36
- return { blocked: true, reason: `"${rel}" es un archivo protegido del guardián` };
38
+ return { blocked: true, reason: t("scope.protected", { path: rel }, L) };
37
39
  if (matchAny(rel, cfg.scope.denyGlobs))
38
- return { blocked: true, reason: `"${rel}" está prohibido en esta fase (denyGlobs)` };
40
+ return { blocked: true, reason: t("scope.denied", { path: rel }, L) };
39
41
  const allow = cfg.scope.allowOnlyGlobs;
40
42
  if (allow.length && !matchAny(rel, allow)) {
41
- return { blocked: true, reason: `"${rel}" no está en el alcance de esta fase (allowOnlyGlobs: ${allow.join(", ")})` };
43
+ return { blocked: true, reason: t("scope.notAllowed", { path: rel, globs: allow.join(", ") }, L) };
42
44
  }
43
45
  return { blocked: false };
44
46
  }
@@ -0,0 +1,38 @@
1
+ import type { InstallResult } from "./installer.js";
2
+ import type { HookTarget } from "./adapters.js";
3
+ export type Target = "opencode" | HookTarget;
4
+ export type Scope = "user" | "project";
5
+ export declare const TARGETS: readonly Target[];
6
+ export declare const LABEL: Record<Target, string>;
7
+ export interface TargetEnv {
8
+ home: string;
9
+ cwd: string;
10
+ env: NodeJS.ProcessEnv;
11
+ }
12
+ export declare function defaultEnv(): TargetEnv;
13
+ /** Archivo donde cada herramienta lee sus hooks (documentado por cada una). */
14
+ export declare function hookFile(target: HookTarget, scope: Scope, e: TargetEnv): string;
15
+ /** ¿Está el ejecutable en el PATH? (los hooks llaman a `loopbreaker` en cada uso de herramienta). */
16
+ export declare function onPath(bin: string, env?: NodeJS.ProcessEnv): boolean;
17
+ export declare function detectTargets(e: TargetEnv): Target[];
18
+ /** "claude,codex" | "auto" | "all" -> lista de destinos. */
19
+ export declare function parseTargets(spec: string, e: TargetEnv): {
20
+ targets: Target[];
21
+ } | {
22
+ error: string;
23
+ };
24
+ export declare const isOurCommand: (c: unknown) => boolean;
25
+ /** ¿Hay hooks de loopbreaker en este archivo? */
26
+ export declare function hasHooks(file: string): boolean;
27
+ export declare function installHooks(target: HookTarget, scope: Scope, e: TargetEnv, opts?: {
28
+ force?: boolean;
29
+ checkPath?: boolean;
30
+ }): InstallResult;
31
+ export declare function uninstallHooks(target: HookTarget, scope: Scope, e: TargetEnv): InstallResult;
32
+ export declare function installTarget(target: Target, scope: Scope, e: TargetEnv, opts?: {
33
+ pin?: boolean;
34
+ force?: boolean;
35
+ }): InstallResult;
36
+ export declare function uninstallTarget(target: Target, scope: Scope, e: TargetEnv): InstallResult;
37
+ /** ¿El destino sigue instalado en este scope? Sirve para avisar cuando queda activo en el otro. */
38
+ export declare function isTargetInstalled(target: Target, scope: Scope, e: TargetEnv): boolean;
@@ -0,0 +1,208 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { globalConfigDir, install, isInstalled, manual, readJsonFile, uninstall } from "./installer.js";
5
+ import { t } from "./messages.js";
6
+ export const TARGETS = ["opencode", "claude", "codex", "grok"];
7
+ export const LABEL = { opencode: "OpenCode", claude: "Claude Code", codex: "Codex CLI", grok: "Grok Build" };
8
+ const BINARY = { opencode: "opencode", claude: "claude", codex: "codex", grok: "grok" };
9
+ export function defaultEnv() {
10
+ return { home: process.env.HOME || process.env.USERPROFILE || os.homedir(), cwd: process.cwd(), env: process.env };
11
+ }
12
+ // ---------------------------------------------------------------- rutas
13
+ const codexHome = (e) => e.env.CODEX_HOME || path.join(e.home, ".codex");
14
+ /** Archivo donde cada herramienta lee sus hooks (documentado por cada una). */
15
+ export function hookFile(target, scope, e) {
16
+ const user = scope === "user";
17
+ switch (target) {
18
+ case "claude":
19
+ return user ? path.join(e.home, ".claude", "settings.json") : path.join(e.cwd, ".claude", "settings.json");
20
+ case "codex":
21
+ return user ? path.join(codexHome(e), "hooks.json") : path.join(e.cwd, ".codex", "hooks.json");
22
+ case "grok":
23
+ return user ? path.join(e.home, ".grok", "hooks", "loopbreaker.json") : path.join(e.cwd, ".grok", "hooks", "loopbreaker.json");
24
+ }
25
+ }
26
+ // ---------------------------------------------------------------- PATH
27
+ /** ¿Está el ejecutable en el PATH? (los hooks llaman a `loopbreaker` en cada uso de herramienta). */
28
+ export function onPath(bin, env = process.env) {
29
+ const exts = process.platform === "win32" ? ["", ".cmd", ".exe", ".bat", ".ps1"] : [""];
30
+ for (const dir of (env.PATH || env.Path || "").split(path.delimiter).filter(Boolean)) {
31
+ for (const x of exts) {
32
+ try {
33
+ if (fs.statSync(path.join(dir, bin + x)).isFile())
34
+ return true;
35
+ }
36
+ catch {
37
+ /* siguiente */
38
+ }
39
+ }
40
+ }
41
+ return false;
42
+ }
43
+ export function detectTargets(e) {
44
+ const dirs = {
45
+ opencode: globalConfigDir(e.env),
46
+ claude: path.join(e.home, ".claude"),
47
+ codex: codexHome(e),
48
+ grok: path.join(e.home, ".grok"),
49
+ };
50
+ return TARGETS.filter((tg) => fs.existsSync(dirs[tg]) || onPath(BINARY[tg], e.env));
51
+ }
52
+ /** "claude,codex" | "auto" | "all" -> lista de destinos. */
53
+ export function parseTargets(spec, e) {
54
+ const out = [];
55
+ for (const raw of spec.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)) {
56
+ if (raw === "all")
57
+ out.push(...TARGETS);
58
+ else if (raw === "auto")
59
+ out.push(...detectTargets(e));
60
+ else if (TARGETS.includes(raw))
61
+ out.push(raw);
62
+ else
63
+ return { error: t("tgt.unknown", { name: raw, valid: `${TARGETS.join(", ")}, auto, all` }) };
64
+ }
65
+ const targets = [...new Set(out)];
66
+ return targets.length ? { targets } : { error: t("tgt.none") };
67
+ }
68
+ const command = (target, phase, failed = false) => `loopbreaker hook ${target} ${phase}${failed ? " --failed" : ""}`;
69
+ export const isOurCommand = (c) => typeof c === "string" && /^loopbreaker hook (claude|codex|grok) /.test(c);
70
+ const groupIsOurs = (g) => !!g && typeof g === "object" && Array.isArray(g.hooks) && g.hooks.some((h) => isOurCommand(h?.command));
71
+ /** Grupos de hooks por evento. Codex y Grok solo documentan PreToolUse/PostToolUse; PostToolUseFailure solo en Claude Code. */
72
+ function groupsFor(target) {
73
+ const mk = (phase, failed = false) => {
74
+ const group = { hooks: [{ type: "command", command: command(target, phase, failed), timeout: 10 }] };
75
+ if (target === "claude")
76
+ group.matcher = "*";
77
+ if (target === "codex")
78
+ group.matcher = ".*";
79
+ return group; // Grok: sin matcher = todas las herramientas
80
+ };
81
+ const base = [
82
+ ["PreToolUse", mk("before")],
83
+ ["PostToolUse", mk("after")],
84
+ ];
85
+ if (target === "claude")
86
+ base.push(["PostToolUseFailure", mk("after", true)]);
87
+ return base;
88
+ }
89
+ /** ¿Hay hooks de loopbreaker en este archivo? */
90
+ export function hasHooks(file) {
91
+ const r = readJsonFile(file);
92
+ if ("error" in r)
93
+ return false;
94
+ const hooks = r.data.hooks;
95
+ if (!hooks || typeof hooks !== "object")
96
+ return false;
97
+ return Object.values(hooks).some((arr) => Array.isArray(arr) && arr.some(groupIsOurs));
98
+ }
99
+ function writeJson(file, data, backup) {
100
+ let note = "";
101
+ if (backup && fs.existsSync(file)) {
102
+ fs.copyFileSync(file, file + ".loopbreaker.bak");
103
+ note = t("inst.backup", { name: `${path.basename(file)}.loopbreaker.bak` });
104
+ }
105
+ fs.mkdirSync(path.dirname(file), { recursive: true });
106
+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
107
+ return note;
108
+ }
109
+ export function installHooks(target, scope, e, opts = {}) {
110
+ const label = LABEL[target];
111
+ const file = hookFile(target, scope, e);
112
+ if (opts.checkPath !== false && !onPath("loopbreaker", e.env)) {
113
+ return { ok: false, changed: false, file, message: `${label}: ${t("tgt.needPath")}` };
114
+ }
115
+ // Grok Build ya lee los hooks de Claude Code: tener ambos ejecutaría cada hook dos veces.
116
+ if (target === "grok" && !opts.force) {
117
+ for (const sc of ["user", "project"]) {
118
+ const cf = hookFile("claude", sc, e);
119
+ if (hasHooks(cf))
120
+ return { ok: true, changed: false, file: cf, message: t("tgt.grokCovered", { file: cf }) };
121
+ }
122
+ }
123
+ const groups = groupsFor(target);
124
+ const snippet = JSON.stringify({ hooks: Object.fromEntries(groups.map(([ev, g]) => [ev, [g]])) });
125
+ const r = readJsonFile(file);
126
+ if ("error" in r)
127
+ return manual(file, `${label}: ${t("inst.cantRead", { file, err: r.error })}`, snippet);
128
+ if (r.hadComments)
129
+ return manual(file, `${label}: ${t("inst.hasComments", { name: path.basename(file) })}`, snippet);
130
+ const cur = r.data.hooks;
131
+ if (cur !== undefined && (cur === null || typeof cur !== "object" || Array.isArray(cur))) {
132
+ return manual(file, `${label}: ${t("tgt.notObject", { file })}`, snippet);
133
+ }
134
+ const nextHooks = { ...(cur ?? {}) };
135
+ for (const [event, group] of groups) {
136
+ const arr = Array.isArray(nextHooks[event]) ? [...nextHooks[event]] : [];
137
+ const idx = arr.findIndex(groupIsOurs);
138
+ const rest = arr.filter((g) => !groupIsOurs(g));
139
+ rest.splice(idx === -1 ? rest.length : idx, 0, group); // conserva la posición si ya estaba
140
+ nextHooks[event] = rest;
141
+ }
142
+ const next = { ...r.data, hooks: nextHooks };
143
+ if (JSON.stringify(next) === JSON.stringify(r.data)) {
144
+ return { ok: true, changed: false, file, message: t("tgt.unchanged", { label, file }) };
145
+ }
146
+ const backup = writeJson(file, next, true);
147
+ const notes = [t("tgt.added", { label, file, backup })];
148
+ if (target === "codex")
149
+ notes.push(t("tgt.codexReview"));
150
+ if (target === "grok" && scope === "project")
151
+ notes.push(t("tgt.grokTrust"));
152
+ notes.push(t("tgt.restart"));
153
+ return { ok: true, changed: true, file, message: notes.join("\n") };
154
+ }
155
+ export function uninstallHooks(target, scope, e) {
156
+ const label = LABEL[target];
157
+ const file = hookFile(target, scope, e);
158
+ if (!fs.existsSync(file))
159
+ return { ok: true, changed: false, file, message: t("tgt.notFound", { label, file }) };
160
+ const r = readJsonFile(file);
161
+ if ("error" in r || r.hadComments)
162
+ return manual(file, `${label}: ${t("inst.cantEdit", { file })}`, "loopbreaker hook …");
163
+ const cur = r.data.hooks;
164
+ if (!cur || typeof cur !== "object" || !hasHooks(file))
165
+ return { ok: true, changed: false, file, message: t("tgt.notFound", { label, file }) };
166
+ const nextHooks = {};
167
+ for (const [event, arr] of Object.entries(cur)) {
168
+ if (!Array.isArray(arr)) {
169
+ nextHooks[event] = arr;
170
+ continue;
171
+ }
172
+ const rest = arr.filter((g) => !groupIsOurs(g));
173
+ if (rest.length)
174
+ nextHooks[event] = rest;
175
+ }
176
+ const next = { ...r.data };
177
+ if (Object.keys(nextHooks).length)
178
+ next.hooks = nextHooks;
179
+ else
180
+ delete next.hooks;
181
+ // El archivo propio de Grok se borra entero si ya no queda nada.
182
+ if (target === "grok" && Object.keys(next).length === 0) {
183
+ fs.rmSync(file, { force: true });
184
+ }
185
+ else {
186
+ writeJson(file, next, true);
187
+ }
188
+ return { ok: true, changed: true, file, message: t("tgt.removed", { label, file }) };
189
+ }
190
+ // ---------------------------------------------------------------- orquestación
191
+ export function installTarget(target, scope, e, opts = {}) {
192
+ if (target === "opencode") {
193
+ const r = install(scope === "project" ? e.cwd : globalConfigDir(e.env), opts.pin !== false);
194
+ return { ...r, message: `${r.message}${r.changed ? `\n${t("cli.restartOpencode")}` : ""}` };
195
+ }
196
+ return installHooks(target, scope, e, { force: opts.force });
197
+ }
198
+ export function uninstallTarget(target, scope, e) {
199
+ if (target === "opencode")
200
+ return uninstall(scope === "project" ? e.cwd : globalConfigDir(e.env));
201
+ return uninstallHooks(target, scope, e);
202
+ }
203
+ /** ¿El destino sigue instalado en este scope? Sirve para avisar cuando queda activo en el otro. */
204
+ export function isTargetInstalled(target, scope, e) {
205
+ if (target === "opencode")
206
+ return isInstalled(scope === "project" ? e.cwd : globalConfigDir(e.env));
207
+ return hasHooks(hookFile(target, scope, e));
208
+ }
@@ -1,11 +1,14 @@
1
+ import type { Locale } from "./messages.js";
1
2
  export type Mode = "block" | "warn";
2
3
  export interface ScopeRules {
3
4
  denyGlobs: string[];
4
5
  allowOnlyGlobs: string[];
5
6
  }
6
- /** Contenido de .aeg.json (todo opcional: sin archivo, solo corre el anti-bucles). */
7
- export interface AegConfig {
7
+ /** Contenido de .loopbreaker.json (todo opcional: sin archivo, solo corre el anti-bucles). */
8
+ export interface LoopbreakerConfig {
8
9
  mode?: Mode;
10
+ /** Idioma de los mensajes: "en" (por defecto) o "es". */
11
+ locale?: Locale;
9
12
  /** Repeticiones consecutivas idénticas (sin progreso) que disparan el bloqueo. */
10
13
  maxConsecutiveRepeats?: number;
11
14
  /** Umbrales por herramienta, p. ej. { "read": 4, "bash": 3 }. */
@@ -33,6 +36,7 @@ export interface PhaseSpec {
33
36
  export interface ResolvedConfig {
34
37
  root: string;
35
38
  mode: Mode;
39
+ locale: Locale;
36
40
  maxConsecutiveRepeats: number;
37
41
  toolThresholds: Record<string, number>;
38
42
  cycleMaxPeriod: number;
@@ -53,6 +57,8 @@ export interface CallEntry {
53
57
  epoch: number;
54
58
  /** Familia del comando: tool, y para bash el primer programa (p. ej. "bash:rtk"). */
55
59
  family?: string;
60
+ /** Id de la llamada según la herramienta: sirve para ignorar invocaciones duplicadas. */
61
+ callID?: string;
56
62
  resultHash?: string;
57
63
  resultLen?: number;
58
64
  /** Primeros caracteres de la salida, para citarla en el mensaje de bloqueo. */
@@ -65,6 +71,8 @@ export interface SessionState {
65
71
  /** Bloqueos por bucle: solo estos escalan a parada dura. */
66
72
  loopBlocks?: number;
67
73
  entries: CallEntry[];
74
+ /** Última actividad (ms): permite descartar sesiones antiguas. */
75
+ updated?: number;
68
76
  }
69
77
  export interface Verdict {
70
78
  blocked: boolean;
@@ -0,0 +1,33 @@
1
+ import type { Target } from "./targets.js";
2
+ import type { LoopbreakerConfig, Mode } from "./types.js";
3
+ export interface InstallChoices {
4
+ target: "global" | "project";
5
+ pin: boolean;
6
+ config?: LoopbreakerConfig;
7
+ gitignore: boolean;
8
+ /** Herramientas elegidas. Solo está presente si el asistente preguntó por ellas. */
9
+ tools?: Target[];
10
+ }
11
+ export interface WizardIo {
12
+ question(prompt: string): Promise<string>;
13
+ }
14
+ export interface WizardOptions {
15
+ /** Preguntar qué herramientas proteger, con las detectadas como valor por defecto. */
16
+ askTools?: boolean;
17
+ detected?: Target[];
18
+ }
19
+ export declare function parsePositive(text: string, def: number, min?: number): number;
20
+ export declare function parseGlobs(text: string): string[];
21
+ /** "claude, codex" -> ["claude","codex"]; ignora lo desconocido. */
22
+ export declare function parseTools(text: string, def: Target[]): Target[];
23
+ /** Respuestas ya normalizadas -> archivo .loopbreaker.json. Separado para poder testearlo. */
24
+ export declare function buildConfig(a: {
25
+ mode: Mode;
26
+ maxConsecutiveRepeats: number;
27
+ stagnationRepeats: number;
28
+ hardStopAfter: number;
29
+ allowOnlyGlobs?: string[];
30
+ denyGlobs?: string[];
31
+ }): LoopbreakerConfig;
32
+ /** Wizard de instalación. Sin TTY el CLI no lo llama y usa los mismos defaults. */
33
+ export declare function runWizard(projectRoot: string, io: WizardIo, fixedTarget?: "global" | "project", opts?: WizardOptions): Promise<InstallChoices | undefined>;