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.
@@ -17,10 +17,14 @@
17
17
  // (solo tipos, borrado al transpilar) cargan sin dependencias externas.
18
18
  import type { Plugin } from "@opencode/plugin"
19
19
  import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, statSync, readdirSync, unlinkSync } from "node:fs"
20
- import { join, dirname, basename, resolve, relative, delimiter } from "node:path"
20
+ import { join, dirname, basename, resolve, relative, delimiter, sep } from "node:path"
21
+ import { homedir } from "node:os"
22
+ import { fileURLToPath } from "node:url"
21
23
  import { SENSITIVE_DEFAULT, BASH_SENSITIVE_RE, isSensitive, extractPathsFromBash } from "./security.ts"
22
- import { isTrivial } from "./tiered.ts"
23
- import { STATES, TRANSITIONS, DEFAULT_STATE } from "./controller-core.ts"
24
+ import { classifyIntent } from "./tiered.ts"
25
+ import { contextTokens as normalizeContextTokens, parseCompactConfig, compactDecision, COMPACT_DEFAULTS } from "./compaction-threshold.ts"
26
+ import { checkBinding, readIndex, slotPath as slotFilePath, handoffFallbackPath } from "./session-store.ts"
27
+ import { STATES, TRANSITIONS, DEFAULT_STATE, normalizeTestCommand, isMaskedExitCommand } from "./controller-core.ts"
24
28
 
25
29
  // ─── Constants ───────────────────────────────────────────────────────────────
26
30
 
@@ -30,6 +34,92 @@ const IDLE_THRESHOLD_MS = 45_000
30
34
 
31
35
  // DEFAULT_STATE imported from controller-core.ts
32
36
 
37
+ // ─── Scope (global vs local) ─────────────────────────────────────────────────
38
+ //
39
+ // OpenCode V2 dedupea plugins por `id` y conserva la PRIMERA ocurrencia en
40
+ // orden de arranque (el config global se descubre antes que el del proyecto).
41
+ // Con el mismo id en las dos copias, la global gana y la local queda
42
+ // `failed: "Duplicate plugin ID"` — el controller deja de aplicar sus gates sin
43
+ // avisar. Para que la precedencia sea local-primero (igual que el resto de la
44
+ // config de OpenCode), la copia global declara OTRO id y se retira sola cuando
45
+ // el proyecto tiene instalación local.
46
+
47
+ /**
48
+ * Config dir GLOBAL de OpenCode. Espeja `Global.Path.config` de OpenCode v2 en
49
+ * las tres plataformas: `OPENCODE_CONFIG_DIR` (override total, sin sufijo) →
50
+ * `$XDG_CONFIG_HOME/opencode` → `~/.config/opencode`. En Windows NO se usa
51
+ * `%APPDATA%` (OpenCode tampoco lo usa para config).
52
+ */
53
+ export function resolveGlobalConfigDir(opts?: {
54
+ env?: NodeJS.ProcessEnv
55
+ home?: string
56
+ }): string {
57
+ const env = opts?.env ?? process.env
58
+ const home = opts?.home ?? homedir()
59
+ const explicit = env.OPENCODE_CONFIG_DIR?.trim()
60
+ if (explicit) return explicit
61
+ const xdg = env.XDG_CONFIG_HOME?.trim()
62
+ if (xdg) return join(xdg, "opencode")
63
+ return join(home, ".config", "opencode")
64
+ }
65
+
66
+ /**
67
+ * id por copia: la global usa uno propio para no colisionar con la local.
68
+ * En win32 la comparación es case-insensitive porque los paths de Windows lo
69
+ * son: si el path real y el config dir difieren en mayúsculas, sin esto la
70
+ * copia global se clasificaría como local y volvería la colisión de ids.
71
+ */
72
+ export function pluginIdFor(
73
+ pluginDir: string,
74
+ globalDir: string,
75
+ platform: string = process.platform
76
+ ): string {
77
+ if (!pluginDir) return "ostacky-controller"
78
+ try {
79
+ const norm = (p: string) => {
80
+ const abs = resolve(p)
81
+ return platform === "win32" ? abs.toLowerCase() : abs
82
+ }
83
+ const d = norm(pluginDir)
84
+ const g = norm(globalDir)
85
+ if (d === g || d.startsWith(g + sep)) return "ostacky-controller-global"
86
+ } catch {}
87
+ return "ostacky-controller"
88
+ }
89
+
90
+ /**
91
+ * ¿El proyecto tiene el plugin instalado en scope local? Mira solo el location
92
+ * dir (lo que descubre OpenCode), no ancestros: si el local vive en un ancestro
93
+ * que el server no carga, ceder la precedencia dejaría el proyecto sin gates.
94
+ */
95
+ export function hasLocalPluginInstall(directory: string): boolean {
96
+ let dir: string
97
+ try {
98
+ dir = resolve(directory)
99
+ } catch {
100
+ return false
101
+ }
102
+ for (const kind of ["plugins", "plugin"]) {
103
+ for (const entry of ["index.ts", "index.js"]) {
104
+ try {
105
+ if (existsSync(join(dir, ".opencode", kind, "ostacky-controller", entry))) return true
106
+ } catch {}
107
+ }
108
+ }
109
+ return false
110
+ }
111
+
112
+ const PLUGIN_DIR = (() => {
113
+ try {
114
+ return dirname(fileURLToPath(import.meta.url))
115
+ } catch {
116
+ return ""
117
+ }
118
+ })()
119
+
120
+ const IS_GLOBAL_COPY = PLUGIN_DIR !== "" && pluginIdFor(PLUGIN_DIR, resolveGlobalConfigDir()) === "ostacky-controller-global"
121
+ const PLUGIN_ID = IS_GLOBAL_COPY ? "ostacky-controller-global" : "ostacky-controller"
122
+
33
123
  // ─── Helpers ─────────────────────────────────────────────────────────────────
34
124
 
