ostacky 0.10.2 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -3
- package/assets/agents/ostacky.md +20 -6
- package/assets/commands/install-stack.md +1 -1
- package/assets/docs/ostacky-reference.md +10 -1
- package/assets/mcp/ostacky-controller/controller-core.js +30 -0
- package/assets/mcp/ostacky-controller/index.js +405 -53
- package/assets/mcp/ostacky-controller/session-slots.js +110 -0
- package/assets/mcp/ostacky-controller/session-store.js +290 -0
- package/assets/plugins/engram.ts +13 -9
- package/assets/plugins/ostacky-controller/compaction-threshold.ts +274 -0
- package/assets/plugins/ostacky-controller/controller-core.ts +30 -0
- package/assets/plugins/ostacky-controller/index.ts +532 -113
- package/assets/plugins/ostacky-controller/session-slots.ts +167 -0
- package/assets/plugins/ostacky-controller/session-store.ts +394 -0
- package/assets/plugins/ostacky-controller/tiered.ts +29 -0
- package/dist/cli.js +446 -141
- package/dist/mcp/openspec/index.js +19335 -0
- package/dist/mcp/openspec/package.json +1 -0
- package/dist/mcp/ostacky-controller/index.js +23662 -0
- package/dist/mcp/ostacky-controller/package.json +1 -0
- package/manifest.json +31 -29
- package/package.json +9 -6
|
@@ -28,6 +28,9 @@ import {
|
|
|
28
28
|
import { dirname, basename, join, resolve, relative } from 'node:path';
|
|
29
29
|
import { writeFile as writeFileAsync, rename as renameAsync, mkdir as mkdirAsync } from 'node:fs/promises';
|
|
30
30
|
import { SENSITIVE_DEFAULT, BASH_SENSITIVE_RE, isSensitive, extractPathsFromBash } from './security.js';
|
|
31
|
+
import { bindSession, checkBinding, recordRequestSummary, noteFileEdit, handoffFallbackPath, isHandoffFallbackFile } from './session-store.js';
|
|
32
|
+
import { parsePoolConfig, isActiveSlot, parseSessionListTitle } from './session-slots.js';
|
|
33
|
+
import { execFileSync } from 'node:child_process';
|
|
31
34
|
import {
|
|
32
35
|
STATES,
|
|
33
36
|
TRANSITIONS,
|
|
@@ -40,6 +43,8 @@ import {
|
|
|
40
43
|
MAX_STATE_FILE_SIZE,
|
|
41
44
|
DEGRADED_THRESHOLD,
|
|
42
45
|
getMaxTasks,
|
|
46
|
+
normalizeTestCommand,
|
|
47
|
+
isMaskedExitCommand,
|
|
43
48
|
} from './controller-core.js';
|
|
44
49
|
|
|
45
50
|
// --- approved-but-blocked recovery (sin timers) ---
|
|
@@ -49,6 +54,11 @@ import {
|
|
|
49
54
|
// y al umbral habilita recovery (refresh_decision) sin ejecutar nada por sí mismo.
|
|
50
55
|
const CONSUME_FAIL_THRESHOLD = 3;
|
|
51
56
|
|
|
57
|
+
// Ownership con heartbeat: un dueño sin latido por más de esto se considera
|
|
58
|
+
// muerto (TUI cerrada, proceso kill) y la sesión nueva puede reclamar la
|
|
59
|
+
// request sin pedirle takeover al usuario. 15 min cubre tools largas.
|
|
60
|
+
const OWNER_STALE_MS = 15 * 60 * 1000;
|
|
61
|
+
|
|
52
62
|
// --- Audit JSONL (D5) — single source: src/audit-jsonl.ts ---
|
|
53
63
|
function getAuditPath(projectRoot) {
|
|
54
64
|
return join(projectRoot, '.opencode', 'ostacky-audit.jsonl');
|
|
@@ -120,6 +130,39 @@ function readAuditJsonl(projectRoot, opts = {}) {
|
|
|
120
130
|
// T1: non-blocking wait — replaces busy-wait spins that froze the event loop
|
|
121
131
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
122
132
|
|
|
133
|
+
function isPidAlive(pid) {
|
|
134
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
135
|
+
try {
|
|
136
|
+
process.kill(pid, 0);
|
|
137
|
+
return true;
|
|
138
|
+
} catch {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Pid dueño del lock, o null si el archivo no existe / está corrupto. */
|
|
144
|
+
function readLockPid(pidPath) {
|
|
145
|
+
try {
|
|
146
|
+
const pid = parseInt(readFileSync(pidPath, 'utf8').trim(), 10);
|
|
147
|
+
return Number.isNaN(pid) ? null : pid;
|
|
148
|
+
} catch {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Antigüedad del archivo de pid. Un lock sin timestamp recién escrito es una
|
|
155
|
+
* adquisición en curso (el dueño escribe el timestamp inmediatamente después);
|
|
156
|
+
* si ya pasó el grace, es basura de un crash.
|
|
157
|
+
*/
|
|
158
|
+
function lockPidAgeMs(pidPath) {
|
|
159
|
+
try {
|
|
160
|
+
return Date.now() - statSync(pidPath).mtimeMs;
|
|
161
|
+
} catch {
|
|
162
|
+
return Number.POSITIVE_INFINITY;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
123
166
|
function getProjectRoot(statePath) {
|
|
124
167
|
if (!statePath) return resolve(process.cwd());
|
|
125
168
|
return dirname(dirname(resolve(statePath)));
|
|
@@ -238,27 +281,46 @@ export function parseTaskVerifications(changeId, statePath) {
|
|
|
238
281
|
*
|
|
239
282
|
* NO usa `status`: el shell tool de OpenCode reporta "completed" incluso con
|
|
240
283
|
* exit != 0 (medido: `sh -c 'exit 3'` -> status "completed", metadata.exit 3).
|
|
241
|
-
* El plugin registra {cmd, exit, ts} por cada
|
|
242
|
-
*
|
|
284
|
+
* El plugin registra {cmd, exit, ts} por cada corrida que matchea un test:
|
|
285
|
+
* declarado; acá se compara la forma normalizada (cd/2>&1), se exige exit 0
|
|
286
|
+
* y posterior a la última mutación, y se rechaza cualquier exit enmascarado
|
|
287
|
+
* por un pipe a tail/head/grep.
|
|
243
288
|
*/
|
|
244
289
|
export function findTestEvidence({ runs, cmd, lastMutationTs, now = Date.now() } = {}) {
|
|
245
|
-
const
|
|
246
|
-
if (!
|
|
290
|
+
const declared = String(cmd || '').trim();
|
|
291
|
+
if (!declared) return { ok: false, reason: 'test: sin comando' };
|
|
292
|
+
const expected = normalizeTestCommand(declared);
|
|
293
|
+
if (!expected) return { ok: false, reason: `test: comando no verificable: "${declared}"` };
|
|
247
294
|
if (!Array.isArray(runs) || runs.length === 0)
|
|
248
|
-
return { ok: false, reason:
|
|
249
|
-
const matches = runs.filter((r) => r &&
|
|
250
|
-
if (matches.length === 0)
|
|
295
|
+
return { ok: false, reason: `sin evidencia para "${declared}": el plugin no registró ninguna corrida de shell que matchee ese comando` };
|
|
296
|
+
const matches = runs.filter((r) => r && normalizeTestCommand(r.cmd) === expected);
|
|
297
|
+
if (matches.length === 0) {
|
|
298
|
+
const recent = runs
|
|
299
|
+
.filter((r) => r && typeof r.cmd === 'string' && r.cmd.trim())
|
|
300
|
+
.sort((a, b) => (Number(b.ts) || 0) - (Number(a.ts) || 0));
|
|
301
|
+
const similar = recent.find((r) => r.cmd.includes(declared)) || recent[0] || null;
|
|
302
|
+
return {
|
|
303
|
+
ok: false,
|
|
304
|
+
reason: `nunca se ejecutó exactamente "${declared}"${similar ? `. La corrida más parecida fue "${similar.cmd}"` : ''}`,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
251
307
|
const last = matches.reduce((a, b) => ((Number(b.ts) || 0) >= (Number(a.ts) || 0) ? b : a));
|
|
308
|
+
if (last.maskedExit === true || isMaskedExitCommand(last.cmd))
|
|
309
|
+
return {
|
|
310
|
+
ok: false,
|
|
311
|
+
reason: `exit enmascarado: "${last.cmd}" usa un pipe a tail/head/grep; corré sin pipe o con "set -o pipefail"`,
|
|
312
|
+
run: last,
|
|
313
|
+
};
|
|
252
314
|
if (typeof last.ts !== 'number' || typeof lastMutationTs !== 'number')
|
|
253
315
|
return {
|
|
254
316
|
ok: false,
|
|
255
|
-
reason: `sin timestamps: no se puede probar que "${
|
|
317
|
+
reason: `sin timestamps: no se puede probar que "${declared}" sea posterior a la última edición`,
|
|
256
318
|
run: last,
|
|
257
319
|
};
|
|
258
320
|
if (last.ts <= lastMutationTs)
|
|
259
|
-
return { ok: false, reason: `la última corrida de "${
|
|
321
|
+
return { ok: false, reason: `la última corrida de "${declared}" es anterior a la última edición`, run: last };
|
|
260
322
|
if (last.exit !== 0)
|
|
261
|
-
return { ok: false, reason: `la última corrida de "${
|
|
323
|
+
return { ok: false, reason: `la última corrida de "${declared}" salió con exit ${last.exit}`, run: last };
|
|
262
324
|
return { ok: true, reason: `exit 0 hace ${Math.max(0, Math.round((now - last.ts) / 1000))}s`, run: last };
|
|
263
325
|
}
|
|
264
326
|
|
|
@@ -394,8 +456,9 @@ function cleanupTmpFiles(statePath) {
|
|
|
394
456
|
for (const entry of readdirSync(dir)) {
|
|
395
457
|
const isTmp = entry.startsWith(name + '.tmp.');
|
|
396
458
|
const isLock = entry.startsWith(name + '.lock');
|
|
397
|
-
const isHandoff = entry
|
|
398
|
-
|
|
459
|
+
const isHandoff = isHandoffFallbackFile(entry);
|
|
460
|
+
const isHandoffTmp = entry.startsWith('.ostacky-handoff-compaction') && entry.includes('.json.tmp.');
|
|
461
|
+
if (!isTmp && !isLock && !isHandoff && !isHandoffTmp) continue;
|
|
399
462
|
// C3: don't delete active lock of another process
|
|
400
463
|
if (isLock) {
|
|
401
464
|
try {
|
|
@@ -410,6 +473,12 @@ function cleanupTmpFiles(statePath) {
|
|
|
410
473
|
try {
|
|
411
474
|
lockTs = parseInt(readFileSync(tsPath, 'utf8').trim(), 10);
|
|
412
475
|
} catch {}
|
|
476
|
+
if (lockPid && String(lockPid) !== String(process.pid) && isPidAlive(parseInt(lockPid, 10))) {
|
|
477
|
+
// Dueño vivo = lock activo, haya o no timestamp. Antes un
|
|
478
|
+
// lock sin timestamp se borraba igual y se robaba el lock
|
|
479
|
+
// de un proceso que estaba escribiendo.
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
413
482
|
if (lockPid && lockTs && !Number.isNaN(lockTs)) {
|
|
414
483
|
const age = Date.now() - lockTs;
|
|
415
484
|
if (age < staleWindow && String(lockPid) !== String(process.pid)) {
|
|
@@ -480,12 +549,16 @@ class OstackyController {
|
|
|
480
549
|
#lockOwner = false;
|
|
481
550
|
#lockDepth = 0; // multi-sesión: reentrancy (el lock se toma una vez por tool call)
|
|
482
551
|
#callerSessionId = null; // sessionId del caller (de _meta), solo en memoria
|
|
552
|
+
#opencodeDir = null; // .opencode del proyecto (ancla fija del handoff, no cambia con el slot)
|
|
483
553
|
#loadedSnapshot = null; // huella del estado recién leído, para detectar "dirty"
|
|
484
554
|
#persistQueue = Promise.resolve(); // cola in-process: las escrituras nunca se solapan
|
|
485
555
|
#persistSeq = 0; // sufijo único por escritura (tmp.<pid>.<seq>)
|
|
556
|
+
#fileEditObserver = null;
|
|
557
|
+
#notices = [];
|
|
486
558
|
|
|
487
559
|
constructor(opts = {}) {
|
|
488
560
|
this.#statePath = opts.statePath;
|
|
561
|
+
this.#opencodeDir = opts.statePath ? dirname(opts.statePath) : null;
|
|
489
562
|
this.#lockPath = opts.statePath ? opts.statePath + '.lock' : null;
|
|
490
563
|
this.#lockPidPath = opts.statePath ? opts.statePath + '.lock.pid' : null;
|
|
491
564
|
this.#lockHeartbeatPath = opts.statePath ? opts.statePath + '.lock.timestamp' : null;
|
|
@@ -567,6 +640,58 @@ class OstackyController {
|
|
|
567
640
|
return true;
|
|
568
641
|
}
|
|
569
642
|
|
|
643
|
+
/**
|
|
644
|
+
* Apunta el controller al state file de un slot (session-state-files). Descarta el estado
|
|
645
|
+
* en memoria: el próximo load lee el slot. Solo lo llama bindCallerSlot antes de cada tool call.
|
|
646
|
+
*/
|
|
647
|
+
rebindStatePath(newPath) {
|
|
648
|
+
if (newPath === this.#statePath) return;
|
|
649
|
+
this.#statePath = newPath;
|
|
650
|
+
this.#lockPath = newPath + '.lock';
|
|
651
|
+
this.#lockPidPath = newPath + '.lock.pid';
|
|
652
|
+
this.#lockHeartbeatPath = newPath + '.lock.timestamp';
|
|
653
|
+
this.#state = null;
|
|
654
|
+
this.#loaded = false;
|
|
655
|
+
this.#loadedSnapshot = null;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
get statePathValue() {
|
|
659
|
+
return this.#statePath;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Resumen de la request (para listar candidatas al usuario en el índice de sesiones). */
|
|
663
|
+
stateSummary() {
|
|
664
|
+
this.#load();
|
|
665
|
+
return {
|
|
666
|
+
requestId: this.#state?.requestId ?? null,
|
|
667
|
+
changeId: this.#state?.changeId ?? null,
|
|
668
|
+
state: this.#state?.state ?? null,
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/** Observador de ediciones por archivo (aviso concurrent_edit); lo fija el entry point. */
|
|
673
|
+
setFileEditObserver(fn) {
|
|
674
|
+
this.#fileEditObserver = typeof fn === 'function' ? fn : null;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
#observeFileEdit(filePath) {
|
|
678
|
+
if (!filePath || !this.#fileEditObserver) return;
|
|
679
|
+
try {
|
|
680
|
+
this.#fileEditObserver(filePath);
|
|
681
|
+
} catch {}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** Avisos no bloqueantes acumulados durante la llamada actual. */
|
|
685
|
+
pushNotice(message) {
|
|
686
|
+
this.#notices.push(message);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
takeNotices() {
|
|
690
|
+
const out = this.#notices;
|
|
691
|
+
this.#notices = [];
|
|
692
|
+
return out;
|
|
693
|
+
}
|
|
694
|
+
|
|
570
695
|
/** Registra el sessionId del caller actual (de `_meta["ai.opencode/sessionID"]`). */
|
|
571
696
|
setCallerSession(sessionId) {
|
|
572
697
|
this.#callerSessionId = typeof sessionId === 'string' && sessionId ? sessionId : null;
|
|
@@ -617,33 +742,48 @@ class OstackyController {
|
|
|
617
742
|
const maxAttempts = this.#lockMaxAttempts;
|
|
618
743
|
const lockTimeout = 1000;
|
|
619
744
|
const staleWindow = 15000;
|
|
745
|
+
const orphanGraceMs = 1000;
|
|
620
746
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
621
747
|
try {
|
|
622
|
-
// Check existing lock BEFORE overwriting — corrects mutual-exclusion bug
|
|
748
|
+
// Check existing lock BEFORE overwriting — corrects mutual-exclusion bug.
|
|
749
|
+
// Sin heartbeat legible el lock es huérfano (proceso muerto entre el
|
|
750
|
+
// write del pid y el del timestamp) o una adquisición en curso. Antes
|
|
751
|
+
// se seguía derecho al `wx`, que fallaba con EEXIST para siempre: el
|
|
752
|
+
// controlador no podía persistir NINGUNA decisión y el consume se
|
|
753
|
+
// perdía (el agente volvía a preguntar ruta/ejecución en loop).
|
|
754
|
+
let lockAge = NaN;
|
|
623
755
|
try {
|
|
624
|
-
|
|
625
|
-
const lockAge = Date.now() - parseInt(lockContent, 10);
|
|
626
|
-
if (!Number.isNaN(lockAge) && lockAge < staleWindow) {
|
|
627
|
-
const base = Math.min(lockTimeout, 100 * Math.pow(2, attempt));
|
|
628
|
-
const jitter = Math.floor(Math.random() * 200) - 100;
|
|
629
|
-
const waitMs = Math.max(0, base + jitter);
|
|
630
|
-
if (waitMs > 0) await sleep(waitMs);
|
|
631
|
-
continue;
|
|
632
|
-
}
|
|
633
|
-
if (!Number.isNaN(lockAge) && lockAge >= staleWindow) {
|
|
634
|
-
try {
|
|
635
|
-
const lockPid = readFileSync(this.#lockPidPath, 'utf8').trim();
|
|
636
|
-
try {
|
|
637
|
-
process.kill(parseInt(lockPid, 10), 0);
|
|
638
|
-
// PID alive but stale beyond window — force release
|
|
639
|
-
} catch {
|
|
640
|
-
// PID dead — force release
|
|
641
|
-
}
|
|
642
|
-
} catch {}
|
|
643
|
-
this.#releaseLock();
|
|
644
|
-
}
|
|
756
|
+
lockAge = Date.now() - parseInt(readFileSync(this.#lockHeartbeatPath, 'utf8'), 10);
|
|
645
757
|
} catch {
|
|
646
|
-
//
|
|
758
|
+
// sin timestamp
|
|
759
|
+
}
|
|
760
|
+
if (!Number.isNaN(lockAge) && lockAge < staleWindow) {
|
|
761
|
+
const base = Math.min(lockTimeout, 100 * Math.pow(2, attempt));
|
|
762
|
+
const jitter = Math.floor(Math.random() * 200) - 100;
|
|
763
|
+
const waitMs = Math.max(0, base + jitter);
|
|
764
|
+
if (waitMs > 0) await sleep(waitMs);
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
if (!Number.isNaN(lockAge) && lockAge >= staleWindow) {
|
|
768
|
+
// Stale: liberar SOLO si el dueño ya no existe. Un dueño vivo
|
|
769
|
+
// con heartbeat viejo puede estar en una operación larga:
|
|
770
|
+
// robarle el lock haría que su write se pierda. (`#releaseLock`
|
|
771
|
+
// no sirve acá: verifica ownership y no toca el lock ajeno, así
|
|
772
|
+
// que este camino era un no-op y el lock quedaba pegado.)
|
|
773
|
+
const ownerPid = readLockPid(this.#lockPidPath);
|
|
774
|
+
if (ownerPid === null || !isPidAlive(ownerPid)) this.#forceReleaseLock();
|
|
775
|
+
} else if (Number.isNaN(lockAge)) {
|
|
776
|
+
const ownerPid = readLockPid(this.#lockPidPath);
|
|
777
|
+
// pid ausente, dueño muerto, o pid viejo sin timestamp (crash
|
|
778
|
+
// entre los dos writes) → basura: liberar. Un pid recién
|
|
779
|
+
// escrito es una adquisición en curso: esperar.
|
|
780
|
+
if (
|
|
781
|
+
ownerPid === null ||
|
|
782
|
+
!isPidAlive(ownerPid) ||
|
|
783
|
+
lockPidAgeMs(this.#lockPidPath) > orphanGraceMs
|
|
784
|
+
) {
|
|
785
|
+
this.#forceReleaseLock();
|
|
786
|
+
}
|
|
647
787
|
}
|
|
648
788
|
// Atomic acquire with wx — fails if another process won the race
|
|
649
789
|
try {
|
|
@@ -705,6 +845,25 @@ class OstackyController {
|
|
|
705
845
|
this.#lockOwner = false;
|
|
706
846
|
}
|
|
707
847
|
|
|
848
|
+
/**
|
|
849
|
+
* Libera un lock que NO es nuestro (huérfano o stale). `#releaseLock` se
|
|
850
|
+
* niega por diseño a tocar el lock de otro proceso, así que el "force
|
|
851
|
+
* release" viejo era un no-op y un lock de un proceso muerto quedaba
|
|
852
|
+
* pegado para siempre (todas las escrituras fallaban con lock timeout).
|
|
853
|
+
*/
|
|
854
|
+
#forceReleaseLock() {
|
|
855
|
+
try {
|
|
856
|
+
unlinkSync(this.#lockPidPath);
|
|
857
|
+
} catch {
|
|
858
|
+
/* best-effort */
|
|
859
|
+
}
|
|
860
|
+
try {
|
|
861
|
+
unlinkSync(this.#lockHeartbeatPath);
|
|
862
|
+
} catch {
|
|
863
|
+
/* best-effort */
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
708
867
|
#heartbeatLock() {
|
|
709
868
|
if (!this.#lockHeartbeatPath) return;
|
|
710
869
|
try {
|
|
@@ -1262,6 +1421,8 @@ class OstackyController {
|
|
|
1262
1421
|
|
|
1263
1422
|
const caller = this.#callerSessionId;
|
|
1264
1423
|
const owner = this.#state.ownerSessionId;
|
|
1424
|
+
const ownerHeartbeat = this.#state.ownerHeartbeat ?? 0;
|
|
1425
|
+
const ownerStale = !ownerHeartbeat || Date.now() - ownerHeartbeat > OWNER_STALE_MS;
|
|
1265
1426
|
// OJO: `INTERPRETATION_PENDING` está en TERMINAL_STATES — es "terminal" para
|
|
1266
1427
|
// decidir si se RESUME, pero NO significa que no haya trabajo. Por eso separamos:
|
|
1267
1428
|
// - resumeEligible: semántica ORIGINAL de start_request (no la tocamos).
|
|
@@ -1272,7 +1433,8 @@ class OstackyController {
|
|
|
1272
1433
|
this.#state.state !== STATES.DONE &&
|
|
1273
1434
|
!!owner &&
|
|
1274
1435
|
!!caller &&
|
|
1275
|
-
owner !== caller
|
|
1436
|
+
owner !== caller &&
|
|
1437
|
+
!ownerStale;
|
|
1276
1438
|
|
|
1277
1439
|
// ── Guard de ownership (multi-sesión) ──
|
|
1278
1440
|
// Si hay una request viva de OTRA sesión y no se fuerza, NO pisamos nada:
|
|
@@ -1297,6 +1459,23 @@ class OstackyController {
|
|
|
1297
1459
|
};
|
|
1298
1460
|
}
|
|
1299
1461
|
|
|
1462
|
+
// Takeover automático de un dueño muerto (sin `force`): la request no se
|
|
1463
|
+
// pierde, solo cambia de manos. Queda auditado para poder rastrearlo.
|
|
1464
|
+
const staleTakeover =
|
|
1465
|
+
!!owner &&
|
|
1466
|
+
!!caller &&
|
|
1467
|
+
owner !== caller &&
|
|
1468
|
+
ownerStale &&
|
|
1469
|
+
this.#state.state !== STATES.DONE &&
|
|
1470
|
+
!!this.#state.requestId;
|
|
1471
|
+
if (staleTakeover) {
|
|
1472
|
+
await this.#audit(
|
|
1473
|
+
this.#state.state,
|
|
1474
|
+
'session_takeover_stale',
|
|
1475
|
+
`from=${owner} to=${caller} heartbeatAgeMs=${Date.now() - ownerHeartbeat} requestId=${this.#state.requestId}`
|
|
1476
|
+
);
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1300
1479
|
// If not forcing and current state is active (not terminal), resume instead of reset
|
|
1301
1480
|
if (!force && resumeEligible) {
|
|
1302
1481
|
// Reclamamos ownership si no había dueño o si cambió (sesión única / reconexión).
|
|
@@ -2066,15 +2245,19 @@ class OstackyController {
|
|
|
2066
2245
|
const task = this.#state.tasks[tid];
|
|
2067
2246
|
if (!task || task.status !== 'COMPLETED') continue;
|
|
2068
2247
|
let needle = String(verif).trim();
|
|
2248
|
+
let declaredPath = null;
|
|
2069
2249
|
if (needle.startsWith('codegraph:')) needle = needle.slice('codegraph:'.length).trim();
|
|
2070
2250
|
else if (needle.startsWith('file:')) {
|
|
2071
2251
|
const rest = needle.slice('file:'.length).trim();
|
|
2072
2252
|
const parts = rest.split('contiene');
|
|
2253
|
+
declaredPath = (parts[0] || '').trim() || null;
|
|
2073
2254
|
needle = (parts[1] || parts[0] || '').trim() || rest;
|
|
2074
2255
|
} else if (needle.startsWith('test:')) continue;
|
|
2075
2256
|
if (!needle) continue;
|
|
2076
2257
|
let content = null;
|
|
2077
|
-
|
|
2258
|
+
// El path de la verificación es la fuente: `task.filePath` puede no
|
|
2259
|
+
// existir (tasks completadas sin archivo declarado).
|
|
2260
|
+
const fp = task.filePath || declaredPath;
|
|
2078
2261
|
if (fp) {
|
|
2079
2262
|
try {
|
|
2080
2263
|
const abs =
|
|
@@ -2366,10 +2549,12 @@ class OstackyController {
|
|
|
2366
2549
|
if (!task || task.status !== 'COMPLETED') continue;
|
|
2367
2550
|
// Re-verificar via file content
|
|
2368
2551
|
let needle = String(verif).trim();
|
|
2552
|
+
let declaredPath = null;
|
|
2369
2553
|
if (needle.startsWith('codegraph:')) needle = needle.slice('codegraph:'.length).trim();
|
|
2370
2554
|
else if (needle.startsWith('file:')) {
|
|
2371
2555
|
const rest = needle.slice('file:'.length).trim();
|
|
2372
2556
|
const parts = rest.split('contiene');
|
|
2557
|
+
declaredPath = (parts[0] || '').trim() || null;
|
|
2373
2558
|
needle = (parts[1] || parts[0] || '').trim() || rest;
|
|
2374
2559
|
} else if (needle.startsWith('test:')) {
|
|
2375
2560
|
// test-verification-execution: cierre re-verifica evidencia; antes se salteaba.
|
|
@@ -2384,7 +2569,9 @@ class OstackyController {
|
|
|
2384
2569
|
}
|
|
2385
2570
|
if (!needle) continue;
|
|
2386
2571
|
let content = null;
|
|
2387
|
-
|
|
2572
|
+
// El path de la verificación es la fuente: `task.filePath` puede no
|
|
2573
|
+
// existir (tasks completadas sin archivo declarado).
|
|
2574
|
+
const fp = task.filePath || declaredPath;
|
|
2388
2575
|
if (fp) {
|
|
2389
2576
|
try {
|
|
2390
2577
|
const abs =
|
|
@@ -2635,7 +2822,7 @@ class OstackyController {
|
|
|
2635
2822
|
// C3: fallback to compaction file — same anchor as writer (dirname(statePath))
|
|
2636
2823
|
if (!this.#statePath) return null;
|
|
2637
2824
|
try {
|
|
2638
|
-
const fallbackPath =
|
|
2825
|
+
const fallbackPath = handoffFallbackPath(this.#opencodeDir, this.#callerSessionId);
|
|
2639
2826
|
const raw = readFileSync(fallbackPath, 'utf8');
|
|
2640
2827
|
const data = JSON.parse(raw);
|
|
2641
2828
|
if (data && typeof data.summary === 'string') return data;
|
|
@@ -2650,7 +2837,7 @@ class OstackyController {
|
|
|
2650
2837
|
// C3: also delete fallback compaction file (same anchor)
|
|
2651
2838
|
if (this.#statePath) {
|
|
2652
2839
|
try {
|
|
2653
|
-
unlinkSync(
|
|
2840
|
+
unlinkSync(handoffFallbackPath(this.#opencodeDir, this.#callerSessionId));
|
|
2654
2841
|
} catch {}
|
|
2655
2842
|
}
|
|
2656
2843
|
await this.#audit('HANDOFF', 'clear_handoff', prev?.summary?.slice(0, 100) || 'none');
|
|
@@ -2679,11 +2866,34 @@ class OstackyController {
|
|
|
2679
2866
|
}
|
|
2680
2867
|
|
|
2681
2868
|
// --- fix-new-file-gate: ligadura validate → complete por filePath (mapa + fallback legacy) ---
|
|
2869
|
+
/**
|
|
2870
|
+
* Clave canónica de `lastValidated`. El plugin escribe paths absolutos y el
|
|
2871
|
+
* agente manda el path relativo (o al revés); comparar por string exacto
|
|
2872
|
+
* hacía que un validate reciente se viera ausente ("validate required").
|
|
2873
|
+
*/
|
|
2874
|
+
_validatedKey(filePath) {
|
|
2875
|
+
if (!filePath) return null;
|
|
2876
|
+
try {
|
|
2877
|
+
const abs =
|
|
2878
|
+
filePath.startsWith('/') || /^[A-Za-z]:/.test(filePath)
|
|
2879
|
+
? resolve(filePath)
|
|
2880
|
+
: resolve(getProjectRoot(this.#statePath), filePath);
|
|
2881
|
+
return process.platform === 'win32' ? abs.toLowerCase() : abs;
|
|
2882
|
+
} catch {
|
|
2883
|
+
return filePath;
|
|
2884
|
+
}
|
|
2885
|
+
}
|
|
2682
2886
|
_getValidatedFor(filePath) {
|
|
2683
2887
|
const lv = this.#state.lastValidated;
|
|
2684
2888
|
if (!lv || !filePath) return null;
|
|
2685
|
-
|
|
2686
|
-
if (lv.
|
|
2889
|
+
const key = this._validatedKey(filePath);
|
|
2890
|
+
if (lv.byFile && typeof lv.byFile === 'object') {
|
|
2891
|
+
if (lv.byFile[filePath]) return lv.byFile[filePath];
|
|
2892
|
+
for (const [k, v] of Object.entries(lv.byFile)) {
|
|
2893
|
+
if (this._validatedKey(k) === key) return v;
|
|
2894
|
+
}
|
|
2895
|
+
}
|
|
2896
|
+
if (lv.filePath && this._validatedKey(lv.filePath) === key) return lv; // fallback slot legacy (single)
|
|
2687
2897
|
return null;
|
|
2688
2898
|
}
|
|
2689
2899
|
async _setValidatedFor(filePath, hash, mode) {
|
|
@@ -2711,7 +2921,12 @@ class OstackyController {
|
|
|
2711
2921
|
async _clearValidatedFor(filePath) {
|
|
2712
2922
|
const lv = this.#state.lastValidated;
|
|
2713
2923
|
if (lv && lv.byFile && typeof lv.byFile === 'object') {
|
|
2714
|
-
if (filePath
|
|
2924
|
+
if (filePath) {
|
|
2925
|
+
const key = this._validatedKey(filePath);
|
|
2926
|
+
for (const k of Object.keys(lv.byFile)) {
|
|
2927
|
+
if (k === filePath || this._validatedKey(k) === key) delete lv.byFile[k];
|
|
2928
|
+
}
|
|
2929
|
+
}
|
|
2715
2930
|
if (Object.keys(lv.byFile).length === 0) this.#state.lastValidated = null;
|
|
2716
2931
|
else this.#state.lastValidated = { byFile: lv.byFile, filePath: null, hash: null, ts: Date.now() };
|
|
2717
2932
|
} else {
|
|
@@ -2722,6 +2937,7 @@ class OstackyController {
|
|
|
2722
2937
|
// --- O6: Validate edit with fast fingerprint + D6/D4 hard gate + 10.4 freshness ---
|
|
2723
2938
|
async validateEdit({ oldString, newString, content, taskId, filePath } = {}) {
|
|
2724
2939
|
this.#load();
|
|
2940
|
+
this.#observeFileEdit(filePath);
|
|
2725
2941
|
if (this.#state.state !== 'EXECUTING_INLINE' && this.#state.state !== 'EXECUTING_SUBAGENTS') {
|
|
2726
2942
|
return { outcome: 'CONFLICT', reason: `Cannot validate edit from state ${this.#state.state}` };
|
|
2727
2943
|
}
|
|
@@ -2887,6 +3103,7 @@ class OstackyController {
|
|
|
2887
3103
|
*/
|
|
2888
3104
|
async completeTask({ taskId, filePath, fileHash } = {}) {
|
|
2889
3105
|
this.#load();
|
|
3106
|
+
this.#observeFileEdit(filePath);
|
|
2890
3107
|
const denied = await this.#foreignOwnerError('complete_task');
|
|
2891
3108
|
if (denied) return denied;
|
|
2892
3109
|
if (this.#state.state !== 'EXECUTING_INLINE' && this.#state.state !== 'EXECUTING_SUBAGENTS') {
|
|
@@ -3122,7 +3339,14 @@ class OstackyController {
|
|
|
3122
3339
|
// Copia plana, NO la referencia de shellRuns: el serializador seguro
|
|
3123
3340
|
// marca referencias repetidas como "[Circular]" y corrompería la
|
|
3124
3341
|
// evidencia persistida (bug detectado por el test de integración).
|
|
3125
|
-
run: ev.run
|
|
3342
|
+
run: ev.run
|
|
3343
|
+
? {
|
|
3344
|
+
cmd: ev.run.cmd,
|
|
3345
|
+
exit: ev.run.exit,
|
|
3346
|
+
ts: ev.run.ts,
|
|
3347
|
+
...(ev.run.maskedExit ? { maskedExit: true } : {}),
|
|
3348
|
+
}
|
|
3349
|
+
: null,
|
|
3126
3350
|
ts: Date.now(),
|
|
3127
3351
|
};
|
|
3128
3352
|
await this.#persist();
|
|
@@ -3237,6 +3461,19 @@ class OstackyController {
|
|
|
3237
3461
|
|
|
3238
3462
|
const statePath = resolve(process.env.OSTACKY_STATE_PATH || join(process.cwd(), '.opencode', 'ostacky-state.json'));
|
|
3239
3463
|
const controller = new OstackyController({ statePath });
|
|
3464
|
+
controller.setFileEditObserver((filePath) => {
|
|
3465
|
+
if (process.env.OSTACKY_SESSION_SLOTS === 'off') return;
|
|
3466
|
+
const sid = controller.callerSessionId;
|
|
3467
|
+
if (!sid) return;
|
|
3468
|
+
const minutes = Number(process.env.OSTACKY_CONCURRENT_EDIT_WINDOW_MIN);
|
|
3469
|
+
const windowMs = (Number.isFinite(minutes) && minutes > 0 ? minutes : 30) * 60_000;
|
|
3470
|
+
const warnings = noteFileEdit(dirname(statePath), sid, filePath, Date.now(), windowMs);
|
|
3471
|
+
for (const w of warnings) {
|
|
3472
|
+
controller.pushNotice(
|
|
3473
|
+
`WARN concurrent_edit: ${w.file} lo editó hace ${w.minutesAgo} min "${w.otherName}" (request ${w.otherRequestId ?? 'sin request'}). No bloquea: coordiná antes de seguir.`
|
|
3474
|
+
);
|
|
3475
|
+
}
|
|
3476
|
+
});
|
|
3240
3477
|
|
|
3241
3478
|
/**
|
|
3242
3479
|
* Wraps an async tool handler to ALWAYS return a response (even on error).
|
|
@@ -3270,19 +3507,122 @@ function extractCallerSessionId(ctx) {
|
|
|
3270
3507
|
return null;
|
|
3271
3508
|
}
|
|
3272
3509
|
|
|
3510
|
+
/**
|
|
3511
|
+
* Título visible de una sesión. OpenCode no lo manda en _meta (solo ai.opencode/sessionID),
|
|
3512
|
+
* así que se consulta con `opencode session list --format json`. Éxitos se cachean por proceso;
|
|
3513
|
+
* fallos se reintentan tras 60 s para no lanzar un subproceso en cada tool call.
|
|
3514
|
+
*/
|
|
3515
|
+
const sessionTitleCache = new Map(); // sid -> { title, at }
|
|
3516
|
+
const SESSION_TITLE_MISS_TTL_MS = 60_000;
|
|
3517
|
+
function sessionTitleFor(sid) {
|
|
3518
|
+
if (!sid) return null;
|
|
3519
|
+
const hit = sessionTitleCache.get(sid);
|
|
3520
|
+
if (hit && (hit.title || Date.now() - hit.at < SESSION_TITLE_MISS_TTL_MS)) return hit.title;
|
|
3521
|
+
let title = null;
|
|
3522
|
+
try {
|
|
3523
|
+
const out = execFileSync('opencode', ['session', 'list', '--format', 'json', '-n', '200'], {
|
|
3524
|
+
encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'],
|
|
3525
|
+
});
|
|
3526
|
+
title = parseSessionListTitle(out, sid);
|
|
3527
|
+
} catch {}
|
|
3528
|
+
sessionTitleCache.set(sid, { title, at: Date.now() });
|
|
3529
|
+
return title;
|
|
3530
|
+
}
|
|
3531
|
+
|
|
3532
|
+
/** Nombre a mostrar: título de la sesión, o changeId/requestId si no hay título. */
|
|
3533
|
+
function displayNameOf(c) {
|
|
3534
|
+
return c.sessionName || c.changeId || c.requestId || 'sesión sin nombre';
|
|
3535
|
+
}
|
|
3536
|
+
|
|
3537
|
+
/**
|
|
3538
|
+
* Asigna/valida el slot de la sesión del caller antes de cada tool call (session-state-files).
|
|
3539
|
+
* Devuelve { block } si la tool no debe ejecutarse (pregunta al usuario o sesión sustituida),
|
|
3540
|
+
* y { notice } con avisos de capacidad para adjuntar a la respuesta.
|
|
3541
|
+
* Sin identidad de caller (clientes legacy) o con OSTACKY_SESSION_SLOTS=off: no aplica.
|
|
3542
|
+
*/
|
|
3543
|
+
function bindCallerSlot(params, ctx) {
|
|
3544
|
+
if (process.env.OSTACKY_SESSION_SLOTS === 'off') return { block: null, notice: [] };
|
|
3545
|
+
const sid = controller.callerSessionId;
|
|
3546
|
+
if (!sid) return { block: null, notice: [] };
|
|
3547
|
+
const cfg = parsePoolConfig(process.env);
|
|
3548
|
+
const opencodeDir = dirname(statePath);
|
|
3549
|
+
const res = bindSession({
|
|
3550
|
+
opencodeDir,
|
|
3551
|
+
sessionId: sid,
|
|
3552
|
+
sessionName: sessionTitleFor(sid),
|
|
3553
|
+
now: Date.now(),
|
|
3554
|
+
cfg,
|
|
3555
|
+
legacyStatePath: statePath,
|
|
3556
|
+
replaceSlot: (params && params.replaceSlot) || null,
|
|
3557
|
+
allowOverflow: !!(params && params.allowExtension),
|
|
3558
|
+
});
|
|
3559
|
+
if (res.kind === 'blocked') return { block: { error: `BLOCKED: ${res.reason}` }, notice: [] };
|
|
3560
|
+
if (res.kind === 'ask') {
|
|
3561
|
+
const now = Date.now();
|
|
3562
|
+
return {
|
|
3563
|
+
block: {
|
|
3564
|
+
conflict: true,
|
|
3565
|
+
question: 'slot_capacity',
|
|
3566
|
+
notify: res.notify,
|
|
3567
|
+
message:
|
|
3568
|
+
'Pregunta al usuario antes de continuar: confirmar sustitución (replaceSlot), confirmar extensión del pool (allowExtension) o esperar a que termine una sesión activa. No cambies nada sin respuesta.',
|
|
3569
|
+
candidates: res.candidates.map((c) => ({
|
|
3570
|
+
slot: c.slot,
|
|
3571
|
+
name: displayNameOf(c),
|
|
3572
|
+
changeId: c.changeId ?? null,
|
|
3573
|
+
state: c.state ?? null,
|
|
3574
|
+
active: isActiveSlot(c, now, cfg),
|
|
3575
|
+
lastActivityMinutesAgo: Math.round((now - (c.lastUsedAt || 0)) / 60000),
|
|
3576
|
+
})),
|
|
3577
|
+
},
|
|
3578
|
+
notice: [],
|
|
3579
|
+
};
|
|
3580
|
+
}
|
|
3581
|
+
controller.rebindStatePath(res.statePath);
|
|
3582
|
+
return { block: null, notice: res.notify };
|
|
3583
|
+
}
|
|
3584
|
+
|
|
3585
|
+
// ── Cola in-process (fix-consume-race-lock) ──────────────────────────────────
|
|
3586
|
+
// Code Mode emite varias tools en paralelo DENTRO del mismo proceso MCP y
|
|
3587
|
+
// `#state` es un único objeto compartido. Un `reloadFresh()` concurrente (p.ej.
|
|
3588
|
+
// un `get_state` en el mismo batch) reemplazaba `#state` mientras otro handler
|
|
3589
|
+
// tenía una transición en vuelo: el `#persist` serializaba el snapshot viejo y
|
|
3590
|
+
// el `consume_*` se perdía. El disco quedaba en `*_PENDING` y el agente volvía
|
|
3591
|
+
// a preguntar DIRECT/SPEC e INLINE/SUBAGENT. Serializar restaura el invariante
|
|
3592
|
+
// "un read-modify-write a la vez" también in-process.
|
|
3593
|
+
let opQueue = Promise.resolve();
|
|
3594
|
+
|
|
3595
|
+
export function serializeOp(run) {
|
|
3596
|
+
const next = opQueue.then(run, run);
|
|
3597
|
+
opQueue = next.then(
|
|
3598
|
+
() => {},
|
|
3599
|
+
() => {}
|
|
3600
|
+
);
|
|
3601
|
+
return next;
|
|
3602
|
+
}
|
|
3603
|
+
|
|
3273
3604
|
function safeHandler(fn, options = {}) {
|
|
3274
3605
|
const { maxRetries = 0, baseTimeout = 5000 } = options;
|
|
3275
3606
|
|
|
3276
|
-
return
|
|
3607
|
+
return (params, ctx) => serializeOp(async () => {
|
|
3277
3608
|
// ── multi-sesión: identidad + estado fresco + lock por operación ──
|
|
3278
|
-
// 1) sessionId del caller (de `_meta`), 2)
|
|
3279
|
-
//
|
|
3280
|
-
//
|
|
3609
|
+
// 1) sessionId del caller (de `_meta`), 2) lock durante TODO el
|
|
3610
|
+
// read-modify-write, 3) re-lectura fresca DENTRO del lock: leer antes de
|
|
3611
|
+
// tomarlo dejaba una ventana donde otro proceso escribía y el persist
|
|
3612
|
+
// posterior revertía esa escritura (lost update).
|
|
3281
3613
|
let heldLock = false;
|
|
3614
|
+
let slotGate = { block: null, notice: [] };
|
|
3615
|
+
controller.takeNotices();
|
|
3282
3616
|
try {
|
|
3283
3617
|
controller.setCallerSession(extractCallerSessionId(ctx));
|
|
3284
|
-
|
|
3618
|
+
slotGate = bindCallerSlot(params, ctx);
|
|
3619
|
+
} catch (error) {
|
|
3620
|
+
return { content: [{ type: 'text', text: safeJsonStringify({ error: `BLOCKED: no se pudo asignar slot de sesión: ${String(error?.message || error)}` }) }] };
|
|
3621
|
+
}
|
|
3622
|
+
if (slotGate.block) return { content: [{ type: 'text', text: safeJsonStringify(slotGate.block) }] };
|
|
3623
|
+
try {
|
|
3285
3624
|
heldLock = await controller.beginWrite();
|
|
3625
|
+
controller.reloadFresh();
|
|
3286
3626
|
} catch {}
|
|
3287
3627
|
const endOp = () => {
|
|
3288
3628
|
if (!heldLock) return;
|
|
@@ -3311,8 +3651,18 @@ function safeHandler(fn, options = {}) {
|
|
|
3311
3651
|
} catch {}
|
|
3312
3652
|
// Update heartbeat on successful completion
|
|
3313
3653
|
controller.updateHeartbeat();
|
|
3654
|
+
// Resumen de la request en el índice compartido (lista de candidatas y avisos).
|
|
3655
|
+
const sidNow = controller.callerSessionId;
|
|
3656
|
+
if (sidNow && process.env.OSTACKY_SESSION_SLOTS !== 'off') {
|
|
3657
|
+
try {
|
|
3658
|
+
recordRequestSummary(dirname(statePath), sidNow, controller.stateSummary(), Date.now());
|
|
3659
|
+
} catch {}
|
|
3660
|
+
}
|
|
3314
3661
|
endOp();
|
|
3315
|
-
|
|
3662
|
+
const notices = controller.takeNotices();
|
|
3663
|
+
let out = slotGate.notice.length && result && typeof result === 'object' ? { ...result, slotNotice: slotGate.notice } : result;
|
|
3664
|
+
if (notices.length && out && typeof out === 'object') out = { ...out, concurrentEdit: notices };
|
|
3665
|
+
return { content: [{ type: 'text', text: safeJsonStringify(out) }] };
|
|
3316
3666
|
} catch (error) {
|
|
3317
3667
|
const isTimeout = error && error.message && error.message.includes('timeout');
|
|
3318
3668
|
const isNetworkError =
|
|
@@ -3361,12 +3711,12 @@ function safeHandler(fn, options = {}) {
|
|
|
3361
3711
|
};
|
|
3362
3712
|
}
|
|
3363
3713
|
}
|
|
3364
|
-
|
|
3714
|
+
});
|
|
3365
3715
|
}
|
|
3366
3716
|
|
|
3367
3717
|
const server = new McpServer({
|
|
3368
3718
|
name: 'ostacky-controller',
|
|
3369
|
-
version: '0.
|
|
3719
|
+
version: '0.11.0',
|
|
3370
3720
|
});
|
|
3371
3721
|
|
|
3372
3722
|
server.registerTool(
|
|
@@ -3377,6 +3727,8 @@ server.registerTool(
|
|
|
3377
3727
|
requestId: z.string().optional().describe('Unique request ID'),
|
|
3378
3728
|
changeId: z.string().optional().describe('Optional change ID for OpenSpec tracking'),
|
|
3379
3729
|
force: z.boolean().optional().describe('Force reset even if work in progress (default: false)'),
|
|
3730
|
+
replaceSlot: z.string().optional().describe('Confirmación del usuario: slot a sustituir (ej. pool-03)'),
|
|
3731
|
+
allowExtension: z.boolean().optional().describe('Confirmación del usuario: crear slot de extensión con 10 sesiones activas'),
|
|
3380
3732
|
}),
|
|
3381
3733
|
},
|
|
3382
3734
|
safeHandler(async ({ requestId, changeId, force }) => {
|
|
@@ -3968,7 +4320,7 @@ function setupGracefulShutdown(ctrl) {
|
|
|
3968
4320
|
}
|
|
3969
4321
|
|
|
3970
4322
|
async function main() {
|
|
3971
|
-
log('Starting ostacky-controller MCP v0.
|
|
4323
|
+
log('Starting ostacky-controller MCP v0.11.0...');
|
|
3972
4324
|
log('State path:', { path: statePath });
|
|
3973
4325
|
// Clean up stale tmp/lock files from previous runs
|
|
3974
4326
|
cleanupTmpFiles(statePath);
|