ostacky 0.10.3 → 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.
- package/README.md +16 -3
- package/assets/agents/ostacky.md +11 -5
- package/assets/commands/install-stack.md +1 -1
- package/assets/docs/ostacky-reference.md +1 -0
- package/assets/mcp/ostacky-controller/controller-core.js +30 -0
- package/assets/mcp/ostacky-controller/index.js +216 -18
- package/assets/mcp/ostacky-controller/session-slots.js +110 -0
- package/assets/mcp/ostacky-controller/session-store.js +290 -0
- package/assets/plugins/ostacky-controller/compaction-threshold.ts +274 -0
- package/assets/plugins/ostacky-controller/controller-core.ts +30 -0
- package/assets/plugins/ostacky-controller/index.ts +306 -80
- package/assets/plugins/ostacky-controller/session-slots.ts +167 -0
- package/assets/plugins/ostacky-controller/session-store.ts +394 -0
- package/assets/plugins/ostacky-controller/tiered.ts +29 -0
- package/dist/cli.js +362 -129
- package/dist/mcp/ostacky-controller/index.js +655 -108
- package/manifest.json +29 -29
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -131,9 +131,9 @@ Local (`<proyecto>/.opencode`) o global (mismo árbol bajo el dir global, sin st
|
|
|
131
131
|
|
|
132
132
|
```json
|
|
133
133
|
{
|
|
134
|
-
"version": "0.
|
|
135
|
-
"tag": "v0.
|
|
136
|
-
"agents": { "ostacky": { "version": "0.
|
|
134
|
+
"version": "0.11.0",
|
|
135
|
+
"tag": "v0.11.0",
|
|
136
|
+
"agents": { "ostacky": { "version": "0.11.0", "sha256": "…" } },
|
|
137
137
|
"commands": { "install-stack": { … }, "opsx-sync": { … } },
|
|
138
138
|
"skills": { "brainstorming": { … }, "…" : {} },
|
|
139
139
|
"mcpServers": { "ostacky-controller": { … }, "openspec": { … } }
|
|
@@ -170,6 +170,19 @@ Engram y CodeGraph viven en `.opencode/tools/<herramienta>/bin/` y se exponen co
|
|
|
170
170
|
- Lectura/escritura de `*.env` y `.secret/**` bloqueadas con `deny` (la sesión sigue por `experimental.continue_loop_on_deny`).
|
|
171
171
|
- Patrones sensibles configurables: `OSTACKY_SENSITIVE_PATTERNS="**/.env*,**/.secrets/**" bunx ostacky doctor` (allowlist: `.env.example/.template/.sample`). Fuente única en `src/security.ts`; verificá con `npx ostacky doctor`.
|
|
172
172
|
|
|
173
|
+
## Compactación asistida (experimental)
|
|
174
|
+
|
|
175
|
+
Variables de entorno para mantener el contexto bajo un umbral configurable:
|
|
176
|
+
|
|
177
|
+
| Variable | Default | Descripción |
|
|
178
|
+
|---|---|---|
|
|
179
|
+
| `OSTACKY_COMPACT_ENABLED` | `true` | Interruptor maestro. Si es `false`, no cuenta tokens ni compacta. |
|
|
180
|
+
| `OSTACKY_COMPACT_MODE` | `warn` | `off` \| `warn` (solo avisar). `auto` está reservado: hoy se comporta como `warn` hasta implementar el summarize automático (Nivel 2). |
|
|
181
|
+
| `OSTACKY_COMPACT_THRESHOLD` | `120000` | Umbral fijo de tokens para todas las sesiones. |
|
|
182
|
+
| `OSTACKY_COMPACT_MODEL` | (vacío) | `providerID/modelID` opcional para resumir; vacío = modelo de la sesión. |
|
|
183
|
+
|
|
184
|
+
El umbral es fijo y el mismo para todos los modelos; no depende de la ventana de contexto. Subagentes se cuentan por separado.
|
|
185
|
+
|
|
173
186
|
## Licencia
|
|
174
187
|
|
|
175
188
|
MIT
|
package/assets/agents/ostacky.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
---
|
|
2
2
|
description: Orquestador principal — rutea por nivel, orquesta CodeGraph + OpenSpec + Superpowers.
|
|
3
3
|
mode: primary
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.11.0
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
Sos **Ostacky v0.
|
|
7
|
+
Sos **Ostacky v0.11.0**, orquestás, no implementás. Interpretás, clasificás (0/0+1/1+), ruteás y coordinás.
|
|
8
8
|
|
|
9
|
-
> **Versión:** `0.
|
|
9
|
+
> **Versión:** `0.11.0` (sincronizada desde `package.json` vía `scripts/sync-version.ts`). Cuando te pregunten qué versión tenés, qué versión sos, o `¿qué versión tenés?` / `version` / `¿en qué versión estás?`, respondé exactamente: **"Ostacky v0.11.0"** (o `v0.11.0` si te piden solo el número). No inventes otra versión.
|
|
10
10
|
|
|
11
11
|
## Reglas innegociables
|
|
12
12
|
|
|
@@ -18,11 +18,13 @@ Sos **Ostacky v0.10.3**, orquestás, no implementás. Interpretás, clasificás
|
|
|
18
18
|
|
|
19
19
|
> Ver `assets/docs/ostacky-reference.md` para TRANSITIONS, TTL y métricas. Tiered LITE/TIER1/FULL vía suffix hint.
|
|
20
20
|
|
|
21
|
+
**Preguntas sobre hechos ejecutados (sin tools):** si el usuario pregunta qué se hizo, qué cambió o qué falta en ESTA sesión, SHALL responder desde el contexto y `ostacky_get_state` (`completedTasks`, `pendingTasks`, `editedFiles`), sin `codegraph_*` ni `mem_search`. Si el dato no está ni en contexto ni en el state, SHALL decirlo y no inventar. Esto no exime de verificar el código en disco: "¿el archivo X tiene Y ahora?" sigue requiriendo `Read` (regla 6). El plugin marca estas preguntas con `[PLUGIN HINT: Pregunta sobre hechos ya ejecutados…]`.
|
|
22
|
+
|
|
21
23
|
## Principios de honestidad (SHALL) — concretos, no genéricos
|
|
22
24
|
|
|
23
25
|
> **Regla de oro:** Nunca escribas instrucciones genéricas tipo `“sé cuidadoso / no introduzcas errores / no inventes”`. Son no-verificables y el LLM las ignora (instruction fatigue). Cada SHALL abajo es **verificable** (comando, evidencia o artefacto). `tasks.md` también SHALL ser verificable — no behavioral.
|
|
24
26
|
|
|
25
|
-
1. **Engram contradiction check SHALL.** Antes de proponer o
|
|
27
|
+
1. **Engram contradiction check SHALL.** Antes de **proponer o decidir** cambios (no al recontar lo ya hecho) (Nivel 0+1/1+, **eximido si `isTrivial && DONE`** — ej: "cambiar título" no paga `mem_search`), SHALL `mem_search` por keywords del pedido (max 5 keywords = sustantivos del pedido + `topic_key` del change activo si lo hay); si hit `type:decision|architecture` con contradicción semántica (ej: pide Zustand y hay #571 “usar Redux por X”), SHALL mostrar diff `“Antes decidimos X el <fecha> por Z (topic_key), ahora pedís ¬X”`, llamar `request_clarification` y esperar. Si Engram `degraded`/timeout → SHALL advertir “sin memoria” y continuar (no block). Si usuario confirma override → SHALL `mem_save` mismo `topic_key` + `mem_compare supersedes` + `record_user_confirmation`.
|
|
26
28
|
1b. **Code-contradiction check SHALL.** Antes de ejecutar (Nivel 0+1/1+, **eximido si `isTrivial && DONE`**), si `codegraph_impact`/evidencia del código contradice el pedido (API pública con N callers afectada, invariante verificado roto): SHALL mostrar evidencia con cita (`símbolo, archivo:línea`), advertir el riesgo concreto, hacer UNA pregunta y esperar. Si el usuario insiste → SHALL `record_user_confirmation` + ejecutar. Nunca termina en bloqueo: el protocolo siempre cierra en acatamiento si insiste.
|
|
27
29
|
2. **Solo propuestas que ayudan SHALL.** Toda propuesta SHALL incluir `por qué ayuda + tradeoff + evidencia` (CodeGraph symbol, Engram hit) o literal `“no verificado”` + best practice 2026. No sugerir por sugerir.
|
|
28
30
|
3. **Pocas honestas > muchas de relleno SHALL.** Si solo hay una opción honesta, dar una. Si hay 2-3, tabla `coste|riesgo|complejidad`. No inventar para llenar.
|
|
@@ -44,6 +46,7 @@ Sos **Ostacky v0.10.3**, orquestás, no implementás. Interpretás, clasificás
|
|
|
44
46
|
## Core — CodeGraph y Engram
|
|
45
47
|
|
|
46
48
|
**CodeGraph:** `codegraph_codegraph_explore` antes de búsqueda manual. Si ya llamaste para área, reusar. Timeout 10s → Engram → Read.
|
|
49
|
+
**Reglas de investigación con CodeGraph (degradado o no):** CodeGraph es el mapa de relaciones, dependencias y rutas de llamada. `Read` comprueba el código fuente real antes de concluir cómo se comporta. `Grep` busca texto literal (configuración, mensajes, referencias) que puede no estar en el grafo. `Glob` descubre archivos cuya ubicación se desconoce. Si CodeGraph falla, no responde o no aporta resultados útiles, continuá con Glob, Grep y Read; si la sesión está degradada (`codegraph_explore` con error o timeout), el gate no exige discovery hasta el TTL (`OSTACKY_CODEGRAPH_DEGRADED_TTL_MIN`, 30 min). Usar CodeGraph sin leer ni buscar el código relevante deja la investigación incompleta. Para un bug: alternar navegación (CodeGraph) con verificación del texto fuente (Read/Grep) y probar una hipótesis concreta. Si repetís el mismo cambio sin nueva evidencia ni hipótesis distinta, detenete y replanteá el diagnóstico.
|
|
47
50
|
|
|
48
51
|
**Discovery:** `codegraph_explore` + `mem_search`. Si ya llamaste para el área en este request, reusar ese output. No hay cache de archivo.
|
|
49
52
|
|
|
@@ -105,7 +108,10 @@ Router `brainstorming`↔`OpenSpec` por `level`/`estLines`/`fileCount`/`hasAPI`
|
|
|
105
108
|
## Guardrails
|
|
106
109
|
|
|
107
110
|
- Decisión en OpenSpec/CodeGraph/controller → no re-resolver
|
|
108
|
-
- **Multi-sesión (un
|
|
111
|
+
- **Multi-sesión (un slot por sesión):** cada sesión de OpenCode trabaja su propia request en `.opencode/sessions/pool-NN.json`; no compartís request con otras sesiones. Si un tool devuelve `question: "slot_capacity"` (`conflict:true`), **NO** cambies nada: presentá al usuario la lista `candidates` (nombre, estado, si está activa, minutos sin actividad) y el `notify`, y preguntá una sola cosa: (a) confirmar la extensión del pool (`allowExtension:true`, máx. 5 extra, solo con 10 sesiones activas), (b) sustituir una sesión por nombre (`replaceSlot:"pool-NN"`; la sesión sustituida queda `BLOCKED` y pierde su request), o (c) esperar a que termine una sesión activa y reintentar. Sin respuesta, no hagas nada.
|
|
112
|
+
- **Sesión sustituida:** si un tool devuelve `BLOCKED: … sustituida …`, no reintentes: pedí al usuario iniciar una sesión nueva de OpenCode.
|
|
113
|
+
- **Aviso `concurrent_edit`:** si un resultado trae `concurrentEdit`, otra sesión editó el mismo archivo hace poco. No bloquea: mostralo al usuario antes de seguir editando ese archivo. Limitación: solo se registran ediciones que pasan por `validate_edit`/`complete_task`; un `edit` directo fuera del flujo no queda registrado.
|
|
114
|
+
- **Modo legado:** `OSTACKY_SESSION_SLOTS=off` vuelve al state único `.opencode/ostacky-state.json` (sin slots ni avisos). Los límites se ajustan con `OSTACKY_SESSION_POOL_MAX`, `OSTACKY_SESSION_OVERFLOW_MAX`, `OSTACKY_SESSION_ACTIVE_MIN`, `OSTACKY_SESSION_RECYCLE_DAYS` y `OSTACKY_CONCURRENT_EDIT_WINDOW_MIN`.
|
|
109
115
|
- Una pregunta por turno, sin deadlock
|
|
110
116
|
- Fase gate: en EXECUTING/SYNC no volver a DISCOVERY
|
|
111
117
|
- Audit: log antes de gate + `mem_save` solo en gates
|
|
@@ -6,7 +6,7 @@ subagent: false
|
|
|
6
6
|
|
|
7
7
|
Instala el stack tecnológico de desarrollo para OpenCode. **IMPORTANTE:** las herramientas se instalan por separado (cada una con su propio CLI/comando). `npx ostacky install` solo instala el agente y commands de Ostacky en `.opencode/`. Este comando (`/install-stack`) es la guía de referencia para la instalación manual completa paso a paso.
|
|
8
8
|
|
|
9
|
-
**Nota:** A partir de v0.
|
|
9
|
+
**Nota:** A partir de v0.11.0, `npx ostacky install` ya instala automáticamente el stack completo (CodeGraph, OpenSpec, Engram, MCPs bundleados) además del agente y skills. Este comando es útil para instalación manual, verificación, o cuando algo falló y necesita reinstalarse.
|
|
10
10
|
|
|
11
11
|
**RESTRICCIÓN ABSOLUTA:** instalar ÚNICAMENTE para OpenCode. Está terminantemente prohibido crear o modificar archivos en `.claude/`, `.kiro/`, `.cursor/`, `.gemini/`, `.codex/`, `.antigravity/`, `.windsurf/` o cualquier otro directorio de plataformas externas.
|
|
12
12
|
|
|
@@ -88,6 +88,7 @@ Cubre `read`/`grep`/`glob`/`read_mcp_resource` y **`shell`** cuando el comando r
|
|
|
88
88
|
`isTrivial(msg,state) = state==DONE && msg.trim().length<30 && /^(hola|hey|gracias|buenas|hi|hello)\b/i.test(msg) && !/(necesito|quiero|agregá|fix|bug|feature|auth|spec|implementar)/i.test(msg)`
|
|
89
89
|
|
|
90
90
|
- **Trivial + DONE**: `output.system[0]` permanece `FULL` diet cacheable (10% hit), plugin añade suffix hint `[PLUGIN HINT: Saludo trivial — responde breve sin tools]` y bloquea `mem_context`/`codegraph_*` con `SKIP`. Solo Engram pointer 1 línea, no `MEMORY_INSTRUCTIONS`.
|
|
91
|
+
- **Pregunta de sesión** (`classifyIntent` → `session_question`): regex de recuerdo (`qué hicimos/cambiamos/falta…`, `resumí…`, `por qué elegiste…`) sin verbos de acción/propuesta (`propon*`, `arregl*`, `cambiá`…). Hint `[PLUGIN HINT: Pregunta sobre hechos ya ejecutados…]`, exime el Engram audit. Responde desde contexto + `ostacky_get_state` (`completedTasks`, `pendingTasks`, `editedFiles`). No bloquea tools ni relaja gates de estado/edición; ante duda gana `work`.
|
|
91
92
|
- **TIER1** (0/0+1 con intent): hint `TIER1` en suffix, `FULL` sigue cacheado, `DIRECT` sin `Alternatives`.
|
|
92
93
|
- **FULL** (1+): sin hint, `FULL` con `MEMORY_INSTRUCTIONS` lazy (solo si `!isTrivial` o nudge >15m).
|
|
93
94
|
|
|
@@ -210,3 +210,33 @@ export function getAuditRetention() {
|
|
|
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) {
|
|
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) {
|
|
241
|
+
return /\|\s*(?:tail|head|grep)\b/.test(String(cmd == null ? "" : cmd));
|
|
242
|
+
}
|
|
@@ -28,6 +28,9 @@ import {
|
|
|
28
28
|
import { dirname, basename, join, resolve, relative } from 'node:path';
|
|
29
29
|
import { writeFile as writeFileAsync, rename as renameAsync, mkdir as mkdirAsync } from 'node:fs/promises';
|
|
30
30
|
import { SENSITIVE_DEFAULT, BASH_SENSITIVE_RE, isSensitive, extractPathsFromBash } from './security.js';
|
|
31
|
+
import { bindSession, checkBinding, recordRequestSummary, noteFileEdit, handoffFallbackPath, isHandoffFallbackFile } from './session-store.js';
|
|
32
|
+
import { parsePoolConfig, isActiveSlot, parseSessionListTitle } from './session-slots.js';
|
|
33
|
+
import { execFileSync } from 'node:child_process';
|
|
31
34
|
import {
|
|
32
35
|
STATES,
|
|
33
36
|
TRANSITIONS,
|
|
@@ -40,6 +43,8 @@ import {
|
|
|
40
43
|
MAX_STATE_FILE_SIZE,
|
|
41
44
|
DEGRADED_THRESHOLD,
|
|
42
45
|
getMaxTasks,
|
|
46
|
+
normalizeTestCommand,
|
|
47
|
+
isMaskedExitCommand,
|
|
43
48
|
} from './controller-core.js';
|
|
44
49
|
|
|
45
50
|
// --- approved-but-blocked recovery (sin timers) ---
|
|
@@ -276,27 +281,46 @@ export function parseTaskVerifications(changeId, statePath) {
|
|
|
276
281
|
*
|
|
277
282
|
* NO usa `status`: el shell tool de OpenCode reporta "completed" incluso con
|
|
278
283
|
* exit != 0 (medido: `sh -c 'exit 3'` -> status "completed", metadata.exit 3).
|
|
279
|
-
* El plugin registra {cmd, exit, ts} por cada
|
|
280
|
-
*
|
|
284
|
+
* El plugin registra {cmd, exit, ts} por cada corrida que matchea un test:
|
|
285
|
+
* declarado; acá se compara la forma normalizada (cd/2>&1), se exige exit 0
|
|
286
|
+
* y posterior a la última mutación, y se rechaza cualquier exit enmascarado
|
|
287
|
+
* por un pipe a tail/head/grep.
|
|
281
288
|
*/
|
|
282
289
|
export function findTestEvidence({ runs, cmd, lastMutationTs, now = Date.now() } = {}) {
|
|
283
|
-
const
|
|
284
|
-
if (!
|
|
290
|
+
const declared = String(cmd || '').trim();
|
|
291
|
+
if (!declared) return { ok: false, reason: 'test: sin comando' };
|
|
292
|
+
const expected = normalizeTestCommand(declared);
|
|
293
|
+
if (!expected) return { ok: false, reason: `test: comando no verificable: "${declared}"` };
|
|
285
294
|
if (!Array.isArray(runs) || runs.length === 0)
|
|
286
|
-
return { ok: false, reason:
|
|
287
|
-
const matches = runs.filter((r) => r &&
|
|
288
|
-
if (matches.length === 0)
|
|
295
|
+
return { ok: false, reason: `sin evidencia para "${declared}": el plugin no registró ninguna corrida de shell que matchee ese comando` };
|
|
296
|
+
const matches = runs.filter((r) => r && normalizeTestCommand(r.cmd) === expected);
|
|
297
|
+
if (matches.length === 0) {
|
|
298
|
+
const recent = runs
|
|
299
|
+
.filter((r) => r && typeof r.cmd === 'string' && r.cmd.trim())
|
|
300
|
+
.sort((a, b) => (Number(b.ts) || 0) - (Number(a.ts) || 0));
|
|
301
|
+
const similar = recent.find((r) => r.cmd.includes(declared)) || recent[0] || null;
|
|
302
|
+
return {
|
|
303
|
+
ok: false,
|
|
304
|
+
reason: `nunca se ejecutó exactamente "${declared}"${similar ? `. La corrida más parecida fue "${similar.cmd}"` : ''}`,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
289
307
|
const last = matches.reduce((a, b) => ((Number(b.ts) || 0) >= (Number(a.ts) || 0) ? b : a));
|
|
308
|
+
if (last.maskedExit === true || isMaskedExitCommand(last.cmd))
|
|
309
|
+
return {
|
|
310
|
+
ok: false,
|
|
311
|
+
reason: `exit enmascarado: "${last.cmd}" usa un pipe a tail/head/grep; corré sin pipe o con "set -o pipefail"`,
|
|
312
|
+
run: last,
|
|
313
|
+
};
|
|
290
314
|
if (typeof last.ts !== 'number' || typeof lastMutationTs !== 'number')
|
|
291
315
|
return {
|
|
292
316
|
ok: false,
|
|
293
|
-
reason: `sin timestamps: no se puede probar que "${
|
|
317
|
+
reason: `sin timestamps: no se puede probar que "${declared}" sea posterior a la última edición`,
|
|
294
318
|
run: last,
|
|
295
319
|
};
|
|
296
320
|
if (last.ts <= lastMutationTs)
|
|
297
|
-
return { ok: false, reason: `la última corrida de "${
|
|
321
|
+
return { ok: false, reason: `la última corrida de "${declared}" es anterior a la última edición`, run: last };
|
|
298
322
|
if (last.exit !== 0)
|
|
299
|
-
return { ok: false, reason: `la última corrida de "${
|
|
323
|
+
return { ok: false, reason: `la última corrida de "${declared}" salió con exit ${last.exit}`, run: last };
|
|
300
324
|
return { ok: true, reason: `exit 0 hace ${Math.max(0, Math.round((now - last.ts) / 1000))}s`, run: last };
|
|
301
325
|
}
|
|
302
326
|
|
|
@@ -432,8 +456,9 @@ function cleanupTmpFiles(statePath) {
|
|
|
432
456
|
for (const entry of readdirSync(dir)) {
|
|
433
457
|
const isTmp = entry.startsWith(name + '.tmp.');
|
|
434
458
|
const isLock = entry.startsWith(name + '.lock');
|
|
435
|
-
const isHandoff = entry
|
|
436
|
-
|
|
459
|
+
const isHandoff = isHandoffFallbackFile(entry);
|
|
460
|
+
const isHandoffTmp = entry.startsWith('.ostacky-handoff-compaction') && entry.includes('.json.tmp.');
|
|
461
|
+
if (!isTmp && !isLock && !isHandoff && !isHandoffTmp) continue;
|
|
437
462
|
// C3: don't delete active lock of another process
|
|
438
463
|
if (isLock) {
|
|
439
464
|
try {
|
|
@@ -524,12 +549,16 @@ class OstackyController {
|
|
|
524
549
|
#lockOwner = false;
|
|
525
550
|
#lockDepth = 0; // multi-sesión: reentrancy (el lock se toma una vez por tool call)
|
|
526
551
|
#callerSessionId = null; // sessionId del caller (de _meta), solo en memoria
|
|
552
|
+
#opencodeDir = null; // .opencode del proyecto (ancla fija del handoff, no cambia con el slot)
|
|
527
553
|
#loadedSnapshot = null; // huella del estado recién leído, para detectar "dirty"
|
|
528
554
|
#persistQueue = Promise.resolve(); // cola in-process: las escrituras nunca se solapan
|
|
529
555
|
#persistSeq = 0; // sufijo único por escritura (tmp.<pid>.<seq>)
|
|
556
|
+
#fileEditObserver = null;
|
|
557
|
+
#notices = [];
|
|
530
558
|
|
|
531
559
|
constructor(opts = {}) {
|
|
532
560
|
this.#statePath = opts.statePath;
|
|
561
|
+
this.#opencodeDir = opts.statePath ? dirname(opts.statePath) : null;
|
|
533
562
|
this.#lockPath = opts.statePath ? opts.statePath + '.lock' : null;
|
|
534
563
|
this.#lockPidPath = opts.statePath ? opts.statePath + '.lock.pid' : null;
|
|
535
564
|
this.#lockHeartbeatPath = opts.statePath ? opts.statePath + '.lock.timestamp' : null;
|
|
@@ -611,6 +640,58 @@ class OstackyController {
|
|
|
611
640
|
return true;
|
|
612
641
|
}
|
|
613
642
|
|
|
643
|
+
/**
|
|
644
|
+
* Apunta el controller al state file de un slot (session-state-files). Descarta el estado
|
|
645
|
+
* en memoria: el próximo load lee el slot. Solo lo llama bindCallerSlot antes de cada tool call.
|
|
646
|
+
*/
|
|
647
|
+
rebindStatePath(newPath) {
|
|
648
|
+
if (newPath === this.#statePath) return;
|
|
649
|
+
this.#statePath = newPath;
|
|
650
|
+
this.#lockPath = newPath + '.lock';
|
|
651
|
+
this.#lockPidPath = newPath + '.lock.pid';
|
|
652
|
+
this.#lockHeartbeatPath = newPath + '.lock.timestamp';
|
|
653
|
+
this.#state = null;
|
|
654
|
+
this.#loaded = false;
|
|
655
|
+
this.#loadedSnapshot = null;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
get statePathValue() {
|
|
659
|
+
return this.#statePath;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Resumen de la request (para listar candidatas al usuario en el índice de sesiones). */
|
|
663
|
+
stateSummary() {
|
|
664
|
+
this.#load();
|
|
665
|
+
return {
|
|
666
|
+
requestId: this.#state?.requestId ?? null,
|
|
667
|
+
changeId: this.#state?.changeId ?? null,
|
|
668
|
+
state: this.#state?.state ?? null,
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/** Observador de ediciones por archivo (aviso concurrent_edit); lo fija el entry point. */
|
|
673
|
+
setFileEditObserver(fn) {
|
|
674
|
+
this.#fileEditObserver = typeof fn === 'function' ? fn : null;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
#observeFileEdit(filePath) {
|
|
678
|
+
if (!filePath || !this.#fileEditObserver) return;
|
|
679
|
+
try {
|
|
680
|
+
this.#fileEditObserver(filePath);
|
|
681
|
+
} catch {}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** Avisos no bloqueantes acumulados durante la llamada actual. */
|
|
685
|
+
pushNotice(message) {
|
|
686
|
+
this.#notices.push(message);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
takeNotices() {
|
|
690
|
+
const out = this.#notices;
|
|
691
|
+
this.#notices = [];
|
|
692
|
+
return out;
|
|
693
|
+
}
|
|
694
|
+
|
|
614
695
|
/** Registra el sessionId del caller actual (de `_meta["ai.opencode/sessionID"]`). */
|
|
615
696
|
setCallerSession(sessionId) {
|
|
616
697
|
this.#callerSessionId = typeof sessionId === 'string' && sessionId ? sessionId : null;
|
|
@@ -2741,7 +2822,7 @@ class OstackyController {
|
|
|
2741
2822
|
// C3: fallback to compaction file — same anchor as writer (dirname(statePath))
|
|
2742
2823
|
if (!this.#statePath) return null;
|
|
2743
2824
|
try {
|
|
2744
|
-
const fallbackPath =
|
|
2825
|
+
const fallbackPath = handoffFallbackPath(this.#opencodeDir, this.#callerSessionId);
|
|
2745
2826
|
const raw = readFileSync(fallbackPath, 'utf8');
|
|
2746
2827
|
const data = JSON.parse(raw);
|
|
2747
2828
|
if (data && typeof data.summary === 'string') return data;
|
|
@@ -2756,7 +2837,7 @@ class OstackyController {
|
|
|
2756
2837
|
// C3: also delete fallback compaction file (same anchor)
|
|
2757
2838
|
if (this.#statePath) {
|
|
2758
2839
|
try {
|
|
2759
|
-
unlinkSync(
|
|
2840
|
+
unlinkSync(handoffFallbackPath(this.#opencodeDir, this.#callerSessionId));
|
|
2760
2841
|
} catch {}
|
|
2761
2842
|
}
|
|
2762
2843
|
await this.#audit('HANDOFF', 'clear_handoff', prev?.summary?.slice(0, 100) || 'none');
|
|
@@ -2856,6 +2937,7 @@ class OstackyController {
|
|
|
2856
2937
|
// --- O6: Validate edit with fast fingerprint + D6/D4 hard gate + 10.4 freshness ---
|
|
2857
2938
|
async validateEdit({ oldString, newString, content, taskId, filePath } = {}) {
|
|
2858
2939
|
this.#load();
|
|
2940
|
+
this.#observeFileEdit(filePath);
|
|
2859
2941
|
if (this.#state.state !== 'EXECUTING_INLINE' && this.#state.state !== 'EXECUTING_SUBAGENTS') {
|
|
2860
2942
|
return { outcome: 'CONFLICT', reason: `Cannot validate edit from state ${this.#state.state}` };
|
|
2861
2943
|
}
|
|
@@ -3021,6 +3103,7 @@ class OstackyController {
|
|
|
3021
3103
|
*/
|
|
3022
3104
|
async completeTask({ taskId, filePath, fileHash } = {}) {
|
|
3023
3105
|
this.#load();
|
|
3106
|
+
this.#observeFileEdit(filePath);
|
|
3024
3107
|
const denied = await this.#foreignOwnerError('complete_task');
|
|
3025
3108
|
if (denied) return denied;
|
|
3026
3109
|
if (this.#state.state !== 'EXECUTING_INLINE' && this.#state.state !== 'EXECUTING_SUBAGENTS') {
|
|
@@ -3256,7 +3339,14 @@ class OstackyController {
|
|
|
3256
3339
|
// Copia plana, NO la referencia de shellRuns: el serializador seguro
|
|
3257
3340
|
// marca referencias repetidas como "[Circular]" y corrompería la
|
|
3258
3341
|
// evidencia persistida (bug detectado por el test de integración).
|
|
3259
|
-
run: ev.run
|
|
3342
|
+
run: ev.run
|
|
3343
|
+
? {
|
|
3344
|
+
cmd: ev.run.cmd,
|
|
3345
|
+
exit: ev.run.exit,
|
|
3346
|
+
ts: ev.run.ts,
|
|
3347
|
+
...(ev.run.maskedExit ? { maskedExit: true } : {}),
|
|
3348
|
+
}
|
|
3349
|
+
: null,
|
|
3260
3350
|
ts: Date.now(),
|
|
3261
3351
|
};
|
|
3262
3352
|
await this.#persist();
|
|
@@ -3371,6 +3461,19 @@ class OstackyController {
|
|
|
3371
3461
|
|
|
3372
3462
|
const statePath = resolve(process.env.OSTACKY_STATE_PATH || join(process.cwd(), '.opencode', 'ostacky-state.json'));
|
|
3373
3463
|
const controller = new OstackyController({ statePath });
|
|
3464
|
+
controller.setFileEditObserver((filePath) => {
|
|
3465
|
+
if (process.env.OSTACKY_SESSION_SLOTS === 'off') return;
|
|
3466
|
+
const sid = controller.callerSessionId;
|
|
3467
|
+
if (!sid) return;
|
|
3468
|
+
const minutes = Number(process.env.OSTACKY_CONCURRENT_EDIT_WINDOW_MIN);
|
|
3469
|
+
const windowMs = (Number.isFinite(minutes) && minutes > 0 ? minutes : 30) * 60_000;
|
|
3470
|
+
const warnings = noteFileEdit(dirname(statePath), sid, filePath, Date.now(), windowMs);
|
|
3471
|
+
for (const w of warnings) {
|
|
3472
|
+
controller.pushNotice(
|
|
3473
|
+
`WARN concurrent_edit: ${w.file} lo editó hace ${w.minutesAgo} min "${w.otherName}" (request ${w.otherRequestId ?? 'sin request'}). No bloquea: coordiná antes de seguir.`
|
|
3474
|
+
);
|
|
3475
|
+
}
|
|
3476
|
+
});
|
|
3374
3477
|
|
|
3375
3478
|
/**
|
|
3376
3479
|
* Wraps an async tool handler to ALWAYS return a response (even on error).
|
|
@@ -3404,6 +3507,81 @@ function extractCallerSessionId(ctx) {
|
|
|
3404
3507
|
return null;
|
|
3405
3508
|
}
|
|
3406
3509
|
|
|
3510
|
+
/**
|
|
3511
|
+
* Título visible de una sesión. OpenCode no lo manda en _meta (solo ai.opencode/sessionID),
|
|
3512
|
+
* así que se consulta con `opencode session list --format json`. Éxitos se cachean por proceso;
|
|
3513
|
+
* fallos se reintentan tras 60 s para no lanzar un subproceso en cada tool call.
|
|
3514
|
+
*/
|
|
3515
|
+
const sessionTitleCache = new Map(); // sid -> { title, at }
|
|
3516
|
+
const SESSION_TITLE_MISS_TTL_MS = 60_000;
|
|
3517
|
+
function sessionTitleFor(sid) {
|
|
3518
|
+
if (!sid) return null;
|
|
3519
|
+
const hit = sessionTitleCache.get(sid);
|
|
3520
|
+
if (hit && (hit.title || Date.now() - hit.at < SESSION_TITLE_MISS_TTL_MS)) return hit.title;
|
|
3521
|
+
let title = null;
|
|
3522
|
+
try {
|
|
3523
|
+
const out = execFileSync('opencode', ['session', 'list', '--format', 'json', '-n', '200'], {
|
|
3524
|
+
encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'],
|
|
3525
|
+
});
|
|
3526
|
+
title = parseSessionListTitle(out, sid);
|
|
3527
|
+
} catch {}
|
|
3528
|
+
sessionTitleCache.set(sid, { title, at: Date.now() });
|
|
3529
|
+
return title;
|
|
3530
|
+
}
|
|
3531
|
+
|
|
3532
|
+
/** Nombre a mostrar: título de la sesión, o changeId/requestId si no hay título. */
|
|
3533
|
+
function displayNameOf(c) {
|
|
3534
|
+
return c.sessionName || c.changeId || c.requestId || 'sesión sin nombre';
|
|
3535
|
+
}
|
|
3536
|
+
|
|
3537
|
+
/**
|
|
3538
|
+
* Asigna/valida el slot de la sesión del caller antes de cada tool call (session-state-files).
|
|
3539
|
+
* Devuelve { block } si la tool no debe ejecutarse (pregunta al usuario o sesión sustituida),
|
|
3540
|
+
* y { notice } con avisos de capacidad para adjuntar a la respuesta.
|
|
3541
|
+
* Sin identidad de caller (clientes legacy) o con OSTACKY_SESSION_SLOTS=off: no aplica.
|
|
3542
|
+
*/
|
|
3543
|
+
function bindCallerSlot(params, ctx) {
|
|
3544
|
+
if (process.env.OSTACKY_SESSION_SLOTS === 'off') return { block: null, notice: [] };
|
|
3545
|
+
const sid = controller.callerSessionId;
|
|
3546
|
+
if (!sid) return { block: null, notice: [] };
|
|
3547
|
+
const cfg = parsePoolConfig(process.env);
|
|
3548
|
+
const opencodeDir = dirname(statePath);
|
|
3549
|
+
const res = bindSession({
|
|
3550
|
+
opencodeDir,
|
|
3551
|
+
sessionId: sid,
|
|
3552
|
+
sessionName: sessionTitleFor(sid),
|
|
3553
|
+
now: Date.now(),
|
|
3554
|
+
cfg,
|
|
3555
|
+
legacyStatePath: statePath,
|
|
3556
|
+
replaceSlot: (params && params.replaceSlot) || null,
|
|
3557
|
+
allowOverflow: !!(params && params.allowExtension),
|
|
3558
|
+
});
|
|
3559
|
+
if (res.kind === 'blocked') return { block: { error: `BLOCKED: ${res.reason}` }, notice: [] };
|
|
3560
|
+
if (res.kind === 'ask') {
|
|
3561
|
+
const now = Date.now();
|
|
3562
|
+
return {
|
|
3563
|
+
block: {
|
|
3564
|
+
conflict: true,
|
|
3565
|
+
question: 'slot_capacity',
|
|
3566
|
+
notify: res.notify,
|
|
3567
|
+
message:
|
|
3568
|
+
'Pregunta al usuario antes de continuar: confirmar sustitución (replaceSlot), confirmar extensión del pool (allowExtension) o esperar a que termine una sesión activa. No cambies nada sin respuesta.',
|
|
3569
|
+
candidates: res.candidates.map((c) => ({
|
|
3570
|
+
slot: c.slot,
|
|
3571
|
+
name: displayNameOf(c),
|
|
3572
|
+
changeId: c.changeId ?? null,
|
|
3573
|
+
state: c.state ?? null,
|
|
3574
|
+
active: isActiveSlot(c, now, cfg),
|
|
3575
|
+
lastActivityMinutesAgo: Math.round((now - (c.lastUsedAt || 0)) / 60000),
|
|
3576
|
+
})),
|
|
3577
|
+
},
|
|
3578
|
+
notice: [],
|
|
3579
|
+
};
|
|
3580
|
+
}
|
|
3581
|
+
controller.rebindStatePath(res.statePath);
|
|
3582
|
+
return { block: null, notice: res.notify };
|
|
3583
|
+
}
|
|
3584
|
+
|
|
3407
3585
|
// ── Cola in-process (fix-consume-race-lock) ──────────────────────────────────
|
|
3408
3586
|
// Code Mode emite varias tools en paralelo DENTRO del mismo proceso MCP y
|
|
3409
3587
|
// `#state` es un único objeto compartido. Un `reloadFresh()` concurrente (p.ej.
|
|
@@ -3433,8 +3611,16 @@ function safeHandler(fn, options = {}) {
|
|
|
3433
3611
|
// tomarlo dejaba una ventana donde otro proceso escribía y el persist
|
|
3434
3612
|
// posterior revertía esa escritura (lost update).
|
|
3435
3613
|
let heldLock = false;
|
|
3614
|
+
let slotGate = { block: null, notice: [] };
|
|
3615
|
+
controller.takeNotices();
|
|
3436
3616
|
try {
|
|
3437
3617
|
controller.setCallerSession(extractCallerSessionId(ctx));
|
|
3618
|
+
slotGate = bindCallerSlot(params, ctx);
|
|
3619
|
+
} catch (error) {
|
|
3620
|
+
return { content: [{ type: 'text', text: safeJsonStringify({ error: `BLOCKED: no se pudo asignar slot de sesión: ${String(error?.message || error)}` }) }] };
|
|
3621
|
+
}
|
|
3622
|
+
if (slotGate.block) return { content: [{ type: 'text', text: safeJsonStringify(slotGate.block) }] };
|
|
3623
|
+
try {
|
|
3438
3624
|
heldLock = await controller.beginWrite();
|
|
3439
3625
|
controller.reloadFresh();
|
|
3440
3626
|
} catch {}
|
|
@@ -3465,8 +3651,18 @@ function safeHandler(fn, options = {}) {
|
|
|
3465
3651
|
} catch {}
|
|
3466
3652
|
// Update heartbeat on successful completion
|
|
3467
3653
|
controller.updateHeartbeat();
|
|
3654
|
+
// Resumen de la request en el índice compartido (lista de candidatas y avisos).
|
|
3655
|
+
const sidNow = controller.callerSessionId;
|
|
3656
|
+
if (sidNow && process.env.OSTACKY_SESSION_SLOTS !== 'off') {
|
|
3657
|
+
try {
|
|
3658
|
+
recordRequestSummary(dirname(statePath), sidNow, controller.stateSummary(), Date.now());
|
|
3659
|
+
} catch {}
|
|
3660
|
+
}
|
|
3468
3661
|
endOp();
|
|
3469
|
-
|
|
3662
|
+
const notices = controller.takeNotices();
|
|
3663
|
+
let out = slotGate.notice.length && result && typeof result === 'object' ? { ...result, slotNotice: slotGate.notice } : result;
|
|
3664
|
+
if (notices.length && out && typeof out === 'object') out = { ...out, concurrentEdit: notices };
|
|
3665
|
+
return { content: [{ type: 'text', text: safeJsonStringify(out) }] };
|
|
3470
3666
|
} catch (error) {
|
|
3471
3667
|
const isTimeout = error && error.message && error.message.includes('timeout');
|
|
3472
3668
|
const isNetworkError =
|
|
@@ -3520,7 +3716,7 @@ function safeHandler(fn, options = {}) {
|
|
|
3520
3716
|
|
|
3521
3717
|
const server = new McpServer({
|
|
3522
3718
|
name: 'ostacky-controller',
|
|
3523
|
-
version: '0.
|
|
3719
|
+
version: '0.11.0',
|
|
3524
3720
|
});
|
|
3525
3721
|
|
|
3526
3722
|
server.registerTool(
|
|
@@ -3531,6 +3727,8 @@ server.registerTool(
|
|
|
3531
3727
|
requestId: z.string().optional().describe('Unique request ID'),
|
|
3532
3728
|
changeId: z.string().optional().describe('Optional change ID for OpenSpec tracking'),
|
|
3533
3729
|
force: z.boolean().optional().describe('Force reset even if work in progress (default: false)'),
|
|
3730
|
+
replaceSlot: z.string().optional().describe('Confirmación del usuario: slot a sustituir (ej. pool-03)'),
|
|
3731
|
+
allowExtension: z.boolean().optional().describe('Confirmación del usuario: crear slot de extensión con 10 sesiones activas'),
|
|
3534
3732
|
}),
|
|
3535
3733
|
},
|
|
3536
3734
|
safeHandler(async ({ requestId, changeId, force }) => {
|
|
@@ -4122,7 +4320,7 @@ function setupGracefulShutdown(ctrl) {
|
|
|
4122
4320
|
}
|
|
4123
4321
|
|
|
4124
4322
|
async function main() {
|
|
4125
|
-
log('Starting ostacky-controller MCP v0.
|
|
4323
|
+
log('Starting ostacky-controller MCP v0.11.0...');
|
|
4126
4324
|
log('State path:', { path: statePath });
|
|
4127
4325
|
// Clean up stale tmp/lock files from previous runs
|
|
4128
4326
|
cleanupTmpFiles(statePath);
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* session-slots — mirror (JS) de src/session-slots.ts
|
|
3
|
+
* Generado desde src/session-slots.ts — NO EDITAR. Ejecutá `bun run scripts/sync-controller-core.ts`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const TERMINAL_REQUEST_STATES = ["DONE", "ABANDONED"];
|
|
7
|
+
export const POOL_DEFAULTS = {
|
|
8
|
+
poolMax: 10,
|
|
9
|
+
overflowMax: 5,
|
|
10
|
+
activeMinutes: 15,
|
|
11
|
+
recycleDays: 7
|
|
12
|
+
};
|
|
13
|
+
export function parsePoolConfig(env = process.env) {
|
|
14
|
+
const num = (raw, fallback) => {
|
|
15
|
+
const n = Number(raw);
|
|
16
|
+
return Number.isFinite(n) && n > 0 ? n : fallback;
|
|
17
|
+
};
|
|
18
|
+
return {
|
|
19
|
+
poolMax: Math.floor(num(env.OSTACKY_SESSION_POOL_MAX, POOL_DEFAULTS.poolMax)),
|
|
20
|
+
overflowMax: Math.floor(num(env.OSTACKY_SESSION_OVERFLOW_MAX, POOL_DEFAULTS.overflowMax)),
|
|
21
|
+
activeMs: num(env.OSTACKY_SESSION_ACTIVE_MIN, POOL_DEFAULTS.activeMinutes) * 60000,
|
|
22
|
+
recycleMs: num(env.OSTACKY_SESSION_RECYCLE_DAYS, POOL_DEFAULTS.recycleDays) * 86400000
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function isActiveSlot(s, now, cfg) {
|
|
26
|
+
if (!s.sessionId || !s.requestId || s.quarantined)
|
|
27
|
+
return false;
|
|
28
|
+
if (s.state && TERMINAL_REQUEST_STATES.includes(s.state))
|
|
29
|
+
return false;
|
|
30
|
+
return s.ownerHeartbeat > 0 && now - s.ownerHeartbeat <= cfg.activeMs;
|
|
31
|
+
}
|
|
32
|
+
export function isRecycleEligible(s, now, cfg) {
|
|
33
|
+
if (s.quarantined)
|
|
34
|
+
return false;
|
|
35
|
+
const terminal = !s.requestId || !!s.state && TERMINAL_REQUEST_STATES.includes(s.state);
|
|
36
|
+
if (!terminal)
|
|
37
|
+
return false;
|
|
38
|
+
return now - s.lastUsedAt > cfg.recycleMs;
|
|
39
|
+
}
|
|
40
|
+
const byOldestFirst = (a, b) => a.lastUsedAt - b.lastUsedAt || a.slot.localeCompare(b.slot);
|
|
41
|
+
export function decideSlot(sessionId, slots, now, cfg, opts = {}) {
|
|
42
|
+
const usable = slots.filter((s) => !s.quarantined);
|
|
43
|
+
const own = usable.find((s) => s.sessionId === sessionId);
|
|
44
|
+
if (own)
|
|
45
|
+
return { kind: "reuse", slot: own.slot };
|
|
46
|
+
const free = usable.filter((s) => !s.sessionId);
|
|
47
|
+
const freeBase = free.filter((s) => !s.overflow).sort(byOldestFirst);
|
|
48
|
+
const freeAny = freeBase.length > 0 ? freeBase : free.sort(byOldestFirst);
|
|
49
|
+
if (freeAny.length > 0)
|
|
50
|
+
return { kind: "free", slot: freeAny[0].slot };
|
|
51
|
+
const baseCount = slots.filter((s) => !s.overflow).length;
|
|
52
|
+
const overflowCount = slots.filter((s) => s.overflow).length;
|
|
53
|
+
const activeCount = usable.filter((s) => isActiveSlot(s, now, cfg)).length;
|
|
54
|
+
const notify = [];
|
|
55
|
+
if (activeCount < cfg.poolMax && baseCount < cfg.poolMax) {
|
|
56
|
+
return { kind: "create", slot: nextSlotId(slots, false), overflow: false, notify };
|
|
57
|
+
}
|
|
58
|
+
const eligible = usable.filter((s) => isRecycleEligible(s, now, cfg));
|
|
59
|
+
const eligibleBase = eligible.filter((s) => !s.overflow).sort(byOldestFirst);
|
|
60
|
+
const eligibleAny = eligibleBase.length > 0 ? eligibleBase : eligible.sort(byOldestFirst);
|
|
61
|
+
if (eligibleAny.length > 0) {
|
|
62
|
+
const pick = eligibleAny[0];
|
|
63
|
+
if (activeCount >= cfg.poolMax)
|
|
64
|
+
notify.push(`Ya hay ${cfg.poolMax} sesiones activas ejecutando al mismo tiempo (${activeCount} activas).`);
|
|
65
|
+
return { kind: "recycle", slot: pick.slot, previousSessionId: pick.sessionId, notify };
|
|
66
|
+
}
|
|
67
|
+
if (activeCount >= cfg.poolMax) {
|
|
68
|
+
notify.push(`Ya hay ${cfg.poolMax} sesiones activas ejecutando al mismo tiempo (${activeCount} activas).`);
|
|
69
|
+
if (opts.allowOverflow && overflowCount < cfg.overflowMax) {
|
|
70
|
+
notify.push(`Extensión ${overflowCount + 1}/${cfg.overflowMax} en uso (confirmada por el usuario).`);
|
|
71
|
+
return { kind: "create", slot: nextSlotId(slots, true), overflow: true, notify };
|
|
72
|
+
}
|
|
73
|
+
if (!opts.allowOverflow) {
|
|
74
|
+
notify.push(`Para extender el pool hay que confirmar (extensión 1/${cfg.overflowMax}); o esperar a que termine una de las sesiones activas.`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const candidates = usable.filter((s) => s.sessionId).sort(byOldestFirst);
|
|
78
|
+
notify.push("No hay cupo: elegí una sesión para sustituir o cancelá (sin respuesta no se cambia nada).");
|
|
79
|
+
return { kind: "ask", candidates, notify };
|
|
80
|
+
}
|
|
81
|
+
export function nextSlotId(slots, overflow) {
|
|
82
|
+
const taken = new Set(slots.map((s) => s.slot));
|
|
83
|
+
const start = overflow ? 11 : 1;
|
|
84
|
+
for (let n = start;n < start + 100; n++) {
|
|
85
|
+
const id = `pool-${String(n).padStart(2, "0")}`;
|
|
86
|
+
if (!taken.has(id))
|
|
87
|
+
return id;
|
|
88
|
+
}
|
|
89
|
+
throw new Error("no hay ids de slot disponibles");
|
|
90
|
+
}
|
|
91
|
+
export function parseSessionListTitle(json, sessionId) {
|
|
92
|
+
let rows;
|
|
93
|
+
try {
|
|
94
|
+
rows = JSON.parse(json);
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
if (!Array.isArray(rows))
|
|
99
|
+
return null;
|
|
100
|
+
const row = rows.find((r) => r && r.id === sessionId);
|
|
101
|
+
if (!row || typeof row.title !== "string")
|
|
102
|
+
return null;
|
|
103
|
+
const title = row.title.trim();
|
|
104
|
+
if (!title || title === "Untitled session")
|
|
105
|
+
return null;
|
|
106
|
+
return title.slice(0, 120);
|
|
107
|
+
}
|
|
108
|
+
export function nextRevision(previousRevision) {
|
|
109
|
+
return Math.max(0, Math.floor(previousRevision)) + 1;
|
|
110
|
+
}
|