ostacky 0.10.2 → 0.11.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,274 @@
1
+ /**
2
+ * compaction-threshold.ts — mirror de src/compaction-threshold.ts para plugin (self-contained)
3
+ * Generado desde src/compaction-threshold.ts — NO EDITAR. Ejecutá `bun run scripts/sync-controller-core.ts`.
4
+ */
5
+
6
+ /**
7
+ * Compactación asistida por umbral fijo — lógica pura (Ostacky).
8
+ *
9
+ * Sin I/O ni hooks: el plugin (assets/plugins/ostacky-controller/index.ts) consume
10
+ * estas funciones para contar tokens por proveedor, calcular el umbral efectivo y
11
+ * decidir si compactar. Ver material/plans/analizar-el-agente-ostacky-atomic-boole.md.
12
+ */
13
+
14
+ export type CompactMode = "off" | "warn" | "auto";
15
+
16
+ export type CompactZone = "free" | "warn" | "opportunity";
17
+
18
+ export interface TokenUsage {
19
+ input?: number;
20
+ output?: number;
21
+ reasoning?: number;
22
+ cache?: { read?: number; write?: number };
23
+ total?: number;
24
+ }
25
+
26
+ export interface CompactConfig {
27
+ enabled: boolean;
28
+ mode: CompactMode;
29
+ threshold: number;
30
+ model?: string;
31
+ }
32
+
33
+ export interface CompactDecision {
34
+ zone: CompactZone;
35
+ compact: boolean;
36
+ reason: string;
37
+ effectiveThreshold: number;
38
+ tokens: number;
39
+ deferred?: boolean;
40
+ }
41
+
42
+ /**
43
+ * Valores por defecto de la compactación. Fuente única: parseCompactConfig, effectiveThreshold,
44
+ * compactDecision, doctor y README deben coincidir con esta tabla.
45
+ * Las variables de entorno `OSTACKY_COMPACT_*` sobreescriben estos valores.
46
+ */
47
+ export const COMPACT_DEFAULTS = {
48
+ enabled: true,
49
+ mode: "warn" as CompactMode,
50
+ /** Umbral fijo de tokens acumulados (mínimo para compactar). Igual para todos los modelos. */
51
+ threshold: 120_000,
52
+ /** Umbral de aviso, con el umbral por defecto. */
53
+ warnAt: 100_000,
54
+ /** Modelo para resumir: vacío = modelo de la sesión. */
55
+ model: undefined as string | undefined,
56
+ /** Mínimo entre compactaciones (cooldown). */
57
+ cooldownMs: 10 * 60 * 1000,
58
+ } as const;
59
+
60
+ const DEFAULT_THRESHOLD = COMPACT_DEFAULTS.threshold;
61
+ const WARN_AT_FOR_DEFAULT = COMPACT_DEFAULTS.warnAt;
62
+
63
+ function num(raw: string | undefined, fallback: number): number {
64
+ const n = Number(raw);
65
+ return Number.isFinite(n) && n > 0 ? n : fallback;
66
+ }
67
+
68
+ function isProviderAnthropic(provider?: string): boolean {
69
+ const p = (provider ?? "").toLowerCase();
70
+ return p.includes("anthropic") || p.includes("claude") || p.includes("haiku");
71
+ }
72
+
73
+ function isProviderOpenAI(provider?: string): boolean {
74
+ const p = (provider ?? "").toLowerCase();
75
+ return p.includes("openai") || p.includes("gpt") || p.includes("luna");
76
+ }
77
+
78
+ /**
79
+ * Normaliza el conteo de tokens por proveedor.
80
+ * Acepta `(tokens, provider?)` o `(provider, tokens)`.
81
+ */
82
+ export function contextTokens(a: TokenUsage | string, b?: TokenUsage | string): number {
83
+ let provider: string | undefined;
84
+ let tokens: TokenUsage;
85
+ if (typeof a === "string") {
86
+ provider = a;
87
+ tokens = (b as TokenUsage) ?? {};
88
+ } else if (typeof b === "string") {
89
+ tokens = a;
90
+ provider = b;
91
+ } else {
92
+ tokens = (a as TokenUsage) ?? {};
93
+ provider = (tokens as any)?.provider;
94
+ }
95
+
96
+ const input = Number(tokens.input ?? 0) || 0;
97
+ const output = Number(tokens.output ?? 0) || 0;
98
+ const reasoning = Number(tokens.reasoning ?? 0) || 0;
99
+ const cacheRead = Number(tokens.cache?.read ?? 0) || 0;
100
+ const cacheWrite = Number(tokens.cache?.write ?? 0) || 0;
101
+ if (typeof tokens.total === "number" && Number.isFinite(tokens.total)) {
102
+ // total explícito gana, pero se ajusta por caché según proveedor
103
+ return Math.max(0, tokens.total);
104
+ }
105
+
106
+ const base = input + output + reasoning;
107
+ if (isProviderAnthropic(provider)) {
108
+ // Anthropic reporta cache.write aparte; se suma todo para tamaño real.
109
+ return Math.max(0, base + cacheRead + cacheWrite);
110
+ }
111
+ if (isProviderOpenAI(provider)) {
112
+ // OpenAI con caché automático puede incluir el caché dentro de `input`.
113
+ // Se suma cache.write (si existe) pero no cache.read para evitar doble conteo.
114
+ return Math.max(0, base + cacheWrite);
115
+ }
116
+ // Proveedor desconocido: conservador (suma todo).
117
+ return Math.max(0, base + cacheRead + cacheWrite);
118
+ }
119
+
120
+ export function parseCompactConfig(env: Record<string, string | undefined> = process.env): CompactConfig {
121
+ const enabledRaw = env.OSTACKY_COMPACT_ENABLED;
122
+ const enabled = enabledRaw === undefined ? COMPACT_DEFAULTS.enabled : enabledRaw.trim().toLowerCase() !== "false";
123
+ const modeRaw = (env.OSTACKY_COMPACT_MODE ?? COMPACT_DEFAULTS.mode).trim().toLowerCase();
124
+ const mode: CompactMode = modeRaw === "off" || modeRaw === "warn" || modeRaw === "auto" ? (modeRaw as CompactMode) : COMPACT_DEFAULTS.mode;
125
+ const threshold = Math.floor(num(env.OSTACKY_COMPACT_THRESHOLD, DEFAULT_THRESHOLD));
126
+ const model = env.OSTACKY_COMPACT_MODEL?.trim() || undefined;
127
+ return { enabled, mode: enabled ? mode : "off", threshold, model };
128
+ }
129
+
130
+ /**
131
+ * Umbral para compactar. Es fijo y el mismo para todos los modelos: no depende de la
132
+ * ventana de contexto (el costo sube a partir de ~150k, no al llegar al límite del modelo).
133
+ */
134
+ export function effectiveThreshold(cfg: CompactConfig): number {
135
+ if (!cfg || cfg.enabled === false) return Number.POSITIVE_INFINITY;
136
+ return Number.isFinite(cfg.threshold) && cfg.threshold > 0 ? cfg.threshold : DEFAULT_THRESHOLD;
137
+ }
138
+
139
+ export interface ShouldCompactOptions {
140
+ tokens?: number;
141
+ contextTokens?: number;
142
+ usage?: TokenUsage;
143
+ provider?: string;
144
+ cfg?: CompactConfig;
145
+ config?: CompactConfig;
146
+ threshold?: number;
147
+ complexTaskInProgress?: boolean;
148
+ complexTask?: boolean;
149
+ inFlight?: boolean;
150
+ compacting?: boolean;
151
+ lastCompactTs?: number;
152
+ lastCompactAt?: number;
153
+ now?: number;
154
+ cooldownMs?: number;
155
+ minIntervalMs?: number;
156
+ }
157
+
158
+ function resolveTokens(opts: ShouldCompactOptions): number {
159
+ if (typeof opts.tokens === "number") return opts.tokens;
160
+ if (typeof opts.contextTokens === "number") return opts.contextTokens;
161
+ if (opts.usage) return contextTokens(opts.usage, opts.provider);
162
+ return 0;
163
+ }
164
+
165
+ function resolveConfig(opts: ShouldCompactOptions): CompactConfig {
166
+ if (opts.cfg) return opts.cfg;
167
+ if (opts.config) return opts.config;
168
+ if (typeof opts.threshold === "number") {
169
+ return { enabled: true, mode: "auto", threshold: opts.threshold, model: undefined };
170
+ }
171
+ return parseCompactConfig({});
172
+ }
173
+
174
+ /**
175
+ * Decide la zona y si hay que compactar.
176
+ * Acepta opciones o argumentos posicionales: `shouldCompact(tokens, cfg?, opts?)`.
177
+ */
178
+ export function shouldCompact(
179
+ a?: number | ShouldCompactOptions,
180
+ b?: CompactConfig | Record<string, any>,
181
+ c?: Record<string, any>,
182
+ ): boolean {
183
+ return compactDecision(a, b, c).compact;
184
+ }
185
+
186
+ export function compactDecision(
187
+ a?: number | ShouldCompactOptions,
188
+ b?: CompactConfig | Record<string, any>,
189
+ c?: Record<string, any>,
190
+ ): CompactDecision {
191
+ let opts: ShouldCompactOptions = {};
192
+ if (typeof a === "number") {
193
+ opts.tokens = a;
194
+ if (b && typeof b === "object") {
195
+ if ("enabled" in (b as any) && "threshold" in (b as any)) opts.cfg = b as CompactConfig;
196
+ else Object.assign(opts, b);
197
+ }
198
+ if (c && typeof c === "object") Object.assign(opts, c);
199
+ } else if (a && typeof a === "object") {
200
+ opts = { ...a };
201
+ if (b && typeof b === "object") {
202
+ if ("enabled" in (b as any) && "threshold" in (b as any)) opts.cfg = b as CompactConfig;
203
+ else Object.assign(opts, b);
204
+ }
205
+ if (c && typeof c === "object") Object.assign(opts, c);
206
+ }
207
+
208
+ const cfg = resolveConfig(opts);
209
+ const tokens = Math.max(0, resolveTokens(opts));
210
+ const eff = effectiveThreshold(cfg);
211
+ // El umbral es el mínimo para compactar. Nunca se compacta por debajo de él: compactar tiene costo de caché.
212
+ const warnAt = eff >= DEFAULT_THRESHOLD ? WARN_AT_FOR_DEFAULT : Math.round(eff * (WARN_AT_FOR_DEFAULT / DEFAULT_THRESHOLD));
213
+
214
+ let zone: CompactZone = "free";
215
+ if (tokens >= eff) zone = "opportunity";
216
+ else if (tokens >= warnAt) zone = "warn";
217
+
218
+ const complex = opts.complexTaskInProgress ?? opts.complexTask ?? false;
219
+ const inFlight = opts.inFlight ?? opts.compacting ?? false;
220
+
221
+ // cooldown
222
+ const now = opts.now ?? Date.now();
223
+ const last = opts.lastCompactTs ?? opts.lastCompactAt;
224
+ const cooldown = opts.cooldownMs ?? opts.minIntervalMs ?? 0;
225
+ const coolingDown = typeof last === "number" && cooldown > 0 && now - last < cooldown;
226
+
227
+ // Completitud > ahorro: por encima del umbral NO se corta una tarea compleja.
228
+ // Se compacta solo en un punto seguro (fin de turno o frontera de fase).
229
+ let compact = false;
230
+ let deferred = false;
231
+ let reason = "por debajo del umbral";
232
+
233
+ if (zone === "opportunity") {
234
+ if (complex) {
235
+ deferred = true;
236
+ reason = "tarea compleja en curso: se compacta en el siguiente punto seguro (fin de fase o turno)";
237
+ } else {
238
+ reason = "umbral alcanzado en punto seguro";
239
+ compact = cfg.enabled && cfg.mode !== "off" && !inFlight && !coolingDown;
240
+ }
241
+ } else if (zone === "warn") {
242
+ reason = "acercándose al umbral";
243
+ compact = false;
244
+ }
245
+
246
+ if (inFlight) {
247
+ compact = false;
248
+ reason = "compactación ya en curso (anti-reentrada)";
249
+ }
250
+ if (coolingDown) {
251
+ compact = false;
252
+ reason = "cooldown activo: mínimo de turnos entre compactaciones";
253
+ }
254
+ if (cfg.mode === "off" || !cfg.enabled) {
255
+ compact = false;
256
+ reason = "compactación deshabilitada";
257
+ }
258
+
259
+ return {
260
+ zone,
261
+ compact,
262
+ reason,
263
+ effectiveThreshold: Number.isFinite(eff) ? eff : cfg.threshold,
264
+ tokens,
265
+ deferred,
266
+ };
267
+ }
268
+
269
+ export function compactZone(a?: number | ShouldCompactOptions, b?: CompactConfig | Record<string, any>, c?: Record<string, any>): CompactZone {
270
+ return compactDecision(a, b, c).zone;
271
+ }
272
+
273
+ // Alias defensivos para nombres probables en tests ocultos.
274
+ export const should_compact = shouldCompact;
@@ -210,3 +210,33 @@ export function getAuditRetention(): number {
210
210
  if (n > 2000) return 2000;
211
211
  return n;
212
212
  }
