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.
@@ -19645,16 +19645,16 @@ var StdioServerTransport = class {
19645
19645
 
19646
19646
  // assets/mcp/ostacky-controller/index.js
19647
19647
  import {
19648
- readFileSync,
19649
- writeFileSync,
19650
- renameSync,
19651
- mkdirSync,
19648
+ readFileSync as readFileSync2,
19649
+ writeFileSync as writeFileSync2,
19650
+ renameSync as renameSync2,
19651
+ mkdirSync as mkdirSync2,
19652
19652
  readdirSync,
19653
19653
  unlinkSync,
19654
- statSync,
19655
- existsSync
19654
+ statSync as statSync2,
19655
+ existsSync as existsSync2
19656
19656
  } from "node:fs";
19657
- import { dirname, basename, join, resolve, relative } from "node:path";
19657
+ import { dirname, basename, join as join2, resolve, relative } from "node:path";
19658
19658
  import { writeFile as writeFileAsync, rename as renameAsync, mkdir as mkdirAsync } from "node:fs/promises";
19659
19659
 
19660
19660
  // assets/mcp/ostacky-controller/security.js
@@ -19701,6 +19701,10 @@ function isSensitive(filePath, patterns = SENSITIVE_DEFAULT) {
19701
19701
  return false;
19702
19702
  }
19703
19703
 
19704
+ // assets/mcp/ostacky-controller/session-store.js
19705
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
19706
+ import { join } from "node:path";
19707
+
19704
19708
  // assets/mcp/ostacky-controller/controller-core.js
19705
19709
  var MAX_TASKS_DEFAULT = 100;
19706
19710
  var MAX_TASKS_CAP = 500;
@@ -19849,22 +19853,398 @@ function getMaxTasks() {
19849
19853
  return MAX_TASKS_CAP;
19850
19854
  return n;
19851
19855
  }
19856
+ function normalizeTestCommand(cmd) {
19857
+ let s = String(cmd == null ? "" : cmd).trim();
19858
+ if (!s)
19859
+ return "";
19860
+ const cd = s.match(/^cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*&&\s*/);
19861
+ if (cd)
19862
+ s = s.slice(cd[0].length).trim();
19863
+ s = s.replace(/\s*2>&1\b/g, "").trim();
19864
+ const pager = s.search(/\|\s*(?:tail|head|grep)\b/);
19865
+ if (pager >= 0)
19866
+ s = s.slice(0, pager).trim();
19867
+ if (/[|;&<>]/.test(s))
19868
+ return "";
19869
+ return s;
19870
+ }
19871
+ function isMaskedExitCommand(cmd) {
19872
+ return /\|\s*(?:tail|head|grep)\b/.test(String(cmd == null ? "" : cmd));
19873
+ }
19874
+
19875
+ // assets/mcp/ostacky-controller/session-slots.js
19876
+ var TERMINAL_REQUEST_STATES = ["DONE", "ABANDONED"];
19877
+ var POOL_DEFAULTS = {
19878
+ poolMax: 10,
19879
+ overflowMax: 5,
19880
+ activeMinutes: 15,
19881
+ recycleDays: 7
19882
+ };
19883
+ function parsePoolConfig(env = process.env) {
19884
+ const num = (raw, fallback) => {
19885
+ const n = Number(raw);
19886
+ return Number.isFinite(n) && n > 0 ? n : fallback;
19887
+ };
19888
+ return {
19889
+ poolMax: Math.floor(num(env.OSTACKY_SESSION_POOL_MAX, POOL_DEFAULTS.poolMax)),
19890
+ overflowMax: Math.floor(num(env.OSTACKY_SESSION_OVERFLOW_MAX, POOL_DEFAULTS.overflowMax)),
19891
+ activeMs: num(env.OSTACKY_SESSION_ACTIVE_MIN, POOL_DEFAULTS.activeMinutes) * 60000,
19892
+ recycleMs: num(env.OSTACKY_SESSION_RECYCLE_DAYS, POOL_DEFAULTS.recycleDays) * 86400000
19893
+ };
19894
+ }
19895
+ function isActiveSlot(s, now, cfg) {
19896
+ if (!s.sessionId || !s.requestId || s.quarantined)
19897
+ return false;
19898
+ if (s.state && TERMINAL_REQUEST_STATES.includes(s.state))
19899
+ return false;
19900
+ return s.ownerHeartbeat > 0 && now - s.ownerHeartbeat <= cfg.activeMs;
19901
+ }
19902
+ function isRecycleEligible(s, now, cfg) {
19903
+ if (s.quarantined)
19904
+ return false;
19905
+ const terminal = !s.requestId || !!s.state && TERMINAL_REQUEST_STATES.includes(s.state);
19906
+ if (!terminal)
19907
+ return false;
19908
+ return now - s.lastUsedAt > cfg.recycleMs;
19909
+ }
19910
+ var byOldestFirst = (a, b) => a.lastUsedAt - b.lastUsedAt || a.slot.localeCompare(b.slot);
19911
+ function decideSlot(sessionId, slots, now, cfg, opts = {}) {
19912
+ const usable = slots.filter((s) => !s.quarantined);
19913
+ const own = usable.find((s) => s.sessionId === sessionId);
19914
+ if (own)
19915
+ return { kind: "reuse", slot: own.slot };
19916
+ const free = usable.filter((s) => !s.sessionId);
19917
+ const freeBase = free.filter((s) => !s.overflow).sort(byOldestFirst);
19918
+ const freeAny = freeBase.length > 0 ? freeBase : free.sort(byOldestFirst);
19919
+ if (freeAny.length > 0)
19920
+ return { kind: "free", slot: freeAny[0].slot };
19921
+ const baseCount = slots.filter((s) => !s.overflow).length;
19922
+ const overflowCount = slots.filter((s) => s.overflow).length;
19923
+ const activeCount = usable.filter((s) => isActiveSlot(s, now, cfg)).length;
19924
+ const notify = [];
19925
+ if (activeCount < cfg.poolMax && baseCount < cfg.poolMax) {
19926
+ return { kind: "create", slot: nextSlotId(slots, false), overflow: false, notify };
19927
+ }
19928
+ const eligible = usable.filter((s) => isRecycleEligible(s, now, cfg));
19929
+ const eligibleBase = eligible.filter((s) => !s.overflow).sort(byOldestFirst);
19930
+ const eligibleAny = eligibleBase.length > 0 ? eligibleBase : eligible.sort(byOldestFirst);
19931
+ if (eligibleAny.length > 0) {
19932
+ const pick = eligibleAny[0];
19933
+ if (activeCount >= cfg.poolMax)
19934
+ notify.push(`Ya hay ${cfg.poolMax} sesiones activas ejecutando al mismo tiempo (${activeCount} activas).`);
19935
+ return { kind: "recycle", slot: pick.slot, previousSessionId: pick.sessionId, notify };
19936
+ }
19937
+ if (activeCount >= cfg.poolMax) {
19938
+ notify.push(`Ya hay ${cfg.poolMax} sesiones activas ejecutando al mismo tiempo (${activeCount} activas).`);
19939
+ if (opts.allowOverflow && overflowCount < cfg.overflowMax) {
19940
+ notify.push(`Extensión ${overflowCount + 1}/${cfg.overflowMax} en uso (confirmada por el usuario).`);
19941
+ return { kind: "create", slot: nextSlotId(slots, true), overflow: true, notify };
19942
+ }
19943
+ if (!opts.allowOverflow) {
19944
+ notify.push(`Para extender el pool hay que confirmar (extensión 1/${cfg.overflowMax}); o esperar a que termine una de las sesiones activas.`);
19945
+ }
19946
+ }
19947
+ const candidates = usable.filter((s) => s.sessionId).sort(byOldestFirst);
19948
+ notify.push("No hay cupo: elegí una sesión para sustituir o cancelá (sin respuesta no se cambia nada).");
19949
+ return { kind: "ask", candidates, notify };
19950
+ }
19951
+ function nextSlotId(slots, overflow) {
19952
+ const taken = new Set(slots.map((s) => s.slot));
19953
+ const start = overflow ? 11 : 1;
19954
+ for (let n = start;n < start + 100; n++) {
19955
+ const id = `pool-${String(n).padStart(2, "0")}`;
19956
+ if (!taken.has(id))
19957
+ return id;
19958
+ }
19959
+ throw new Error("no hay ids de slot disponibles");
19960
+ }
19961
+ function parseSessionListTitle(json, sessionId) {
19962
+ let rows;
19963
+ try {
19964
+ rows = JSON.parse(json);
19965
+ } catch {
19966
+ return null;
19967
+ }
19968
+ if (!Array.isArray(rows))
19969
+ return null;
19970
+ const row = rows.find((r) => r && r.id === sessionId);
19971
+ if (!row || typeof row.title !== "string")
19972
+ return null;
19973
+ const title = row.title.trim();
19974
+ if (!title || title === "Untitled session")
19975
+ return null;
19976
+ return title.slice(0, 120);
19977
+ }
19978
+ function nextRevision(previousRevision) {
19979
+ return Math.max(0, Math.floor(previousRevision)) + 1;
19980
+ }
19981
+
19982
+ // assets/mcp/ostacky-controller/session-store.js
19983
+ var FILE_ACTIVITY_RETENTION_MS = 24 * 60 * 60 * 1000;
19984
+ function noteFileEdit(opencodeDir, sessionId, filePath, now, windowMs) {
19985
+ return withIndexLock(opencodeDir, () => {
19986
+ const idx = readIndex(opencodeDir);
19987
+ const own = Object.values(idx.slots).find((r) => r.sessionId === sessionId);
19988
+ if (!own)
19989
+ return [];
19990
+ const activity = idx.fileActivity ?? {};
19991
+ for (const [file, entry] of Object.entries(activity)) {
19992
+ if (now - entry.ts > FILE_ACTIVITY_RETENTION_MS)
19993
+ delete activity[file];
19994
+ }
19995
+ const prev = activity[filePath];
19996
+ const warnings = [];
19997
+ if (prev && prev.sessionId !== sessionId && now - prev.ts <= windowMs) {
19998
+ warnings.push({
19999
+ file: filePath,
20000
+ otherName: prev.sessionName || prev.requestId || "sesión sin nombre",
20001
+ otherRequestId: prev.requestId,
20002
+ minutesAgo: Math.round((now - prev.ts) / 60000)
20003
+ });
20004
+ }
20005
+ activity[filePath] = { sessionId, sessionName: own.sessionName, requestId: own.requestId, ts: now };
20006
+ idx.fileActivity = activity;
20007
+ idx.revision += 1;
20008
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
20009
+ return warnings;
20010
+ });
20011
+ }
20012
+ function sessionsDir(opencodeDir) {
20013
+ return join(opencodeDir, "sessions");
20014
+ }
20015
+ function slotPath(opencodeDir, slot) {
20016
+ return join(sessionsDir(opencodeDir), `${slot}.json`);
20017
+ }
20018
+ function indexPath(opencodeDir) {
20019
+ return join(sessionsDir(opencodeDir), "index.json");
20020
+ }
20021
+ function emptyIndex() {
20022
+ return { version: 1, revision: 0, migrated: false, slots: {} };
20023
+ }
20024
+ function readIndex(opencodeDir) {
20025
+ try {
20026
+ const parsed = JSON.parse(readFileSync(indexPath(opencodeDir), "utf-8"));
20027
+ if (parsed && typeof parsed === "object" && parsed.slots && typeof parsed.slots === "object")
20028
+ return parsed;
20029
+ } catch {}
20030
+ return emptyIndex();
20031
+ }
20032
+ function writeAtomic(path, content) {
20033
+ const tmp = `${path}.tmp.${process.pid}.${Date.now()}`;
20034
+ writeFileSync(tmp, content, "utf-8");
20035
+ renameSync(tmp, path);
20036
+ }
20037
+ function sleepSync(ms) {
20038
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
20039
+ }
20040
+ function withIndexLock(opencodeDir, fn) {
20041
+ mkdirSync(sessionsDir(opencodeDir), { recursive: true });
20042
+ const lockDir = indexPath(opencodeDir) + ".lock";
20043
+ for (let attempt = 0;attempt < 200; attempt++) {
20044
+ try {
20045
+ mkdirSync(lockDir);
20046
+ try {
20047
+ return fn();
20048
+ } finally {
20049
+ try {
20050
+ rmSync(lockDir, { recursive: true, force: true });
20051
+ } catch {}
20052
+ }
20053
+ } catch (err) {
20054
+ if (err?.code !== "EEXIST")
20055
+ throw err;
20056
+ try {
20057
+ const ageMs = Date.now() - statMtime(lockDir);
20058
+ if (ageMs > 15000)
20059
+ rmSync(lockDir, { recursive: true, force: true });
20060
+ } catch {}
20061
+ sleepSync(10 + Math.floor(Math.random() * 20));
20062
+ }
20063
+ }
20064
+ throw new Error("no se pudo tomar el lock del índice de sesiones");
20065
+ }
20066
+ function statMtime(path) {
20067
+ return statSync(path).mtimeMs;
20068
+ }
20069
+ function toInfo(slot, r) {
20070
+ return {
20071
+ slot,
20072
+ overflow: r.overflow,
20073
+ quarantined: r.quarantined,
20074
+ sessionId: r.sessionId,
20075
+ requestId: r.requestId,
20076
+ state: r.state,
20077
+ ownerHeartbeat: r.ownerHeartbeat,
20078
+ lastUsedAt: r.lastUsedAt
20079
+ };
20080
+ }
20081
+ function resetSlotFile(opencodeDir, slot, previousRevision) {
20082
+ const state = { ...structuredClone(DEFAULT_STATE), revision: nextRevision(previousRevision) };
20083
+ writeAtomic(slotPath(opencodeDir, slot), JSON.stringify(state, null, 2));
20084
+ }
20085
+ function readSlotRevision(opencodeDir, slot) {
20086
+ try {
20087
+ const st = JSON.parse(readFileSync(slotPath(opencodeDir, slot), "utf-8"));
20088
+ return typeof st.revision === "number" ? st.revision : 0;
20089
+ } catch {
20090
+ return 0;
20091
+ }
20092
+ }
20093
+ function slotProblem(opencodeDir, slot) {
20094
+ const path = slotPath(opencodeDir, slot);
20095
+ if (!existsSync(path))
20096
+ return null;
20097
+ try {
20098
+ const st = JSON.parse(readFileSync(path, "utf-8"));
20099
+ if (!st || typeof st !== "object" || typeof st.state !== "string")
20100
+ return "estado sin campo state";
20101
+ return null;
20102
+ } catch (err) {
20103
+ return `JSON inválido: ${err?.message ?? "error"}`;
20104
+ }
20105
+ }
20106
+ function bindSession(args) {
20107
+ const { opencodeDir, sessionId, now, cfg } = args;
20108
+ const name = args.sessionName ?? null;
20109
+ return withIndexLock(opencodeDir, () => {
20110
+ const idx = readIndex(opencodeDir);
20111
+ if (!idx.migrated && args.legacyStatePath && existsSync(args.legacyStatePath) && Object.keys(idx.slots).length === 0) {
20112
+ const legacy = readFileSync(args.legacyStatePath, "utf-8");
20113
+ writeAtomic(slotPath(opencodeDir, "pool-01"), legacy);
20114
+ idx.slots["pool-01"] = emptyRecord({ requestId: null });
20115
+ idx.migrated = true;
20116
+ try {
20117
+ renameSync(args.legacyStatePath, args.legacyStatePath + ".migrated");
20118
+ } catch {}
20119
+ }
20120
+ for (const [slot, rec] of Object.entries(idx.slots)) {
20121
+ const problem = slotProblem(opencodeDir, slot);
20122
+ if (problem) {
20123
+ rec.quarantined = true;
20124
+ rec.quarantineReason = problem;
20125
+ }
20126
+ }
20127
+ const view = Object.entries(idx.slots).map(([s, r]) => toInfo(s, r));
20128
+ const names = new Map(Object.entries(idx.slots).map(([s, r]) => [s, r.sessionName]));
20129
+ if (args.replaceSlot) {
20130
+ const target = idx.slots[args.replaceSlot];
20131
+ if (!target)
20132
+ return { kind: "blocked", reason: `slot ${args.replaceSlot} no existe` };
20133
+ resetSlotFile(opencodeDir, args.replaceSlot, readSlotRevision(opencodeDir, args.replaceSlot));
20134
+ if (target.sessionId) {
20135
+ idx.replaced = idx.replaced ?? {};
20136
+ idx.replaced[target.sessionId] = { slot: args.replaceSlot, at: now };
20137
+ }
20138
+ Object.assign(target, emptyRecord({ sessionId, sessionName: name, assignedAt: now, lastUsedAt: now, ownerHeartbeat: now, overflow: target.overflow }));
20139
+ idx.revision += 1;
20140
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
20141
+ return { kind: "bound", slot: args.replaceSlot, statePath: slotPath(opencodeDir, args.replaceSlot), notify: [`Slot ${args.replaceSlot} sustituido por confirmación del usuario (slot_takeover).`] };
20142
+ }
20143
+ const replacedInfo = idx.replaced?.[sessionId];
20144
+ if (replacedInfo) {
20145
+ return { kind: "blocked", reason: `tu sesión fue sustituida en ${replacedInfo.slot} por confirmación del usuario; iniciá una sesión nueva de OpenCode para continuar` };
20146
+ }
20147
+ const own = Object.entries(idx.slots).find(([, r]) => r.sessionId === sessionId && !r.quarantined);
20148
+ if (own) {
20149
+ const rec = own[1];
20150
+ rec.lastUsedAt = now;
20151
+ rec.ownerHeartbeat = now;
20152
+ if (name)
20153
+ rec.sessionName = name;
20154
+ idx.revision += 1;
20155
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
20156
+ return { kind: "bound", slot: own[0], statePath: slotPath(opencodeDir, own[0]), notify: [] };
20157
+ }
20158
+ const decision = decideSlot(sessionId, view, now, cfg, { allowOverflow: !!args.allowOverflow });
20159
+ if (decision.kind === "ask") {
20160
+ return {
20161
+ kind: "ask",
20162
+ candidates: decision.candidates.map((c) => ({ ...c, sessionName: names.get(c.slot) ?? null })),
20163
+ notify: decision.notify
20164
+ };
20165
+ }
20166
+ let slot;
20167
+ let notify = [];
20168
+ if (decision.kind === "create") {
20169
+ slot = decision.slot;
20170
+ notify = decision.notify;
20171
+ idx.slots[slot] = emptyRecord({ overflow: decision.overflow });
20172
+ resetSlotFile(opencodeDir, slot, 0);
20173
+ } else if (decision.kind === "free") {
20174
+ slot = decision.slot;
20175
+ idx.slots[slot] = emptyRecord({ overflow: idx.slots[slot].overflow });
20176
+ } else {
20177
+ slot = decision.slot;
20178
+ if (decision.kind === "recycle")
20179
+ notify = decision.notify;
20180
+ const overflow = idx.slots[slot].overflow;
20181
+ resetSlotFile(opencodeDir, slot, readSlotRevision(opencodeDir, slot));
20182
+ idx.slots[slot] = emptyRecord({ overflow });
20183
+ }
20184
+ const rec = idx.slots[slot];
20185
+ rec.sessionId = sessionId;
20186
+ rec.sessionName = name;
20187
+ rec.assignedAt = now;
20188
+ rec.lastUsedAt = now;
20189
+ rec.ownerHeartbeat = now;
20190
+ idx.revision += 1;
20191
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
20192
+ return { kind: "bound", slot, statePath: slotPath(opencodeDir, slot), notify };
20193
+ });
20194
+ }
20195
+ function emptyRecord(patch = {}) {
20196
+ return {
20197
+ sessionId: null,
20198
+ sessionName: null,
20199
+ requestId: null,
20200
+ changeId: null,
20201
+ state: null,
20202
+ ownerHeartbeat: 0,
20203
+ assignedAt: 0,
20204
+ lastUsedAt: 0,
20205
+ overflow: false,
20206
+ quarantined: false,
20207
+ quarantineReason: null,
20208
+ ...patch
20209
+ };
20210
+ }
20211
+ function recordRequestSummary(opencodeDir, sessionId, summary, now) {
20212
+ withIndexLock(opencodeDir, () => {
20213
+ const idx = readIndex(opencodeDir);
20214
+ const own = Object.entries(idx.slots).find(([, r]) => r.sessionId === sessionId);
20215
+ if (!own)
20216
+ return;
20217
+ Object.assign(own[1], { requestId: summary.requestId, changeId: summary.changeId, state: summary.state, lastUsedAt: now, ownerHeartbeat: now });
20218
+ idx.revision += 1;
20219
+ writeAtomic(indexPath(opencodeDir), JSON.stringify(idx, null, 2));
20220
+ });
20221
+ }
20222
+ var HANDOFF_FALLBACK_BASE = ".ostacky-handoff-compaction";
20223
+ function handoffFallbackPath(opencodeDir, sessionId) {
20224
+ const sid = process.env.OSTACKY_SESSION_SLOTS === "off" ? null : sessionId;
20225
+ const key = sid ? sid.replace(/[^A-Za-z0-9_-]/g, "_") : null;
20226
+ return join(opencodeDir, key ? `${HANDOFF_FALLBACK_BASE}-${key}.json` : `${HANDOFF_FALLBACK_BASE}.json`);
20227
+ }
20228
+ function isHandoffFallbackFile(name) {
20229
+ return name === HANDOFF_FALLBACK_BASE + ".json" || name.startsWith(HANDOFF_FALLBACK_BASE + "-") && name.endsWith(".json");
20230
+ }
19852
20231
 
19853
20232
  // assets/mcp/ostacky-controller/index.js
20233
+ import { execFileSync } from "node:child_process";
19854
20234
  var CONSUME_FAIL_THRESHOLD = 3;
19855
20235
  var OWNER_STALE_MS = 15 * 60 * 1000;
19856
20236
  function appendAuditJsonl(projectRoot, entry) {
19857
20237
  if (projectRoot === "/tmp" || projectRoot === "/")
19858
20238
  return;
19859
20239
  try {
19860
- const p = join(projectRoot, ".opencode", "ostacky-audit.jsonl");
20240
+ const p = join2(projectRoot, ".opencode", "ostacky-audit.jsonl");
19861
20241
  const dir = dirname(p);
19862
20242
  try {
19863
- mkdirSync(dir, { recursive: true });
20243
+ mkdirSync2(dir, { recursive: true });
19864
20244
  } catch {}
19865
20245
  try {
19866
- const prev = existsSync(p) ? readFileSync(p, "utf-8") : "";
19867
- writeFileSync(p, prev + JSON.stringify(entry) + `
20246
+ const prev = existsSync2(p) ? readFileSync2(p, "utf-8") : "";
20247
+ writeFileSync2(p, prev + JSON.stringify(entry) + `
19868
20248
  `, "utf-8");
19869
20249
  try {
19870
20250
  const retention = (() => {
@@ -19878,24 +20258,24 @@ function appendAuditJsonl(projectRoot, entry) {
19878
20258
  return 2000;
19879
20259
  return n;
19880
20260
  })();
19881
- const raw2 = readFileSync(p, "utf-8");
20261
+ const raw2 = readFileSync2(p, "utf-8");
19882
20262
  const entries = raw2.split(`
19883
20263
  `).filter(Boolean);
19884
20264
  if (entries.length > retention) {
19885
20265
  const keep = entries.slice(-retention);
19886
- writeFileSync(p, keep.join(`
20266
+ writeFileSync2(p, keep.join(`
19887
20267
  `) + `
19888
20268
  `, "utf-8");
19889
20269
  }
19890
20270
  } catch {}
19891
20271
  try {
19892
- const s = statSync(p);
20272
+ const s = statSync2(p);
19893
20273
  if (s.size > 500 * 1024) {
19894
- const raw = readFileSync(p, "utf-8");
20274
+ const raw = readFileSync2(p, "utf-8");
19895
20275
  const entries = raw.split(`
19896
20276
  `).filter(Boolean).map((l) => JSON.parse(l));
19897
20277
  const keep = entries.slice(-500);
19898
- writeFileSync(p, keep.map((e) => JSON.stringify(e)).join(`
20278
+ writeFileSync2(p, keep.map((e) => JSON.stringify(e)).join(`
19899
20279
  `) + `
19900
20280
  `, "utf-8");
19901
20281
  }
@@ -19905,10 +20285,10 @@ function appendAuditJsonl(projectRoot, entry) {
19905
20285
  }
19906
20286
  function readAuditJsonl(projectRoot, opts = {}) {
19907
20287
  try {
19908
- const p = join(projectRoot, ".opencode", "ostacky-audit.jsonl");
19909
- if (!existsSync(p))
20288
+ const p = join2(projectRoot, ".opencode", "ostacky-audit.jsonl");
20289
+ if (!existsSync2(p))
19910
20290
  return [];
19911
- const raw = readFileSync(p, "utf-8");
20291
+ const raw = readFileSync2(p, "utf-8");
19912
20292
  let entries = raw.split(`
19913
20293
  `).filter(Boolean).map((l) => JSON.parse(l));
19914
20294
  if (opts.phase)
@@ -19937,7 +20317,7 @@ function isPidAlive(pid) {
19937
20317
  }
19938
20318
  function readLockPid(pidPath) {
19939
20319
  try {
19940
- const pid = parseInt(readFileSync(pidPath, "utf8").trim(), 10);
20320
+ const pid = parseInt(readFileSync2(pidPath, "utf8").trim(), 10);
19941
20321
  return Number.isNaN(pid) ? null : pid;
19942
20322
  } catch {
19943
20323
  return null;
@@ -19945,7 +20325,7 @@ function readLockPid(pidPath) {
19945
20325
  }
19946
20326
  function lockPidAgeMs(pidPath) {
19947
20327
  try {
19948
- return Date.now() - statSync(pidPath).mtimeMs;
20328
+ return Date.now() - statSync2(pidPath).mtimeMs;
19949
20329
  } catch {
19950
20330
  return Number.POSITIVE_INFINITY;
19951
20331
  }
@@ -19962,7 +20342,7 @@ function isPathInsideProject(filePath, statePath) {
19962
20342
  const projectRoot = getProjectRoot(statePath);
19963
20343
  const resolved = resolve(projectRoot, filePath);
19964
20344
  const rel = relative(projectRoot, resolved);
19965
- if (rel.startsWith(".." + join("", "")) || rel === ".." || rel.startsWith(".."))
20345
+ if (rel.startsWith(".." + join2("", "")) || rel === ".." || rel.startsWith(".."))
19966
20346
  return false;
19967
20347
  if (resolve(filePath) !== resolved && filePath.startsWith("/")) {
19968
20348
  const absRel = relative(projectRoot, resolve(filePath));
@@ -19979,19 +20359,19 @@ function parseTasksMd(changeId, statePath) {
19979
20359
  return [];
19980
20360
  try {
19981
20361
  const projectRoot = getProjectRoot(statePath);
19982
- const tasksPath = join(projectRoot, "openspec", "changes", changeId, "tasks.md");
20362
+ const tasksPath = join2(projectRoot, "openspec", "changes", changeId, "tasks.md");
19983
20363
  let content = null;
19984
- if (existsSync(tasksPath)) {
19985
- content = readFileSync(tasksPath, "utf-8");
20364
+ if (existsSync2(tasksPath)) {
20365
+ content = readFileSync2(tasksPath, "utf-8");
19986
20366
  } else {
19987
20367
  try {
19988
- const archiveDir = join(projectRoot, "openspec", "changes", "archive");
19989
- if (existsSync(archiveDir)) {
20368
+ const archiveDir = join2(projectRoot, "openspec", "changes", "archive");
20369
+ if (existsSync2(archiveDir)) {
19990
20370
  for (const entry of readdirSync(archiveDir)) {
19991
20371
  if (entry.endsWith(`-${changeId}`) || entry === changeId) {
19992
- const alt = join(archiveDir, entry, "tasks.md");
19993
- if (existsSync(alt)) {
19994
- content = readFileSync(alt, "utf-8");
20372
+ const alt = join2(archiveDir, entry, "tasks.md");
20373
+ if (existsSync2(alt)) {
20374
+ content = readFileSync2(alt, "utf-8");
19995
20375
  break;
19996
20376
  }
19997
20377
  }
@@ -20019,19 +20399,19 @@ function parseTaskVerifications(changeId, statePath) {
20019
20399
  return {};
20020
20400
  try {
20021
20401
  const projectRoot = getProjectRoot(statePath);
20022
- const tasksPath = join(projectRoot, "openspec", "changes", changeId, "tasks.md");
20402
+ const tasksPath = join2(projectRoot, "openspec", "changes", changeId, "tasks.md");
20023
20403
  let content = null;
20024
- if (existsSync(tasksPath)) {
20025
- content = readFileSync(tasksPath, "utf-8");
20404
+ if (existsSync2(tasksPath)) {
20405
+ content = readFileSync2(tasksPath, "utf-8");
20026
20406
  } else {
20027
20407
  try {
20028
- const archiveDir = join(projectRoot, "openspec", "changes", "archive");
20029
- if (existsSync(archiveDir)) {
20408
+ const archiveDir = join2(projectRoot, "openspec", "changes", "archive");
20409
+ if (existsSync2(archiveDir)) {
20030
20410
  for (const entry of readdirSync(archiveDir)) {
20031
20411
  if (entry.endsWith(`-${changeId}`) || entry === changeId) {
20032
- const alt = join(archiveDir, entry, "tasks.md");
20033
- if (existsSync(alt)) {
20034
- content = readFileSync(alt, "utf-8");
20412
+ const alt = join2(archiveDir, entry, "tasks.md");
20413
+ if (existsSync2(alt)) {
20414
+ content = readFileSync2(alt, "utf-8");
20035
20415
  break;
20036
20416
  }
20037
20417
  }
@@ -20064,25 +20444,40 @@ function parseTaskVerifications(changeId, statePath) {
20064
20444
  }
20065
20445
  }
20066
20446
  function findTestEvidence({ runs, cmd, lastMutationTs, now = Date.now() } = {}) {
20067
- const expected = String(cmd || "").trim();
20068
- if (!expected)
20447
+ const declared = String(cmd || "").trim();
20448
+ if (!declared)
20069
20449
  return { ok: false, reason: "test: sin comando" };
20450
+ const expected = normalizeTestCommand(declared);
20451
+ if (!expected)
20452
+ return { ok: false, reason: `test: comando no verificable: "${declared}"` };
20070
20453
  if (!Array.isArray(runs) || runs.length === 0)
20071
- return { ok: false, reason: "sin evidencia: el plugin no registró corridas de shell (¿está corriendo?)" };
20072
- const matches = runs.filter((r) => r && String(r.cmd || "").trim() === expected);
20073
- if (matches.length === 0)
20074
- return { ok: false, reason: `nunca se ejecutó exactamente "${expected}"` };
20454
+ return { ok: false, reason: `sin evidencia para "${declared}": el plugin no registró ninguna corrida de shell que matchee ese comando` };
20455
+ const matches = runs.filter((r) => r && normalizeTestCommand(r.cmd) === expected);
20456
+ if (matches.length === 0) {
20457
+ const recent = runs.filter((r) => r && typeof r.cmd === "string" && r.cmd.trim()).sort((a, b) => (Number(b.ts) || 0) - (Number(a.ts) || 0));
20458
+ const similar = recent.find((r) => r.cmd.includes(declared)) || recent[0] || null;
20459
+ return {
20460
+ ok: false,
20461
+ reason: `nunca se ejecutó exactamente "${declared}"${similar ? `. La corrida más parecida fue "${similar.cmd}"` : ""}`
20462
+ };
20463
+ }
20075
20464
  const last = matches.reduce((a, b) => (Number(b.ts) || 0) >= (Number(a.ts) || 0) ? b : a);
20465
+ if (last.maskedExit === true || isMaskedExitCommand(last.cmd))
20466
+ return {
20467
+ ok: false,
20468
+ reason: `exit enmascarado: "${last.cmd}" usa un pipe a tail/head/grep; corré sin pipe o con "set -o pipefail"`,
20469
+ run: last
20470
+ };
20076
20471
  if (typeof last.ts !== "number" || typeof lastMutationTs !== "number")
20077
20472
  return {
20078
20473
  ok: false,
20079
- reason: `sin timestamps: no se puede probar que "${expected}" sea posterior a la última edición`,
20474
+ reason: `sin timestamps: no se puede probar que "${declared}" sea posterior a la última edición`,
20080
20475
  run: last
20081
20476
  };
20082
20477
  if (last.ts <= lastMutationTs)
20083
- return { ok: false, reason: `la última corrida de "${expected}" es anterior a la última edición`, run: last };
20478
+ return { ok: false, reason: `la última corrida de "${declared}" es anterior a la última edición`, run: last };
20084
20479
  if (last.exit !== 0)
20085
- return { ok: false, reason: `la última corrida de "${expected}" salió con exit ${last.exit}`, run: last };
20480
+ return { ok: false, reason: `la última corrida de "${declared}" salió con exit ${last.exit}`, run: last };
20086
20481
  return { ok: true, reason: `exit 0 hace ${Math.max(0, Math.round((now - last.ts) / 1000))}s`, run: last };
20087
20482
  }
20088
20483
  function isValidTaskId(taskId) {
@@ -20182,20 +20577,21 @@ function cleanupTmpFiles(statePath) {
20182
20577
  for (const entry of readdirSync(dir)) {
20183
20578
  const isTmp = entry.startsWith(name + ".tmp.");
20184
20579
  const isLock = entry.startsWith(name + ".lock");
20185
- const isHandoff = entry === ".ostacky-handoff-compaction.json";
20186
- if (!isTmp && !isLock && !isHandoff)
20580
+ const isHandoff = isHandoffFallbackFile(entry);
20581
+ const isHandoffTmp = entry.startsWith(".ostacky-handoff-compaction") && entry.includes(".json.tmp.");
20582
+ if (!isTmp && !isLock && !isHandoff && !isHandoffTmp)
20187
20583
  continue;
20188
20584
  if (isLock) {
20189
20585
  try {
20190
- const pidPath = join(dir, name + ".lock.pid");
20191
- const tsPath = join(dir, name + ".lock.timestamp");
20586
+ const pidPath = join2(dir, name + ".lock.pid");
20587
+ const tsPath = join2(dir, name + ".lock.timestamp");
20192
20588
  let lockPid = null;
20193
20589
  let lockTs = null;
20194
20590
  try {
20195
- lockPid = readFileSync(pidPath, "utf8").trim();
20591
+ lockPid = readFileSync2(pidPath, "utf8").trim();
20196
20592
  } catch {}
20197
20593
  try {
20198
- lockTs = parseInt(readFileSync(tsPath, "utf8").trim(), 10);
20594
+ lockTs = parseInt(readFileSync2(tsPath, "utf8").trim(), 10);
20199
20595
  } catch {}
20200
20596
  if (lockPid && String(lockPid) !== String(process.pid) && isPidAlive(parseInt(lockPid, 10))) {
20201
20597
  continue;
@@ -20210,8 +20606,8 @@ function cleanupTmpFiles(statePath) {
20210
20606
  }
20211
20607
  if (isHandoff) {
20212
20608
  try {
20213
- const handoffPath = join(dir, entry);
20214
- const raw = readFileSync(handoffPath, "utf8");
20609
+ const handoffPath = join2(dir, entry);
20610
+ const raw = readFileSync2(handoffPath, "utf8");
20215
20611
  const data = JSON.parse(raw);
20216
20612
  const ts = data?.ts ?? data?.timestamp ?? 0;
20217
20613
  if (ts && Date.now() - ts < handoffTtl)
@@ -20219,14 +20615,14 @@ function cleanupTmpFiles(statePath) {
20219
20615
  } catch {}
20220
20616
  }
20221
20617
  try {
20222
- unlinkSync(join(dir, entry));
20618
+ unlinkSync(join2(dir, entry));
20223
20619
  } catch {}
20224
20620
  }
20225
20621
  } catch {}
20226
20622
  }
20227
20623
  function fastFingerprint(filePath) {
20228
20624
  try {
20229
- const stat = statSync(filePath);
20625
+ const stat = statSync2(filePath);
20230
20626
  return `${stat.mtimeMs}-${stat.size}`;
20231
20627
  } catch {
20232
20628
  return null;
@@ -20258,11 +20654,15 @@ class OstackyController {
20258
20654
  #lockOwner = false;
20259
20655
  #lockDepth = 0;
20260
20656
  #callerSessionId = null;
20657
+ #opencodeDir = null;
20261
20658
  #loadedSnapshot = null;
20262
20659
  #persistQueue = Promise.resolve();
20263
20660
  #persistSeq = 0;
20661
+ #fileEditObserver = null;
20662
+ #notices = [];
20264
20663
  constructor(opts = {}) {
20265
20664
  this.#statePath = opts.statePath;
20665
+ this.#opencodeDir = opts.statePath ? dirname(opts.statePath) : null;
20266
20666
  this.#lockPath = opts.statePath ? opts.statePath + ".lock" : null;
20267
20667
  this.#lockPidPath = opts.statePath ? opts.statePath + ".lock.pid" : null;
20268
20668
  this.#lockHeartbeatPath = opts.statePath ? opts.statePath + ".lock.timestamp" : null;
@@ -20313,6 +20713,46 @@ class OstackyController {
20313
20713
  this.#loadedSnapshot = this.#diffableState();
20314
20714
  return true;
20315
20715
  }
20716
+ rebindStatePath(newPath) {
20717
+ if (newPath === this.#statePath)
20718
+ return;
20719
+ this.#statePath = newPath;
20720
+ this.#lockPath = newPath + ".lock";
20721
+ this.#lockPidPath = newPath + ".lock.pid";
20722
+ this.#lockHeartbeatPath = newPath + ".lock.timestamp";
20723
+ this.#state = null;
20724
+ this.#loaded = false;
20725
+ this.#loadedSnapshot = null;
20726
+ }
20727
+ get statePathValue() {
20728
+ return this.#statePath;
20729
+ }
20730
+ stateSummary() {
20731
+ this.#load();
20732
+ return {
20733
+ requestId: this.#state?.requestId ?? null,
20734
+ changeId: this.#state?.changeId ?? null,
20735
+ state: this.#state?.state ?? null
20736
+ };
20737
+ }
20738
+ setFileEditObserver(fn) {
20739
+ this.#fileEditObserver = typeof fn === "function" ? fn : null;
20740
+ }
20741
+ #observeFileEdit(filePath) {
20742
+ if (!filePath || !this.#fileEditObserver)
20743
+ return;
20744
+ try {
20745
+ this.#fileEditObserver(filePath);
20746
+ } catch {}
20747
+ }
20748
+ pushNotice(message) {
20749
+ this.#notices.push(message);
20750
+ }
20751
+ takeNotices() {
20752
+ const out = this.#notices;
20753
+ this.#notices = [];
20754
+ return out;
20755
+ }
20316
20756
  setCallerSession(sessionId) {
20317
20757
  this.#callerSessionId = typeof sessionId === "string" && sessionId ? sessionId : null;
20318
20758
  }
@@ -20353,7 +20793,7 @@ class OstackyController {
20353
20793
  try {
20354
20794
  let lockAge = NaN;
20355
20795
  try {
20356
- lockAge = Date.now() - parseInt(readFileSync(this.#lockHeartbeatPath, "utf8"), 10);
20796
+ lockAge = Date.now() - parseInt(readFileSync2(this.#lockHeartbeatPath, "utf8"), 10);
20357
20797
  } catch {}
20358
20798
  if (!Number.isNaN(lockAge) && lockAge < staleWindow) {
20359
20799
  const base = Math.min(lockTimeout, 100 * Math.pow(2, attempt));
@@ -20374,7 +20814,7 @@ class OstackyController {
20374
20814
  }
20375
20815
  }
20376
20816
  try {
20377
- writeFileSync(this.#lockPidPath, String(process.pid), { encoding: "utf8", flag: "wx" });
20817
+ writeFileSync2(this.#lockPidPath, String(process.pid), { encoding: "utf8", flag: "wx" });
20378
20818
  } catch (e) {
20379
20819
  if (e && e.code === "EEXIST") {
20380
20820
  const base = Math.min(lockTimeout, 100 * Math.pow(2, attempt));
@@ -20411,7 +20851,7 @@ class OstackyController {
20411
20851
  }
20412
20852
  this.#lockDepth = 0;
20413
20853
  try {
20414
- const ownerPid = readFileSync(this.#lockPidPath, "utf8").trim();
20854
+ const ownerPid = readFileSync2(this.#lockPidPath, "utf8").trim();
20415
20855
  if (ownerPid !== String(process.pid)) {
20416
20856
  this.#lockOwner = false;
20417
20857
  return;
@@ -20440,7 +20880,7 @@ class OstackyController {
20440
20880
  if (!this.#lockHeartbeatPath)
20441
20881
  return;
20442
20882
  try {
20443
- writeFileSync(this.#lockHeartbeatPath, String(Date.now()), "utf8");
20883
+ writeFileSync2(this.#lockHeartbeatPath, String(Date.now()), "utf8");
20444
20884
  } catch {}
20445
20885
  }
20446
20886
  #load() {
@@ -20452,7 +20892,7 @@ class OstackyController {
20452
20892
  return;
20453
20893
  }
20454
20894
  try {
20455
- const raw = readFileSync(this.#statePath, "utf8");
20895
+ const raw = readFileSync2(this.#statePath, "utf8");
20456
20896
  if (raw.length > MAX_STATE_FILE_SIZE)
20457
20897
  throw new Error(`State file too large: ${raw.length} bytes`);
20458
20898
  const parsed = JSON.parse(raw);
@@ -20526,7 +20966,7 @@ class OstackyController {
20526
20966
  for (const suffix of [".backup", ".backup.1", ".backup.2"]) {
20527
20967
  const backupPath = this.#statePath + suffix;
20528
20968
  try {
20529
- const raw = readFileSync(backupPath, "utf8");
20969
+ const raw = readFileSync2(backupPath, "utf8");
20530
20970
  if (raw.length > MAX_STATE_FILE_SIZE)
20531
20971
  throw new Error(`Backup too large: ${raw.length} bytes`);
20532
20972
  const parsed = JSON.parse(raw);
@@ -20676,10 +21116,10 @@ class OstackyController {
20676
21116
  await renameAsync(tmp, this.#statePath);
20677
21117
  try {
20678
21118
  try {
20679
- renameSync(this.#statePath + ".backup.1", this.#statePath + ".backup.2");
21119
+ renameSync2(this.#statePath + ".backup.1", this.#statePath + ".backup.2");
20680
21120
  } catch {}
20681
21121
  try {
20682
- renameSync(this.#statePath + ".backup", this.#statePath + ".backup.1");
21122
+ renameSync2(this.#statePath + ".backup", this.#statePath + ".backup.1");
20683
21123
  } catch {}
20684
21124
  } catch {}
20685
21125
  try {
@@ -21592,8 +22032,8 @@ class OstackyController {
21592
22032
  if (fp) {
21593
22033
  try {
21594
22034
  const abs = fp.startsWith("/") || /^[A-Za-z]:/.test(fp) ? resolve(fp) : resolve(getProjectRoot(this.#statePath), fp);
21595
- if (existsSync(abs))
21596
- content = readFileSync(abs, "utf-8");
22035
+ if (existsSync2(abs))
22036
+ content = readFileSync2(abs, "utf-8");
21597
22037
  } catch {}
21598
22038
  }
21599
22039
  const found = content ? content.includes(needle) : false;
@@ -21854,8 +22294,8 @@ class OstackyController {
21854
22294
  if (fp) {
21855
22295
  try {
21856
22296
  const abs = fp.startsWith("/") || /^[A-Za-z]:/.test(fp) ? resolve(fp) : resolve(getProjectRoot(this.#statePath), fp);
21857
- if (existsSync(abs))
21858
- content = readFileSync(abs, "utf-8");
22297
+ if (existsSync2(abs))
22298
+ content = readFileSync2(abs, "utf-8");
21859
22299
  } catch {}
21860
22300
  }
21861
22301
  const found = content ? content.includes(needle) : false;
@@ -21910,7 +22350,7 @@ class OstackyController {
21910
22350
  let auditSize = 0;
21911
22351
  let diskFreeMB = null;
21912
22352
  try {
21913
- const stat = statSync(this.#statePath);
22353
+ const stat = statSync2(this.#statePath);
21914
22354
  stateFileSize = stat.size;
21915
22355
  } catch {}
21916
22356
  try {
@@ -22083,8 +22523,8 @@ class OstackyController {
22083
22523
  if (!this.#statePath)
22084
22524
  return null;
22085
22525
  try {
22086
- const fallbackPath = join(dirname(this.#statePath), ".ostacky-handoff-compaction.json");
22087
- const raw = readFileSync(fallbackPath, "utf8");
22526
+ const fallbackPath = handoffFallbackPath(this.#opencodeDir, this.#callerSessionId);
22527
+ const raw = readFileSync2(fallbackPath, "utf8");
22088
22528
  const data = JSON.parse(raw);
22089
22529
  if (data && typeof data.summary === "string")
22090
22530
  return data;
@@ -22097,7 +22537,7 @@ class OstackyController {
22097
22537
  this.#state.lastHandoff = null;
22098
22538
  if (this.#statePath) {
22099
22539
  try {
22100
- unlinkSync(join(dirname(this.#statePath), ".ostacky-handoff-compaction.json"));
22540
+ unlinkSync(handoffFallbackPath(this.#opencodeDir, this.#callerSessionId));
22101
22541
  } catch {}
22102
22542
  }
22103
22543
  await this.#audit("HANDOFF", "clear_handoff", prev?.summary?.slice(0, 100) || "none");
@@ -22191,6 +22631,7 @@ class OstackyController {
22191
22631
  }
22192
22632
  async validateEdit({ oldString, newString, content, taskId, filePath } = {}) {
22193
22633
  this.#load();
22634
+ this.#observeFileEdit(filePath);
22194
22635
  if (this.#state.state !== "EXECUTING_INLINE" && this.#state.state !== "EXECUTING_SUBAGENTS") {
22195
22636
  return { outcome: "CONFLICT", reason: `Cannot validate edit from state ${this.#state.state}` };
22196
22637
  }
@@ -22213,7 +22654,7 @@ class OstackyController {
22213
22654
  try {
22214
22655
  const projectRoot = getProjectRoot(this.#statePath);
22215
22656
  const absolutePath = filePath.startsWith("/") || /^[A-Za-z]:/.test(filePath) ? resolve(filePath) : resolve(projectRoot, filePath);
22216
- const diskContent = readFileSync(absolutePath, "utf8");
22657
+ const diskContent = readFileSync2(absolutePath, "utf8");
22217
22658
  if (diskContent !== content) {
22218
22659
  this.#state.staleContentAttempts = (this.#state.staleContentAttempts || 0) + 1;
22219
22660
  await this.#persist();
@@ -22232,7 +22673,7 @@ class OstackyController {
22232
22673
  const _prevValidated = this._getValidatedFor(filePath);
22233
22674
  if (currentHash && hashArg === currentHash && _prevValidated && _prevValidated.hash === currentHash) {
22234
22675
  try {
22235
- content = readFileSync(absolutePath, "utf8");
22676
+ content = readFileSync2(absolutePath, "utf8");
22236
22677
  } catch {
22237
22678
  return { outcome: "CONFLICT", reason: "stale fingerprint", filePath };
22238
22679
  }
@@ -22253,7 +22694,7 @@ class OstackyController {
22253
22694
  const currentHash = fastFingerprint(absolutePath);
22254
22695
  if (currentHash && currentHash === _optValidated.hash) {
22255
22696
  try {
22256
- const diskContent = readFileSync(absolutePath, "utf8");
22697
+ const diskContent = readFileSync2(absolutePath, "utf8");
22257
22698
  content = diskContent;
22258
22699
  } catch {}
22259
22700
  }
@@ -22266,7 +22707,7 @@ class OstackyController {
22266
22707
  try {
22267
22708
  const projectRoot = getProjectRoot(this.#statePath);
22268
22709
  const absolutePath = filePath.startsWith("/") || /^[A-Za-z]:/.test(filePath) ? resolve(filePath) : resolve(projectRoot, filePath);
22269
- if (existsSync(absolutePath)) {
22710
+ if (existsSync2(absolutePath)) {
22270
22711
  return { outcome: "CONFLICT", reason: "file exists, use replace mode", filePath };
22271
22712
  }
22272
22713
  } catch {
@@ -22320,6 +22761,7 @@ class OstackyController {
22320
22761
  }
22321
22762
  async completeTask({ taskId, filePath, fileHash } = {}) {
22322
22763
  this.#load();
22764
+ this.#observeFileEdit(filePath);
22323
22765
  const denied = await this.#foreignOwnerError("complete_task");
22324
22766
  if (denied)
22325
22767
  return denied;
@@ -22349,7 +22791,7 @@ class OstackyController {
22349
22791
  const isTestTaskEarly = verifEarly && verifEarly.trim().startsWith("test:");
22350
22792
  if (filePath) {
22351
22793
  const absPath = filePath.startsWith("/") || /^[A-Za-z]:/.test(filePath) ? resolve(filePath) : resolve(getProjectRoot(this.#statePath), filePath);
22352
- if (!existsSync(absPath)) {
22794
+ if (!existsSync2(absPath)) {
22353
22795
  return { error: `filePath does not exist: ${filePath}`, taskId, filePath };
22354
22796
  }
22355
22797
  }
@@ -22446,7 +22888,7 @@ class OstackyController {
22446
22888
  }
22447
22889
  const projectRoot = getProjectRoot(this.#statePath);
22448
22890
  const abs = target.startsWith("/") || /^[A-Za-z]:/.test(target) ? resolve(target) : resolve(projectRoot, target);
22449
- if (!existsSync(abs))
22891
+ if (!existsSync2(abs))
22450
22892
  return { error: `file not found: ${target}`, ok: false, filePath: target };
22451
22893
  const current = fingerprintFor(target, this.#statePath);
22452
22894
  if (!current)
@@ -22509,7 +22951,12 @@ class OstackyController {
22509
22951
  ok: ev.ok,
22510
22952
  verif,
22511
22953
  reason: ev.reason,
22512
- run: ev.run ? { cmd: ev.run.cmd, exit: ev.run.exit, ts: ev.run.ts } : null,
22954
+ run: ev.run ? {
22955
+ cmd: ev.run.cmd,
22956
+ exit: ev.run.exit,
22957
+ ts: ev.run.ts,
22958
+ ...ev.run.maskedExit ? { maskedExit: true } : {}
22959
+ } : null,
22513
22960
  ts: Date.now()
22514
22961
  };
22515
22962
  await this.#persist();
@@ -22519,9 +22966,9 @@ class OstackyController {
22519
22966
  let checkPath = fileHint || info?.filePath || filePathParam || null;
22520
22967
  if (checkPath) {
22521
22968
  const abs = checkPath.startsWith("/") || /^[A-Za-z]:/.test(checkPath) ? resolve(checkPath) : resolve(getProjectRoot(this.#statePath), checkPath);
22522
- if (existsSync(abs)) {
22969
+ if (existsSync2(abs)) {
22523
22970
  try {
22524
- content = readFileSync(abs, "utf-8");
22971
+ content = readFileSync2(abs, "utf-8");
22525
22972
  } catch {}
22526
22973
  }
22527
22974
  }
@@ -22560,7 +23007,7 @@ class OstackyController {
22560
23007
  return;
22561
23008
  try {
22562
23009
  try {
22563
- const tsRaw = readFileSync(this.#lockHeartbeatPath, "utf8");
23010
+ const tsRaw = readFileSync2(this.#lockHeartbeatPath, "utf8");
22564
23011
  const age = Date.now() - parseInt(tsRaw, 10);
22565
23012
  if (!Number.isNaN(age) && age >= 15000) {
22566
23013
  try {
@@ -22572,18 +23019,18 @@ class OstackyController {
22572
23019
  this.#lockOwner = false;
22573
23020
  } else if (!Number.isNaN(age) && age < 15000) {
22574
23021
  try {
22575
- const pidRaw = readFileSync(this.#lockPidPath, "utf8").trim();
23022
+ const pidRaw = readFileSync2(this.#lockPidPath, "utf8").trim();
22576
23023
  if (pidRaw !== String(process.pid))
22577
23024
  return;
22578
23025
  } catch {}
22579
23026
  }
22580
23027
  } catch {}
22581
23028
  try {
22582
- writeFileSync(this.#lockPidPath, String(process.pid), { encoding: "utf8", flag: "wx" });
23029
+ writeFileSync2(this.#lockPidPath, String(process.pid), { encoding: "utf8", flag: "wx" });
22583
23030
  } catch (e) {
22584
23031
  if (e && e.code === "EEXIST") {
22585
23032
  try {
22586
- const tsRaw2 = readFileSync(this.#lockHeartbeatPath, "utf8");
23033
+ const tsRaw2 = readFileSync2(this.#lockHeartbeatPath, "utf8");
22587
23034
  const age2 = Date.now() - parseInt(tsRaw2, 10);
22588
23035
  if (!Number.isNaN(age2) && age2 >= 15000) {
22589
23036
  try {
@@ -22592,7 +23039,7 @@ class OstackyController {
22592
23039
  try {
22593
23040
  unlinkSync(this.#lockHeartbeatPath);
22594
23041
  } catch {}
22595
- writeFileSync(this.#lockPidPath, String(process.pid), { encoding: "utf8", flag: "wx" });
23042
+ writeFileSync2(this.#lockPidPath, String(process.pid), { encoding: "utf8", flag: "wx" });
22596
23043
  } else
22597
23044
  return;
22598
23045
  } catch {
@@ -22602,20 +23049,33 @@ class OstackyController {
22602
23049
  throw e;
22603
23050
  }
22604
23051
  try {
22605
- writeFileSync(this.#lockPidPath, String(process.pid), { encoding: "utf8", flag: "wx" });
23052
+ writeFileSync2(this.#lockPidPath, String(process.pid), { encoding: "utf8", flag: "wx" });
22606
23053
  this.#heartbeatLock();
22607
23054
  this.#lockOwner = true;
22608
23055
  } catch {}
22609
23056
  const serialized = safeJsonStringify(this.#state, true);
22610
23057
  const tmp = this.#statePath + ".tmp." + process.pid;
22611
- writeFileSync(tmp, serialized, "utf8");
22612
- renameSync(tmp, this.#statePath);
23058
+ writeFileSync2(tmp, serialized, "utf8");
23059
+ renameSync2(tmp, this.#statePath);
22613
23060
  this.#releaseLock();
22614
23061
  } catch {}
22615
23062
  }
22616
23063
  }
22617
- var statePath = resolve(process.env.OSTACKY_STATE_PATH || join(process.cwd(), ".opencode", "ostacky-state.json"));
23064
+ var statePath = resolve(process.env.OSTACKY_STATE_PATH || join2(process.cwd(), ".opencode", "ostacky-state.json"));
22618
23065
  var controller = new OstackyController({ statePath });
23066
+ controller.setFileEditObserver((filePath) => {
23067
+ if (process.env.OSTACKY_SESSION_SLOTS === "off")
23068
+ return;
23069
+ const sid = controller.callerSessionId;
23070
+ if (!sid)
23071
+ return;
23072
+ const minutes = Number(process.env.OSTACKY_CONCURRENT_EDIT_WINDOW_MIN);
23073
+ const windowMs = (Number.isFinite(minutes) && minutes > 0 ? minutes : 30) * 60000;
23074
+ const warnings = noteFileEdit(dirname(statePath), sid, filePath, Date.now(), windowMs);
23075
+ for (const w of warnings) {
23076
+ controller.pushNotice(`WARN concurrent_edit: ${w.file} lo editó hace ${w.minutesAgo} min "${w.otherName}" (request ${w.otherRequestId ?? "sin request"}). No bloquea: coordiná antes de seguir.`);
23077
+ }
23078
+ });
22619
23079
  function extractCallerSessionId(ctx) {
22620
23080
  try {
22621
23081
  const meta = ctx && ctx.mcpReq && ctx.mcpReq._meta;
@@ -22631,6 +23091,72 @@ function extractCallerSessionId(ctx) {
22631
23091
  } catch {}
22632
23092
  return null;
22633
23093
  }
23094
+ var sessionTitleCache = new Map;
23095
+ var SESSION_TITLE_MISS_TTL_MS = 60000;
23096
+ function sessionTitleFor(sid) {
23097
+ if (!sid)
23098
+ return null;
23099
+ const hit = sessionTitleCache.get(sid);
23100
+ if (hit && (hit.title || Date.now() - hit.at < SESSION_TITLE_MISS_TTL_MS))
23101
+ return hit.title;
23102
+ let title = null;
23103
+ try {
23104
+ const out = execFileSync("opencode", ["session", "list", "--format", "json", "-n", "200"], {
23105
+ encoding: "utf8",
23106
+ timeout: 4000,
23107
+ stdio: ["ignore", "pipe", "ignore"]
23108
+ });
23109
+ title = parseSessionListTitle(out, sid);
23110
+ } catch {}
23111
+ sessionTitleCache.set(sid, { title, at: Date.now() });
23112
+ return title;
23113
+ }
23114
+ function displayNameOf(c) {
23115
+ return c.sessionName || c.changeId || c.requestId || "sesión sin nombre";
23116
+ }
23117
+ function bindCallerSlot(params, ctx) {
23118
+ if (process.env.OSTACKY_SESSION_SLOTS === "off")
23119
+ return { block: null, notice: [] };
23120
+ const sid = controller.callerSessionId;
23121
+ if (!sid)
23122
+ return { block: null, notice: [] };
23123
+ const cfg = parsePoolConfig(process.env);
23124
+ const opencodeDir = dirname(statePath);
23125
+ const res = bindSession({
23126
+ opencodeDir,
23127
+ sessionId: sid,
23128
+ sessionName: sessionTitleFor(sid),
23129
+ now: Date.now(),
23130
+ cfg,
23131
+ legacyStatePath: statePath,
23132
+ replaceSlot: params && params.replaceSlot || null,
23133
+ allowOverflow: !!(params && params.allowExtension)
23134
+ });
23135
+ if (res.kind === "blocked")
23136
+ return { block: { error: `BLOCKED: ${res.reason}` }, notice: [] };
23137
+ if (res.kind === "ask") {
23138
+ const now = Date.now();
23139
+ return {
23140
+ block: {
23141
+ conflict: true,
23142
+ question: "slot_capacity",
23143
+ notify: res.notify,
23144
+ message: "Pregunta al usuario antes de continuar: confirmar sustitución (replaceSlot), confirmar extensión del pool (allowExtension) o esperar a que termine una sesión activa. No cambies nada sin respuesta.",
23145
+ candidates: res.candidates.map((c) => ({
23146
+ slot: c.slot,
23147
+ name: displayNameOf(c),
23148
+ changeId: c.changeId ?? null,
23149
+ state: c.state ?? null,
23150
+ active: isActiveSlot(c, now, cfg),
23151
+ lastActivityMinutesAgo: Math.round((now - (c.lastUsedAt || 0)) / 60000)
23152
+ }))
23153
+ },
23154
+ notice: []
23155
+ };
23156
+ }
23157
+ controller.rebindStatePath(res.statePath);
23158
+ return { block: null, notice: res.notify };
23159
+ }
22634
23160
  var opQueue = Promise.resolve();
22635
23161
  function serializeOp(run) {
22636
23162
  const next = opQueue.then(run, run);
@@ -22641,8 +23167,17 @@ function safeHandler(fn, options = {}) {
22641
23167
  const { maxRetries = 0, baseTimeout = 5000 } = options;
22642
23168
  return (params, ctx) => serializeOp(async () => {
22643
23169
  let heldLock = false;
23170
+ let slotGate = { block: null, notice: [] };
23171
+ controller.takeNotices();
22644
23172
  try {
22645
23173
  controller.setCallerSession(extractCallerSessionId(ctx));
23174
+ slotGate = bindCallerSlot(params, ctx);
23175
+ } catch (error) {
23176
+ return { content: [{ type: "text", text: safeJsonStringify({ error: `BLOCKED: no se pudo asignar slot de sesión: ${String(error?.message || error)}` }) }] };
23177
+ }
23178
+ if (slotGate.block)
23179
+ return { content: [{ type: "text", text: safeJsonStringify(slotGate.block) }] };
23180
+ try {
22646
23181
  heldLock = await controller.beginWrite();
22647
23182
  controller.reloadFresh();
22648
23183
  } catch {}
@@ -22670,8 +23205,18 @@ function safeHandler(fn, options = {}) {
22670
23205
  await controller.persistIfDirty();
22671
23206
  } catch {}
22672
23207
  controller.updateHeartbeat();
23208
+ const sidNow = controller.callerSessionId;
23209
+ if (sidNow && process.env.OSTACKY_SESSION_SLOTS !== "off") {
23210
+ try {
23211
+ recordRequestSummary(dirname(statePath), sidNow, controller.stateSummary(), Date.now());
23212
+ } catch {}
23213
+ }
22673
23214
  endOp();
22674
- return { content: [{ type: "text", text: safeJsonStringify(result) }] };
23215
+ const notices = controller.takeNotices();
23216
+ let out = slotGate.notice.length && result && typeof result === "object" ? { ...result, slotNotice: slotGate.notice } : result;
23217
+ if (notices.length && out && typeof out === "object")
23218
+ out = { ...out, concurrentEdit: notices };
23219
+ return { content: [{ type: "text", text: safeJsonStringify(out) }] };
22675
23220
  } catch (error) {
22676
23221
  const isTimeout = error && error.message && error.message.includes("timeout");
22677
23222
  const isNetworkError = error && error.code && ["ECONNRESET", "ETIMEDOUT", "ENOTFOUND"].includes(error.code);
@@ -22720,14 +23265,16 @@ function safeHandler(fn, options = {}) {
22720
23265
  }
22721
23266
  var server = new McpServer({
22722
23267
  name: "ostacky-controller",
22723
- version: "0.10.3"
23268
+ version: "0.11.0"
22724
23269
  });
22725
23270
  server.registerTool("start_request", {
22726
23271
  description: "Start or resume request",
22727
23272
  inputSchema: object({
22728
23273
  requestId: string2().optional().describe("Unique request ID"),
22729
23274
  changeId: string2().optional().describe("Optional change ID for OpenSpec tracking"),
22730
- force: boolean2().optional().describe("Force reset even if work in progress (default: false)")
23275
+ force: boolean2().optional().describe("Force reset even if work in progress (default: false)"),
23276
+ replaceSlot: string2().optional().describe("Confirmación del usuario: slot a sustituir (ej. pool-03)"),
23277
+ allowExtension: boolean2().optional().describe("Confirmación del usuario: crear slot de extensión con 10 sesiones activas")
22731
23278
  })
22732
23279
  }, safeHandler(async ({ requestId, changeId, force }) => {
22733
23280
  log("tool:start_request", { force: !!force });
@@ -22893,11 +23440,11 @@ server.registerTool("check_file_access", {
22893
23440
  }, safeHandler(async ({ filePath, reason }) => {
22894
23441
  log("tool:check_file_access", { filePath });
22895
23442
  try {
22896
- const pluginPath = join(process.cwd(), ".opencode", "plugins", "ostacky-plugin.ts");
22897
- const assetsPath = join(process.cwd(), "assets", "plugins", "ostacky-plugin.ts");
22898
- const legacyPluginPath = join(process.cwd(), ".opencode", "plugins", "ostacky-controller.ts");
22899
- const legacyAssetsPath = join(process.cwd(), "assets", "plugins", "ostacky-controller.ts");
22900
- if (existsSync(pluginPath) || existsSync(assetsPath) || existsSync(legacyPluginPath) || existsSync(legacyAssetsPath)) {
23443
+ const pluginPath = join2(process.cwd(), ".opencode", "plugins", "ostacky-plugin.ts");
23444
+ const assetsPath = join2(process.cwd(), "assets", "plugins", "ostacky-plugin.ts");
23445
+ const legacyPluginPath = join2(process.cwd(), ".opencode", "plugins", "ostacky-controller.ts");
23446
+ const legacyAssetsPath = join2(process.cwd(), "assets", "plugins", "ostacky-controller.ts");
23447
+ if (existsSync2(pluginPath) || existsSync2(assetsPath) || existsSync2(legacyPluginPath) || existsSync2(legacyAssetsPath)) {
22901
23448
  const res = await controller.checkFileAccess({ filePath, reason });
22902
23449
  return { ...res, deprecated: true, hint: "plugin enforces" };
22903
23450
  }
@@ -22994,9 +23541,9 @@ server.registerTool("check_pending_state", {
22994
23541
  inputSchema: object({})
22995
23542
  }, safeHandler(async () => {
22996
23543
  try {
22997
- const pluginPath = join(process.cwd(), ".opencode", "plugins", "ostacky-controller.ts");
22998
- const assetsPath = join(process.cwd(), "assets", "plugins", "ostacky-controller.ts");
22999
- if (existsSync(pluginPath) || existsSync(assetsPath)) {
23544
+ const pluginPath = join2(process.cwd(), ".opencode", "plugins", "ostacky-controller.ts");
23545
+ const assetsPath = join2(process.cwd(), "assets", "plugins", "ostacky-controller.ts");
23546
+ if (existsSync2(pluginPath) || existsSync2(assetsPath)) {
23000
23547
  return { deprecated: true, hint: "plugin enforces", status: "ALLOW" };
23001
23548
  }
23002
23549
  } catch {}
@@ -23031,11 +23578,11 @@ server.registerTool("validate_edit", {
23031
23578
  filePath
23032
23579
  });
23033
23580
  try {
23034
- const pluginPath = join(process.cwd(), ".opencode", "plugins", "ostacky-plugin.ts");
23035
- const assetsPath = join(process.cwd(), "assets", "plugins", "ostacky-plugin.ts");
23036
- const legacyPluginPath = join(process.cwd(), ".opencode", "plugins", "ostacky-controller.ts");
23037
- const legacyAssetsPath = join(process.cwd(), "assets", "plugins", "ostacky-controller.ts");
23038
- if (existsSync(pluginPath) || existsSync(assetsPath) || existsSync(legacyPluginPath) || existsSync(legacyAssetsPath)) {
23581
+ const pluginPath = join2(process.cwd(), ".opencode", "plugins", "ostacky-plugin.ts");
23582
+ const assetsPath = join2(process.cwd(), "assets", "plugins", "ostacky-plugin.ts");
23583
+ const legacyPluginPath = join2(process.cwd(), ".opencode", "plugins", "ostacky-controller.ts");
23584
+ const legacyAssetsPath = join2(process.cwd(), "assets", "plugins", "ostacky-controller.ts");
23585
+ if (existsSync2(pluginPath) || existsSync2(assetsPath) || existsSync2(legacyPluginPath) || existsSync2(legacyAssetsPath)) {
23039
23586
  return { deprecated: true, hint: "plugin enforces" };
23040
23587
  }
23041
23588
  } catch {}
@@ -23089,7 +23636,7 @@ function setupGracefulShutdown(ctrl) {
23089
23636
  });
23090
23637
  }
23091
23638
  async function main() {
23092
- log("Starting ostacky-controller MCP v0.10.3...");
23639
+ log("Starting ostacky-controller MCP v0.11.0...");
23093
23640
  log("State path:", { path: statePath });
23094
23641
  cleanupTmpFiles(statePath);
23095
23642
  setupGracefulShutdown(controller);