Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: gate sentinel recovery on validated content
Adam Eivy110fe6372a0c
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex e3932c8394..520c6ebd17 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -351,22 +351,28 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {})));if (doneSentinelPath) {- agent.doneWatcher = sentinelAccess.watch(() => {+ const handleSentinel = () => {agent.sentinelWork = lifecycle.trackWork(async () => {const current = activeAgents.get(agentId);if (!current) return;- current.completedBySentinel = true;let sentinelReadSucceeded = true;const contents = await sentinelAccess.read().catch(err => {sentinelReadSucceeded = false;console.error(`❌ TUI agent ${agentId} sentinel read failed: ${err.message}`);return '';});+ let sentinelValidated = sentinelReadSucceeded;if (sentinelReadSucceeded) {- await sentinelAccess.promote(contents).catch(err => {+ sentinelValidated = await sentinelAccess.promote(contents).catch(err => {console.error(`❌ TUI agent ${agentId} canonical sentinel promotion failed: ${err.message}`);+ return false;});}+ if (!sentinelValidated) {+ if (activeAgents.get(agentId) === current) current.doneWatcher = sentinelAccess.watch(handleSentinel);+ return;+ }+ current.completedBySentinel = true;const { summary } = parseSentinelPayload(contents);if (summary) {emitToServer('agent:output', {@@ -375,10 +381,11 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {});}if (!current.exited) current.process.kill();- if (sentinelReadSucceeded) await sentinelAccess.cleanup();+ await sentinelAccess.cleanup();});return agent.sentinelWork;- });+ };+ agent.doneWatcher = sentinelAccess.watch(handleSentinel);}await withState((state) => {diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsindex 4b48e4b045..02b2ce5b70 100644--- a/server/cos-runner/index.test.js+++ b/server/cos-runner/index.test.js@@ -119,6 +119,16 @@ describe('cos-runner termination', () => {});describe('cos-runner durable TUI ownership (#3202)', () => {+ it('does not complete a TUI until sentinel read and recovery promotion both validate', () => {+ const guard = RUNNER_SRC.indexOf('if (!sentinelValidated) {');+ const completed = RUNNER_SRC.indexOf('current.completedBySentinel = true;');+ const killed = RUNNER_SRC.indexOf('current.process.kill();');+ expect(guard, 'sentinel failures must stay on the watch path').toBeGreaterThan(-1);+ expect(completed, 'completion must be marked only after validation').toBeGreaterThan(guard);+ expect(killed, 'the PTY must be killed only after validation').toBeGreaterThan(completed);+ expect(RUNNER_SRC).toContain('current.doneWatcher = sentinelAccess.watch(handleSentinel);');+ });+it('checks the TUI executable against its child PATH before opening a PTY', () => {// node-pty otherwise turns a missing binary into exit 1 with no transcript,// which loses the real configuration error to a generic startup failure.diff --git a/server/services/agentSentinelWatcher.js b/server/services/agentSentinelWatcher.jsindex a3086907ba..2b03a8b490 100644--- a/server/services/agentSentinelWatcher.js+++ b/server/services/agentSentinelWatcher.js@@ -62,23 +62,19 @@ export function createAgentSentinelAccess({: [canonicalPath]: [];const fallbackPaths = candidatePaths.slice(1);- const blockedFallbacks = new Set();let detectedPath = null;let callbackDelivered = false;+ let recoveryPromoted = false;const fallbackIsUnambiguous = (filePath) => {- if (blockedFallbacks.has(filePath)) return false;const candidateId = doneSentinelAgentId(basename(filePath));if (!candidateId) return false;const ids = activeIds(getActiveAgentIds);- if (!ids) {- blockedFallbacks.add(filePath);- return false;- }- if (ids.some((activeId) => activeId !== agentId && activeId.startsWith(candidateId))) {- blockedFallbacks.add(filePath);- return false;- }+ // Registry reads can fail transiently. Fail closed for this check, but do+ // not cache that answer: a sibling that is still active now may finish+ // before the next watcher poll, and then this recovery becomes safe.+ if (!ids) return false;+ if (ids.some((activeId) => activeId !== agentId && activeId.startsWith(candidateId))) return false;return isFreshFile(filePath, startedAt);};@@ -109,6 +105,9 @@ export function createAgentSentinelAccess({const watch = (onDetected, watchOptions = {}) => {if (!canonicalPath || typeof onDetected !== 'function') return null;+ // A failed read or promotion may re-arm the same access object. The prior+ // one-shot callback must not permanently suppress that retry.+ callbackDelivered = false;if (candidatePaths.length === 1) return watchForFile(canonicalPath, onDetected, watchOptions);const closers = candidatePaths.map((filePath) => watchForFile(filePath,@@ -145,24 +144,38 @@ export function createAgentSentinelAccess({await Promise.all([...paths].map((filePath) => rm(filePath, { force: true }).catch(() => {})));detectedPath = null;callbackDelivered = false;+ recoveryPromoted = false;};const promote = async (contents) => {const sourcePath = resolvedPath();- if (!sourcePath || sourcePath === canonicalPath || fs.existsSync(canonicalPath)) return;- await writeFile(canonicalPath, contents, { flag: 'wx' }).catch((err) => {+ if (!sourcePath) return false;+ if (sourcePath === canonicalPath || fs.existsSync(canonicalPath)) {+ recoveryPromoted = true;+ return true;+ }+ try {+ await writeFile(canonicalPath, contents, { flag: 'wx' });+ recoveryPromoted = true;+ return true;+ } catch (err) {if (err?.code !== 'EEXIST') throw err;- });+ recoveryPromoted = fs.existsSync(canonicalPath);+ return recoveryPromoted;+ }};// Shared cleanup removes the canonical path by design. Remove only the// recovery path this access object actually accepted; never glob or delete a// sibling's similarly-prefixed sentinel.const cleanup = async () => {+ if (!recoveryPromoted) return false;if (detectedPath && detectedPath !== canonicalPath) {await rm(detectedPath, { force: true }).catch(() => {});}detectedPath = null;+ recoveryPromoted = false;+ return true;};return {diff --git a/server/services/agentSentinelWatcher.test.js b/server/services/agentSentinelWatcher.test.jsindex a6fc390459..d8d2719536 100644--- a/server/services/agentSentinelWatcher.test.js+++ b/server/services/agentSentinelWatcher.test.js@@ -28,7 +28,7 @@ describe('createAgentSentinelAccess', () => {expect(access.resolvedPath()).toBe(recoveredPath);expect(await access.read()).toBe(contents);- await access.promote(contents);+ expect(await access.promote(contents)).toBe(true);expect(await readFile(join(workspace, '.agent-done-agent-ded2dccb'), 'utf8')).toBe(contents);await access.cleanup();await expect(readFile(recoveredPath, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' });@@ -87,6 +87,31 @@ describe('createAgentSentinelAccess', () => {}});+ it('rechecks a fallback after a transient active-agent registry failure', async () => {+ const workspace = await makeWorkspace();+ try {+ let registryAvailable = false;+ const recoveredPath = join(workspace, '.agent-done-agent-ded2dcc');+ await writeFile(recoveredPath, 'done');+ const access = createAgentSentinelAccess({+ workspacePath: workspace,+ agentId: AGENT_ID,+ startedAt: Date.now() - 1000,+ getActiveAgentIds: () => {+ if (!registryAvailable) throw new Error('registry temporarily unavailable');+ return [AGENT_ID];+ },+ });++ expect(access.exists()).toBe(false);+ registryAvailable = true;+ expect(access.exists()).toBe(true);+ expect(access.resolvedPath()).toBe(recoveredPath);+ } finally {+ await rm(workspace, { recursive: true, force: true });+ }+ });+it('watches for a recovery file written after the run starts', async () => {const workspace = await makeWorkspace();try {diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.jsindex a7a26a7cf6..01c37ea314 100644--- a/server/services/agentTuiSpawning/sessionController.js+++ b/server/services/agentTuiSpawning/sessionController.js@@ -91,6 +91,7 @@ import {// Agent-specific timing/lifecycle constants (not shared with the one-shot// runner — agents stay alive much longer and write a sentinel file when done).const PROVIDER_SIGNAL_POLL_MS = 5000;+const SENTINEL_RECOVERY_RETRY_MS = 250;// Paste + submit-Enter retry machinery for the controller's prompt delivery.// Separated so retries don't re-run the liveness guard or re-set the outer@@ -562,6 +563,11 @@ export function createTuiSessionController({// is itself guarded by `sessionPhase`, so this is defensive — it pins the// read-at-most-once invariant at the helper.let sentinelIngested = false;+ // A recovered sentinel is not completion until its contents have been read+ // and promoted to the canonical path. If either step races the filesystem,+ // keep the run alive and let the watcher retry instead of finalizing from a+ // partial/ambiguous signal.+ let sentinelRecoveryPending = false;let hasStartedWorking = false;// Guards the once-per-run `run.output` boundary (#4540). Kept separate from// `firstOutputAt` / `hasStartedWorking`: both of those are also set by paths@@ -672,6 +678,7 @@ export function createTuiSessionController({let providerSignalTimer = null;let claudeLowPriorityResubmitTimer = null;let doneSentinelWatcher = null;+ let sentinelRecoveryRetryTimer = null;const streamingStrip = createStreamingAnsiStripper();@@ -706,10 +713,21 @@ export function createTuiSessionController({// shared finalization/output-hook path reads the sentinel again, so a// structured completion has the same behavior as an exact write.const sentinelSourcePath = sentinel.resolvedPath?.();- if (sentinelReadSucceeded && sentinel.promote && sentinelSourcePath && sentinelSourcePath !== sentinel.path) {- await sentinel.promote(contents).catch(err => {- console.error(`❌ ingestDoneSentinel canonical promotion failed: ${err.message}`);- });+ let sentinelValidated = sentinelReadSucceeded;+ if (sentinelReadSucceeded && sentinelSourcePath && sentinelSourcePath !== sentinel.path) {+ if (typeof sentinel.promote !== 'function') {+ sentinelValidated = false;+ } else {+ sentinelValidated = await sentinel.promote(contents).catch(err => {+ console.error(`❌ ingestDoneSentinel canonical promotion failed: ${err.message}`);+ return false;+ });+ }+ }+ if (!sentinelValidated) {+ sentinelIngested = false;+ sentinelRecoveryPending = true;+ return null;}// A programmatic-I/O task type writes a JSON `{ summary, payload }` sentinel;// append only the human `summary` to the agent output (the structured@@ -746,6 +764,15 @@ export function createTuiSessionController({await finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' });});+ const scheduleSentinelRecoveryRetry = () => {+ if (sentinelRecoveryRetryTimer || isTerminal()) return;+ sentinelRecoveryRetryTimer = setTimeout(() => {+ sentinelRecoveryRetryTimer = null;+ if (isTerminal()) return;+ doneSentinelWatcher = armSentinelWatcher();+ }, SENTINEL_RECOVERY_RETRY_MS);+ };+/*** Merge Gate contract check (#5876) — runs on a successful sentinel, before* ANY teardown, for a run whose own task shape said it owed a merge. Asks@@ -794,6 +821,7 @@ export function createTuiSessionController({if (providerSignalTimer) { clearInterval(providerSignalTimer); providerSignalTimer = null; }if (promptTimer) { clearInterval(promptTimer); promptTimer = null; }if (claudeLowPriorityResubmitTimer) { clearTimeout(claudeLowPriorityResubmitTimer); claudeLowPriorityResubmitTimer = null; }+ if (sentinelRecoveryRetryTimer) { clearTimeout(sentinelRecoveryRetryTimer); sentinelRecoveryRetryTimer = null; }doneSentinelWatcher?.();doneSentinelWatcher = null;// Cancels the paste-attempt timers and releases the post-paste accumulator@@ -886,6 +914,19 @@ export function createTuiSessionController({// what normally calls finish(). Idempotent via `sentinelIngested`.const sentinelSummary = await ingestDoneSentinel();+ if (sentinelRecoveryPending) {+ sentinelRecoveryPending = false;+ sessionPhase = 'running';+ scheduleSentinelRecoveryRetry();+ if (pendingFinish && !sentinelPresent()) {+ const replay = pendingFinish;+ pendingFinish = null;+ return finish(replay);+ }+ pendingFinish = null;+ return;+ }+// Merge Gate contract check (#5876): only for a run that actually// succeeded AND signaled that success via a real `.agent-done` summary —// an ordinary clean exit with no sentinel (or one with an empty summary)diff --git a/server/services/agentTuiSpawning/sessionController.test.js b/server/services/agentTuiSpawning/sessionController.test.jsindex dde976dfc6..359ac25833 100644--- a/server/services/agentTuiSpawning/sessionController.test.js+++ b/server/services/agentTuiSpawning/sessionController.test.js@@ -44,6 +44,7 @@ function makeController({provider = { id: 'codex-tui', name: 'Codex' },tuiConfig = TUI_CONFIG,prompt = 'do the work',+ sentinelRead = async () => sentinelSummary ?? '',} = {}) {// A DISTINCT closer per arm: the merge-gate case below has to tell the// re-armed watcher apart from the one it replaced, which one shared spy@@ -106,7 +107,7 @@ function makeController({sentinel: {path: '/tmp/workspace/.agent-done-agent-8021',exists: () => sentinelSummary !== null,- read: async () => sentinelSummary ?? '',+ read: sentinelRead,remove: seams.remove,watch,},@@ -144,6 +145,30 @@ describe('TUI session controller — teardown owns its own machinery (#8021)', (expect(releaseRunRecord).toHaveBeenCalledWith(null);});+ it('keeps the run alive when a completion sentinel read fails, then retries it', async () => {+ let reads = 0;+ const { controller, finalizeAgent, watch } = makeController({+ sentinelSummary: 'Recovered completion.',+ sentinelRead: async () => {+ reads += 1;+ if (reads === 1) throw new Error('sentinel is still being written');+ return 'Recovered completion.';+ },+ });++ controller.attachSession({ sessionId: 'session-abcdef12', pid: 4242 });+ await controller.finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' });++ expect(finalizeAgent).not.toHaveBeenCalled();+ expect(controller.isTerminal()).toBe(false);+ await vi.advanceTimersByTimeAsync(250);+ expect(watch).toHaveBeenCalledTimes(2);++ await controller.finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' });+ expect(finalizeAgent).toHaveBeenCalledTimes(1);+ expect(controller.isTerminal()).toBe(true);+ });+it('tears down the watcher the merge-gate nudge re-armed, not the one it replaced', async () => {const { controller, watch, closers, remove, paste, finalizeAgent } = makeController({mergeGateIsOwed: true,