Skip to content

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

fix: prevent sentinel recovery races

Adam Eivy5818bccabf30
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 520c6ebd17..80515a3af5 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -355,6 +355,7 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {
agent.sentinelWork = lifecycle.trackWork(async () => {
const current = activeAgents.get(agentId);
if (!current) return;
+ const sentinelSourcePath = sentinelAccess.resolvedPath?.();
let sentinelReadSucceeded = true;
const contents = await sentinelAccess.read().catch(err => {
sentinelReadSucceeded = false;
@@ -362,18 +363,31 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {
return '';
});
let sentinelValidated = sentinelReadSucceeded;
+ let validatedContents = contents;
if (sentinelReadSucceeded) {
sentinelValidated = await sentinelAccess.promote(contents).catch(err => {
console.error(`❌ TUI agent ${agentId} canonical sentinel promotion failed: ${err.message}`);
return false;
});
+ if (sentinelValidated && sentinelSourcePath && sentinelSourcePath !== sentinelAccess.path) {
+ let canonicalReadSucceeded = true;
+ validatedContents = await sentinelAccess.read().catch(err => {
+ canonicalReadSucceeded = false;
+ console.error(`❌ TUI agent ${agentId} canonical sentinel read failed: ${err.message}`);
+ return '';
+ });
+ sentinelValidated = canonicalReadSucceeded;
+ }
}
if (!sentinelValidated) {
- if (activeAgents.get(agentId) === current) current.doneWatcher = sentinelAccess.watch(handleSentinel);
+ if (activeAgents.get(agentId) === current) {
+ current.doneWatcher?.();
+ current.doneWatcher = sentinelAccess.watch(handleSentinel);
+ }
return;
}
current.completedBySentinel = true;
- const { summary } = parseSentinelPayload(contents);
+ const { summary } = parseSentinelPayload(validatedContents);
if (summary) {
emitToServer('agent:output', {
agentId,
diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.js
index 02b2ce5b70..a4c6b1fc8e 100644
--- a/server/cos-runner/index.test.js
+++ b/server/cos-runner/index.test.js
@@ -173,7 +173,7 @@ describe('cos-runner durable TUI ownership (#3202)', () => {
expect(RUNNER_SRC).toMatch(/prepareCliSpawn\(executable, args, childEnv\)/);
expect(RUNNER_SRC).toMatch(/pty\.spawn\(ptyCommand,\s*ptyArgs/);
expect(RUNNER_SRC).toMatch(/io\.emit\('tui:output'/);
- expect(RUNNER_SRC).toMatch(/parseSentinelPayload\(contents\)/);
+ expect(RUNNER_SRC).toMatch(/parseSentinelPayload\(validatedContents\)/);
expect(RUNNER_SRC).toMatch(/emitToServer\('agent:completed'/);
});
});
diff --git a/server/services/agentSentinelWatcher.js b/server/services/agentSentinelWatcher.js
index 2b03a8b490..862f7e723c 100644
--- a/server/services/agentSentinelWatcher.js
+++ b/server/services/agentSentinelWatcher.js
@@ -62,19 +62,28 @@ export function createAgentSentinelAccess({
: [canonicalPath]
: [];
const fallbackPaths = candidatePaths.slice(1);
+ const rejectedFallbackIds = new Set();
let detectedPath = null;
let callbackDelivered = false;
+ let activeWatcherCloser = null;
let recoveryPromoted = false;
const fallbackIsUnambiguous = (filePath) => {
const candidateId = doneSentinelAgentId(basename(filePath));
if (!candidateId) return false;
+ if (rejectedFallbackIds.has(candidateId)) return false;
const ids = activeIds(getActiveAgentIds);
// 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;
+ if (ids.some((activeId) => activeId !== agentId && activeId.startsWith(candidateId))) {
+ // Once a colliding run was observed, its sentinel name can no longer be
+ // attributed safely for the rest of this run. Do not reopen the race
+ // after that sibling exits and leaves its fresh file behind.
+ rejectedFallbackIds.add(candidateId);
+ return false;
+ }
return isFreshFile(filePath, startedAt);
};
@@ -105,19 +114,30 @@ export function createAgentSentinelAccess({
const watch = (onDetected, watchOptions = {}) => {
if (!canonicalPath || typeof onDetected !== 'function') return null;
+ activeWatcherCloser?.();
// 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,
- () => notify(filePath, onDetected),
- {
- ...watchOptions,
- shouldDetect: () => filePath === canonicalPath || fallbackIsUnambiguous(filePath),
- },
- ));
- return () => closers.forEach((close) => close?.());
+ const rawCloser = candidatePaths.length === 1
+ ? watchForFile(canonicalPath, onDetected, watchOptions)
+ : (() => {
+ const closers = candidatePaths.map((filePath) => watchForFile(
+ filePath,
+ () => notify(filePath, onDetected),
+ {
+ ...watchOptions,
+ shouldDetect: () => filePath === canonicalPath || fallbackIsUnambiguous(filePath),
+ },
+ ));
+ return () => closers.forEach((close) => close?.());
+ })();
+ let wrappedCloser;
+ wrappedCloser = () => {
+ if (activeWatcherCloser === wrappedCloser) activeWatcherCloser = null;
+ rawCloser?.();
+ };
+ activeWatcherCloser = wrappedCloser;
+ return wrappedCloser;
};
const resolvedPath = () => {
@@ -138,6 +158,7 @@ export function createAgentSentinelAccess({
};
const remove = async () => {
+ activeWatcherCloser?.();
const paths = new Set();
if (canonicalPath) paths.add(canonicalPath);
if (detectedPath && detectedPath !== canonicalPath) paths.add(detectedPath);
@@ -169,6 +190,7 @@ export function createAgentSentinelAccess({
// recovery path this access object actually accepted; never glob or delete a
// sibling's similarly-prefixed sentinel.
const cleanup = async () => {
+ activeWatcherCloser?.();
if (!recoveryPromoted) return false;
if (detectedPath && detectedPath !== canonicalPath) {
await rm(detectedPath, { force: true }).catch(() => {});
diff --git a/server/services/agentSentinelWatcher.test.js b/server/services/agentSentinelWatcher.test.js
index d8d2719536..99d9c5d7dc 100644
--- a/server/services/agentSentinelWatcher.test.js
+++ b/server/services/agentSentinelWatcher.test.js
@@ -54,13 +54,16 @@ describe('createAgentSentinelAccess', () => {
expect(staleAccess.exists()).toBe(false);
await writeFile(recoveredPath, 'sibling');
+ let activeIds = [AGENT_ID, 'agent-ded2dcc'];
const siblingAccess = createAgentSentinelAccess({
workspacePath: workspace,
agentId: AGENT_ID,
startedAt: Date.now() - 1000,
- getActiveAgentIds: () => [AGENT_ID, 'agent-ded2dcc'],
+ getActiveAgentIds: () => activeIds,
});
expect(siblingAccess.exists()).toBe(false);
+ activeIds = [AGENT_ID];
+ expect(siblingAccess.exists()).toBe(false);
} finally {
await rm(workspace, { recursive: true, force: true });
}
@@ -127,6 +130,7 @@ describe('createAgentSentinelAccess', () => {
detected,
new Promise((_, reject) => setTimeout(() => reject(new Error('sentinel was not detected')), 1000)),
])).resolves.toBe(join(workspace, '.agent-done-agent-ded2dcc'));
+ await access.cleanup();
} finally {
await rm(workspace, { recursive: true, force: true });
}
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index 01c37ea314..2ab0eb41ae 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -702,8 +702,9 @@ export function createTuiSessionController({
if (sentinelIngested) return null;
if (!sentinelPresent()) return null;
sentinelIngested = true;
+ const sentinelSourcePath = sentinel.resolvedPath?.();
let sentinelReadSucceeded = true;
- const contents = await sentinel.read().catch(err => {
+ let contents = await sentinel.read().catch(err => {
sentinelReadSucceeded = false;
console.error(`❌ ingestDoneSentinel readFile failed: ${err.message}`);
return '';
@@ -712,7 +713,6 @@ export function createTuiSessionController({
// sentinel access. Promote its contents to the canonical name before the
// 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?.();
let sentinelValidated = sentinelReadSucceeded;
if (sentinelReadSucceeded && sentinelSourcePath && sentinelSourcePath !== sentinel.path) {
if (typeof sentinel.promote !== 'function') {
@@ -722,6 +722,16 @@ export function createTuiSessionController({
console.error(`❌ ingestDoneSentinel canonical promotion failed: ${err.message}`);
return false;
});
+ if (sentinelValidated) {
+ let canonicalReadSucceeded = true;
+ const canonicalContents = await sentinel.read().catch(err => {
+ canonicalReadSucceeded = false;
+ console.error(`❌ ingestDoneSentinel canonical read failed: ${err.message}`);
+ return '';
+ });
+ sentinelValidated = canonicalReadSucceeded;
+ if (sentinelValidated) contents = canonicalContents;
+ }
}
}
if (!sentinelValidated) {
@@ -769,6 +779,7 @@ export function createTuiSessionController({
sentinelRecoveryRetryTimer = setTimeout(() => {
sentinelRecoveryRetryTimer = null;
if (isTerminal()) return;
+ doneSentinelWatcher?.();
doneSentinelWatcher = armSentinelWatcher();
}, SENTINEL_RECOVERY_RETRY_MS);
};
diff --git a/server/services/agentTuiSpawning/sessionController.test.js b/server/services/agentTuiSpawning/sessionController.test.js
index 359ac25833..224a1955b3 100644
--- a/server/services/agentTuiSpawning/sessionController.test.js
+++ b/server/services/agentTuiSpawning/sessionController.test.js
@@ -147,7 +147,7 @@ describe('TUI session controller — teardown owns its own machinery (#8021)', (
it('keeps the run alive when a completion sentinel read fails, then retries it', async () => {
let reads = 0;
- const { controller, finalizeAgent, watch } = makeController({
+ const { controller, closers, finalizeAgent, watch } = makeController({
sentinelSummary: 'Recovered completion.',
sentinelRead: async () => {
reads += 1;
@@ -162,6 +162,7 @@ describe('TUI session controller — teardown owns its own machinery (#8021)', (
expect(finalizeAgent).not.toHaveBeenCalled();
expect(controller.isTerminal()).toBe(false);
await vi.advanceTimersByTimeAsync(250);
+ expect(closers[0]).toHaveBeenCalledTimes(1);
expect(watch).toHaveBeenCalledTimes(2);
await controller.finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' });