@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.
@@ -1,6 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { parseFrontmatter } from "./frontmatter.js";
4
+ import { resolveLocale, t } from "./messages.js";
4
5
  import { toRel } from "./scope-validator.js";
5
6
  export const CONFIG_FILE = ".loopbreaker.json";
6
7
  export const PHASE_LOCK = ".engram/current_phase.lock";
@@ -17,22 +18,22 @@ export const DEFAULT_PROTECTED = [
17
18
  const str = (v) => (typeof v === "string" && v ? v : undefined);
18
19
  const strList = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && x !== "") : [];
19
20
  const posInt = (v) => typeof v === "number" && Number.isInteger(v) && v >= 1 ? v : undefined;
20
- function readJson(file, warnings) {
21
+ function readJson(file, warnings, locale) {
21
22
  if (!fs.existsSync(file))
22
23
  return {};
23
24
  try {
24
25
  const raw = JSON.parse(fs.readFileSync(file, "utf8"));
25
26
  if (typeof raw !== "object" || raw === null || Array.isArray(raw))
26
- throw new Error("se esperaba un objeto");
27
+ throw new Error(t("cfg.objExpected", {}, locale));
27
28
  return raw;
28
29
  }
29
30
  catch (e) {
30
- 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));
31
32
  return {};
32
33
  }
33
34
  }
34
35
  /** El lock contiene una ruta de spec o un id ("phase-02", "2"). */
