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,167 @@
1
+ /**
2
+ * session-slots — mirror 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
+ /**
7
+ * Política pura de asignación de slots de estado por sesión (session-state-files).
8
+ *
9
+ * No hace I/O: recibe el índice (metadatos de cada slot) y decide. El controller es quien
10
+ * persiste la decisión bajo lock + revision. Ver openspec/changes/session-state-files.
11
+ */
12
+
13
+ export const TERMINAL_REQUEST_STATES = ["DONE", "ABANDONED"] as const;
14
+
15
+ export interface SlotInfo {
16
+ slot: string;
17
+ overflow: boolean;
18
+ quarantined: boolean;
19
+ sessionId: string | null;
20
+ requestId: string | null;
21
+ state: string | null;
22
+ /** epoch ms del último heartbeat de la sesión dueña (0 si no hay). */
23
+ ownerHeartbeat: number;
24
+ /** epoch ms del último uso del slot. */
25
+ lastUsedAt: number;
26
+ }
27
+
28
+ export interface PoolConfig {
29
+ poolMax: number;
30
+ overflowMax: number;
31
+ activeMs: number;
32
+ recycleMs: number;
33
+ }
34
+
35
+ export const POOL_DEFAULTS = {
36
+ poolMax: 10,
37
+ overflowMax: 5,
38
+ activeMinutes: 15,
39
+ recycleDays: 7,
40
+ } as const;
41
+
42
+ /** Lee la configuración de variables de entorno; valores inválidos o no positivos → default. */
43
+ export function parsePoolConfig(env: Record<string, string | undefined> = process.env): PoolConfig {
44
+ const num = (raw: string | undefined, fallback: number): number => {
45
+ const n = Number(raw);
46
+ return Number.isFinite(n) && n > 0 ? n : fallback;
47
+ };
48
+ return {
49
+ poolMax: Math.floor(num(env.OSTACKY_SESSION_POOL_MAX, POOL_DEFAULTS.poolMax)),
50
+ overflowMax: Math.floor(num(env.OSTACKY_SESSION_OVERFLOW_MAX, POOL_DEFAULTS.overflowMax)),
51
+ activeMs: num(env.OSTACKY_SESSION_ACTIVE_MIN, POOL_DEFAULTS.activeMinutes) * 60_000,
52
+ recycleMs: num(env.OSTACKY_SESSION_RECYCLE_DAYS, POOL_DEFAULTS.recycleDays) * 86_400_000,
53
+ };
54
+ }
55
+
56
+ /** Sesión activa: request no terminal con heartbeat dentro de la ventana. */
57
+ export function isActiveSlot(s: SlotInfo, now: number, cfg: PoolConfig): boolean {
58
+ if (!s.sessionId || !s.requestId || s.quarantined) return false;
59
+ if (s.state && (TERMINAL_REQUEST_STATES as readonly string[]).includes(s.state)) return false;
60
+ return s.ownerHeartbeat > 0 && now - s.ownerHeartbeat <= cfg.activeMs;
61
+ }
62
+
63
+ /** Elegible para reemplazo automático: sin request o terminal, no activa, y sin uso hace más de N días. */
64
+ export function isRecycleEligible(s: SlotInfo, now: number, cfg: PoolConfig): boolean {
65
+ if (s.quarantined) return false;
66
+ const terminal = !s.requestId || (!!s.state && (TERMINAL_REQUEST_STATES as readonly string[]).includes(s.state));
67
+ if (!terminal) return false;
68
+ return now - s.lastUsedAt > cfg.recycleMs;
69
+ }
70
+
71
+ export type SlotDecision =
72
+ | { kind: "reuse"; slot: string }
73
+ | { kind: "free"; slot: string }
74
+ | { kind: "create"; slot: string; overflow: boolean; notify: string[] }
75
+ | { kind: "recycle"; slot: string; previousSessionId: string | null; notify: string[] }
76
+ | { kind: "ask"; candidates: SlotInfo[]; notify: string[] };
77
+
78
+ const byOldestFirst = (a: SlotInfo, b: SlotInfo) => a.lastUsedAt - b.lastUsedAt || a.slot.localeCompare(b.slot);
79
+
80
+ /**
81
+ * Decide qué slot usa `sessionId`. Orden:
82
+ * 1) slot propio; 2) libre (base antes que extensión); 3) crear base si hay tope disponible;
83
+ * 4) reciclar elegible (base antes que extensión, más antiguo primero);
84
+ * 5) con `poolMax` o más activas: notificar y crear extensión si quedan cupos;
85
+ * 6) si nada aplica: preguntar al usuario con candidatas, de la más antigua a la más reciente.
86
+ */
87
+ export function decideSlot(
88
+ sessionId: string,
89
+ slots: SlotInfo[],
90
+ now: number,
91
+ cfg: PoolConfig,
92
+ opts: { allowOverflow?: boolean } = {},
93
+ ): SlotDecision {
94
+ const usable = slots.filter((s) => !s.quarantined);
95
+
96
+ const own = usable.find((s) => s.sessionId === sessionId);
97
+ if (own) return { kind: "reuse", slot: own.slot };
98
+
99
+ const free = usable.filter((s) => !s.sessionId);
100
+ const freeBase = free.filter((s) => !s.overflow).sort(byOldestFirst);
101
+ const freeAny = freeBase.length > 0 ? freeBase : free.sort(byOldestFirst);
102
+ if (freeAny.length > 0) return { kind: "free", slot: freeAny[0].slot };
103
+
104
+ const baseCount = slots.filter((s) => !s.overflow).length;
105
+ const overflowCount = slots.filter((s) => s.overflow).length;
106
+ const activeCount = usable.filter((s) => isActiveSlot(s, now, cfg)).length;
107
+ const notify: string[] = [];
108
+ if (activeCount < cfg.poolMax && baseCount < cfg.poolMax) {
109
+ return { kind: "create", slot: nextSlotId(slots, false), overflow: false, notify };
110
+ }
111
+
112
+ // Reciclar elegibles no cuesta cupo: no son activas.
113
+ const eligible = usable.filter((s) => isRecycleEligible(s, now, cfg));
114
+ const eligibleBase = eligible.filter((s) => !s.overflow).sort(byOldestFirst);
115
+ const eligibleAny = eligibleBase.length > 0 ? eligibleBase : eligible.sort(byOldestFirst);
116
+ if (eligibleAny.length > 0) {
117
+ const pick = eligibleAny[0];
118
+ if (activeCount >= cfg.poolMax) notify.push(`Ya hay ${cfg.poolMax} sesiones activas ejecutando al mismo tiempo (${activeCount} activas).`);
119
+ return { kind: "recycle", slot: pick.slot, previousSessionId: pick.sessionId, notify };
120
+ }
121
+
122
+ if (activeCount >= cfg.poolMax) {
123
+ notify.push(`Ya hay ${cfg.poolMax} sesiones activas ejecutando al mismo tiempo (${activeCount} activas).`);
124
+ if (opts.allowOverflow && overflowCount < cfg.overflowMax) {
125
+ notify.push(`Extensión ${overflowCount + 1}/${cfg.overflowMax} en uso (confirmada por el usuario).`);
126
+ return { kind: "create", slot: nextSlotId(slots, true), overflow: true, notify };
127
+ }
128
+ if (!opts.allowOverflow) {
129
+ notify.push(`Para extender el pool hay que confirmar (extensión 1/${cfg.overflowMax}); o esperar a que termine una de las sesiones activas.`);
130
+ }
131
+ }
132
+
133
+ const candidates = usable.filter((s) => s.sessionId).sort(byOldestFirst);
134
+ notify.push("No hay cupo: elegí una sesión para sustituir o cancelá (sin respuesta no se cambia nada).");
135
+ return { kind: "ask", candidates, notify };
136
+ }
137
+
138
+ /** Siguiente id libre: `pool-NN` base (01..10) o extensión (11..15). */
139
+ export function nextSlotId(slots: SlotInfo[], overflow: boolean): string {
140
+ const taken = new Set(slots.map((s) => s.slot));
141
+ const start = overflow ? 11 : 1;
142
+ for (let n = start; n < start + 100; n++) {
143
+ const id = `pool-${String(n).padStart(2, "0")}`;
144
+ if (!taken.has(id)) return id;
145
+ }
146
+ throw new Error("no hay ids de slot disponibles");
147
+ }
148
+
149
+ /** Revisión monotónica al reciclar: continúa desde la del slot, nunca retrocede. */
150
+ /**
151
+ * Extrae el título de una sesión de la salida JSON de `opencode session list --format json`.
152
+ * Devuelve null si no existe, si el título está vacío o si OpenCode lo dejó como "Untitled session".
153
+ */
154
+ export function parseSessionListTitle(json: string, sessionId: string): string | null {
155
+ let rows: unknown;
156
+ try { rows = JSON.parse(json); } catch { return null; }
157
+ if (!Array.isArray(rows)) return null;
158
+ const row = rows.find((r: any) => r && r.id === sessionId) as { title?: unknown } | undefined;
159
+ if (!row || typeof row.title !== "string") return null;
160
+ const title = row.title.trim();
161
+ if (!title || title === "Untitled session") return null;
162
+ return title.slice(0, 120);
163
+ }
164
+
165
+ export function nextRevision(previousRevision: number): number {
166
+ return Math.max(0, Math.floor(previousRevision)) + 1;
167
+ }
@@ -0,0 +1,394 @@
1
+ /**
2
+ * session-store — mirror de src/session-store.ts
3
+ * Generado desde src/session-store.ts — NO EDITAR. Ejecutá `bun run scripts/sync-controller-core.ts`.
4
+ */
5
+
6
+ /**
7
+ * Almacén de slots por sesión (session-state-files): índice compartido + archivos de slot.
8
+ *
9
+ * Layout bajo `<opencodeDir>/sessions/`:
10
+ * index.json índice (revision, slots, migrated) — escrito bajo lock, atómico (tmp + rename)
11
+ * pool-NN.json state de cada slot (formato del controller)
12
+ *
13
+ * La decisión de asignación vive en session-slots.ts (pura). Este módulo hace el I/O.
14
+ * Si el controller MCP o el plugin cambian, deben usar `bindSession` / `checkBinding` de aquí.
15
+ */
16
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { DEFAULT_STATE } from "./controller-core.ts";
19
+ import { decideSlot, isActiveSlot, nextRevision, type PoolConfig, type SlotInfo } from "./session-slots.ts";
20
+
21
+ export interface SlotRecord {
22
+ sessionId: string | null;
23
+ sessionName: string | null;
24
+ requestId: string | null;
25
+ changeId: string | null;
26
+ state: string | null;
27
+ ownerHeartbeat: number;
28
+ assignedAt: number;
29
+ lastUsedAt: number;
30
+ overflow: boolean;
31
+ quarantined: boolean;
32
+ quarantineReason: string | null;
33
+ }
34
+
35
+ export interface SessionIndex {
36
+ version: 1;
37
+ revision: number;
38
+ migrated: boolean;
39
+ slots: Record<string, SlotRecord>;
40
+ /** Sesiones sustituidas por confirmación: bloqueadas hasta iniciar una sesión nueva. */
41
+ replaced?: Record<string, { slot: string; at: number }>;
42
+ /** Última edición validada por archivo (aviso concurrent_edit). */
43
+ fileActivity?: Record<string, { sessionId: string; sessionName: string | null; requestId: string | null; ts: number }>;
44
+ }
45
+
46
+ export interface ConcurrentEditWarning {
47
+ file: string;
48
+ otherName: string;
49
+ otherRequestId: string | null;
50
+ minutesAgo: number;
51
+ }
52
+
53
+ const FILE_ACTIVITY_RETENTION_MS = 24 * 60 * 60 * 1000;
54
+
55
+ /**
56
+ * Registra una edición validada del archivo por la sesión y devuelve avisos si otra sesión lo
57
+ * editó dentro de `windowMs`. No bloquea: solo informa (concurrent_edit).
58
+ */
59
+ export function noteFileEdit(opencodeDir: string, sessionId: string, filePath: string, now: number, windowMs: number): ConcurrentEditWarning[] {
60
+ return withIndexLock(opencodeDir, () => {
61
+ const idx = readIndex(opencodeDir);
62
+ const own = Object.values(idx.slots).find((r) => r.sessionId === sessionId);
63
+ if (!own) return [];
64
+ const activity = idx.fileActivity ?? {};
65
+ for (const [file, entry] of Object.entries(activity)) {
66
+ if (now - entry.ts > FILE_ACTIVITY_RETENTION_MS) delete activity[file];
67
+ }
68
+ const prev = activity[filePath];
69
+ const warnings: ConcurrentEditWarning[] = [];
70
+ if (prev && prev.sessionId !== sessionId && now - prev.ts <= windowMs) {
71
+ warnings.push({
72
+ file: filePath,
73
+ otherName: prev.sessionName || prev.requestId || "sesión sin nombre",
74
+ otherRequestId: prev.requestId,
75
+ minutesAgo: Math.round((now - prev.ts) / 60000),
76
+ });
77
+ }
78
+ activity[filePath] = { sessionId, sessionName: own.sessionName, requestId: own.requestId, ts: now };
79
+ idx.fileActivity = activity;
80
+ idx.revision += 1;
81
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
82
+ return warnings;
83
+ });
84
+ }
85
+
86
+ export type BindResult =
87
+ | { kind: "bound"; slot: string; statePath: string; notify: string[] }
88
+ | { kind: "ask"; candidates: Array<SlotInfo & { sessionName: string | null }>; notify: string[] }
89
+ | { kind: "blocked"; reason: string };
90
+
91
+ export function sessionsDir(opencodeDir: string): string {
92
+ return join(opencodeDir, "sessions");
93
+ }
94
+
95
+ export function slotPath(opencodeDir: string, slot: string): string {
96
+ return join(sessionsDir(opencodeDir), `${slot}.json`);
97
+ }
98
+
99
+ function indexPath(opencodeDir: string): string {
100
+ return join(sessionsDir(opencodeDir), "index.json");
101
+ }
102
+
103
+ function emptyIndex(): SessionIndex {
104
+ return { version: 1, revision: 0, migrated: false, slots: {} };
105
+ }
106
+
107
+ export function readIndex(opencodeDir: string): SessionIndex {
108
+ try {
109
+ const parsed = JSON.parse(readFileSync(indexPath(opencodeDir), "utf-8"));
110
+ if (parsed && typeof parsed === "object" && parsed.slots && typeof parsed.slots === "object") return parsed as SessionIndex;
111
+ } catch {}
112
+ return emptyIndex();
113
+ }
114
+
115
+ function writeAtomic(path: string, content: string): void {
116
+ const tmp = `${path}.tmp.${process.pid}.${Date.now()}`;
117
+ writeFileSync(tmp, content, "utf-8");
118
+ renameSync(tmp, path);
119
+ }
120
+
121
+ function sleepSync(ms: number): void {
122
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
123
+ }
124
+
125
+ /** Lock de índice: directorio `index.json.lock` creado con mkdir (atómico). Lock viejo (>15s) se libera. */
126
+ function withIndexLock<T>(opencodeDir: string, fn: () => T): T {
127
+ mkdirSync(sessionsDir(opencodeDir), { recursive: true });
128
+ const lockDir = indexPath(opencodeDir) + ".lock";
129
+ for (let attempt = 0; attempt < 200; attempt++) {
130
+ try {
131
+ mkdirSync(lockDir);
132
+ try {
133
+ return fn();
134
+ } finally {
135
+ try { rmSync(lockDir, { recursive: true, force: true }); } catch {}
136
+ }
137
+ } catch (err: any) {
138
+ if (err?.code !== "EEXIST") throw err;
139
+ try {
140
+ const ageMs = Date.now() - statMtime(lockDir);
141
+ if (ageMs > 15_000) rmSync(lockDir, { recursive: true, force: true });
142
+ } catch {}
143
+ sleepSync(10 + Math.floor(Math.random() * 20));
144
+ }
145
+ }
146
+ throw new Error("no se pudo tomar el lock del índice de sesiones");
147
+ }
148
+
149
+ function statMtime(path: string): number {
150
+ return statSync(path).mtimeMs;
151
+ }
152
+
153
+ function toInfo(slot: string, r: SlotRecord): SlotInfo {
154
+ return {
155
+ slot,
156
+ overflow: r.overflow,
157
+ quarantined: r.quarantined,
158
+ sessionId: r.sessionId,
159
+ requestId: r.requestId,
160
+ state: r.state,
161
+ ownerHeartbeat: r.ownerHeartbeat,
162
+ lastUsedAt: r.lastUsedAt,
163
+ };
164
+ }
165
+
166
+ function resetSlotFile(opencodeDir: string, slot: string, previousRevision: number): void {
167
+ const state = { ...structuredClone(DEFAULT_STATE), revision: nextRevision(previousRevision) };
168
+ writeAtomic(slotPath(opencodeDir, slot), JSON.stringify(state, null, 2));
169
+ }
170
+
171
+ function readSlotRevision(opencodeDir: string, slot: string): number {
172
+ try {
173
+ const st = JSON.parse(readFileSync(slotPath(opencodeDir, slot), "utf-8"));
174
+ return typeof st.revision === "number" ? st.revision : 0;
175
+ } catch {
176
+ return 0;
177
+ }
178
+ }
179
+
180
+ /** Valida un archivo de slot; si falla, devuelve el motivo. */
181
+ function slotProblem(opencodeDir: string, slot: string): string | null {
182
+ const path = slotPath(opencodeDir, slot);
183
+ if (!existsSync(path)) return null;
184
+ try {
185
+ const st = JSON.parse(readFileSync(path, "utf-8"));
186
+ if (!st || typeof st !== "object" || typeof st.state !== "string") return "estado sin campo state";
187
+ return null;
188
+ } catch (err: any) {
189
+ return `JSON inválido: ${err?.message ?? "error"}`;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Asigna (o reutiliza) un slot a la sesión. Bajo lock del índice.
195
+ * `replaceSlot` = confirmación explícita del usuario para sustituir un slot ocupado.
196
+ */
197
+ export function bindSession(args: {
198
+ opencodeDir: string;
199
+ sessionId: string;
200
+ sessionName?: string | null;
201
+ now: number;
202
+ cfg: PoolConfig;
203
+ legacyStatePath?: string;
204
+ replaceSlot?: string | null;
205
+ /** Confirmación del usuario para crear slots de extensión con 10 activas. */
206
+ allowOverflow?: boolean;
207
+ }): BindResult {
208
+ const { opencodeDir, sessionId, now, cfg } = args;
209
+ const name = args.sessionName ?? null;
210
+ return withIndexLock(opencodeDir, () => {
211
+ const idx = readIndex(opencodeDir);
212
+
213
+ // Migración única del state legado al primer slot libre.
214
+ if (!idx.migrated && args.legacyStatePath && existsSync(args.legacyStatePath) && Object.keys(idx.slots).length === 0) {
215
+ const legacy = readFileSync(args.legacyStatePath, "utf-8");
216
+ writeAtomic(slotPath(opencodeDir, "pool-01"), legacy);
217
+ idx.slots["pool-01"] = emptyRecord({ requestId: null });
218
+ idx.migrated = true;
219
+ try { renameSync(args.legacyStatePath, args.legacyStatePath + ".migrated"); } catch {}
220
+ }
221
+
222
+ // Cuarentena: slot con archivo inválido no cuenta como libre.
223
+ for (const [slot, rec] of Object.entries(idx.slots)) {
224
+ const problem = slotProblem(opencodeDir, slot);
225
+ if (problem) {
226
+ rec.quarantined = true;
227
+ rec.quarantineReason = problem;
228
+ }
229
+ }
230
+
231
+ const view: SlotInfo[] = Object.entries(idx.slots).map(([s, r]) => toInfo(s, r));
232
+ const names = new Map(Object.entries(idx.slots).map(([s, r]) => [s, r.sessionName]));
233
+
234
+ // Sustitución confirmada por el usuario.
235
+ if (args.replaceSlot) {
236
+ const target = idx.slots[args.replaceSlot];
237
+ if (!target) return { kind: "blocked", reason: `slot ${args.replaceSlot} no existe` } as BindResult;
238
+ resetSlotFile(opencodeDir, args.replaceSlot, readSlotRevision(opencodeDir, args.replaceSlot));
239
+ if (target.sessionId) {
240
+ idx.replaced = idx.replaced ?? {};
241
+ idx.replaced[target.sessionId] = { slot: args.replaceSlot, at: now };
242
+ }
243
+ Object.assign(target, emptyRecord({ sessionId, sessionName: name, assignedAt: now, lastUsedAt: now, ownerHeartbeat: now, overflow: target.overflow }));
244
+ idx.revision += 1;
245
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
246
+ return { kind: "bound", slot: args.replaceSlot, statePath: slotPath(opencodeDir, args.replaceSlot), notify: [`Slot ${args.replaceSlot} sustituido por confirmación del usuario (slot_takeover).`] };
247
+ }
248
+
249
+ const replacedInfo = idx.replaced?.[sessionId];
250
+ if (replacedInfo) {
251
+ return { kind: "blocked", reason: `tu sesión fue sustituida en ${replacedInfo.slot} por confirmación del usuario; iniciá una sesión nueva de OpenCode para continuar` };
252
+ }
253
+
254
+ const own = Object.entries(idx.slots).find(([, r]) => r.sessionId === sessionId && !r.quarantined);
255
+ if (own) {
256
+ const rec = own[1];
257
+ rec.lastUsedAt = now;
258
+ rec.ownerHeartbeat = now;
259
+ if (name) rec.sessionName = name;
260
+ idx.revision += 1;
261
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
262
+ return { kind: "bound", slot: own[0], statePath: slotPath(opencodeDir, own[0]), notify: [] };
263
+ }
264
+
265
+ const decision = decideSlot(sessionId, view, now, cfg, { allowOverflow: !!args.allowOverflow });
266
+ if (decision.kind === "ask") {
267
+ return {
268
+ kind: "ask",
269
+ candidates: decision.candidates.map((c) => ({ ...c, sessionName: names.get(c.slot) ?? null })),
270
+ notify: decision.notify,
271
+ };
272
+ }
273
+
274
+ let slot: string;
275
+ let notify: string[] = [];
276
+ if (decision.kind === "create") {
277
+ slot = decision.slot;
278
+ notify = decision.notify;
279
+ idx.slots[slot] = emptyRecord({ overflow: decision.overflow });
280
+ resetSlotFile(opencodeDir, slot, 0);
281
+ } else if (decision.kind === "free") {
282
+ // Libre: conserva el contenido (p. ej. state migrado del legado); no se vacía.
283
+ slot = decision.slot;
284
+ idx.slots[slot] = emptyRecord({ overflow: idx.slots[slot].overflow });
285
+ } else {
286
+ slot = decision.slot;
287
+ if (decision.kind === "recycle") notify = decision.notify;
288
+ const overflow = idx.slots[slot].overflow;
289
+ resetSlotFile(opencodeDir, slot, readSlotRevision(opencodeDir, slot));
290
+ idx.slots[slot] = emptyRecord({ overflow });
291
+ }
292
+ const rec = idx.slots[slot];
293
+ rec.sessionId = sessionId;
294
+ rec.sessionName = name;
295
+ rec.assignedAt = now;
296
+ rec.lastUsedAt = now;
297
+ rec.ownerHeartbeat = now;
298
+ idx.revision += 1;
299
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
300
+ return { kind: "bound", slot, statePath: slotPath(opencodeDir, slot), notify };
301
+ });
302
+ }
303
+
304
+ function emptyRecord(patch: Partial<SlotRecord> = {}): SlotRecord {
305
+ return {
306
+ sessionId: null,
307
+ sessionName: null,
308
+ requestId: null,
309
+ changeId: null,
310
+ state: null,
311
+ ownerHeartbeat: 0,
312
+ assignedAt: 0,
313
+ lastUsedAt: 0,
314
+ overflow: false,
315
+ quarantined: false,
316
+ quarantineReason: null,
317
+ ...patch,
318
+ };
319
+ }
320
+
321
+ /**
322
+ * Comprueba que el slot de la sesión sigue siendo suyo (no fue sustituido).
323
+ * Lectura sin lock: las escrituras del índice son atómicas (rename).
324
+ */
325
+ export function checkBinding(opencodeDir: string, sessionId: string): { ok: true; slot: string } | { ok: false; reason: string } {
326
+ const idx = readIndex(opencodeDir);
327
+ if (idx.replaced?.[sessionId]) return { ok: false, reason: `sesión sustituida en ${idx.replaced[sessionId].slot}` };
328
+ const own = Object.entries(idx.slots).find(([, r]) => r.sessionId === sessionId);
329
+ if (!own) return { ok: false, reason: "la sesión no tiene slot asignado" };
330
+ return { ok: true, slot: own[0] };
331
+ }
332
+
333
+ /** Actualiza el resumen de la request del slot (para listar candidatas y para el aviso de concurrencia). */
334
+ export function recordRequestSummary(opencodeDir: string, sessionId: string, summary: { requestId: string | null; changeId: string | null; state: string | null }, now: number): void {
335
+ withIndexLock(opencodeDir, () => {
336
+ const idx = readIndex(opencodeDir);
337
+ const own = Object.entries(idx.slots).find(([, r]) => r.sessionId === sessionId);
338
+ if (!own) return;
339
+ Object.assign(own[1], { requestId: summary.requestId, changeId: summary.changeId, state: summary.state, lastUsedAt: now, ownerHeartbeat: now });
340
+ idx.revision += 1;
341
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
342
+ });
343
+ }
344
+
345
+ /** Renueva el heartbeat de la sesión (cada mutación). */
346
+ export function touchSession(opencodeDir: string, sessionId: string, now: number): void {
347
+ withIndexLock(opencodeDir, () => {
348
+ const idx = readIndex(opencodeDir);
349
+ const own = Object.entries(idx.slots).find(([, r]) => r.sessionId === sessionId);
350
+ if (!own) return;
351
+ own[1].ownerHeartbeat = now;
352
+ own[1].lastUsedAt = now;
353
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
354
+ });
355
+ }
356
+
357
+ /** Resumen del pool para `doctor` y para la pregunta al usuario. Solo lectura. */
358
+ export function poolReport(opencodeDir: string, now: number, cfg: PoolConfig): {
359
+ base: number; overflow: number; active: number; quarantined: string[]; occupied: Array<SlotInfo & { sessionName: string | null; active: boolean }>;
360
+ } {
361
+ const idx = readIndex(opencodeDir);
362
+ const entries = Object.entries(idx.slots);
363
+ const infos = entries.map(([s, r]) => toInfo(s, r));
364
+ const active = infos.filter((i) => i.sessionId && i.requestId && i.ownerHeartbeat > 0 && now - i.ownerHeartbeat <= cfg.activeMs && !["DONE", "ABANDONED"].includes(i.state ?? "")).length;
365
+ return {
366
+ base: entries.filter(([, r]) => !r.overflow).length,
367
+ overflow: entries.filter(([, r]) => r.overflow).length,
368
+ active,
369
+ quarantined: entries.filter(([, r]) => r.quarantined).map(([s, r]) => `${s}: ${r.quarantineReason ?? "motivo desconocido"}`),
370
+ occupied: infos
371
+ .filter((i) => i.sessionId)
372
+ .sort((a, b) => a.lastUsedAt - b.lastUsedAt)
373
+ .map((i) => ({ ...i, sessionName: idx.slots[i.slot].sessionName, active: isActiveSlot(i, now, cfg) })),
374
+ };
375
+ }
376
+
377
+
378
+ /** Prefijo del archivo de handoff de compaction (uno por sesión; sin sesión, el nombre legado). */
379
+ export const HANDOFF_FALLBACK_BASE = ".ostacky-handoff-compaction";
380
+
381
+ /**
382
+ * Ruta del fallback de compaction de una sesión. Ancla fija: el directorio .opencode del proyecto
383
+ * (no el de un slot). Con OSTACKY_SESSION_SLOTS=off o sin sesión usa el nombre legado.
384
+ */
385
+ export function handoffFallbackPath(opencodeDir: string, sessionId?: string | null): string {
386
+ const sid = process.env.OSTACKY_SESSION_SLOTS === "off" ? null : sessionId;
387
+ const key = sid ? sid.replace(/[^A-Za-z0-9_-]/g, "_") : null;
388
+ return join(opencodeDir, key ? `${HANDOFF_FALLBACK_BASE}-${key}.json` : `${HANDOFF_FALLBACK_BASE}.json`);
389
+ }
390
+
391
+ /** true si el nombre es un archivo de fallback de compaction (legado o por sesión). */
392
+ export function isHandoffFallbackFile(name: string): boolean {
393
+ return name === HANDOFF_FALLBACK_BASE + ".json" || (name.startsWith(HANDOFF_FALLBACK_BASE + "-") && name.endsWith(".json"));
394
+ }
@@ -31,6 +31,35 @@ export function isTrivial(msg: string, state: string): boolean {
31
31
  return true
32
32
  }
33
33
 
34
+ /**
35
+ * Pregunta sobre hechos ya ejecutados en ESTA sesión (qué hicimos, qué cambió, qué falta).
36
+ * Se responde desde el contexto + ostacky_get_state, sin codegraph ni mem_search.
37
+ * Excluye pedidos de acción o propuesta: ante la duda gana "work" (costo completo, fail-safe).
38
+ */
39
+ const SESSION_RECALL_RE =
40
+ /\b(qu[eé]\s+(hicimos|hiciste|hizo|cambiamos|cambiaste|cambi[oó]|tocamos|tocaste|modificamos|modificaste|complet[oó]|completamos|falt[ao]n?|qued[oó]|quedaron|pendientes?)|(resum[ií]|resumen)\s+(de\s+)?(lo|la|esto|esta|el)\b|por\s+qu[eé]\s+(elegiste|decidiste|cambiaste|hiciste)|(cu[aá]l|cu[aá]les)\s+(fue|fueron|son|era|eran)\s+(los?|las?)?\s*(cambios?|archivos?|tasks?|pendientes?))\b/i;
41
+
42
+ const SESSION_ACTION_RE =
43
+ /\b(propon\w*|sugier\w*|recomend\w*|arregl\w*|implement\w*|agreg\w*|cre(a|á)\w*|borr\w*|modific\w*|corr(e|é|ig\w*)|continu\w*|ejecut\w*|refactor\w*|fix\w*|hac(e|é)r?|cambi(a|á)\b|escrib\w*|quit\w*|actualiz\w*)/i;
44
+
45
+ export function isSessionQuestion(msg: string): boolean {
46
+ if (!msg || msg.trim().length === 0) return false
47
+ if (SESSION_ACTION_RE.test(msg)) return false
48
+ return SESSION_RECALL_RE.test(msg)
49
+ }
50
+
51
+ export type Intent = "greeting" | "session_question" | "work"
52
+
53
+ /**
54
+ * Clasificación única de intención del prompt. Orden: saludo > pregunta de sesión > trabajo.
55
+ * `greeting` conserva la semántica histórica de isTrivial (solo estado DONE).
56
+ */
57
+ export function classifyIntent(msg: string, state: string): Intent {
58
+ if (isTrivial(msg, state)) return "greeting"
59
+ if (isSessionQuestion(msg)) return "session_question"
60
+ return "work"
61
+ }
62
+
34
63
  export function getControllerState(directory: string): string {
35
64
  try {
36
65
  const { readFileSync } = require("node:fs") as typeof import("node:fs")