35
125
  function lookupOnPath(name: string): string | null {
@@ -48,9 +138,18 @@ function lookupOnPath(name: string): string | null {
48
138
  return null
49
139
  }
50
140
 
51
- function getStatePath(directory: string): string {
141
+ export function getStatePath(directory: string): string {
52
142
  if (process.env.OSTACKY_STATE_PATH) return process.env.OSTACKY_STATE_PATH
53
143
  const candidates = [join(directory, "opencode.json"), join(directory, "opencode.jsonc")]
144
+ // El MCP puede estar configurado en el opencode.json GLOBAL: si el plugin solo
145
+ // mira el del proyecto, lee/escribe OTRO state file y todos los gates (PENDING,
146
+ // ownership, lastValidated) quedan ciegos. Mismo orden que assets/plugins/engram.ts.
147
+ try {
148
+ const globalDir = resolveGlobalConfigDir()
149
+ if (globalDir) {
150
+ candidates.push(join(globalDir, "opencode.json"), join(globalDir, "opencode.jsonc"))
151
+ }
152
+ } catch {}
54
153
  for (const cand of candidates) {
55
154
  try {
56
155
  const raw = readFileSync(cand, "utf-8")
@@ -63,8 +162,34 @@ function getStatePath(directory: string): string {
63
162
  return join(directory, ".opencode", "ostacky-state.json")
64
163
  }
65
164
 
66
- function readState(directory: string): any | null {
67
- const p = getStatePath(directory)
165
+ /**
166
+ * Archivo de state de la sesión (session-state-files). Con slots activos, cada sesión tiene su
167
+ * slot en .opencode/sessions/; sin sessionId válido (o sin slot asignado) no hay state para ella.
168
+ * Con OSTACKY_SESSION_SLOTS=off se usa el state único legado (mismo comportamiento que antes).
169
+ * Debe coincidir con bindCallerSlot del MCP (assets/mcp/ostacky-controller/index.js).
170
+ */
171
+ export function resolveStatePath(directory: string, sessionId?: string | null): string | null {
172
+ const legacy = getStatePath(directory)
173
+ if (process.env.OSTACKY_SESSION_SLOTS === "off") return legacy
174
+ if (!sessionId || sessionId === "default") return null
175
+ const opencodeDir = dirname(legacy)
176
+ const bound = checkBinding(opencodeDir, sessionId)
177
+ return bound.ok ? slotFilePath(opencodeDir, bound.slot) : null
178
+ }
179
+
180
+ /**
181
+ * Session id del contexto de ejecución de un tool del plugin. "default" y ausencia cuentan como
182
+ * sin identidad. Con slots activos, sin identidad no hay state que leer (no se cae al legado).
183
+ */
184
+ export function toolSessionId(toolCtx: unknown): string | null {
185
+ const c = toolCtx as any
186
+ const v = c?.sessionID ?? c?.sessionId
187
+ return typeof v === "string" && v && v !== "default" ? v : null
188
+ }
189
+
190
+ export function readState(directory: string, sessionId?: string | null): any | null {
191
+ const p = resolveStatePath(directory, sessionId)
192
+ if (!p) return null
68
193
  try {
69
194
  const raw = readFileSync(p, "utf-8")
70
195
  return JSON.parse(raw)
@@ -73,6 +198,59 @@ function readState(directory: string): any | null {
73
198
  }
74
199
  }
75
200
 
201
+ /**
202
+ * Pendientes para recovery post-compaction. Fuente única del hook `compaction`
203
+ * y del hint de `chat.message`: lastHandoff → fallback <24h → expectedTasks.
204
+ * El checkpoint count-based del MCP solo escribe lastHandoff cada 3er
205
+ * complete_task, así que sin la tercera fuente el hint quedaba mudo en T1/T2.
206
+ */
207
+ export function recoveryPending(state: any, directory?: string, sessionId?: string | null): { pending: string[]; nextSteps: string[] } {
208
+ const isPending = (id: string) => !state?.tasks?.[id] || state.tasks[id].status !== "COMPLETED"
209
+ const fromExpected = () => (Array.isArray(state?.expectedTasks) ? state.expectedTasks.filter(isPending) : [])
210
+ let pending: string[] = Array.isArray(state?.lastHandoff?.pendingTasks)
211
+ ? state.lastHandoff.pendingTasks.filter(isPending)
212
+ : []
213
+ let nextSteps: string[] = Array.isArray(state?.lastHandoff?.nextSteps) ? state.lastHandoff.nextSteps : []
214
+ if (pending.length === 0 && directory) {
215
+ try {
216
+ const fallbackPath = handoffFallbackPath(dirname(getStatePath(directory)), sessionId)
217
+ if (existsSync(fallbackPath)) {
218
+ const data = JSON.parse(readFileSync(fallbackPath, "utf-8"))
219
+ if (data && Array.isArray(data.pendingTasks) && typeof data.ts === "number" && Date.now() - data.ts < 24 * 60 * 60 * 1000) {
220
+ pending = data.pendingTasks.filter(isPending)
221
+ if (Array.isArray(data.nextSteps) && data.nextSteps.length > 0) nextSteps = data.nextSteps
222
+ }
223
+ }
224
+ } catch {}
225
+ }
226
+ if (pending.length === 0) pending = fromExpected()
227
+ if (pending.length === 0) nextSteps = []
228
+ else if (nextSteps.length === 0) nextSteps = [`Continuar con ${pending.join(", ")}`]
229
+ return { pending, nextSteps }
230
+ }
231
+
232
+ /** Texto del hint de recovery (null si no hay pendientes). Puro: testeable sin hooks. */
233
+ export function recoveryHint(state: any, directory?: string, sessionId?: string | null): string | null {
234
+ if (!state || ["DONE", "INTERPRETATION_PENDING"].includes(state.state)) return null
235
+ const { pending } = recoveryPending(state, directory, sessionId)
236
+ if (pending.length === 0) return null
237
+ return `\n\n[RECOVERY: te quedan ${pending.slice(0, 3).join(",")}${pending.length > 3 ? `, +${pending.length - 3} más` : ""} - usa get_handoff / mem_context para retomar]`
238
+ }
239
+
240
+ /** Payload del fallback de compaction, con los pendientes reales del state. */
241
+ export function compactionPayload(state: any, directory: string, sessionID?: string, contextSnippet = "") {
242
+ const { pending, nextSteps } = recoveryPending(state, directory, sessionID)
243
+ return {
244
+ summary: state?.requestId
245
+ ? `Compaction fallback for request ${state.requestId} — ${pending.length} pendientes`
246
+ : `Compaction fallback for session ${sessionID ?? "unknown"} — plugin`,
247
+ nextSteps,
248
+ pendingTasks: pending,
249
+ ts: Date.now(),
250
+ contextSnippet,
251
+ }
252
+ }
253
+
76
254
  /** Sleep sincrónico acotado — los call sites del plugin son sync. */
77
255
  function sleepSync(ms: number): void {
78
256
  try {
@@ -97,10 +275,11 @@ function isPidAlive(pid: number): boolean {
97
275
 
98
276
  /**
99
277
  * Toma EL MISMO lock que el MCP (`<state>.lock.pid` con `wx`) para serializar
100
- * plugin ↔ MCP cross-proceso. Devuelve una función de release; si no se pudo
101
- * tomar, devuelve un no-op (la escritura sigue siendo segura por el merge).
278
+ * plugin ↔ MCP cross-proceso. Devuelve la función de release, o `null` si no se
279
+ * pudo tomar: el caller NO debe escribir sin lock — un `read` viejo + `rename`
280
+ * posterior puede revertir la transición que el MCP todavía no escribió.
102
281
  */
103
- function acquireStateLock(statePath: string): () => void {
282
+ function acquireStateLock(statePath: string): (() => void) | null {
104
283
  const pidPath = statePath + ".lock.pid"
105
284
  const tsPath = statePath + ".lock.timestamp"
106
285
  const staleWindow = 15_000
@@ -119,13 +298,21 @@ function acquireStateLock(statePath: string): () => void {
119
298
  } catch {}
120
299
  try {
121
300
  writeFileSync(pidPath, String(process.pid), { encoding: "utf-8", flag: "wx" })
122
- try { writeFileSync(tsPath, String(Date.now()), "utf-8") } catch {}
123
- acquired = true
301
+ try {
302
+ writeFileSync(tsPath, String(Date.now()), "utf-8")
303
+ acquired = true
304
+ } catch {
305
+ // Sin timestamp el lock es indistinguible de un huérfano y el MCP no
306
+ // puede liberarlo: queda pegado y ninguna escritura vuelve a entrar.
307
+ // Mejor soltarlo y reintentar.
308
+ try { unlinkSync(pidPath) } catch {}
309
+ sleepSync(5 + attempt * 10)
310
+ }
124
311
  } catch {
125
312
  sleepSync(5 + attempt * 10)
126
313
  }
127
314
  }
128
- if (!acquired) return () => {}
315
+ if (!acquired) return null
129
316
  return () => {
130
317
  try {
131
318
  if (readFileSync(pidPath, "utf-8").trim() !== String(process.pid)) return
@@ -139,6 +326,25 @@ function acquireStateLock(statePath: string): () => void {
139
326
 
140
327
  let persistSeq = 0
141
328
 
329
+ /**
330
+ * Patch que no se pudo escribir por falta de lock. Se aplica en la próxima
331
+ * escritura que sí lo consiga: perder un `lastValidated` rompería el gate de
332
+ * `complete_task`, pero escribir sin lock puede revertir un avance del MCP.
333
+ */
334
+ let pendingPatch: { patch: Record<string, unknown>; ts: number } | null = null
335
+ const PENDING_PATCH_TTL_MS = 60_000
336
+
337
+ function queuePatch(state: any, ownedKeys?: string[]): void {
338
+ if (!ownedKeys || ownedKeys.length === 0) return
339
+ const patch: Record<string, unknown> = {}
340
+ for (const k of ownedKeys) {
341
+ if (Object.prototype.hasOwnProperty.call(state, k)) patch[k] = state[k]
342
+ }
343
+ if (Object.keys(patch).length > 0) {
344
+ pendingPatch = { patch: { ...(pendingPatch?.patch ?? {}), ...patch }, ts: Date.now() }
345
+ }
346
+ }
347
+
142
348
  /**
143
349
  * Merge puro: parte del estado FRESCO de disco y le aplica SOLO las claves que
144
350
  * el plugin posee. Garantiza estructuralmente que una escritura del plugin no
@@ -193,12 +399,17 @@ export function nextPendingGateCache(
193
399
  * (4) write atómico (tmp único + rename). El `revision` se preserva del disco:
194
400
  * las escrituras del plugin no son transiciones de la máquina de estados.
195
401
  */
196
- export function persistState(directory: string, state: any, ownedKeys?: string[]): void {
197
- const p = getStatePath(directory)
402
+ export function persistState(directory: string, state: any, ownedKeys?: string[], sessionId?: string | null): void {
403
+ const p = resolveStatePath(directory, sessionId)
404
+ if (!p) return
198
405
  const dir = dirname(p)
199
406
  try { mkdirSync(dir, { recursive: true }) } catch {}
200
407
 
201
408
  const release = acquireStateLock(p)
409
+ if (!release) {
410
+ queuePatch(state, ownedKeys)
411
+ return
412
+ }
202
413
  try {
203
414
  let payload: any = state
204
415
  if (ownedKeys && ownedKeys.length > 0) {
@@ -207,6 +418,16 @@ export function persistState(directory: string, state: any, ownedKeys?: string[]
207
418
  if (fresh && typeof fresh === "object" && !Array.isArray(fresh)) {
208
419
  payload = mergePluginOwnedState(fresh, state, ownedKeys)
209
420
  }
421
+ if (pendingPatch) {
422
+ // TTL: un patch viejo (p.ej. de otra request) no debe satisfacer gates
423
+ // actuales, como un `lastValidated` que ya no corresponde.
424
+ if (Date.now() - pendingPatch.ts > PENDING_PATCH_TTL_MS) {
425
+ pendingPatch = null
426
+ } else {
427
+ payload = { ...payload, ...pendingPatch.patch }
428
+ pendingPatch = null
429
+ }
430
+ }
210
431
  }
211
432
  let serialized = JSON.stringify(payload, null, 2)
212
433
  if (serialized.length > MAX_STATE_FILE_SIZE) {
@@ -234,6 +455,34 @@ export function persistState(directory: string, state: any, ownedKeys?: string[]
234
455
  }
235
456
  }
236
457
 
458
+ /**
459
+ * Proyección del state que expone `ostacky_get_state`. Incluye los decision IDs:
460
+ * sin ellos el agente no puede consumir la decisión pendiente sin volver a
461
+ * llamar a get_state por MCP (fuente del doble pregunta).
462
+ */
463
+ export function projectStateForTool(state: any): Record<string, unknown> {
464
+ if (!state) return { error: "no state", state: "UNKNOWN", revision: 0 }
465
+ return {
466
+ state: state.state,
467
+ revision: state.revision,
468
+ requestId: state.requestId,
469
+ changeId: state.changeId ?? null,
470
+ degraded: !!state.degraded,
471
+ level: state.level ?? null,
472
+ routeChoice: state.routeChoice ?? null,
473
+ routeDecisionId: state.routeDecisionId ?? null,
474
+ executionDecisionId: state.executionDecisionId ?? null,
475
+ executionMode: state.executionMode ?? null,
476
+ // Hechos ejecutados (fuente para preguntas de sesión; no requiere CodeGraph ni Engram)
477
+ expectedTasks: Array.isArray(state.expectedTasks) ? state.expectedTasks : null,
478
+ completedTasks: Object.keys(state.tasks ?? {}).filter((id) => state.tasks[id]?.status === "COMPLETED"),
479
+ pendingTasks: Array.isArray(state.expectedTasks)
480
+ ? state.expectedTasks.filter((id: string) => state.tasks?.[id]?.status !== "COMPLETED")
481
+ : null,
482
+ editedFiles: Object.keys(state.fileFingerprints ?? {}),
483
+ }
484
+ }
485
+
237
486
  function fastFingerprint(filePath: string): string | null {
238
487
  try {
239
488
  const s = statSync(filePath)
@@ -268,6 +517,50 @@ function isCodegraphAvailable(directory: string): boolean {
268
517
  } catch { return false }
269
518
  }
270
519
 
520
+ /** Modo del gate de CodeGraph: auto (degrada ante fallo real), strict (nunca degrada), off (sin gate). */
521
+ export type CodegraphMode = "auto" | "strict" | "off"
522
+
523
+ export function codegraphMode(env: Record<string, string | undefined> = process.env): CodegraphMode {
524
+ const v = (env.OSTACKY_CODEGRAPH || "auto").trim().toLowerCase()
525
+ return v === "strict" || v === "off" ? v : "auto"
526
+ }
527
+
528
+ export const CODEGRAPH_DEGRADED_TTL_MIN_DEFAULT = 30
529
+
530
+ /** TTL de la degradación en minutos (OSTACKY_CODEGRAPH_DEGRADED_TTL_MIN); inválido → default. */
531
+ export function codegraphDegradedTtlMs(env: Record<string, string | undefined> = process.env): number {
532
+ const n = Number(env.OSTACKY_CODEGRAPH_DEGRADED_TTL_MIN)
533
+ const min = Number.isFinite(n) && n > 0 ? n : CODEGRAPH_DEGRADED_TTL_MIN_DEFAULT
534
+ return min * 60_000
535
+ }
536
+
537
+ /**
538
+ * ¿Este resultado de tool es un fallo real de CodeGraph (MCP caído, error o timeout de explore)?
539
+ * Solo cuenta `codegraph_explore`: es la tool que el gate exige para abrir la lectura de código.
540
+ * Un explore completado (aunque vacío) NO es fallo.
541
+ */
542
+ export function marksCodegraphFailure(toolName: string, status: unknown): boolean {
543
+ return toolName.includes("codegraph_explore") && (status === "error" || status === "failed" || status === "timeout")
544
+ }
545
+
546
+ /**
547
+ * ¿El gate de lectura de código está activo para esta sesión?
548
+ * - off: nunca. Sin binario/PATH: nunca (no hay CodeGraph que exigir).
549
+ * - strict: siempre que haya CodeGraph, ignorando degradación.
550
+ * - auto: inactivo mientras la sesión esté degradada; vuelve a activo al vencer el TTL.
551
+ */
552
+ export function isCodegraphGateActive(input: {
553
+ mode: CodegraphMode
554
+ available: boolean
555
+ degradedSince: number | null
556
+ now: number
557
+ ttlMs: number
558
+ }): boolean {
559
+ if (input.mode === "off" || !input.available) return false
560
+ if (input.mode === "strict" || input.degradedSince === null) return true
561
+ return input.now - input.degradedSince >= input.ttlMs
562
+ }
563
+
271
564
  /**
272
565
  * ¿Este read/grep/glob esta sujeto al gate de discovery?
273
566
  * Exenciones: docs/json/md, openspec/changes|specs, grep de literales, y archivos ya
@@ -368,6 +661,14 @@ export function shellEvidence(event: any): { cmd: string; exit: number; ts: numb
368
661
  return { cmd: cmd.trim(), exit, ts: Date.now() }
369
662
  }
370
663
 
664
+ /** Log estructurado opt-in: no ensucia el server log salvo OSTACKY_DEBUG=1. */
665
+ function debugLog(event: string, data?: any): void {
666
+ if (process.env.OSTACKY_DEBUG !== "1") return
667
+ try {
668
+ console.log(JSON.stringify({ level: "debug", event, ...(data || {}) }))
669
+ } catch {}
670
+ }
671
+
371
672
  /** Tools que mutan archivos: avanzan `lastMutationTs`. */
372
673
  export function isMutatingTool(tool: string): boolean {
373
674
  return tool === "edit" || tool === "write" || tool === "patch"
@@ -479,7 +780,7 @@ export function isShellPathExempt(p: string, directory: string, freshState: any)
479
780
  return false
480
781
  }
481
782
 
482
- /** Comandos `test:` declarados en taskVerifications, ya normalizados (sin prefijo). */
783
+ /** Comandos `test:` declarados en taskVerifications, tal cual (el matching los normaliza). */
483
784
  export function testVerifyCommands(state: any): Set<string> {
484
785
  const out = new Set<string>()
485
786
  try {
@@ -525,18 +826,28 @@ function extractPathsFromPatch(patchText: string): string[] {
525
826
  // Objeto literal directo (ver nota en imports): el server V2 acepta
526
827
  // `{ id, setup }` sin pasar por `Plugin.define()`.
527
828
  export default {
528
- id: "ostacky-controller",
829
+ id: PLUGIN_ID,
529
830
  async setup(ctx) {
530
831
  const directory = ctx.location.directory
531
832
 
833
+ // Precedencia local: si el proyecto tiene su propia instalación, esta copia
834
+ // global no registra hooks ni tools (OpenCode ya la cargó porque el config
835
+ // global se descubre primero; ver nota de scope arriba).
836
+ if (IS_GLOBAL_COPY && hasLocalPluginInstall(directory)) return
837
+
532
838
  // Track trivial flag per session to gate tools
533
839
  const trivialBySession = new Map<string, boolean>()
840
+ // Pregunta sobre hechos ya ejecutados: responde desde contexto + ostacky_get_state (no discovery ni Engram)
841
+ const sessionQuestionBySession = new Map<string, boolean>()
534
842
  // Track discovery hit per requestId to avoid blocking after hit
535
843
  const discoveryHitByRequest = new Map<string, boolean>()
844
+ // Degradación de CodeGraph por sesión: timestamp del último fallo real de codegraph_explore.
845
+ const codegraphDegradedBySession = new Map<string, number>()
536
846
  // Track Engram hit per session to audit bypass (soft, no BLOCK)
537
847
  const engramHitBySession = new Map<string, boolean>()
848
+ // Compactación asistida: tokens acumulados por sesión (contextTokens normalizado por proveedor)
849
+ const contextTokensBySession = new Map<string, { tokens: number; provider?: string; model?: string; lastCompactTs?: number; lastStepTs?: number }>()
538
850
  // ─── Heartbeat ping — evita sensación de trancado en tareas largas ──
539
- let lastPingTs = 0
540
851
  let pingInterval: ReturnType<typeof setInterval> | null = null
541
852
 
542
853
  const patterns = (() => {
@@ -548,26 +859,42 @@ export default {
548
859
  let lastCheck: { revision: number; result: string } | null = null
549
860
  let checkCount = 0
550
861
 
551
- // Heartbeat ping — evita sensación de trancado en tareas largas
552
- // (V2: sin canal TUI en ctx; se loguea al server log y se persiste lastPingTs)
862
+ // Heartbeat ping por sesión — evita sensación de trancado en tareas largas.
863
+ // Con slots se evalúa cada sesión con slot asignado; sin slots (legacy) el state único (sid null).
864
+ // (V2: sin canal TUI en ctx; se loguea al server log y se persiste lastPingTs por sesión)
865
+ const lastPingBySession = new Map<string, number>()
866
+ const pingCandidateSessions = (): Array<string | null> => {
867
+ if (process.env.OSTACKY_SESSION_SLOTS === "off") return [null]
868
+ try {
869
+ return Object.values(readIndex(dirname(getStatePath(directory))).slots)
870
+ .map((r: any) => r?.sessionId)
871
+ .filter((x: unknown): x is string => typeof x === "string" && !!x)
872
+ } catch {
873
+ return []
874
+ }
875
+ }
553
876
  if (!pingInterval) {
554
877
  pingInterval = setInterval(() => {
555
- try {
556
- const s = readState(directory)
557
- if (!s || !["EXECUTING_INLINE", "EXECUTING_SUBAGENTS", "SYNC"].includes(s.state)) return
558
- const now = Date.now()
559
- const lastHeartbeat = s.lastHeartbeat || s.ts || now
560
- const idle = now - lastHeartbeat
561
- if (idle < IDLE_THRESHOLD_MS) return
562
- if (now - lastPingTs < PING_INTERVAL_MS) return
563
- lastPingTs = now
564
- const completed = Object.values(s.tasks || {}).filter((t: any) => t.status === "COMPLETED").length
565
- const total = s.expectedTaskCount ?? s.expectedTasks?.length ?? "?"
566
- const pending = Array.isArray(s.expectedTasks) ? s.expectedTasks.filter((id: string) => !s.tasks?.[id] || s.tasks[id].status !== "COMPLETED").length : "?"
567
- const msg = `[ostacky] Sigo trabajando — ${s.state} • ${completed}/${total} (${pending} pendientes) • hace ${Math.round(idle/1000)}s sin output`
568
- try { console.log(msg) } catch {}
569
- try { const st = readState(directory); if (st) { (st as any).lastPingTs = now; persistState(directory, st, ["lastPingTs"]) } } catch {}
570
- } catch {}
878
+ const now = Date.now()
879
+ for (const sid of pingCandidateSessions()) {
880
+ try {
881
+ const s = readState(directory, sid)
882
+ if (!s || !["EXECUTING_INLINE", "EXECUTING_SUBAGENTS", "SYNC"].includes(s.state)) continue
883
+ const lastHeartbeat = s.lastHeartbeat || s.ts || now
884
+ const idle = now - lastHeartbeat
885
+ if (idle < IDLE_THRESHOLD_MS) continue
886
+ const key = sid ?? "__legacy__"
887
+ if (now - (lastPingBySession.get(key) ?? 0) < PING_INTERVAL_MS) continue
888
+ lastPingBySession.set(key, now)
889
+ const completed = Object.values(s.tasks || {}).filter((t: any) => t.status === "COMPLETED").length
890
+ const total = s.expectedTaskCount ?? s.expectedTasks?.length ?? "?"
891
+ const pending = Array.isArray(s.expectedTasks) ? s.expectedTasks.filter((id: string) => !s.tasks?.[id] || s.tasks[id].status !== "COMPLETED").length : "?"
892
+ const msg = `[ostacky] Sigo trabajando — ${s.state} • ${completed}/${total} (${pending} pendientes) • hace ${Math.round(idle / 1000)}s sin output`
893
+ try { console.log(msg) } catch {}
894
+ const st = readState(directory, sid)
895
+ if (st) { st.lastPingTs = now; persistState(directory, st, ["lastPingTs"], sid) }
896
+ } catch {}
897
+ }
571
898
  }, 30_000)
572
899
  if (pingInterval && typeof (pingInterval as any).unref === 'function') (pingInterval as any).unref()
573
900
  }
@@ -590,8 +917,10 @@ export default {
590
917
  } catch {}
591
918
  }
592
919
  const currentState = state?.state ?? "DONE"
593
- const trivial = isTrivial(text, currentState)
920
+ const intent = classifyIntent(text, currentState)
921
+ const trivial = intent === "greeting"
594
922
  trivialBySession.set(sessionId, trivial)
923
+ sessionQuestionBySession.set(sessionId, intent === "session_question")
595
924
  // Horizonte por request: prompts NO-triviales invalidan el discovery hit —
596
925
  // la siguiente lectura de código exige un explore fresco (contrato
597
926
  // remove-discovery-cache-phantom + instrucción §1 del agente).
@@ -600,32 +929,44 @@ export default {
600
929
  // Preserve system FULL cacheable, add suffix hint to user prompt text
601
930
  const hint = "\n\n[PLUGIN HINT: Saludo trivial — responde breve sin tools. No hagas Discovery.]"
602
931
  event.prompt.text = (event.prompt.text ?? "") + hint
932
+ } else if (intent === "session_question") {
933
+ // A+B+C: respuesta desde contexto y ostacky_get_state. Solo relaja discovery/Engram; los gates de estado y edición siguen intactos.
934
+ const hint = "\n\n[PLUGIN HINT: Pregunta sobre hechos ya ejecutados en esta sesión — responde desde el contexto y ostacky_get_state, sin codegraph ni mem_search. Si el dato no está ni en contexto ni en el state, decilo y no inventes.]"
935
+ event.prompt.text = (event.prompt.text ?? "") + hint
603
936
  }
604
937
  // harden-compaction-resume: auto-inject recovery hint when pending (determinístico, no depende del modelo)
605
938
  if (!trivial && state && !["DONE", "INTERPRETATION_PENDING"].includes(state.state)) {
606
939
  try {
607
- let pending: string[] = Array.isArray(state.lastHandoff?.pendingTasks)
608
- ? state.lastHandoff.pendingTasks.filter((id: string) => !state.tasks?.[id] || state.tasks[id].status !== "COMPLETED")
609
- : []
610
- if (pending.length === 0) {
611
- try {
612
- const fallbackPath = join(dirname(getStatePath(directory)), ".ostacky-handoff-compaction.json")
613
- if (existsSync(fallbackPath)) {
614
- const raw = readFileSync(fallbackPath, "utf-8")
615
- const data = JSON.parse(raw)
616
- if (data && Array.isArray(data.pendingTasks) && typeof data.ts === "number" && Date.now() - data.ts < 24 * 60 * 60 * 1000) {
617
- const fbPending = data.pendingTasks.filter((id: string) => !state.tasks?.[id] || state.tasks[id].status !== "COMPLETED")
618
- if (fbPending.length > 0) pending = fbPending
619
- }
620
- }
621
- } catch {}
622
- }
623
- if (pending.length > 0) {
624
- const hint = `\n\n[RECOVERY: te quedan ${pending.slice(0, 3).join(",")}${pending.length > 3 ? `, +${pending.length - 3} más` : ""} - usa get_handoff / mem_context para retomar]`
625
- event.prompt.text = (event.prompt.text ?? "") + hint
626
- }
940
+ const hint = recoveryHint(state, directory, sessionId)
941
+ if (hint) event.prompt.text = (event.prompt.text ?? "") + hint
627
942
  } catch {}
628
943
  }
944
+ // Compactación asistida por umbral fijo: aviso/hint (Nivel 1). No corta la tarea.
945
+ try {
946
+ const cfg = parseCompactConfig(process.env)
947
+ if (cfg.enabled && cfg.mode !== "off") {
948
+ const rec = contextTokensBySession.get(sessionId)
949
+ if (rec) {
950
+ const complex = !["DONE", "INTERPRETATION_PENDING"].includes(state?.state ?? "DONE")
951
+ const decision = compactDecision({
952
+ tokens: rec.tokens,
953
+ cfg,
954
+ complexTaskInProgress: complex,
955
+ lastCompactTs: rec.lastCompactTs,
956
+ cooldownMs: COMPACT_DEFAULTS.cooldownMs,
957
+ now: Date.now(),
958
+ })
959
+ // Nivel 1: solo aviso. La compactación automática (summarize) aún no está implementada,
960
+ // así que el hint nunca afirma que se compactó ni que se compactará.
961
+ if (decision.zone === "warn") {
962
+ event.prompt.text = (event.prompt.text ?? "") + `\n\n[COMPACT HINT: contexto en ${rec.tokens} tokens (umbral ${cfg.threshold}); acercándose al umbral. Conviene cerrar la subunidad actual y dejar el estado guardado.]`
963
+ } else if (decision.zone === "opportunity") {
964
+ const why = decision.deferred ? "tarea compleja en curso" : decision.reason
965
+ event.prompt.text = (event.prompt.text ?? "") + `\n\n[COMPACT HINT: contexto en ${rec.tokens} tokens (umbral ${cfg.threshold}); ${why}. Compactación automática no activa: conviene guardar el estado en un punto seguro.]`
966
+ }
967
+ }
968
+ }
969
+ } catch {}
629
970
  })
630
971
 
631
972
  // ── Hard gates before any tool ──
@@ -636,7 +977,7 @@ export default {
636
977
 
637
978
  // ── 0) Trivial greeting blocks for expensive tools (SKIP, not BLOCKED) ──
638
979
  const isTrivialSession = trivialBySession.get(sessionId) ?? false
639
- const stateForTrivial = readState(directory)
980
+ const stateForTrivial = readState(directory, sessionId)
640
981
  if (isTrivialSession && stateForTrivial?.state === "DONE") {
641
982
  const blockedForTrivial = [
642
983
  "engram_mem_context", "mem_context",
@@ -650,7 +991,7 @@ export default {
650
991
 
651
992
  // ── 1) PENDING hard gate (0 tokens) ──
652
993
  checkCount++
653
- const freshState = readState(directory)
994
+ const freshState = readState(directory, sessionId)
654
995
  const pendingStates = ["ROUTE_DECISION_PENDING", "EXECUTION_DECISION_PENDING", "CLARIFICATION_PENDING"]
655
996
  // multisession-ownership-guard: el PENDING de OTRA sesión no congela esta sesión.
656
997
  const foreignPendingOwner = !!freshState && isForeignPendingOwner(freshState, sessionId)
@@ -684,16 +1025,16 @@ export default {
684
1025
  const isEngramRelevantTool = tool.includes("record_discovery") || (tool.includes("openspec") && (tool.includes("propose") || (typeof args?.filePath === "string" && args.filePath.includes("openspec/changes")) || (typeof args?.path === "string" && args.path.includes("openspec/changes"))))
685
1026
  if (isEngramRelevantTool) {
686
1027
  const hasEngramHit = engramHitBySession.get(sessionId) ?? false
687
- const isTrivialForEngram = trivialBySession.get(sessionId) ?? false
1028
+ const isTrivialForEngram = (trivialBySession.get(sessionId) ?? false) || (sessionQuestionBySession.get(sessionId) ?? false)
688
1029
  const stateForEngram = freshState
689
1030
  const shouldAudit = !hasEngramHit && !isTrivialForEngram && stateForEngram && ["DISCOVERY", "ROUTE_DECISION_PENDING", "SPECIFICATION", "INTERPRETATION_PENDING"].includes(stateForEngram.state)
690
1031
  if (shouldAudit) {
691
1032
  try {
692
- const st = readState(directory)
1033
+ const st = readState(directory, sessionId)
693
1034
  if (st) {
694
1035
  st.engramBypassCount = (st.engramBypassCount || 0) + 1
695
1036
  // no persist cada vez si es muy frecuente: single-writer ya persiste en after, pero acá persistimos directo para auditoría
696
- persistState(directory, st, ["engramBypassCount"])
1037
+ persistState(directory, st, ["engramBypassCount"], sessionId)
697
1038
  }
698
1039
  } catch {}
699
1040
  }
@@ -702,7 +1043,7 @@ export default {
702
1043
  // ── 1.5) Router determinista: openspec-propose bloquea si 1+ no-downgradeable sin Alternatives ──
703
1044
  const isOpenspecPropose = tool.includes("openspec") && (tool.includes("propose") || args?.filePath?.includes("openspec/changes") || args?.path?.includes("openspec/changes"))
704
1045
  if (isOpenspecPropose) {
705
- const s = readState(directory)
1046
+ const s = readState(directory, sessionId)
706
1047
  if (s?.level === "1+" && s?._routerNeedsAlternatives) {
707
1048
  // check if design.md has Alternatives
708
1049
  try {
@@ -774,7 +1115,15 @@ export default {
774
1115
  // Orden cheap -> caro: el path no hace I/O; codegraph y la cache en disco solo se evalúan
775
1116
  // si el path esta realmente sujeto al gate (`read`/`grep`/`glob` corren en cada turno).
776
1117
  const gated = isCodeReadGated({ isCodeFile, isLiteralGrep, isSpecTasksPath, isDocsPath, isTaskTracked })
777
- const codegraphOk = gated ? isCodegraphAvailable(directory) : false
1118
+ const codegraphOk = gated
1119
+ ? isCodegraphGateActive({
1120
+ mode: codegraphMode(),
1121
+ available: isCodegraphAvailable(directory),
1122
+ degradedSince: codegraphDegradedBySession.get(sessionId) ?? null,
1123
+ now: Date.now(),
1124
+ ttlMs: codegraphDegradedTtlMs(),
1125
+ })
1126
+ : false
778
1127
  // Sin fallback a disco: la única evidencia válida es un codegraph_explore
779
1128
  // COMPLETADO en este request (discoveryHitByRequest; el hook "prompt"
780
1129
  // invalida el hit en cada prompt no-trivial). session.deleted también lo limpia.
@@ -785,10 +1134,10 @@ export default {
785
1134
  // Métrica de evasión real (misma convención que engramBypassCount:648):
786
1135
  // cuántas lecturas de código saltaron el gate sin explore completado.
787
1136
  try {
788
- const st = readState(directory)
1137
+ const st = readState(directory, sessionId)
789
1138
  if (st) {
790
1139
  st.codeReadBlockedCount = (st.codeReadBlockedCount || 0) + 1
791
- persistState(directory, st, ["codeReadBlockedCount"])
1140
+ persistState(directory, st, ["codeReadBlockedCount"], sessionId)
792
1141
  }
793
1142
  } catch {}
794
1143
  try { console.warn(`[ostacky] code_read_blocked: sin codegraph_explore completado en sesión (${targetPath || "query"})`) } catch {}
@@ -809,7 +1158,7 @@ export default {
809
1158
  if (hasSensitivePattern || sensitivePaths.length > 0) {
810
1159
  if (sensitivePaths.length > 0) {
811
1160
  for (const p of sensitivePaths) {
812
- const s = readState(directory)
1161
+ const s = readState(directory, sessionId)
813
1162
  const candidates = [p, resolve(directory, p), join(directory, p)]
814
1163
  const allowed = candidates.some((c) => s?.allowedFiles?.[c] || s?.allowedFiles?.[p])
815
1164
  const baseAllowed = s?.allowedFiles?.[p] || s?.allowedFiles?.[basename(p)] || s?.allowedFiles?.[resolve(directory, p)]
@@ -820,7 +1169,7 @@ export default {
820
1169
  }
821
1170
  }
822
1171
  } else if (hasSensitivePattern) {
823
- const s = readState(directory)
1172
+ const s = readState(directory, sessionId)
824
1173
  const hasAllowed = Object.keys(s?.allowedFiles || {}).some((k) => isSensitive(k, patterns))
825
1174
  if (!hasAllowed) throw new Error(`BLOCKED: shell contiene acceso sensible (.env). Llamá check_file_access con reason antes.`)
826
1175
  }
@@ -839,7 +1188,15 @@ export default {
839
1188
  const shellTargets = shellReadTargets(cmdForRead)
840
1189
  if (shellTargets.length > 0) {
841
1190
  const gatedShell = shellTargets.filter((p) => !isShellPathExempt(p, directory, freshState))
842
- const codegraphOkShell = gatedShell.length > 0 ? isCodegraphAvailable(directory) : false
1191
+ const codegraphOkShell = gatedShell.length > 0
1192
+ ? isCodegraphGateActive({
1193
+ mode: codegraphMode(),
1194
+ available: isCodegraphAvailable(directory),
1195
+ degradedSince: codegraphDegradedBySession.get(sessionId) ?? null,
1196
+ now: Date.now(),
1197
+ ttlMs: codegraphDegradedTtlMs(),
1198
+ })
1199
+ : false
843
1200
  const hasDiscoveryShell = codegraphOkShell ? discoveryHitByRequest.get(sessionId) === true : false
844
1201
  if (gatedShell.length > 0 && codegraphOkShell && !hasDiscoveryShell) {
845
1202
  throw new Error(
@@ -889,7 +1246,7 @@ export default {
889
1246
  }
890
1247
  }
891
1248
  if (filePath && isSensitive(filePath, patterns)) {
892
- const s = readState(directory)
1249
+ const s = readState(directory, sessionId)
893
1250
  const allowed = s?.allowedFiles?.[filePath] || s?.allowedFiles?.[resolve(directory, filePath)] || s?.allowedFiles?.[basename(filePath)]
894
1251
  if (!allowed) {
895
1252
  const denied = s?.deniedFiles?.[filePath] || s?.deniedFiles?.[basename(filePath)]
@@ -901,7 +1258,7 @@ export default {
901
1258
  if (tool === "patch" && typeof args?.patchText === "string" && args.patchText) {
902
1259
  for (const patchPath of extractPathsFromPatch(args.patchText)) {
903
1260
  if (!patchPath || !isSensitive(patchPath, patterns)) continue
904
- const s = readState(directory)
1261
+ const s = readState(directory, sessionId)
905
1262
  const allowed = s?.allowedFiles?.[patchPath] || s?.allowedFiles?.[resolve(directory, patchPath)] || s?.allowedFiles?.[basename(patchPath)]
906
1263
  if (!allowed) {
907
1264
  const denied = s?.deniedFiles?.[patchPath] || s?.deniedFiles?.[basename(patchPath)]
@@ -927,15 +1284,15 @@ export default {
927
1284
  if (oldString.startsWith("hash:")) {
928
1285
  const claimed = oldString.slice(5)
929
1286
  const currentFp = fastFingerprint(resolve(directory, targetPath))
930
- const s = readState(directory)
1287
+ const s = readState(directory, sessionId)
931
1288
  const last: any = s?.lastValidated
932
1289
  const lastEntry = last?.byFile?.[targetPath] || (last?.filePath === targetPath ? last : null)
933
1290
  if (claimed !== currentFp || (lastEntry && lastEntry.hash !== currentFp)) {
934
1291
  // mark stale attempt
935
1292
  try {
936
- const st = readState(directory) || { ...DEFAULT_STATE }
1293
+ const st = readState(directory, sessionId) || { ...DEFAULT_STATE }
937
1294
  st.staleContentAttempts = (st.staleContentAttempts || 0) + 1
938
- persistState(directory, st, ["staleContentAttempts"])
1295
+ persistState(directory, st, ["staleContentAttempts"], sessionId)
939
1296
  } catch {}
940
1297
  throw new Error(`CONFLICT: stale fingerprint for ${targetPath}`)
941
1298
  }
@@ -974,7 +1331,7 @@ export default {
974
1331
  }
975
1332
  // Record lastValidated per-file for future hash checks (fix-new-file-gate: mapa + fallback legacy)
976
1333
  try {
977
- const st = readState(directory)
1334
+ const st = readState(directory, sessionId)
978
1335
  if (st) {
979
1336
  const fp = fastFingerprint(resolve(directory, targetPath))
980
1337
  const prev: any = (st as any).lastValidated
@@ -999,7 +1356,7 @@ export default {
999
1356
  // (implementation_complete) se bloqueaba.
1000
1357
  // `["lastValidated"]` = se escribe SOLO esa clave sobre el estado
1001
1358
  // fresco que se re-lee bajo el lock compartido con el MCP.
1002
- persistState(directory, st, ["lastValidated"])
1359
+ persistState(directory, st, ["lastValidated"], sessionId)
1003
1360
  }
1004
1361
  } catch {}
1005
1362
  }
@@ -1017,8 +1374,24 @@ export default {
1017
1374
  // Read TIENE que poder pasar si hubo `codegraph_explore`.
1018
1375
  if (marksDiscovery(tool)) {
1019
1376
  try {
1020
- if (event.status === "completed") discoveryHitByRequest.set(sessionId, true)
1377
+ if (event.status === "completed") {
1378
+ discoveryHitByRequest.set(sessionId, true)
1379
+ // Recuperación: un explore OK vuelve a activar el gate estricto.
1380
+ codegraphDegradedBySession.delete(sessionId)
1381
+ }
1382
+ } catch {}
1383
+ }
1384
+ // Fallo real de CodeGraph → sesión degradada: el gate deja de exigir discovery hasta el TTL.
1385
+ if (marksCodegraphFailure(tool, event.status) && !codegraphDegradedBySession.has(sessionId)) {
1386
+ codegraphDegradedBySession.set(sessionId, Date.now())
1387
+ try {
1388
+ const st = readState(directory, sessionId)
1389
+ if (st) {
1390
+ st.codegraphDegradedCount = (st.codegraphDegradedCount || 0) + 1
1391
+ persistState(directory, st, ["codegraphDegradedCount"], sessionId)
1392
+ }
1021
1393
  } catch {}
1394
+ try { console.warn(`[ostacky] codegraph_degraded: ${tool} status=${String(event.status)}; lectura de código sin gate hasta TTL`) } catch {}
1022
1395
  }
1023
1396
  // Track Engram hit (mem_search / mem_context / dedup) para soft gate 1.6
1024
1397
  if (tool.includes("engram_mem_search") || tool.includes("engram_mem_context") || tool.includes("mem_search") || tool.includes("mem_context") || tool.includes("engram_mem_")) {
@@ -1039,34 +1412,54 @@ export default {
1039
1412
  const mutating =
1040
1413
  (isMutatingTool(tool) && event.status === "completed") ||
1041
1414
  (!!ev && ev.exit === 0 && isShellMutation(ev.cmd))
1042
- const isTestRun = !!ev && testVerifyCommands(readState(directory)).has(ev.cmd)
1415
+ const declaredTests = testVerifyCommands(readState(directory, sessionId))
1416
+ const normalizedCmd = ev ? normalizeTestCommand(ev.cmd) : ""
1417
+ const isTestRun =
1418
+ !!ev &&
1419
+ normalizedCmd !== "" &&
1420
+ [...declaredTests].some((d) => normalizeTestCommand(d) === normalizedCmd)
1421
+ if (ev && !isTestRun && declaredTests.size > 0) {
1422
+ for (const d of declaredTests) {
1423
+ if (ev.cmd.includes(d) || (normalizedCmd !== "" && normalizeTestCommand(d) === normalizedCmd)) {
1424
+ debugLog("test_evidence_rejected", {
1425
+ declared: d,
1426
+ normalized: normalizedCmd,
1427
+ reason: normalizedCmd === "" ? "operadores" : "no_matchea",
1428
+ })
1429
+ break
1430
+ }
1431
+ }
1432
+ }
1043
1433
  if (isTestRun || mutating) {
1044
- const s = readState(directory)
1434
+ const s = readState(directory, sessionId)
1045
1435
  if (s) {
1046
1436
  const owned: string[] = []
1047
1437
  if (ev && isTestRun) {
1438
+ // El cmd se guarda crudo (las mutaciones lo necesitan); maskedExit sólo
1439
+ // marca que el exit registrado es el del pager, no el del test.
1440
+ const run = isMaskedExitCommand(ev.cmd) ? { ...ev, maskedExit: true } : ev
1048
1441
  const prev = Array.isArray((s as any).shellRuns) ? (s as any).shellRuns : []
1049
- ;(s as any).shellRuns = [...prev, ev].slice(-25)
1442
+ ;(s as any).shellRuns = [...prev, run].slice(-25)
1050
1443
  owned.push("shellRuns")
1051
1444
  }
1052
1445
  if (mutating) {
1053
1446
  ;(s as any).lastMutationTs = Date.now()
1054
1447
  owned.push("lastMutationTs")
1055
1448
  }
1056
- if (owned.length > 0) persistState(directory, s, owned)
1449
+ if (owned.length > 0) persistState(directory, s, owned, sessionId)
1057
1450
  }
1058
1451
  }
1059
1452
  } catch {}
1060
1453
  // Heartbeat: single-writer — plugin memo, no persist cada tool (D10)
1061
1454
  try {
1062
- const s = readState(directory)
1455
+ const s = readState(directory, sessionId)
1063
1456
  if (s) {
1064
1457
  const now = Date.now()
1065
1458
  // Single-writer: solo persiste si OSTACKY_PLUGIN_PERSIST=1 o idle>30s o state cambió
1066
1459
  const shouldPersist = process.env.OSTACKY_PLUGIN_PERSIST === "1" || (now - (s.lastHeartbeat || 0) > 30000)
1067
1460
  if (shouldPersist) {
1068
1461
  s.lastHeartbeat = now
1069
- try { persistState(directory, s, ["lastHeartbeat"]) } catch {}
1462
+ try { persistState(directory, s, ["lastHeartbeat"], sessionId) } catch {}
1070
1463
  }
1071
1464
  }
1072
1465
  } catch {}
@@ -1080,33 +1473,38 @@ export default {
1080
1473
  } as const
1081
1474
 
1082
1475
  // ── Observable tools (MCP thin replacement) ──
1476
+ // Cada tool lee el state de SU sesión (sessionID del contexto de ejecución). Sin identidad con
1477
+ // slots activos devuelve error explícito en vez de leer el state de otra sesión.
1478
+ const withSessionState = (fn: (state: any, sid: string | null) => unknown) =>
1479
+ async (_args: unknown, toolCtx?: unknown) => {
1480
+ const sid = toolSessionId(toolCtx)
1481
+ if (!sid && process.env.OSTACKY_SESSION_SLOTS !== "off") {
1482
+ return jsonContent({
1483
+ error: "identity_unavailable",
1484
+ hint: "El tool no recibió sessionID; usa el MCP ostacky-controller (identidad por _meta).",
1485
+ })
1486
+ }
1487
+ return fn(readState(directory, sid), sid)
1488
+ }
1083
1489
  await ctx.tool.transform((editor) => {
1084
1490
  editor.add({
1085
1491
  name: "ostacky_get_state",
1086
1492
  description: "Get Ostacky controller state (plugin, no MCP needed)",
1087
1493
  input: emptySchema,
1088
- execute: async () => {
1089
- const state = readState(directory)
1090
- if (!state) return jsonContent({ error: "no state", state: "UNKNOWN", revision: 0 })
1091
- return jsonContent({ state: state.state, revision: state.revision, requestId: state.requestId, degraded: !!state.degraded, level: state.level, routeChoice: state.routeChoice })
1092
- },
1494
+ execute: withSessionState((state) => jsonContent(projectStateForTool(state))),
1093
1495
  })
1094
1496
  editor.add({
1095
1497
  name: "ostacky_get_audit",
1096
1498
  description: "Get audit trail (plugin)",
1097
1499
  input: emptySchema,
1098
- execute: async () => {
1099
- const state = readState(directory)
1100
- return jsonContent({ audit: state?.audit ?? [], revision: state?.revision ?? 0 })
1101
- },
1500
+ execute: withSessionState((state) => jsonContent({ audit: state?.audit ?? [], revision: state?.revision ?? 0 })),
1102
1501
  })
1103
1502
  editor.add({
1104
1503
  name: "ostacky_get_metrics",
1105
1504
  description: "Get controller metrics (plugin)",
1106
1505
  input: emptySchema,
1107
- execute: async () => {
1108
- const state = readState(directory)
1109
- return jsonContent({
1506
+ execute: withSessionState((state) =>
1507
+ jsonContent({
1110
1508
  cacheHitCount: state?.cacheHitCount ?? 0,
1111
1509
  discoveryCacheHitCount: state?.discoveryCacheHitCount ?? 0,
1112
1510
  tokenSavingEstimate: state?.tokenSavingEstimate ?? 0,
@@ -1115,36 +1513,33 @@ export default {
1115
1513
  engramBypassCount: state?.engramBypassCount ?? 0,
1116
1514
  revision: state?.revision ?? 0,
1117
1515
  })
1118
- },
1516
+ ),
1119
1517
  })
1120
1518
  editor.add({
1121
1519
  name: "ostacky_get_handoff",
1122
1520
  description: "Get last handoff (plugin)",
1123
1521
  input: emptySchema,
1124
- execute: async () => {
1125
- const state = readState(directory)
1126
- // also check compaction fallback
1522
+ execute: withSessionState((state, sid) => {
1523
+ // Fallback de compaction por sesión (mismo ancla que el writer).
1127
1524
  try {
1128
- const fallback = join(dirname(getStatePath(directory)), ".ostacky-handoff-compaction.json")
1525
+ const fallback = handoffFallbackPath(dirname(getStatePath(directory)), sid)
1129
1526
  if (existsSync(fallback)) {
1130
- const raw = readFileSync(fallback, "utf-8")
1131
- const data = JSON.parse(raw)
1527
+ const data = JSON.parse(readFileSync(fallback, "utf-8"))
1132
1528
  if (data && !state?.lastHandoff) return jsonContent(data)
1133
1529
  }
1134
1530
  } catch {}
1135
1531
  return jsonContent(state?.lastHandoff ?? null)
1136
- },
1532
+ }),
1137
1533
  })
1138
1534
  editor.add({
1139
1535
  name: "ostacky_get_available_transitions",
1140
1536
  description: "Get available transitions from current state",
1141
1537
  input: emptySchema,
1142
- execute: async () => {
1143
- const state = readState(directory)
1538
+ execute: withSessionState((state) => {
1144
1539
  const cur = state?.state ?? "INTERPRETATION_PENDING"
1145
1540
  const trans = TRANSITIONS[cur] ?? []
1146
1541
  return jsonContent({ currentState: cur, transitions: trans })
1147
- },
1542
+ }),
1148
1543
  })
1149
1544
  // Compatibility for old MCP calls that expect deprecated response
1150
1545
  editor.add({
@@ -1172,10 +1567,31 @@ export default {
1172
1567
  const sid = event.data.sessionID as string
1173
1568
  if (sid) {
1174
1569
  trivialBySession.delete(sid)
1570
+ sessionQuestionBySession.delete(sid)
1175
1571
  discoveryHitByRequest.delete(sid)
1176
1572
  engramHitBySession.delete(sid)
1573
+ contextTokensBySession.delete(sid)
1177
1574
  }
1178
1575
  }
1576
+ if (event.type === "session.next.step.ended") {
1577
+ try {
1578
+ const sid = (event.data?.sessionID ?? event.data?.session_id) as string | undefined
1579
+ if (sid) {
1580
+ const tokens = (event.data as any)?.tokens ?? {}
1581
+ const provider = (event.data as any)?.providerID ?? (event.data as any)?.provider
1582
+ const model = (event.data as any)?.modelID ?? (event.data as any)?.model
1583
+ const normalized = normalizeContextTokens(tokens, provider)
1584
+ const prev = contextTokensBySession.get(sid)
1585
+ contextTokensBySession.set(sid, {
1586
+ tokens: normalized,
1587
+ provider,
1588
+ model,
1589
+ lastCompactTs: prev?.lastCompactTs,
1590
+ lastStepTs: Date.now(),
1591
+ })
1592
+ }
1593
+ } catch {}
1594
+ }
1179
1595
  }
1180
1596
  })()
1181
1597
 
@@ -1184,22 +1600,25 @@ export default {
1184
1600
  const statePath = getStatePath(directory)
1185
1601
  const dir = dirname(statePath)
1186
1602
  try { mkdirSync(dir, { recursive: true }) } catch {}
1187
- const fallbackPath = join(dir, ".ostacky-handoff-compaction.json")
1603
+ const fallbackPath = handoffFallbackPath(dir, event.sessionID as string | undefined)
1188
1604
  const contextSnippet = (() => {
1189
1605
  try {
1190
1606
  return JSON.stringify(event.messages.slice(0, 2)).slice(0, 800)
1191
1607
  } catch { return "" }
1192
1608
  })()
1193
- const payload = {
1194
- summary: `Compaction fallback for session ${event.sessionID ?? "unknown"} — plugin`,
1195
- nextSteps: [] as string[],
1196
- pendingTasks: [] as string[],
1197
- ts: Date.now(),
1198
- contextSnippet,
1199
- }
1609
+ // Los pendientes salen del state real, no de una lista vacía: sin esto
1610
+ // el hint de recovery nunca disparaba mid-run (checkpoint cada 3 tasks).
1611
+ const current = readState(directory, event.sessionID as string | undefined)
1612
+ const payload = compactionPayload(current, directory, event.sessionID as string | undefined, contextSnippet)
1200
1613
  const tmp = `${fallbackPath}.tmp.${process.pid}`
1201
1614
  writeFileSync(tmp, JSON.stringify(payload, null, 2), "utf-8")
1202
1615
  renameSync(tmp, fallbackPath)
1616
+ const sid = event.sessionID as string | undefined
1617
+ if (sid) {
1618
+ const rec = contextTokensBySession.get(sid)
1619
+ // Tras compactar, el conteo previo se descarta hasta el siguiente step.ended.
1620
+ if (rec) contextTokensBySession.set(sid, { tokens: 0, provider: rec.provider, model: rec.model, lastCompactTs: Date.now(), lastStepTs: rec.lastStepTs })
1621
+ }
1203
1622
  } catch {}
1204
1623
  })
1205
1624