@adayacas/loopbreaker 0.0.0-stage → 0.2.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.
- package/LICENSE +9 -0
- package/README.md +64 -2
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +62 -0
- package/dist/src/config-loader.d.ts +10 -0
- package/dist/src/config-loader.js +125 -0
- package/dist/src/frontmatter.d.ts +2 -0
- package/dist/src/frontmatter.js +132 -0
- package/dist/src/glob.d.ts +3 -0
- package/dist/src/glob.js +75 -0
- package/dist/src/guard.d.ts +24 -0
- package/dist/src/guard.js +153 -0
- package/dist/src/index.d.ts +37 -0
- package/dist/src/index.js +64 -0
- package/dist/src/installer.d.ts +16 -0
- package/dist/src/installer.js +123 -0
- package/dist/src/loop-detector.d.ts +24 -0
- package/dist/src/loop-detector.js +136 -0
- package/dist/src/scope-validator.d.ts +16 -0
- package/dist/src/scope-validator.js +114 -0
- package/dist/src/types.d.ts +72 -0
- package/dist/src/types.js +1 -0
- package/package.json +51 -4
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
type Args = Record<string, unknown>;
|
|
2
|
+
type PluginCtx = {
|
|
3
|
+
directory?: string;
|
|
4
|
+
worktree?: string;
|
|
5
|
+
};
|
|
6
|
+
export declare const AegPlugin: (ctx?: PluginCtx) => Promise<{
|
|
7
|
+
"tool.execute.before": (input: {
|
|
8
|
+
tool: string;
|
|
9
|
+
sessionID: string;
|
|
10
|
+
callID: string;
|
|
11
|
+
}, output: {
|
|
12
|
+
args?: Args;
|
|
13
|
+
}) => Promise<void>;
|
|
14
|
+
"tool.execute.after": (input: {
|
|
15
|
+
tool: string;
|
|
16
|
+
sessionID: string;
|
|
17
|
+
callID: string;
|
|
18
|
+
}, output: {
|
|
19
|
+
output?: unknown;
|
|
20
|
+
metadata?: {
|
|
21
|
+
error?: unknown;
|
|
22
|
+
};
|
|
23
|
+
}) => Promise<void>;
|
|
24
|
+
"experimental.chat.system.transform": (_i: unknown, output: {
|
|
25
|
+
system: string[];
|
|
26
|
+
}) => Promise<void>;
|
|
27
|
+
"experimental.session.compacting": (_i: unknown, output: {
|
|
28
|
+
context: string[];
|
|
29
|
+
}) => Promise<void>;
|
|
30
|
+
event: ({ event }: {
|
|
31
|
+
event: {
|
|
32
|
+
type: string;
|
|
33
|
+
};
|
|
34
|
+
}) => Promise<void>;
|
|
35
|
+
tool?: Record<string, unknown> | undefined;
|
|
36
|
+
}>;
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { Guard } from "./guard.js";
|
|
2
|
+
import { phaseCard } from "./config-loader.js";
|
|
3
|
+
export const AegPlugin = 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
|
+
// aeg_status es de solo lectura. Si el paquete de plugin no está, el guardián funciona igual.
|
|
9
|
+
let tools;
|
|
10
|
+
try {
|
|
11
|
+
const mod = await import("@opencode-ai/plugin");
|
|
12
|
+
if (mod?.tool) {
|
|
13
|
+
tools = {
|
|
14
|
+
aeg_status: mod.tool({
|
|
15
|
+
description: "Muestra el estado del guardián de ejecución (fase activa, alcance, bloqueos).",
|
|
16
|
+
args: {},
|
|
17
|
+
async execute(_a, c) {
|
|
18
|
+
return guard.status(c?.sessionID);
|
|
19
|
+
},
|
|
20
|
+
}),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
/* paquete no disponible */
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
...(tools ? { tool: tools } : {}),
|
|
29
|
+
"tool.execute.before": async (input, output) => {
|
|
30
|
+
const args = output?.args ?? {};
|
|
31
|
+
pending.set(input.callID, args);
|
|
32
|
+
const msg = guard.before(input.sessionID, input.tool, args);
|
|
33
|
+
if (msg) {
|
|
34
|
+
pending.delete(input.callID);
|
|
35
|
+
throw new Error(msg);
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"tool.execute.after": async (input, output) => {
|
|
39
|
+
const args = pending.get(input.callID);
|
|
40
|
+
pending.delete(input.callID);
|
|
41
|
+
if (!args)
|
|
42
|
+
return;
|
|
43
|
+
guard.after(input.sessionID, input.tool, args, output?.output, Boolean(output?.metadata?.error));
|
|
44
|
+
},
|
|
45
|
+
// Inyecta la tarjeta de fase en cada prompt y durante la compactación (no después).
|
|
46
|
+
"experimental.chat.system.transform": async (_i, output) => {
|
|
47
|
+
guard.reload();
|
|
48
|
+
const card = phaseCard(guard.cfg);
|
|
49
|
+
if (card)
|
|
50
|
+
output.system.push(card);
|
|
51
|
+
},
|
|
52
|
+
"experimental.session.compacting": async (_i, output) => {
|
|
53
|
+
guard.reload();
|
|
54
|
+
const card = phaseCard(guard.cfg);
|
|
55
|
+
if (card)
|
|
56
|
+
output.context.push(card);
|
|
57
|
+
},
|
|
58
|
+
event: async ({ event }) => {
|
|
59
|
+
if (event.type === "session.idle")
|
|
60
|
+
guard.gitCheck();
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
// Solo se exporta AegPlugin: OpenCode invoca como plugin CADA export de función/clase del módulo.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const PLUGIN_NAME = "@adayacas/loopbreaker";
|
|
2
|
+
export interface InstallResult {
|
|
3
|
+
ok: boolean;
|
|
4
|
+
changed: boolean;
|
|
5
|
+
file: string;
|
|
6
|
+
message: string;
|
|
7
|
+
}
|
|
8
|
+
/** Config global de OpenCode: $XDG_CONFIG_HOME/opencode o ~/.config/opencode. */
|
|
9
|
+
export declare function globalConfigDir(env?: NodeJS.ProcessEnv): string;
|
|
10
|
+
/** Busca opencode.json (o .jsonc); si no existe ninguno, devuelve opencode.json como destino a crear. */
|
|
11
|
+
export declare function configFile(dir: string): string;
|
|
12
|
+
/** Añade el plugin a opencode.json de forma idempotente, con copia de seguridad. */
|
|
13
|
+
export declare function install(dir: string, spec?: string): InstallResult;
|
|
14
|
+
export declare function uninstall(dir: string): InstallResult;
|
|
15
|
+
/** Crea un .aeg.json mínimo en el proyecto (no sobrescribe). */
|
|
16
|
+
export declare function init(projectDir: string): InstallResult;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
export const PLUGIN_NAME = "@adayacas/loopbreaker";
|
|
5
|
+
/** Config global de OpenCode: $XDG_CONFIG_HOME/opencode o ~/.config/opencode. */
|
|
6
|
+
export function globalConfigDir(env = process.env) {
|
|
7
|
+
const base = env.XDG_CONFIG_HOME || path.join(env.HOME || env.USERPROFILE || os.homedir(), ".config");
|
|
8
|
+
return path.join(base, "opencode");
|
|
9
|
+
}
|
|
10
|
+
/** Busca opencode.json (o .jsonc); si no existe ninguno, devuelve opencode.json como destino a crear. */
|
|
11
|
+
export function configFile(dir) {
|
|
12
|
+
for (const n of ["opencode.json", "opencode.jsonc"]) {
|
|
13
|
+
const f = path.join(dir, n);
|
|
14
|
+
if (fs.existsSync(f))
|
|
15
|
+
return f;
|
|
16
|
+
}
|
|
17
|
+
return path.join(dir, "opencode.json");
|
|
18
|
+
}
|
|
19
|
+
/** Quita comentarios // y /* *\/ y comas finales sin tocar el contenido de las cadenas. */
|
|
20
|
+
function stripJsonc(text) {
|
|
21
|
+
let out = "";
|
|
22
|
+
let inStr = false;
|
|
23
|
+
for (let i = 0; i < text.length; i++) {
|
|
24
|
+
const c = text[i];
|
|
25
|
+
const n = text[i + 1];
|
|
26
|
+
if (inStr) {
|
|
27
|
+
out += c;
|
|
28
|
+
if (c === "\\")
|
|
29
|
+
out += text[++i] ?? "";
|
|
30
|
+
else if (c === '"')
|
|
31
|
+
inStr = false;
|
|
32
|
+
}
|
|
33
|
+
else if (c === '"') {
|
|
34
|
+
inStr = true;
|
|
35
|
+
out += c;
|
|
36
|
+
}
|
|
37
|
+
else if (c === "/" && n === "/") {
|
|
38
|
+
while (i < text.length && text[i] !== "\n")
|
|
39
|
+
i++;
|
|
40
|
+
out += "\n";
|
|
41
|
+
}
|
|
42
|
+
else if (c === "/" && n === "*") {
|
|
43
|
+
i += 2;
|
|
44
|
+
while (i < text.length && !(text[i] === "*" && text[i + 1] === "/"))
|
|
45
|
+
i++;
|
|
46
|
+
i++;
|
|
47
|
+
}
|
|
48
|
+
else
|
|
49
|
+
out += c;
|
|
50
|
+
}
|
|
51
|
+
return out.replace(/,(\s*[}\]])/g, "$1");
|
|
52
|
+
}
|
|
53
|
+
function read(file) {
|
|
54
|
+
if (!fs.existsSync(file))
|
|
55
|
+
return { data: {}, hadComments: false };
|
|
56
|
+
const raw = fs.readFileSync(file, "utf8");
|
|
57
|
+
try {
|
|
58
|
+
return { data: raw.trim() ? JSON.parse(raw) : {}, hadComments: false };
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
try {
|
|
62
|
+
return { data: JSON.parse(stripJsonc(raw)), hadComments: true };
|
|
63
|
+
}
|
|
64
|
+
catch (e) {
|
|
65
|
+
return { error: e.message };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const isAeg = (p) => typeof p === "string" && (p === PLUGIN_NAME || p.startsWith(PLUGIN_NAME + "@"));
|
|
70
|
+
function manual(file, why, line) {
|
|
71
|
+
return { ok: false, changed: false, file, message: `${why}\nNo toqué tu archivo. Añade a mano en ${file}:\n ${line}` };
|
|
72
|
+
}
|
|
73
|
+
/** Añade el plugin a opencode.json de forma idempotente, con copia de seguridad. */
|
|
74
|
+
export function install(dir, spec = PLUGIN_NAME) {
|
|
75
|
+
const file = configFile(dir);
|
|
76
|
+
const r = read(file);
|
|
77
|
+
if ("error" in r)
|
|
78
|
+
return manual(file, `No pude leer ${file} (${r.error}).`, `"plugin": ["${spec}"]`);
|
|
79
|
+
if (r.hadComments) {
|
|
80
|
+
// Reescribir perdería los comentarios del usuario: mejor no tocar nada.
|
|
81
|
+
return manual(file, `${path.basename(file)} tiene comentarios y reescribirlo los borraría.`, `"plugin": [..., "${spec}"]`);
|
|
82
|
+
}
|
|
83
|
+
const cur = r.data.plugin;
|
|
84
|
+
if (cur !== undefined && !Array.isArray(cur))
|
|
85
|
+
return manual(file, `"plugin" en ${file} no es una lista.`, `"plugin": ["${spec}"]`);
|
|
86
|
+
const list = Array.isArray(cur) ? cur : [];
|
|
87
|
+
if (list.some(isAeg))
|
|
88
|
+
return { ok: true, changed: false, file, message: `Ya estaba instalado en ${file}.` };
|
|
89
|
+
if (fs.existsSync(file))
|
|
90
|
+
fs.copyFileSync(file, file + ".aeg.bak");
|
|
91
|
+
const next = { ...(fs.existsSync(file) ? r.data : { $schema: "https://opencode.ai/config.json" }), plugin: [...list, spec] };
|
|
92
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
93
|
+
fs.writeFileSync(file, JSON.stringify(next, null, 2) + "\n");
|
|
94
|
+
return { ok: true, changed: true, file, message: `Plugin añadido a ${file}${fs.existsSync(file + ".aeg.bak") ? ` (copia: ${path.basename(file)}.aeg.bak)` : ""}.` };
|
|
95
|
+
}
|
|
96
|
+
export function uninstall(dir) {
|
|
97
|
+
const file = configFile(dir);
|
|
98
|
+
if (!fs.existsSync(file))
|
|
99
|
+
return { ok: true, changed: false, file, message: "No hay configuración que modificar." };
|
|
100
|
+
const r = read(file);
|
|
101
|
+
if ("error" in r || r.hadComments)
|
|
102
|
+
return manual(file, `No puedo editar ${file} automáticamente.`, `quita "${PLUGIN_NAME}" de "plugin"`);
|
|
103
|
+
const cur = r.data.plugin;
|
|
104
|
+
if (!Array.isArray(cur) || !cur.some(isAeg))
|
|
105
|
+
return { ok: true, changed: false, file, message: "El plugin no estaba registrado." };
|
|
106
|
+
fs.copyFileSync(file, file + ".aeg.bak");
|
|
107
|
+
const rest = cur.filter((p) => !isAeg(p));
|
|
108
|
+
const next = { ...r.data };
|
|
109
|
+
if (rest.length)
|
|
110
|
+
next.plugin = rest;
|
|
111
|
+
else
|
|
112
|
+
delete next.plugin;
|
|
113
|
+
fs.writeFileSync(file, JSON.stringify(next, null, 2) + "\n");
|
|
114
|
+
return { ok: true, changed: true, file, message: `Plugin quitado de ${file}.` };
|
|
115
|
+
}
|
|
116
|
+
/** Crea un .aeg.json mínimo en el proyecto (no sobrescribe). */
|
|
117
|
+
export function init(projectDir) {
|
|
118
|
+
const file = path.join(projectDir, ".aeg.json");
|
|
119
|
+
if (fs.existsSync(file))
|
|
120
|
+
return { ok: true, changed: false, file, message: `${file} ya existe.` };
|
|
121
|
+
fs.writeFileSync(file, JSON.stringify({ mode: "block", maxConsecutiveRepeats: 3, stagnationRepeats: 3 }, null, 2) + "\n");
|
|
122
|
+
return { ok: true, changed: true, file, message: `Creado ${file}.` };
|
|
123
|
+
}
|
|
@@ -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 ? "🛑 [AEG PARADA DURA]" : "🛑 [AEG 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
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ResolvedConfig, Verdict } from "./types.js";
|
|
2
|
+
/** Normaliza a ruta relativa al proyecto con "/". Devuelve null si queda fuera de la raíz. */
|
|
3
|
+
export declare function toRel(root: string, p: string): string | null;
|
|
4
|
+
/** Valida UNA ruta que se va a escribir. */
|
|
5
|
+
export declare function checkPath(cfg: ResolvedConfig, p: string): Verdict;
|
|
6
|
+
export declare function checkPaths(cfg: ResolvedConfig, paths: string[]): Verdict;
|
|
7
|
+
/** Rutas que toca una llamada de escritura. Para edit/write/patch es exacto. */
|
|
8
|
+
export declare function writtenPaths(tool: string, args: Record<string, unknown>): string[];
|
|
9
|
+
/**
|
|
10
|
+
* Mejor esfuerzo sobre bash: redirecciones y comandos de escritura obvios.
|
|
11
|
+
* NO es una garantía (variables, scripts, subshells lo evaden): la red de seguridad
|
|
12
|
+
* fiable es `git diff` al terminar el turno (ver gitViolations).
|
|
13
|
+
*/
|
|
14
|
+
export declare function bashWrites(command: string): string[];
|
|
15
|
+
/** Archivos modificados según git, fuera del alcance de la fase. */
|
|
16
|
+
export declare function gitViolations(cfg: ResolvedConfig, changed: string[]): string[];
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { matchAny } from "./glob.js";
|
|
4
|
+
/** realpath del ancestro existente más profundo (resuelve symlinks aunque el archivo aún no exista). */
|
|
5
|
+
function realish(abs) {
|
|
6
|
+
let cur = abs;
|
|
7
|
+
const tail = [];
|
|
8
|
+
for (;;) {
|
|
9
|
+
try {
|
|
10
|
+
return path.join(fs.realpathSync(cur), ...tail);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
const parent = path.dirname(cur);
|
|
14
|
+
if (parent === cur)
|
|
15
|
+
return abs;
|
|
16
|
+
tail.unshift(path.basename(cur));
|
|
17
|
+
cur = parent;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Normaliza a ruta relativa al proyecto con "/". Devuelve null si queda fuera de la raíz. */
|
|
22
|
+
export function toRel(root, p) {
|
|
23
|
+
const realRoot = realish(root);
|
|
24
|
+
const abs = realish(path.resolve(root, p));
|
|
25
|
+
const rel = path.relative(realRoot, abs);
|
|
26
|
+
if (rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel))
|
|
27
|
+
return null;
|
|
28
|
+
return rel.split(path.sep).join("/");
|
|
29
|
+
}
|
|
30
|
+
/** Valida UNA ruta que se va a escribir. */
|
|
31
|
+
export function checkPath(cfg, p) {
|
|
32
|
+
const rel = toRel(cfg.root, p);
|
|
33
|
+
if (rel === null)
|
|
34
|
+
return { blocked: true, reason: `"${p}" está fuera del proyecto` };
|
|
35
|
+
if (matchAny(rel, cfg.protectedGlobs))
|
|
36
|
+
return { blocked: true, reason: `"${rel}" es un archivo protegido del guardián` };
|
|
37
|
+
if (matchAny(rel, cfg.scope.denyGlobs))
|
|
38
|
+
return { blocked: true, reason: `"${rel}" está prohibido en esta fase (denyGlobs)` };
|
|
39
|
+
const allow = cfg.scope.allowOnlyGlobs;
|
|
40
|
+
if (allow.length && !matchAny(rel, allow)) {
|
|
41
|
+
return { blocked: true, reason: `"${rel}" no está en el alcance de esta fase (allowOnlyGlobs: ${allow.join(", ")})` };
|
|
42
|
+
}
|
|
43
|
+
return { blocked: false };
|
|
44
|
+
}
|
|
45
|
+
export function checkPaths(cfg, paths) {
|
|
46
|
+
for (const p of paths) {
|
|
47
|
+
const v = checkPath(cfg, p);
|
|
48
|
+
if (v.blocked)
|
|
49
|
+
return v;
|
|
50
|
+
}
|
|
51
|
+
return { blocked: false };
|
|
52
|
+
}
|
|
53
|
+
/** Rutas que toca una llamada de escritura. Para edit/write/patch es exacto. */
|
|
54
|
+
export function writtenPaths(tool, args) {
|
|
55
|
+
const out = [];
|
|
56
|
+
const f = args.filePath ?? args.file_path ?? args.path;
|
|
57
|
+
if (typeof f === "string")
|
|
58
|
+
out.push(f);
|
|
59
|
+
if (tool === "patch") {
|
|
60
|
+
const text = String(args.patchText ?? args.patch ?? args.diff ?? "");
|
|
61
|
+
// formato "*** Update/Add/Delete File: x" y diff unificado (--- a/x / +++ b/x)
|
|
62
|
+
for (const m of text.matchAll(/^\*\*\* (?:Update|Add|Delete) File:\s*(.+)$/gm))
|
|
63
|
+
out.push(m[1].trim());
|
|
64
|
+
for (const m of text.matchAll(/^\+\+\+ (?:b\/)?(\S+)/gm))
|
|
65
|
+
if (m[1] !== "/dev/null")
|
|
66
|
+
out.push(m[1]);
|
|
67
|
+
for (const m of text.matchAll(/^--- (?:a\/)?(\S+)/gm))
|
|
68
|
+
if (m[1] !== "/dev/null")
|
|
69
|
+
out.push(m[1]);
|
|
70
|
+
}
|
|
71
|
+
return [...new Set(out)];
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Mejor esfuerzo sobre bash: redirecciones y comandos de escritura obvios.
|
|
75
|
+
* NO es una garantía (variables, scripts, subshells lo evaden): la red de seguridad
|
|
76
|
+
* fiable es `git diff` al terminar el turno (ver gitViolations).
|
|
77
|
+
*/
|
|
78
|
+
export function bashWrites(command) {
|
|
79
|
+
const out = [];
|
|
80
|
+
const clean = (s) => s.replace(/^["']|["']$/g, "");
|
|
81
|
+
for (const m of command.matchAll(/(?:^|[^>&0-9])>>?\s*(?!&)([^\s;|&<>()]+)/g))
|
|
82
|
+
out.push(clean(m[1]));
|
|
83
|
+
for (const m of command.matchAll(/\btee\s+(?:-[a-z]+\s+)*([^\s;|&<>]+)/g))
|
|
84
|
+
out.push(clean(m[1]));
|
|
85
|
+
for (const m of command.matchAll(/\bsed\s+(?:-[A-Za-z]*i[A-Za-z]*(?:\.\w+)?\s+)(?:-e\s+)?(?:'[^']*'|"[^"]*"|\S+)\s+([^\s;|&]+)/g))
|
|
86
|
+
out.push(clean(m[1]));
|
|
87
|
+
for (const m of command.matchAll(/\b(?:rm|touch|mkdir|rmdir|truncate)\s+((?:-\S+\s+)*)([^;|&<>]+)/g)) {
|
|
88
|
+
for (const t of m[2].trim().split(/\s+/))
|
|
89
|
+
if (!t.startsWith("-"))
|
|
90
|
+
out.push(clean(t));
|
|
91
|
+
}
|
|
92
|
+
for (const m of command.matchAll(/\b(?:mv|cp)\s+((?:-\S+\s+)*)([^;|&<>]+)/g)) {
|
|
93
|
+
const toks = m[2].trim().split(/\s+/).filter((t) => !t.startsWith("-"));
|
|
94
|
+
if (toks.length)
|
|
95
|
+
out.push(clean(toks[toks.length - 1])); // destino
|
|
96
|
+
if (/^\s*mv/.test(m[0]))
|
|
97
|
+
toks.slice(0, -1).forEach((t) => out.push(clean(t))); // origen desaparece
|
|
98
|
+
}
|
|
99
|
+
return [...new Set(out.filter((p) => p && !p.startsWith("/dev/") && !/^\$/.test(p)))];
|
|
100
|
+
}
|
|
101
|
+
/** Archivos modificados según git, fuera del alcance de la fase. */
|
|
102
|
+
export function gitViolations(cfg, changed) {
|
|
103
|
+
return changed.filter((p) => {
|
|
104
|
+
const rel = toRel(cfg.root, p);
|
|
105
|
+
if (rel === null)
|
|
106
|
+
return true;
|
|
107
|
+
if (matchAny(rel, cfg.protectedGlobs))
|
|
108
|
+
return false; // archivos del guardián: los edita el humano
|
|
109
|
+
if (matchAny(rel, cfg.scope.denyGlobs))
|
|
110
|
+
return true;
|
|
111
|
+
const allow = cfg.scope.allowOnlyGlobs;
|
|
112
|
+
return allow.length > 0 && !matchAny(rel, allow);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
export type Mode = "block" | "warn";
|
|
2
|
+
export interface ScopeRules {
|
|
3
|
+
denyGlobs: string[];
|
|
4
|
+
allowOnlyGlobs: string[];
|
|
5
|
+
}
|
|
6
|
+
/** Contenido de .aeg.json (todo opcional: sin archivo, solo corre el anti-bucles). */
|
|
7
|
+
export interface AegConfig {
|
|
8
|
+
mode?: Mode;
|
|
9
|
+
/** Repeticiones consecutivas idénticas (sin progreso) que disparan el bloqueo. */
|
|
10
|
+
maxConsecutiveRepeats?: number;
|
|
11
|
+
/** Umbrales por herramienta, p. ej. { "read": 4, "bash": 3 }. */
|
|
12
|
+
toolThresholds?: Record<string, number>;
|
|
13
|
+
/** Periodo máximo de ciclo a detectar (2 = A-B-A-B, 3 = A-B-C-A-B-C). */
|
|
14
|
+
cycleMaxPeriod?: number;
|
|
15
|
+
/** Salidas idénticas seguidas (misma familia de comando) que indican estancamiento. */
|
|
16
|
+
stagnationRepeats?: number;
|
|
17
|
+
/** Tamaño de la ventana deslizante de historial por sesión. */
|
|
18
|
+
window?: number;
|
|
19
|
+
/** Bloqueos acumulados en una sesión tras los cuales el mensaje pasa a "parada dura". */
|
|
20
|
+
hardStopAfter?: number;
|
|
21
|
+
activeSpecFile?: string;
|
|
22
|
+
scope?: Partial<ScopeRules>;
|
|
23
|
+
/** Globs adicionales que el agente nunca puede escribir. */
|
|
24
|
+
protectedGlobs?: string[];
|
|
25
|
+
}
|
|
26
|
+
/** Frontmatter de .engram/specs/phase-XX.md */
|
|
27
|
+
export interface PhaseSpec {
|
|
28
|
+
id?: string;
|
|
29
|
+
goal?: string;
|
|
30
|
+
scope?: Partial<ScopeRules>;
|
|
31
|
+
exitCriteria?: string[];
|
|
32
|
+
}
|
|
33
|
+
export interface ResolvedConfig {
|
|
34
|
+
root: string;
|
|
35
|
+
mode: Mode;
|
|
36
|
+
maxConsecutiveRepeats: number;
|
|
37
|
+
toolThresholds: Record<string, number>;
|
|
38
|
+
cycleMaxPeriod: number;
|
|
39
|
+
stagnationRepeats: number;
|
|
40
|
+
window: number;
|
|
41
|
+
hardStopAfter: number;
|
|
42
|
+
scope: ScopeRules;
|
|
43
|
+
protectedGlobs: string[];
|
|
44
|
+
specFile?: string;
|
|
45
|
+
phase?: PhaseSpec;
|
|
46
|
+
/** Errores de configuración: el guardián sigue activo y los reporta. */
|
|
47
|
+
warnings: string[];
|
|
48
|
+
}
|
|
49
|
+
export interface CallEntry {
|
|
50
|
+
sig: string;
|
|
51
|
+
tool: string;
|
|
52
|
+
/** Época de escritura: sube cada vez que una herramienta de escritura termina bien. */
|
|
53
|
+
epoch: number;
|
|
54
|
+
/** Familia del comando: tool, y para bash el primer programa (p. ej. "bash:rtk"). */
|
|
55
|
+
family?: string;
|
|
56
|
+
resultHash?: string;
|
|
57
|
+
resultLen?: number;
|
|
58
|
+
/** Primeros caracteres de la salida, para citarla en el mensaje de bloqueo. */
|
|
59
|
+
snippet?: string;
|
|
60
|
+
}
|
|
61
|
+
export interface SessionState {
|
|
62
|
+
epoch: number;
|
|
63
|
+
/** Bloqueos totales (informativo). */
|
|
64
|
+
blocks: number;
|
|
65
|
+
/** Bloqueos por bucle: solo estos escalan a parada dura. */
|
|
66
|
+
loopBlocks?: number;
|
|
67
|
+
entries: CallEntry[];
|
|
68
|
+
}
|
|
69
|
+
export interface Verdict {
|
|
70
|
+
blocked: boolean;
|
|
71
|
+
reason?: string;
|
|
72
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adayacas/loopbreaker",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Loop breaker y guardián de alcance para agentes de OpenCode: corta bucles de herramientas y limita lo que el agente puede escribir por fase.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/src/index.js",
|
|
7
|
+
"types": "dist/src/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./dist/src/index.js"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"loopbreaker": "dist/src/cli.js",
|
|
13
|
+
"aeg": "dist/src/cli.js"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist/src",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc -p tsconfig.json",
|
|
22
|
+
"test": "tsc -p tsconfig.json && node --test \"dist/test/*.test.js\"",
|
|
23
|
+
"prepublishOnly": "rm -rf dist && npm test && tsc -p tsconfig.build.json"
|
|
24
|
+
},
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"@opencode-ai/plugin": "*"
|
|
27
|
+
},
|
|
28
|
+
"peerDependenciesMeta": {
|
|
29
|
+
"@opencode-ai/plugin": {
|
|
30
|
+
"optional": true
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"typescript": "^5.6.0",
|
|
35
|
+
"@types/node": "^22.0.0"
|
|
36
|
+
},
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=18"
|
|
40
|
+
},
|
|
41
|
+
"keywords": [
|
|
42
|
+
"opencode",
|
|
43
|
+
"opencode-plugin",
|
|
44
|
+
"agent",
|
|
45
|
+
"loop-detection",
|
|
46
|
+
"circuit-breaker",
|
|
47
|
+
"guardrails",
|
|
48
|
+
"scope"
|
|
49
|
+
],
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
}
|
|
53
|
+
}
|