@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.
@@ -1,8 +1,8 @@
1
1
  import type { ResolvedConfig } from "./types.js";
2
- export declare const CONFIG_FILE = ".aeg.json";
2
+ export declare const CONFIG_FILE = ".loopbreaker.json";
3
3
  export declare const PHASE_LOCK = ".engram/current_phase.lock";
4
- export declare const STATE_FILE = ".opencode/.aeg-state.json";
5
- export declare const LOG_FILE = ".opencode/aeg.log.jsonl";
4
+ export declare const STATE_FILE = ".opencode/loopbreaker-state.json";
5
+ export declare const LOG_FILE = ".opencode/loopbreaker.log.jsonl";
6
6
  /** Rutas que el agente nunca puede escribir, sea cual sea la fase. */
7
7
  export declare const DEFAULT_PROTECTED: string[];
8
8
  export declare function loadConfig(root: string): ResolvedConfig;
@@ -1,10 +1,12 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { parseFrontmatter } from "./frontmatter.js";
4
- export const CONFIG_FILE = ".aeg.json";
4
+ import { resolveLocale, t } from "./messages.js";
5
+ import { toRel } from "./scope-validator.js";
6
+ export const CONFIG_FILE = ".loopbreaker.json";
5
7
  export const PHASE_LOCK = ".engram/current_phase.lock";
6
- export const STATE_FILE = ".opencode/.aeg-state.json";
7
- export const LOG_FILE = ".opencode/aeg.log.jsonl";
8
+ export const STATE_FILE = ".opencode/loopbreaker-state.json";
9
+ export const LOG_FILE = ".opencode/loopbreaker.log.jsonl";
8
10
  /** Rutas que el agente nunca puede escribir, sea cual sea la fase. */
