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.
@@ -21,8 +21,10 @@ import { join, dirname, basename, resolve, relative, delimiter, sep } from "node
21
21
  import { homedir } from "node:os"
22
22
  import { fileURLToPath } from "node:url"
23
23
  import { SENSITIVE_DEFAULT, BASH_SENSITIVE_RE, isSensitive, extractPathsFromBash } from "./security.ts"
24
- import { isTrivial } from "./tiered.ts"
25
- 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"
26
28
 
27
29
  // ─── Constants ───────────────────────────────────────────────────────────────
28
30
 
@@ -160,8 +162,34 @@ export function getStatePath(directory: string): string {
160
162
  return join(directory, ".opencode", "ostacky-state.json")
161
163
  }
162
164
 
163
- function readState(directory: string): any | null {
164
- 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
165
193
  try {
166
194
  const raw = readFileSync(p, "utf-8")
167
195
  return JSON.parse(raw)
@@ -176,7 +204,7 @@ function readState(directory: string): any | null {
176
204
  * El checkpoint count-based del MCP solo escribe lastHandoff cada 3er
177
205
  * complete_task, así que sin la tercera fuente el hint quedaba mudo en T1/T2.
178
206
  */
179
- export function recoveryPending(state: any, directory?: string): { pending: string[]; nextSteps: string[] } {
207
+ export function recoveryPending(state: any, directory?: string, sessionId?: string | null): { pending: string[]; nextSteps: string[] } {
180
208
  const isPending = (id: string) => !state?.tasks?.[id] || state.tasks[id].status !== "COMPLETED"
181
209
  const fromExpected = () => (Array.isArray(state?.expectedTasks) ? state.expectedTasks.filter(isPending) : [])
182
210
  let pending: string[] = Array.isArray(state?.lastHandoff?.pendingTasks)
@@ -185,7 +213,7 @@ export function recoveryPending(state: any, directory?: string): { pending: stri
185
213
  let nextSteps: string[] = Array.isArray(state?.lastHandoff?.nextSteps) ? state.lastHandoff.nextSteps : []
186
214
  if (pending.length === 0 && directory) {
187
215
  try {
188
- const fallbackPath = join(dirname(getStatePath(directory)), ".ostacky-handoff-compaction.json")
216
+ const fallbackPath = handoffFallbackPath(dirname(getStatePath(directory)), sessionId)
189
217
  if (existsSync(fallbackPath)) {
190
218
  const data = JSON.parse(readFileSync(fallbackPath, "utf-8"))
191
219
  if (data && Array.isArray(data.pendingTasks) && typeof data.ts === "number" && Date.now() - data.ts < 24 * 60 * 60 * 1000) {
@@ -202,16 +230,16 @@ export function recoveryPending(state: any, directory?: string): { pending: stri
202
230
  }
203
231
 
204
232
  /** Texto del hint de recovery (null si no hay pendientes). Puro: testeable sin hooks. */
205
- export function recoveryHint(state: any, directory?: string): string | null {
233
+ export function recoveryHint(state: any, directory?: string, sessionId?: string | null): string | null {
206
234
  if (!state || ["DONE", "INTERPRETATION_PENDING"].includes(state.state)) return null
207
- const { pending } = recoveryPending(state, directory)
235
+ const { pending } = recoveryPending(state, directory, sessionId)
208
236
  if (pending.length === 0) return null
209
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]`
210
238
  }
211
239
 
212
240
  /** Payload del fallback de compaction, con los pendientes reales del state. */
213
241
  export function compactionPayload(state: any, directory: string, sessionID?: string, contextSnippet = "") {
214
- const { pending, nextSteps } = recoveryPending(state, directory)
242
+ const { pending, nextSteps } = recoveryPending(state, directory, sessionID)
215
243
  return {
216
244
  summary: state?.requestId
217
245
  ? `Compaction fallback for request ${state.requestId} — ${pending.length} pendientes`
@@ -371,8 +399,9 @@ export function nextPendingGateCache(
371
399
  * (4) write atómico (tmp único + rename). El `revision` se preserva del disco:
372
400
  * las escrituras del plugin no son transiciones de la máquina de estados.
373
401
  */
374
- export function persistState(directory: string, state: any, ownedKeys?: string[]): void {
375
- 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
376
405
  const dir = dirname(p)
377
406
  try { mkdirSync(dir, { recursive: true }) } catch {}
378
407
 
@@ -444,6 +473,13 @@ export function projectStateForTool(state: any): Record<string, unknown> {
444
473
  routeDecisionId: state.routeDecisionId ?? null,
445
474
  executionDecisionId: state.executionDecisionId ?? null,
446
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 ?? {}),
447
483
  }
448
484
  }
449
485
 
@@ -481,6 +517,50 @@ function isCodegraphAvailable(directory: string): boolean {
481
517
  } catch { return false }
482
518
  }
483
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
+
484
564
  /**
485
565
  * ¿Este read/grep/glob esta sujeto al gate de discovery?
486
566
  * Exenciones: docs/json/md, openspec/changes|specs, grep de literales, y archivos ya
@@ -581,6 +661,14 @@ export function shellEvidence(event: any): { cmd: string; exit: number; ts: numb
581
661
  return { cmd: cmd.trim(), exit, ts: Date.now() }
582
662
  }
583
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
+
584
672
  /** Tools que mutan archivos: avanzan `lastMutationTs`. */
585
673
  export function isMutatingTool(tool: string): boolean {
586
674
  return tool === "edit" || tool === "write" || tool === "patch"
@@ -692,7 +780,7 @@ export function isShellPathExempt(p: string, directory: string, freshState: any)
692
780
  return false
693
781
  }
694
782
 
695
- /** Comandos `test:` declarados en taskVerifications, ya normalizados (sin prefijo). */
783
+ /** Comandos `test:` declarados en taskVerifications, tal cual (el matching los normaliza). */
696
784
  export function testVerifyCommands(state: any): Set<string> {
697
785
  const out = new Set<string>()
698
786
  try {
@@ -749,12 +837,17 @@ export default {
749
837
 
750
838
  // Track trivial flag per session to gate tools
751
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>()
752
842
  // Track discovery hit per requestId to avoid blocking after hit
753
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>()
754
846
  // Track Engram hit per session to audit bypass (soft, no BLOCK)
755
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 }>()
756
850
  // ─── Heartbeat ping — evita sensación de trancado en tareas largas ──
757
- let lastPingTs = 0
758
851
  let pingInterval: ReturnType<typeof setInterval> | null = null
759
852
 
760
853
  const patterns = (() => {
@@ -766,26 +859,42 @@ export default {
766
859
  let lastCheck: { revision: number; result: string } | null = null
767
860
  let checkCount = 0
768
861
 
769
- // Heartbeat ping — evita sensación de trancado en tareas largas
770
- // (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
+ }
771
876
  if (!pingInterval) {
772
877
  pingInterval = setInterval(() => {
773
- try {
774
- const s = readState(directory)
775
- if (!s || !["EXECUTING_INLINE", "EXECUTING_SUBAGENTS", "SYNC"].includes(s.state)) return
776
- const now = Date.now()
777
- const lastHeartbeat = s.lastHeartbeat || s.ts || now
778
- const idle = now - lastHeartbeat
779
- if (idle < IDLE_THRESHOLD_MS) return
780
- if (now - lastPingTs < PING_INTERVAL_MS) return
781
- lastPingTs = now
782
- const completed = Object.values(s.tasks || {}).filter((t: any) => t.status === "COMPLETED").length
783
- const total = s.expectedTaskCount ?? s.expectedTasks?.length ?? "?"
784
- const pending = Array.isArray(s.expectedTasks) ? s.expectedTasks.filter((id: string) => !s.tasks?.[id] || s.tasks[id].status !== "COMPLETED").length : "?"
785
- const msg = `[ostacky] Sigo trabajando — ${s.state} • ${completed}/${total} (${pending} pendientes) • hace ${Math.round(idle/1000)}s sin output`
786
- try { console.log(msg) } catch {}
787
- try { const st = readState(directory); if (st) { (st as any).lastPingTs = now; persistState(directory, st, ["lastPingTs"]) } } catch {}
788
- } 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
+ }
789
898
  }, 30_000)
790
899
  if (pingInterval && typeof (pingInterval as any).unref === 'function') (pingInterval as any).unref()
791
900
  }
@@ -808,8 +917,10 @@ export default {
808
917
  } catch {}
809
918
  }
810
919
  const currentState = state?.state ?? "DONE"
811
- const trivial = isTrivial(text, currentState)
920
+ const intent = classifyIntent(text, currentState)
921
+ const trivial = intent === "greeting"
812
922
  trivialBySession.set(sessionId, trivial)
923
+ sessionQuestionBySession.set(sessionId, intent === "session_question")
813
924
  // Horizonte por request: prompts NO-triviales invalidan el discovery hit —
814
925
  // la siguiente lectura de código exige un explore fresco (contrato
815
926
  // remove-discovery-cache-phantom + instrucción §1 del agente).
@@ -818,14 +929,44 @@ export default {
818
929
  // Preserve system FULL cacheable, add suffix hint to user prompt text
819
930
  const hint = "\n\n[PLUGIN HINT: Saludo trivial — responde breve sin tools. No hagas Discovery.]"
820
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
821
936
  }
822
937
  // harden-compaction-resume: auto-inject recovery hint when pending (determinístico, no depende del modelo)
823
938
  if (!trivial && state && !["DONE", "INTERPRETATION_PENDING"].includes(state.state)) {
824
939
  try {
825
- const hint = recoveryHint(state, directory)
940
+ const hint = recoveryHint(state, directory, sessionId)
826
941
  if (hint) event.prompt.text = (event.prompt.text ?? "") + hint
827
942
  } catch {}
828
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 {}
829
970
  })
830
971
 
831
972
  // ── Hard gates before any tool ──
@@ -836,7 +977,7 @@ export default {
836
977
 
837
978
  // ── 0) Trivial greeting blocks for expensive tools (SKIP, not BLOCKED) ──
838
979
  const isTrivialSession = trivialBySession.get(sessionId) ?? false
839
- const stateForTrivial = readState(directory)
980
+ const stateForTrivial = readState(directory, sessionId)
840
981
  if (isTrivialSession && stateForTrivial?.state === "DONE") {
841
982
  const blockedForTrivial = [
842
983
  "engram_mem_context", "mem_context",
@@ -850,7 +991,7 @@ export default {
850
991
 
851
992
  // ── 1) PENDING hard gate (0 tokens) ──
852
993
  checkCount++
853
- const freshState = readState(directory)
994
+ const freshState = readState(directory, sessionId)
854
995
  const pendingStates = ["ROUTE_DECISION_PENDING", "EXECUTION_DECISION_PENDING", "CLARIFICATION_PENDING"]
855
996
  // multisession-ownership-guard: el PENDING de OTRA sesión no congela esta sesión.
856
997
  const foreignPendingOwner = !!freshState && isForeignPendingOwner(freshState, sessionId)
@@ -884,16 +1025,16 @@ export default {
884
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"))))
885
1026
  if (isEngramRelevantTool) {
886
1027
  const hasEngramHit = engramHitBySession.get(sessionId) ?? false
887
- const isTrivialForEngram = trivialBySession.get(sessionId) ?? false
1028
+ const isTrivialForEngram = (trivialBySession.get(sessionId) ?? false) || (sessionQuestionBySession.get(sessionId) ?? false)
888
1029
  const stateForEngram = freshState
889
1030
  const shouldAudit = !hasEngramHit && !isTrivialForEngram && stateForEngram && ["DISCOVERY", "ROUTE_DECISION_PENDING", "SPECIFICATION", "INTERPRETATION_PENDING"].includes(stateForEngram.state)
890
1031
  if (shouldAudit) {
891
1032
  try {
892
- const st = readState(directory)
1033
+ const st = readState(directory, sessionId)
893
1034
  if (st) {
894
1035
  st.engramBypassCount = (st.engramBypassCount || 0) + 1
895
1036
  // no persist cada vez si es muy frecuente: single-writer ya persiste en after, pero acá persistimos directo para auditoría
896
- persistState(directory, st, ["engramBypassCount"])
1037
+ persistState(directory, st, ["engramBypassCount"], sessionId)
897
1038
  }
898
1039
  } catch {}
899
1040
  }
@@ -902,7 +1043,7 @@ export default {
902
1043
  // ── 1.5) Router determinista: openspec-propose bloquea si 1+ no-downgradeable sin Alternatives ──
903
1044
  const isOpenspecPropose = tool.includes("openspec") && (tool.includes("propose") || args?.filePath?.includes("openspec/changes") || args?.path?.includes("openspec/changes"))
904
1045
  if (isOpenspecPropose) {
905
- const s = readState(directory)
1046
+ const s = readState(directory, sessionId)
906
1047
  if (s?.level === "1+" && s?._routerNeedsAlternatives) {
907
1048
  // check if design.md has Alternatives
908
1049
  try {
@@ -974,7 +1115,15 @@ export default {
974
1115
  // Orden cheap -> caro: el path no hace I/O; codegraph y la cache en disco solo se evalúan
975
1116
  // si el path esta realmente sujeto al gate (`read`/`grep`/`glob` corren en cada turno).
976
1117
  const gated = isCodeReadGated({ isCodeFile, isLiteralGrep, isSpecTasksPath, isDocsPath, isTaskTracked })
977
- 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
978
1127
  // Sin fallback a disco: la única evidencia válida es un codegraph_explore
979
1128
  // COMPLETADO en este request (discoveryHitByRequest; el hook "prompt"
980
1129
  // invalida el hit en cada prompt no-trivial). session.deleted también lo limpia.
@@ -985,10 +1134,10 @@ export default {
985
1134
  // Métrica de evasión real (misma convención que engramBypassCount:648):
986
1135
  // cuántas lecturas de código saltaron el gate sin explore completado.
987
1136
  try {
988
- const st = readState(directory)
1137
+ const st = readState(directory, sessionId)
989
1138
  if (st) {
990
1139
  st.codeReadBlockedCount = (st.codeReadBlockedCount || 0) + 1
991
- persistState(directory, st, ["codeReadBlockedCount"])
1140
+ persistState(directory, st, ["codeReadBlockedCount"], sessionId)
992
1141
  }
993
1142
  } catch {}
994
1143
  try { console.warn(`[ostacky] code_read_blocked: sin codegraph_explore completado en sesión (${targetPath || "query"})`) } catch {}
@@ -1009,7 +1158,7 @@ export default {
1009
1158
  if (hasSensitivePattern || sensitivePaths.length > 0) {
1010
1159
  if (sensitivePaths.length > 0) {
1011
1160
  for (const p of sensitivePaths) {
1012
- const s = readState(directory)
1161
+ const s = readState(directory, sessionId)
1013
1162
  const candidates = [p, resolve(directory, p), join(directory, p)]
1014
1163
  const allowed = candidates.some((c) => s?.allowedFiles?.[c] || s?.allowedFiles?.[p])
1015
1164
  const baseAllowed = s?.allowedFiles?.[p] || s?.allowedFiles?.[basename(p)] || s?.allowedFiles?.[resolve(directory, p)]
@@ -1020,7 +1169,7 @@ export default {
1020
1169
  }
1021
1170
  }
1022
1171
  } else if (hasSensitivePattern) {
1023
- const s = readState(directory)
1172
+ const s = readState(directory, sessionId)
1024
1173
  const hasAllowed = Object.keys(s?.allowedFiles || {}).some((k) => isSensitive(k, patterns))
1025
1174
  if (!hasAllowed) throw new Error(`BLOCKED: shell contiene acceso sensible (.env). Llamá check_file_access con reason antes.`)
1026
1175
  }
@@ -1039,7 +1188,15 @@ export default {
1039
1188
  const shellTargets = shellReadTargets(cmdForRead)
1040
1189
  if (shellTargets.length > 0) {
1041
1190
  const gatedShell = shellTargets.filter((p) => !isShellPathExempt(p, directory, freshState))
1042
- 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
1043
1200
  const hasDiscoveryShell = codegraphOkShell ? discoveryHitByRequest.get(sessionId) === true : false
1044
1201
  if (gatedShell.length > 0 && codegraphOkShell && !hasDiscoveryShell) {
1045
1202
  throw new Error(
@@ -1089,7 +1246,7 @@ export default {
1089
1246
  }
1090
1247
  }
1091
1248
  if (filePath && isSensitive(filePath, patterns)) {
1092
- const s = readState(directory)
1249
+ const s = readState(directory, sessionId)
1093
1250
  const allowed = s?.allowedFiles?.[filePath] || s?.allowedFiles?.[resolve(directory, filePath)] || s?.allowedFiles?.[basename(filePath)]
1094
1251
  if (!allowed) {
1095
1252
  const denied = s?.deniedFiles?.[filePath] || s?.deniedFiles?.[basename(filePath)]
@@ -1101,7 +1258,7 @@ export default {
1101
1258
  if (tool === "patch" && typeof args?.patchText === "string" && args.patchText) {
1102
1259
  for (const patchPath of extractPathsFromPatch(args.patchText)) {
1103
1260
  if (!patchPath || !isSensitive(patchPath, patterns)) continue
1104
- const s = readState(directory)
1261
+ const s = readState(directory, sessionId)
1105
1262
  const allowed = s?.allowedFiles?.[patchPath] || s?.allowedFiles?.[resolve(directory, patchPath)] || s?.allowedFiles?.[basename(patchPath)]
1106
1263
  if (!allowed) {
1107
1264
  const denied = s?.deniedFiles?.[patchPath] || s?.deniedFiles?.[basename(patchPath)]
@@ -1127,15 +1284,15 @@ export default {
1127
1284
  if (oldString.startsWith("hash:")) {
1128
1285
  const claimed = oldString.slice(5)
1129
1286
  const currentFp = fastFingerprint(resolve(directory, targetPath))
1130
- const s = readState(directory)
1287
+ const s = readState(directory, sessionId)
1131
1288
  const last: any = s?.lastValidated
1132
1289
  const lastEntry = last?.byFile?.[targetPath] || (last?.filePath === targetPath ? last : null)
1133
1290
  if (claimed !== currentFp || (lastEntry && lastEntry.hash !== currentFp)) {
1134
1291
  // mark stale attempt
1135
1292
  try {
1136
- const st = readState(directory) || { ...DEFAULT_STATE }
1293
+ const st = readState(directory, sessionId) || { ...DEFAULT_STATE }
1137
1294
  st.staleContentAttempts = (st.staleContentAttempts || 0) + 1
1138
- persistState(directory, st, ["staleContentAttempts"])
1295
+ persistState(directory, st, ["staleContentAttempts"], sessionId)
1139
1296
  } catch {}
1140
1297
  throw new Error(`CONFLICT: stale fingerprint for ${targetPath}`)
1141
1298
  }
@@ -1174,7 +1331,7 @@ export default {
1174
1331
  }
1175
1332
  // Record lastValidated per-file for future hash checks (fix-new-file-gate: mapa + fallback legacy)
1176
1333
  try {
1177
- const st = readState(directory)
1334
+ const st = readState(directory, sessionId)
1178
1335
  if (st) {
1179
1336
  const fp = fastFingerprint(resolve(directory, targetPath))
1180
1337
  const prev: any = (st as any).lastValidated
@@ -1199,7 +1356,7 @@ export default {
1199
1356
  // (implementation_complete) se bloqueaba.
1200
1357
  // `["lastValidated"]` = se escribe SOLO esa clave sobre el estado
1201
1358
  // fresco que se re-lee bajo el lock compartido con el MCP.
1202
- persistState(directory, st, ["lastValidated"])
1359
+ persistState(directory, st, ["lastValidated"], sessionId)
1203
1360
  }
1204
1361
  } catch {}
1205
1362
  }
@@ -1217,9 +1374,25 @@ export default {
1217
1374
  // Read TIENE que poder pasar si hubo `codegraph_explore`.
1218
1375
  if (marksDiscovery(tool)) {
1219
1376
  try {
1220
- 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
+ }
1221
1382
  } catch {}
1222
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
+ }
1393
+ } catch {}
1394
+ try { console.warn(`[ostacky] codegraph_degraded: ${tool} status=${String(event.status)}; lectura de código sin gate hasta TTL`) } catch {}
1395
+ }
1223
1396
  // Track Engram hit (mem_search / mem_context / dedup) para soft gate 1.6
1224
1397
  if (tool.includes("engram_mem_search") || tool.includes("engram_mem_context") || tool.includes("mem_search") || tool.includes("mem_context") || tool.includes("engram_mem_")) {
1225
1398
  engramHitBySession.set(sessionId, true)
@@ -1239,34 +1412,54 @@ export default {
1239
1412
  const mutating =
1240
1413
  (isMutatingTool(tool) && event.status === "completed") ||
1241
1414
  (!!ev && ev.exit === 0 && isShellMutation(ev.cmd))
1242
- 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
+ }
1243
1433
  if (isTestRun || mutating) {
1244
- const s = readState(directory)
1434
+ const s = readState(directory, sessionId)
1245
1435
  if (s) {
1246
1436
  const owned: string[] = []
1247
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
1248
1441
  const prev = Array.isArray((s as any).shellRuns) ? (s as any).shellRuns : []
1249
- ;(s as any).shellRuns = [...prev, ev].slice(-25)
1442
+ ;(s as any).shellRuns = [...prev, run].slice(-25)
1250
1443
  owned.push("shellRuns")
1251
1444
  }
1252
1445
  if (mutating) {
1253
1446
  ;(s as any).lastMutationTs = Date.now()
1254
1447
  owned.push("lastMutationTs")
1255
1448
  }
1256
- if (owned.length > 0) persistState(directory, s, owned)
1449
+ if (owned.length > 0) persistState(directory, s, owned, sessionId)
1257
1450
  }
1258
1451
  }
1259
1452
  } catch {}
1260
1453
  // Heartbeat: single-writer — plugin memo, no persist cada tool (D10)
1261
1454
  try {
1262
- const s = readState(directory)
1455
+ const s = readState(directory, sessionId)
1263
1456
  if (s) {
1264
1457
  const now = Date.now()
1265
1458
  // Single-writer: solo persiste si OSTACKY_PLUGIN_PERSIST=1 o idle>30s o state cambió
1266
1459
  const shouldPersist = process.env.OSTACKY_PLUGIN_PERSIST === "1" || (now - (s.lastHeartbeat || 0) > 30000)
1267
1460
  if (shouldPersist) {
1268
1461
  s.lastHeartbeat = now
1269
- try { persistState(directory, s, ["lastHeartbeat"]) } catch {}
1462
+ try { persistState(directory, s, ["lastHeartbeat"], sessionId) } catch {}
1270
1463
  }
1271
1464
  }
1272
1465
  } catch {}
@@ -1280,29 +1473,38 @@ export default {
1280
1473
  } as const
1281
1474
 
1282
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
+ }
1283
1489
  await ctx.tool.transform((editor) => {
1284
1490
  editor.add({
1285
1491
  name: "ostacky_get_state",
1286
1492
  description: "Get Ostacky controller state (plugin, no MCP needed)",
1287
1493
  input: emptySchema,
1288
- execute: async () => jsonContent(projectStateForTool(readState(directory))),
1494
+ execute: withSessionState((state) => jsonContent(projectStateForTool(state))),
1289
1495
  })
1290
1496
  editor.add({
1291
1497
  name: "ostacky_get_audit",
1292
1498
  description: "Get audit trail (plugin)",
1293
1499
  input: emptySchema,
1294
- execute: async () => {
1295
- const state = readState(directory)
1296
- return jsonContent({ audit: state?.audit ?? [], revision: state?.revision ?? 0 })
1297
- },
1500
+ execute: withSessionState((state) => jsonContent({ audit: state?.audit ?? [], revision: state?.revision ?? 0 })),
1298
1501
  })
1299
1502
  editor.add({
1300
1503
  name: "ostacky_get_metrics",
1301
1504
  description: "Get controller metrics (plugin)",
1302
1505
  input: emptySchema,
1303
- execute: async () => {
1304
- const state = readState(directory)
1305
- return jsonContent({
1506
+ execute: withSessionState((state) =>
1507
+ jsonContent({
1306
1508
  cacheHitCount: state?.cacheHitCount ?? 0,
1307
1509
  discoveryCacheHitCount: state?.discoveryCacheHitCount ?? 0,
1308
1510
  tokenSavingEstimate: state?.tokenSavingEstimate ?? 0,
@@ -1311,36 +1513,33 @@ export default {
1311
1513
  engramBypassCount: state?.engramBypassCount ?? 0,
1312
1514
  revision: state?.revision ?? 0,
1313
1515
  })
1314
- },
1516
+ ),
1315
1517
  })
1316
1518
  editor.add({
1317
1519
  name: "ostacky_get_handoff",
1318
1520
  description: "Get last handoff (plugin)",
1319
1521
  input: emptySchema,
1320
- execute: async () => {
1321
- const state = readState(directory)
1322
- // also check compaction fallback
1522
+ execute: withSessionState((state, sid) => {
1523
+ // Fallback de compaction por sesión (mismo ancla que el writer).
1323
1524
  try {
1324
- const fallback = join(dirname(getStatePath(directory)), ".ostacky-handoff-compaction.json")
1525
+ const fallback = handoffFallbackPath(dirname(getStatePath(directory)), sid)
1325
1526
  if (existsSync(fallback)) {
1326
- const raw = readFileSync(fallback, "utf-8")
1327
- const data = JSON.parse(raw)
1527
+ const data = JSON.parse(readFileSync(fallback, "utf-8"))
1328
1528
  if (data && !state?.lastHandoff) return jsonContent(data)
1329
1529
  }
1330
1530
  } catch {}
1331
1531
  return jsonContent(state?.lastHandoff ?? null)
1332
- },
1532
+ }),
1333
1533
  })
1334
1534
  editor.add({
1335
1535
  name: "ostacky_get_available_transitions",
1336
1536
  description: "Get available transitions from current state",
1337
1537
  input: emptySchema,
1338
- execute: async () => {
1339
- const state = readState(directory)
1538
+ execute: withSessionState((state) => {
1340
1539
  const cur = state?.state ?? "INTERPRETATION_PENDING"
1341
1540
  const trans = TRANSITIONS[cur] ?? []
1342
1541
  return jsonContent({ currentState: cur, transitions: trans })
1343
- },
1542
+ }),
1344
1543
  })
1345
1544
  // Compatibility for old MCP calls that expect deprecated response
1346
1545
  editor.add({
@@ -1368,10 +1567,31 @@ export default {
1368
1567
  const sid = event.data.sessionID as string
1369
1568
  if (sid) {
1370
1569
  trivialBySession.delete(sid)
1570
+ sessionQuestionBySession.delete(sid)
1371
1571
  discoveryHitByRequest.delete(sid)
1372
1572
  engramHitBySession.delete(sid)
1573
+ contextTokensBySession.delete(sid)
1373
1574
  }
1374
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
+ }
1375
1595
  }
1376
1596
  })()
1377
1597
 
@@ -1380,7 +1600,7 @@ export default {
1380
1600
  const statePath = getStatePath(directory)
1381
1601
  const dir = dirname(statePath)
1382
1602
  try { mkdirSync(dir, { recursive: true }) } catch {}
1383
- const fallbackPath = join(dir, ".ostacky-handoff-compaction.json")
1603
+ const fallbackPath = handoffFallbackPath(dir, event.sessionID as string | undefined)
1384
1604
  const contextSnippet = (() => {
1385
1605
  try {
1386
1606
  return JSON.stringify(event.messages.slice(0, 2)).slice(0, 800)
@@ -1388,11 +1608,17 @@ export default {
1388
1608
  })()
1389
1609
  // Los pendientes salen del state real, no de una lista vacía: sin esto
1390
1610
  // el hint de recovery nunca disparaba mid-run (checkpoint cada 3 tasks).
1391
- const current = readState(directory)
1611
+ const current = readState(directory, event.sessionID as string | undefined)
1392
1612
  const payload = compactionPayload(current, directory, event.sessionID as string | undefined, contextSnippet)
1393
1613
  const tmp = `${fallbackPath}.tmp.${process.pid}`
1394
1614
  writeFileSync(tmp, JSON.stringify(payload, null, 2), "utf-8")
1395
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
+ }
1396
1622
  } catch {}
1397
1623
  })
1398
1624