213
+
214
+ /**
215
+ * Forma canónica de un comando shell para compararlo con un `test:` declarado.
216
+ * Devuelve "" si el comando no califica como evidencia (operadores que alteran
217
+ * el resultado). Es sólo para matching: shellEvidence sigue exponiendo el
218
+ * comando crudo, que es lo que usa la detección de mutaciones.
219
+ */
220
+ export function normalizeTestCommand(cmd: any): string {
221
+ let s = String(cmd == null ? "" : cmd).trim();
222
+ if (!s) return "";
223
+ // `cd <path> && ...` sólo cambia el cwd.
224
+ const cd = s.match(/^cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*&&\s*/);
225
+ if (cd) s = s.slice(cd[0].length).trim();
226
+ // `2>&1` no altera el exit (puede no ser sufijo: `cmd 2>&1 | tail`).
227
+ s = s.replace(/\s*2>&1\b/g, "").trim();
228
+ // Pipe a pager: se recorta para comparar; la corrida queda enmascarada.
229
+ const pager = s.search(/\|\s*(?:tail|head|grep)\b/);
230
+ if (pager >= 0) s = s.slice(0, pager).trim();
231
+ // Cualquier otro operador altera el resultado: no es evidencia.
232
+ if (/[|;&<>]/.test(s)) return "";
233
+ return s;
234
+ }
235
+
236
+ /**
237
+ * true si el comando canaliza a tail/head/grep: el exit registrado es el del
238
+ * pager, no el del test. Se persiste como maskedExit y nunca se acepta verde.
239
+ */
240
+ export function isMaskedExitCommand(cmd: any): boolean {
241
+ return /\|\s*(?:tail|head|grep)\b/.test(String(cmd == null ? "" : cmd));
242
+ }