9
11
  export const DEFAULT_PROTECTED = [
10
12
  CONFIG_FILE,
@@ -16,22 +18,22 @@ export const DEFAULT_PROTECTED = [
16
18
  const str = (v) => (typeof v === "string" && v ? v : undefined);
17
19
  const strList = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && x !== "") : [];
18
20
  const posInt = (v) => typeof v === "number" && Number.isInteger(v) && v >= 1 ? v : undefined;
19
- function readJson(file, warnings) {
21
+ function readJson(file, warnings, locale) {
20
22
  if (!fs.existsSync(file))
21
23
  return {};
22
24
  try {
23
25
  const raw = JSON.parse(fs.readFileSync(file, "utf8"));
24
26
  if (typeof raw !== "object" || raw === null || Array.isArray(raw))
25
- throw new Error("se esperaba un objeto");
27
+ throw new Error(t("cfg.objExpected", {}, locale));
26
28
  return raw;
27
29
  }
28
30
  catch (e) {
29
- warnings.push(`${CONFIG_FILE} inválido (${e.message}); se usan valores por defecto.`);
31
+ warnings.push(t("cfg.invalid", { file: CONFIG_FILE, err: e.message }, locale));
30
32
  return {};
31
33
  }
32
34
  }
33
35
  /** El lock contiene una ruta de spec o un id ("phase-02", "2"). */
34
- function resolveSpecPath(root, cfg, warnings) {
36
+ function resolveSpecPath(root, cfg, warnings, locale) {
35
37
  const lock = path.join(root, PHASE_LOCK);
36
38
  let ref;
37
39
  if (fs.existsSync(lock))
@@ -42,15 +44,22 @@ function resolveSpecPath(root, cfg, warnings) {
42
44
  const candidates = [ref, `.engram/specs/${ref}`, `.engram/specs/${ref}.md`];
43
45
  if (/^\d+$/.test(ref))
44
46
  candidates.push(`.engram/specs/phase-${ref.padStart(2, "0")}.md`);
47
+ let outside = false;
45
48
  for (const c of candidates) {
46
- const abs = path.resolve(root, c);
49
+ // toRel resuelve symlinks y devuelve null si el destino queda fuera del proyecto.
50
+ const rel = toRel(root, c);
51
+ if (rel === null) {
52
+ outside = true;
53
+ continue;
54
+ }
55
+ const abs = path.join(root, rel);
47
56
  if (fs.existsSync(abs) && fs.statSync(abs).isFile())
48
- return path.relative(root, abs).split(path.sep).join("/");
57
+ return rel;
49
58
  }
50
- warnings.push(`Fase activa "${ref}" no encontrada; el control de alcance queda sin reglas de fase.`);
59
+ warnings.push(outside ? t("cfg.phaseOutside", { ref }, locale) : t("cfg.phaseMissing", { ref }, locale));
51
60
  return undefined;
52
61
  }
53
- function readSpec(root, rel, warnings) {
62
+ function readSpec(root, rel, warnings, locale) {
54
63
  try {
55
64
  const fm = parseFrontmatter(fs.readFileSync(path.join(root, rel), "utf8"));
56
65
  if (!fm)
@@ -64,23 +73,24 @@ function readSpec(root, rel, warnings) {
64
73
  };
65
74
  }
66
75
  catch (e) {
67
- warnings.push(`Frontmatter de ${rel} inválido (${e.message}); se ignora.`);
76
+ warnings.push(t("cfg.specInvalid", { file: rel, err: e.message }, locale));
68
77
  return undefined;
69
78
  }
70
79
  }
71
80
  export function loadConfig(root) {
72
81
  const warnings = [];
73
- const cfg = readJson(path.join(root, CONFIG_FILE), warnings);
74
- const specFile = resolveSpecPath(root, cfg, warnings);
75
- const phase = specFile ? readSpec(root, specFile, warnings) : undefined;
76
- // Prioridad del alcance: frontmatter de la fase > .aeg.json
82
+ const cfg = readJson(path.join(root, CONFIG_FILE), warnings, resolveLocale());
83
+ const locale = resolveLocale(cfg.locale);
84
+ const specFile = resolveSpecPath(root, cfg, warnings, locale);
85
+ const phase = specFile ? readSpec(root, specFile, warnings, locale) : undefined;
86
+ // Prioridad del alcance: frontmatter de la fase > .loopbreaker.json
77
87
  const pick = (k) => {
78
88
  const fromPhase = phase?.scope?.[k] ?? [];
79
89
  return fromPhase.length ? fromPhase : strList(cfg.scope?.[k]);
80
90
  };
81
91
  const mode = cfg.mode === "warn" ? "warn" : "block";
82
92
  if (cfg.mode !== undefined && cfg.mode !== "warn" && cfg.mode !== "block") {
83
- warnings.push(`mode "${String(cfg.mode)}" desconocido; se usa "block".`);
93
+ warnings.push(t("cfg.modeUnknown", { mode: String(cfg.mode) }, locale));
84
94
  }
85
95
  const thresholds = {};
86
96
  for (const [k, v] of Object.entries(cfg.toolThresholds ?? {})) {
@@ -88,12 +98,13 @@ export function loadConfig(root) {
88
98
  if (n)
89
99
  thresholds[k] = n;
90
100
  else
91
- warnings.push(`toolThresholds.${k} debe ser un entero >= 1; se ignora.`);
101
+ warnings.push(t("cfg.thresholdInvalid", { key: k }, locale));
92
102
  }
93
103
  const maxRepeats = Math.max(2, posInt(cfg.maxConsecutiveRepeats) ?? 3);
94
104
  return {
95
105
  root,
96
106
  mode,
107
+ locale,
97
108
  maxConsecutiveRepeats: maxRepeats,
98
109
  toolThresholds: thresholds,
99
110
  cycleMaxPeriod: Math.min(5, posInt(cfg.cycleMaxPeriod) ?? 3),
@@ -107,19 +118,28 @@ export function loadConfig(root) {
107
118
  warnings,
108
119
  };
109
120
  }
121
+ /** El spec es contenido del repositorio: se aplana, se recorta y se trata como dato, no como instrucción. */
122
+ const oneLine = (v, max) => v.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
123
+ const globList = (v) => v.slice(0, 20).map((g) => oneLine(g, 100)).filter(Boolean).join(", ");
110
124
  /** Resumen corto de la fase activa para inyectar en el prompt o en la compactación. */
111
125
  export function phaseCard(cfg) {
112
126
  if (!cfg.specFile && !cfg.scope.allowOnlyGlobs.length && !cfg.scope.denyGlobs.length)
113
127
  return undefined;
114
- const lines = ["[AEG] Fase activa" + (cfg.phase?.id ? `: ${cfg.phase.id}` : "") + (cfg.specFile ? ` (${cfg.specFile})` : "")];
128
+ const id = cfg.phase?.id ? `: ${oneLine(cfg.phase.id, 80)}` : "";
129
+ const file = cfg.specFile ? ` (${oneLine(cfg.specFile, 200)})` : "";
130
+ const L = cfg.locale;
131
+ const lines = [t("card.header", { id, file }, L)];
115
132
  if (cfg.phase?.goal)
116
- lines.push(`Objetivo: ${cfg.phase.goal}`);
117
- if (cfg.scope.allowOnlyGlobs.length)
118
- lines.push(`Solo puedes modificar: ${cfg.scope.allowOnlyGlobs.join(", ")}`);
119
- if (cfg.scope.denyGlobs.length)
120
- lines.push(`Prohibido modificar: ${cfg.scope.denyGlobs.join(", ")}`);
121
- if (cfg.phase?.exitCriteria?.length)
122
- lines.push("Criterios de salida: " + cfg.phase.exitCriteria.join(" | "));
123
- lines.push("Si repites una acción sin progreso, cambia de enfoque o pide ayuda al usuario.");
133
+ lines.push(t("card.goal", { v: oneLine(cfg.phase.goal, 300) }, L));
134
+ const allow = globList(cfg.scope.allowOnlyGlobs);
135
+ if (allow)
136
+ lines.push(t("card.allow", { v: allow }, L));
137
+ const deny = globList(cfg.scope.denyGlobs);
138
+ if (deny)
139
+ lines.push(t("card.deny", { v: deny }, L));
140
+ const criteria = (cfg.phase?.exitCriteria ?? []).slice(0, 5).map((c) => oneLine(c, 200)).filter(Boolean);
141
+ if (criteria.length)
142
+ lines.push(t("card.criteria", { v: criteria.join(" | ") }, L));
143
+ lines.push(t("card.footer", {}, L));
124
144
  return lines.join("\n");
125
145
  }
@@ -0,0 +1,8 @@
1
+ import type { TargetEnv } from "./targets.js";
2
+ export interface Check {
3
+ level: "ok" | "warn" | "fail";
4
+ text: string;
5
+ }
6
+ export declare const formatCheck: (c: Check) => string;
7
+ /** Revisa la instalación y la configuración. No modifica nada. */
8
+ export declare function doctor(root: string, e: TargetEnv): Check[];
@@ -0,0 +1,87 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { LOG_FILE, loadConfig } from "./config-loader.js";
4
+ import { GITIGNORE_ENTRY, globalConfigDir, isInstalled } from "./installer.js";
5
+ import { t } from "./messages.js";
6
+ import { LABEL, TARGETS, hasHooks, hookFile, onPath } from "./targets.js";
7
+ const ICON = { ok: "✓", warn: "⚠", fail: "✗" };
8
+ export const formatCheck = (c) => `${ICON[c.level]} ${c.text}`;
9
+ /** Revisa la instalación y la configuración. No modifica nada. */
10
+ export function doctor(root, e) {
11
+ const out = [];
12
+ const add = (level, text) => void out.push({ level, text });
13
+ // 1) Node
14
+ const nodeV = process.versions.node;
15
+ if (Number(nodeV.split(".")[0]) >= 18)
16
+ add("ok", t("doc.node", { v: nodeV }));
17
+ else
18
+ add("fail", t("doc.nodeOld", { v: nodeV }));
19
+ // 2) dónde está instalado cada destino
20
+ const where = new Map();
21
+ const mark = (tg, w) => void where.set(tg, [...(where.get(tg) ?? []), w]);
22
+ const ocGlobal = isInstalled(globalConfigDir(e.env));
23
+ const ocProject = isInstalled(root);
24
+ if (ocGlobal)
25
+ mark("opencode", "global");
26
+ if (ocProject)
27
+ mark("opencode", "project");
28
+ for (const tg of ["claude", "codex", "grok"]) {
29
+ for (const sc of ["user", "project"])
30
+ if (hasHooks(hookFile(tg, sc, { ...e, cwd: root })))
31
+ mark(tg, sc);
32
+ }
33
+ for (const tg of TARGETS) {
34
+ const w = where.get(tg);
35
+ add(w ? "ok" : "warn", w ? t("doc.installed", { label: LABEL[tg], where: w.join(", ") }) : t("doc.notInstalled", { label: LABEL[tg] }));
36
+ }
37
+ // 3) PATH: imprescindible solo para las herramientas con hooks
38
+ const hookInstalled = ["claude", "codex", "grok"].some((tg) => where.has(tg));
39
+ if (onPath("loopbreaker", e.env))
40
+ add("ok", t("doc.pathOk"));
41
+ else
42
+ add(hookInstalled ? "fail" : "warn", t("doc.pathMissing"));
43
+ // 4) duplicados: cada uno haría que una llamada se cuente dos veces
44
+ if (where.has("grok") && where.has("claude"))
45
+ add("warn", t("doc.dupGrok"));
46
+ if (ocGlobal && ocProject)
47
+ add("warn", t("doc.dupOpencode"));
48
+ const codexToml = path.join(e.env.CODEX_HOME || path.join(e.home, ".codex"), "config.toml");
49
+ try {
50
+ if (where.has("codex") && /loopbreaker hook/.test(fs.readFileSync(codexToml, "utf8")))
51
+ add("warn", t("doc.codexBoth"));
52
+ }
53
+ catch {
54
+ /* sin config.toml */
55
+ }
56
+ // 5) configuración del proyecto
57
+ const cfg = loadConfig(root);
58
+ if (cfg.warnings.length)
59
+ for (const w of cfg.warnings)
60
+ add("warn", w);
61
+ else
62
+ add("ok", t("doc.configOk"));
63
+ // 6) .gitignore (solo si es un repositorio git)
64
+ if (fs.existsSync(path.join(root, ".git"))) {
65
+ let has = false;
66
+ try {
67
+ has = fs.readFileSync(path.join(root, ".gitignore"), "utf8").split(/\r?\n/).some((l) => l.trim() === GITIGNORE_ENTRY || l.trim() === ".opencode");
68
+ }
69
+ catch {
70
+ /* sin .gitignore */
71
+ }
72
+ add(has ? "ok" : "warn", has ? t("doc.gitignoreOk") : t("doc.gitignoreMissing"));
73
+ }
74
+ // 7) errores internos que el guardián haya registrado
75
+ try {
76
+ const lines = fs.readFileSync(path.join(root, LOG_FILE), "utf8").split("\n").filter(Boolean);
77
+ const errs = lines.map((l) => JSON.parse(l)).filter((x) => x?.event === "internal-error");
78
+ if (errs.length)
79
+ add("warn", t("doc.internalErrors", { n: errs.length, msg: String(errs[errs.length - 1].message ?? "").slice(0, 160) }));
80
+ else
81
+ add("ok", t("doc.noInternalErrors"));
82
+ }
83
+ catch {
84
+ add("ok", t("doc.noInternalErrors"));
85
+ }
86
+ return out;
87
+ }
@@ -125,7 +125,12 @@ export function parseFrontmatter(text) {
125
125
  });
126
126
  if (lines.length === 0)
127
127
  return {};
128
- const [val] = parseBlock(lines, 0, lines[0].indent);
128
+ const [val, next] = parseBlock(lines, 0, lines[0].indent);
129
+ if (next < lines.length) {
130
+ // Un dedent por debajo de la primera clave descartaría claves en silencio:
131
+ // en un guardián, un scope que no se aplica debe fallar fuerte, no callarse.
132
+ throw new Error(`frontmatter línea ${lines[next].no}: las claves de primer nivel deben compartir la indentación de la primera`);
133
+ }
129
134
  if (typeof val !== "object" || val === null || Array.isArray(val))
130
135
  throw new Error("frontmatter: se esperaba un mapa");
131
136
  return val;
@@ -1,22 +1,62 @@
1
1
  import type { ResolvedConfig, SessionState } from "./types.js";
2
- /** Núcleo del guardián: independiente de OpenCode para poder probarlo en aislamiento. */
2
+ /** Núcleo del guardián: independiente de la herramienta que lo llame (plugin de OpenCode o hooks por CLI). */
3
3
  export declare class Guard {
4
4
  readonly root: string;
5
5
  cfg: ResolvedConfig;
6
6
  private state;
7
+ /** Sesiones que ESTE proceso ha tocado: al guardar solo se sobrescriben estas, no las de otros procesos. */
8
+ private touched;
9
+ /** Sesiones que este proceso ya guardó con éxito: si luego desaparecen del disco, se reseteó desde fuera. */
10
+ private savedOk;
11
+ private clearAll;
12
+ private lockDepth;
13
+ /** Errores internos ya registrados (evita llenar el log con el mismo fallo repetido). */
14
+ private reported;
15
+ lastError?: string;
16
+ errorCount: number;
7
17
  constructor(root: string);
18
+ private get L();
19
+ /**
20
+ * Un fallo interno nunca rompe la sesión del agente, pero tampoco se esconde:
21
+ * queda en el log (una vez por tipo) y en `status`.
22
+ */
23
+ private fail;
24
+ /** Endurece archivos existentes de versiones anteriores (0644 -> 0600). */
25
+ private harden;
8
26
  /** La configuración se relee en cada llamada: cambiar de fase surte efecto sin reiniciar. */
9
27
  reload(): void;
28
+ /**
29
+ * Exclusión mutua entre procesos con un archivo creado con O_EXCL ("wx").
30
+ * Cada hook de una herramienta es un proceso nuevo y puede haber llamadas en paralelo:
31
+ * sin esto, dos procesos leen el mismo estado y el último en escribir borra el cambio del otro.
32
+ * Si no se consigue el bloqueo a tiempo, se sigue sin él: el guardián nunca frena al agente por esto.
33
+ */
34
+ private withLock;
35
+ /** Lee el estado del disco. Sin archivo = undefined sin error; archivo ilegible = undefined y se reporta. */
36
+ private readDisk;
10
37
  private load;
38
+ /**
39
+ * Trae la sesión del disco, que es la verdad cuando hay varios procesos.
40
+ * El fragmento de salida solo vive en memoria (nunca se persiste), así que se conserva al recargar.
41
+ */
42
+ private syncSession;
43
+ /**
44
+ * Guarda el estado sin corromperlo ni pisar a otros procesos:
45
+ * - mezcla con lo que haya en disco y solo sobrescribe las sesiones que este proceso tocó;
46
+ * - escribe a un archivo temporal (flag "wx": nunca sigue un symlink previo) y lo renombra,
47
+ * así un lector o un fallo a mitad de escritura nunca ve JSON a medias.
48
+ */
11
49
  private save;
12
50
  private log;
13
51
  session(id: string): SessionState;
14
52
  /**
15
53
  * Antes de ejecutar una herramienta. Devuelve el mensaje de bloqueo o undefined si puede seguir.
16
- * En modo "warn" solo registra en el log.
54
+ * En modo "warn" solo registra en el log. `callID` (si la herramienta lo da) evita contar dos veces
55
+ * una misma llamada cuando el hook está registrado más de una vez.
17
56
  */
18
- before(sessionID: string, tool: string, args?: Record<string, unknown>): string | undefined;
19
- after(sessionID: string, tool: string, args: Record<string, unknown>, output: unknown, failed?: boolean): void;
57
+ before(sessionID: string, tool: string, args?: Record<string, unknown>, callID?: string): string | undefined;
58
+ private beforeLocked;
59
+ after(sessionID: string, tool: string, args: Record<string, unknown>, output: unknown, failed?: boolean, callID?: string): void;
20
60
  /** Red de seguridad fiable: archivos cambiados según git que violan el alcance. */
21
61
  gitCheck(): string[];
22
62
  reset(sessionID?: string): void;