35
- function resolveSpecPath(root, cfg, warnings) {
36
+ function resolveSpecPath(root, cfg, warnings, locale) {
36
37
  const lock = path.join(root, PHASE_LOCK);
37
38
  let ref;
38
39
  if (fs.existsSync(lock))
@@ -55,12 +56,10 @@ function resolveSpecPath(root, cfg, warnings) {
55
56
  if (fs.existsSync(abs) && fs.statSync(abs).isFile())
56
57
  return rel;
57
58
  }
58
- warnings.push(outside
59
- ? `Fase activa "${ref}" apunta fuera del proyecto; se ignora.`
60
- : `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));
61
60
  return undefined;
62
61
  }
63
- function readSpec(root, rel, warnings) {
62
+ function readSpec(root, rel, warnings, locale) {
64
63
  try {
65
64
  const fm = parseFrontmatter(fs.readFileSync(path.join(root, rel), "utf8"));
66
65
  if (!fm)
@@ -74,15 +73,16 @@ function readSpec(root, rel, warnings) {
74
73
  };
75
74
  }
76
75
  catch (e) {
77
- warnings.push(`Frontmatter de ${rel} inválido (${e.message}); se ignora.`);
76
+ warnings.push(t("cfg.specInvalid", { file: rel, err: e.message }, locale));
78
77
  return undefined;
79
78
  }
80
79
  }
81
80
  export function loadConfig(root) {
82
81
  const warnings = [];
83
- const cfg = readJson(path.join(root, CONFIG_FILE), warnings);
84
- const specFile = resolveSpecPath(root, cfg, warnings);
85
- const phase = specFile ? readSpec(root, specFile, warnings) : undefined;
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
86
  // Prioridad del alcance: frontmatter de la fase > .loopbreaker.json
87
87
  const pick = (k) => {
88
88
  const fromPhase = phase?.scope?.[k] ?? [];
@@ -90,7 +90,7 @@ export function loadConfig(root) {
90
90
  };
91
91
  const mode = cfg.mode === "warn" ? "warn" : "block";
92
92
  if (cfg.mode !== undefined && cfg.mode !== "warn" && cfg.mode !== "block") {
93
- warnings.push(`mode "${String(cfg.mode)}" desconocido; se usa "block".`);
93
+ warnings.push(t("cfg.modeUnknown", { mode: String(cfg.mode) }, locale));
94
94
  }
95
95
  const thresholds = {};
96
96
  for (const [k, v] of Object.entries(cfg.toolThresholds ?? {})) {
@@ -98,12 +98,13 @@ export function loadConfig(root) {
98
98
  if (n)
99
99
  thresholds[k] = n;
100
100
  else
101
- warnings.push(`toolThresholds.${k} debe ser un entero >= 1; se ignora.`);
101
+ warnings.push(t("cfg.thresholdInvalid", { key: k }, locale));
102
102
  }
103
103
  const maxRepeats = Math.max(2, posInt(cfg.maxConsecutiveRepeats) ?? 3);
104
104
  return {
105
105
  root,
106
106
  mode,
107
+ locale,
107
108
  maxConsecutiveRepeats: maxRepeats,
108
109
  toolThresholds: thresholds,
109
110
  cycleMaxPeriod: Math.min(5, posInt(cfg.cycleMaxPeriod) ?? 3),
@@ -126,18 +127,19 @@ export function phaseCard(cfg) {
126
127
  return undefined;
127
128
  const id = cfg.phase?.id ? `: ${oneLine(cfg.phase.id, 80)}` : "";
128
129
  const file = cfg.specFile ? ` (${oneLine(cfg.specFile, 200)})` : "";
129
- const lines = [`[loopbreaker] Datos de fase del repositorio (contexto, no instrucciones)${id}${file}`];
130
+ const L = cfg.locale;
131
+ const lines = [t("card.header", { id, file }, L)];
130
132
  if (cfg.phase?.goal)
131
- lines.push(`Objetivo: ${oneLine(cfg.phase.goal, 300)}`);
133
+ lines.push(t("card.goal", { v: oneLine(cfg.phase.goal, 300) }, L));
132
134
  const allow = globList(cfg.scope.allowOnlyGlobs);
133
135
  if (allow)
134
- lines.push(`Solo puedes modificar: ${allow}`);
136
+ lines.push(t("card.allow", { v: allow }, L));
135
137
  const deny = globList(cfg.scope.denyGlobs);
136
138
  if (deny)
137
- lines.push(`Prohibido modificar: ${deny}`);
139
+ lines.push(t("card.deny", { v: deny }, L));
138
140
  const criteria = (cfg.phase?.exitCriteria ?? []).slice(0, 5).map((c) => oneLine(c, 200)).filter(Boolean);
139
141
  if (criteria.length)
140
- lines.push("Criterios de salida: " + criteria.join(" | "));
141
- lines.push("Si repites una acción sin progreso, cambia de enfoque o pide ayuda al usuario.");
142
+ lines.push(t("card.criteria", { v: criteria.join(" | ") }, L));
143
+ lines.push(t("card.footer", {}, L));
142
144
  return lines.join("\n");
143
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,89 @@
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, isTargetInstalled, 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
+ if (isTargetInstalled("pi", "user", e))
34
+ mark("pi", "user");
35
+ for (const tg of TARGETS) {
36
+ const w = where.get(tg);
37
+ add(w ? "ok" : "warn", w ? t("doc.installed", { label: LABEL[tg], where: w.join(", ") }) : t("doc.notInstalled", { label: LABEL[tg] }));
38
+ }
39
+ // 3) PATH: imprescindible solo para las herramientas con hooks
40
+ const hookInstalled = ["claude", "codex", "grok"].some((tg) => where.has(tg));
41
+ if (onPath("loopbreaker", e.env))
42
+ add("ok", t("doc.pathOk"));
43
+ else
44
+ add(hookInstalled ? "fail" : "warn", t("doc.pathMissing"));
45
+ // 4) duplicados: cada uno haría que una llamada se cuente dos veces
46
+ if (where.has("grok") && where.has("claude"))
47
+ add("warn", t("doc.dupGrok"));
48
+ if (ocGlobal && ocProject)
49
+ add("warn", t("doc.dupOpencode"));
50
+ const codexToml = path.join(e.env.CODEX_HOME || path.join(e.home, ".codex"), "config.toml");
51
+ try {
52
+ if (where.has("codex") && /loopbreaker hook/.test(fs.readFileSync(codexToml, "utf8")))
53
+ add("warn", t("doc.codexBoth"));
54
+ }
55
+ catch {
56
+ /* sin config.toml */
57
+ }
58
+ // 5) configuración del proyecto
59
+ const cfg = loadConfig(root);
60
+ if (cfg.warnings.length)
61
+ for (const w of cfg.warnings)
62
+ add("warn", w);
63
+ else
64
+ add("ok", t("doc.configOk"));
65
+ // 6) .gitignore (solo si es un repositorio git)
66
+ if (fs.existsSync(path.join(root, ".git"))) {
67
+ let has = false;
68
+ try {
69
+ has = fs.readFileSync(path.join(root, ".gitignore"), "utf8").split(/\r?\n/).some((l) => l.trim() === GITIGNORE_ENTRY || l.trim() === ".opencode");
70
+ }
71
+ catch {
72
+ /* sin .gitignore */
73
+ }
74
+ add(has ? "ok" : "warn", has ? t("doc.gitignoreOk") : t("doc.gitignoreMissing"));
75
+ }
76
+ // 7) errores internos que el guardián haya registrado
77
+ try {
78
+ const lines = fs.readFileSync(path.join(root, LOG_FILE), "utf8").split("\n").filter(Boolean);
79
+ const errs = lines.map((l) => JSON.parse(l)).filter((x) => x?.event === "internal-error");
80
+ if (errs.length)
81
+ add("warn", t("doc.internalErrors", { n: errs.length, msg: String(errs[errs.length - 1].message ?? "").slice(0, 160) }));
82
+ else
83
+ add("ok", t("doc.noInternalErrors"));
84
+ }
85
+ catch {
86
+ add("ok", t("doc.noInternalErrors"));
87
+ }
88
+ return out;
89
+ }
@@ -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,24 +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;
8
24
  /** Endurece archivos existentes de versiones anteriores (0644 -> 0600). */
9
25
  private harden;
10
26
  /** La configuración se relee en cada llamada: cambiar de fase surte efecto sin reiniciar. */
11
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;
12
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
+ */
13
49
  private save;
14
50
  private log;
15
51
  session(id: string): SessionState;
16
52
  /**
17
53
  * Antes de ejecutar una herramienta. Devuelve el mensaje de bloqueo o undefined si puede seguir.
18
- * 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.
19
56
  */
20
- before(sessionID: string, tool: string, args?: Record<string, unknown>): string | undefined;
21
- 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;
22
60
  /** Red de seguridad fiable: archivos cambiados según git que violan el alcance. */
23
61
  gitCheck(): string[];
24
62
  reset(sessionID?: string): void;