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
feat: watch CoS completion sentinels (#4505)
[._.]/ Adam Eivy417718072112
diff --git a/scripts/migrations/193-cd-plan-locked-render-settings.js b/scripts/migrations/193-cd-plan-locked-render-settings.jsindex 5311e05406..78cd6c8760 100644--- a/scripts/migrations/193-cd-plan-locked-render-settings.js+++ b/scripts/migrations/193-cd-plan-locked-render-settings.js@@ -25,7 +25,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'cd-plan.md': 'ef0d96f6ebde43af6c4579969d31cfb7', // post-199 (cross-step result references)+ 'cd-plan.md': '41a61590896d1327df2c6915557361de', // post-277 (commission/model controls)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/199-cd-plan-result-references.js b/scripts/migrations/199-cd-plan-result-references.jsindex 8909e7d431..98df6d7d1f 100644--- a/scripts/migrations/199-cd-plan-result-references.js+++ b/scripts/migrations/199-cd-plan-result-references.js@@ -24,7 +24,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'cd-plan.md': 'ef0d96f6ebde43af6c4579969d31cfb7', // post-199 (cross-step result references)+ 'cd-plan.md': '41a61590896d1327df2c6915557361de', // post-277 (commission/model controls)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex baef72ff80..00c95fec95 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -49,7 +49,7 @@ const EXPECTED_STAGE_OLD = {'pipeline-editorial-on-the-nose.md': ['48182b49149e6b5829fbed71b3ffc242'],'pipeline-tv-script.md': ['3f6fecc25573ed054b47db392250034a'],'cd-treatment.md': ['2ffa482e7bfb6fe8b7224505fedbf712', '16d0ef6a7fd2533719a846019122ebee', '95b7685690ecfee4f682b0293b790277'],- 'cd-plan.md': ['3ce871196a8fd04781b71b6780e89c86', '0768d6809645c2c1fe73cacae9740fe9'],+ 'cd-plan.md': ['3ce871196a8fd04781b71b6780e89c86', '0768d6809645c2c1fe73cacae9740fe9', 'ef0d96f6ebde43af6c4579969d31cfb7'],'pipeline-series-generate.md': ['bc72731124a2bd6304362f4402c6305d'],'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c', 'cda34127b40754ddbcc8544e3d82572b', 'd6c449c06de73a0868141c899b26e52c', '04419e382f3b46ed92bfaaa1d4f39e13'],'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f'],@@ -82,7 +82,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-editorial-on-the-nose.md': 'e5786fb019e5bf19c7aa6ed0c8b35cda','pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a','cd-treatment.md': 'd940eadfb406ce584f0e244032f33382',- 'cd-plan.md': 'ef0d96f6ebde43af6c4579969d31cfb7',+ 'cd-plan.md': '41a61590896d1327df2c6915557361de','pipeline-series-generate.md': '21352c21ed6d4edb7a4b7c32704eff55','pipeline-character-foundation.md': 'b7d2bac347e11171606f4c6acfcd32e1','pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410',diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 5ef20998af..c64df1c4f1 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -16,7 +16,7 @@ import { writeFile, readFile } from 'fs/promises';import { existsSync } from 'fs';import http from 'http';import { Server as SocketServer } from 'socket.io';-import { ensureDir, PATHS, sleep } from '../lib/fileUtils.js';+import { ensureDir, PATHS, sleep, watchForFile } from '../lib/fileUtils.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { prepareCliPrompt } from '../lib/cliProviderArgs.js';@@ -50,7 +50,6 @@ setupProcessErrorHandlers();const SIGKILL_GRACE_MS = 5000; // wait after SIGTERM before forcing SIGKILLconst ORPHAN_CLEANUP_DELAY_MS = 3000; // delay on boot before reaping orphaned agentsconst SHUTDOWN_DRAIN_MS = 5000; // SIGTERM drain window before closing the server-const TUI_DONE_POLL_MS = 2000;// Agentic CLIs can spend several seconds loading config/plugins before their// lightweight version command returns. Keep this aligned with commandExists'// documented heavy-CLI probe budget so a cold but runnable provider is not@@ -230,7 +229,7 @@ app.post('/spawn-tui', async (req, res) => {command,doneSentinelPath,completedBySentinel: false,- doneTimer: null,+ doneWatcher: null,};activeAgents.set(agentId, agent);@@ -248,7 +247,7 @@ app.post('/spawn-tui', async (req, res) => {try {const current = activeAgents.get(agentId);if (!current) return;- if (current.doneTimer) clearInterval(current.doneTimer);+ current.doneWatcher?.();const duration = Date.now() - current.startedAt;const success = current.completedBySentinel;const effectiveExitCode = success ? 0 : exitCode;@@ -283,29 +282,23 @@ app.post('/spawn-tui', async (req, res) => {});if (doneSentinelPath) {- agent.doneTimer = setInterval(async () => {- try {- const current = activeAgents.get(agentId);- if (!current || !existsSync(doneSentinelPath)) return;- current.completedBySentinel = true;- clearInterval(current.doneTimer);- current.doneTimer = null;- const contents = await readFile(doneSentinelPath, 'utf8').catch(err => {- console.error(`❌ TUI agent ${agentId} sentinel read failed: ${err.message}`);- return '';+ agent.doneWatcher = watchForFile(doneSentinelPath, async () => {+ const current = activeAgents.get(agentId);+ if (!current) return;+ current.completedBySentinel = true;+ const contents = await readFile(doneSentinelPath, 'utf8').catch(err => {+ console.error(`❌ TUI agent ${agentId} sentinel read failed: ${err.message}`);+ return '';+ });+ const { summary } = parseSentinelPayload(contents);+ if (summary) {+ emitToServer('agent:output', {+ agentId,+ text: `${SENTINEL_COMPLETION_MARKER}\n${summary.slice(0, 4096)}\n`,});- const { summary } = parseSentinelPayload(contents);- if (summary) {- emitToServer('agent:output', {- agentId,- text: `${SENTINEL_COMPLETION_MARKER}\n${summary.slice(0, 4096)}\n`,- });- }- current.process.kill();- } catch (err) {- console.error(`❌ TUI agent ${agentId} sentinel poll failed: ${err.message}`);}- }, TUI_DONE_POLL_MS);+ current.process.kill();+ });}await withState((state) => {diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.jsindex 9d9d541b71..7141bc79bc 100644--- a/server/lib/agentSentinel.js+++ b/server/lib/agentSentinel.js@@ -2,7 +2,7 @@* The `.agent-done` completion sentinel — shared naming + parser.** A finishing agent writes this file into its workspace to signal completion- * (see agentTuiSpawning's sentinel poll). The file is named per agent instance+ * (see agentTuiSpawning's sentinel watcher). The file is named per agent instance* (`.agent-done-<agentId>`, see `doneSentinelName`) because worktree-less runs* share one workspace and would otherwise clobber each other's signal.*@@ -50,7 +50,7 @@ export function doneSentinelName(agentId) {* The one path this run's sentinel lives at — `null` without a workspace.** Every producer and consumer resolves it here: the prompt the agent is given- * (agentPromptBuilder), the 2s poll and the durable runner's watch+ * (agentPromptBuilder), the sentinel watchers and the durable runner's watch* (agentTuiSpawning), the CLI exit check (agentCliSpawning), and the* output-hook payload read (agentFinalization). One path, not a candidate list:* a second accepted name would give those pollers different answers to "diddiff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex f50c851182..56d204c2d2 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -5,7 +5,7 @@*/import { access, appendFile, chmod, mkdir, open, readFile, readdir, stat, writeFile, rename, unlink, copyFile } from 'fs/promises';-import { existsSync, statSync, createReadStream } from 'fs';+import { existsSync, statSync, createReadStream, watch as watchFileSystem } from 'fs';import { execFile } from './childProcess.js';import { promisify } from 'util';import { createHash, randomUUID } from 'crypto';@@ -39,6 +39,46 @@ const WIN_RENAME_LOCK_CODES = ['EPERM', 'EACCES', 'EEXIST'];// read failures with the same transient meaning on the reader side.const WIN_READ_LOCK_CODES = ['EPERM', 'EACCES', 'EBUSY'];+/** Watch for a file to appear without repeatedly stat'ing its parent directory. */+export function watchForFile(filePath, onDetected, { settleMs = 50 } = {}) {+ const targetName = basename(filePath);+ const targetDir = dirname(filePath);+ let closed = false;+ let detected = false;+ let settleTimer = null;++ const notify = () => {+ Promise.resolve(onDetected()).catch((err) => {+ console.error(`❌ File watcher callback failed: ${err.message}`);+ });+ };+ const close = (onClosed) => {+ if (closed) return;+ closed = true;+ if (settleTimer) clearTimeout(settleTimer);+ if (onClosed) watcher.once('close', onClosed);+ watcher.close();+ };+ const detect = (settle = true) => {+ if (closed || detected || !existsSync(filePath)) return;+ detected = true;+ if (!settle) {+ close(notify);+ return;+ }+ settleTimer = setTimeout(() => {+ settleTimer = null;+ if (closed) return;+ close(notify);+ }, settleMs);+ };+ const watcher = watchFileSystem(targetDir, (_eventType, changedName) => {+ if (changedName == null || changedName.toString() === targetName) detect();+ });+ detect(false);+ return close;+}+// Cache __dirname calculation for services importing this moduleconst __lib_filename = fileURLToPath(import.meta.url);const __lib_dirname = dirname(__lib_filename);diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex b167ea112d..ae95b34944 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -64,6 +64,7 @@ import {saveBase64Upload,saveImageUpload,serveLocalFile,+ watchForFile,} from './fileUtils.js';import { copyFileSync, existsSync, mkdirSync } from 'fs';import { dirname } from 'path';@@ -1621,6 +1622,26 @@ describe('createCachedStore', () => {});});+describe('watchForFile', () => {+ // Node 24's Windows libuv watcher can abort the worker in src/win/fs-event.c+ // after a watched temp directory is removed, even after FSWatcher emits+ // `close`. Linux covers the native integration; agentTuiSpawning tests cover+ // the close-event and process-exit races with a platform-neutral watcher.+ it.skipIf(process.platform === 'win32')('detects a newly written file without interval polling', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'watch-file-test-'));+ const target = join(dir, 'done.sentinel');+ const detected = new Promise((resolve) => watchForFile(target, resolve, { settleMs: 0 }));+ await new Promise((resolve) => setImmediate(resolve));+ await writeFile(target, 'done');+ await expect(detected).resolves.toBeUndefined();+ // FSWatcher emits `close` before libuv's Windows endgame has fully released+ // the directory handle. Let that native cleanup finish before removing the+ // watched temp directory, or Node can abort in src/win/fs-event.c.+ await new Promise((resolve) => setImmediate(resolve));+ rmSync(dir, { recursive: true, force: true });+ });+});+// =============================================================================// sanitizeFilename / getFileExtension / getMimeType / allowlists (#1140)// =============================================================================diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 2e3c310df5..0124cbf172 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -1425,7 +1425,7 @@ export function buildProgrammaticOutputCompletionSection(sentinelPath) {'## Completion (Reasoning-Only Task)','This is a reasoning task, not a code change. The worktree you are in is **discarded on exit** — any commits, pushes, or PRs are thrown away and have no effect. Do NOT run `/do:push`, `/do:pr`, `git commit`, `git push`, or open a pull request.','',- `When you have finished reasoning, write your result to \`${sentinelPath}\` in the exact payload format described in your task instructions, then stop. PortOS polls this sentinel every 2s, finalizes the run, and closes the session for you — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`+ `When you have finished reasoning, write your result to \`${sentinelPath}\` in the exact payload format described in your task instructions, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`].join('\n');}@@ -1434,8 +1434,8 @@ export function buildProgrammaticOutputCompletionSection(sentinelPath) {* scan stage). The agent must NOT commit/push/modify source; its real output is* recorded elsewhere DURING the run (a tracker issue, PLAN.md, a report).*- * A TUI agent still needs a `.agent-done` sentinel to signal completion — the 2s- * sentinel poll in `spawnTuiAgent` is the primary finalize path and the channel+ * A TUI agent still needs a `.agent-done` sentinel to signal completion — the+ * sentinel watcher in `spawnTuiAgent` is the primary finalize path and the channel* that ingests the run summary. Without it a read-only TUI run relies on shell* exit, so the resolution summary is not captured cleanly (the bug this* repairs). CLI/API read-only agents complete on process exit and never poll a@@ -1447,7 +1447,7 @@ export function buildReadOnlyCompletionSection({ isTui = false, sentinelPath = nreturn [notice,'',- `When you have finished, write a short markdown summary of what you found (and where you recorded it) to \`${sentinelPath}\`, then stop. PortOS polls this sentinel every 2s, finalizes the run, and closes the session for you — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`+ `When you have finished, write a short markdown summary of what you found (and where you recorded it) to \`${sentinelPath}\`, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`].join('\n');}@@ -1459,7 +1459,7 @@ export function buildReadOnlyCompletionSection({ isTui = false, sentinelPath = n* nothing to commit or push, and telling the agent to run `/do:push` just makes it* load that skill for no reason (and can contradict the task prompt's own* "on a 200 your task is complete"). A TUI agent still writes a `.agent-done`- * sentinel so the 2s poll finalizes it promptly instead of waiting for a runtime+ * sentinel so the watcher finalizes it promptly instead of waiting for a runtime* reaper.*/export function buildActionOutputCompletionSection({ isTui = false, sentinelPath = null } = {}) {@@ -1468,7 +1468,7 @@ export function buildActionOutputCompletionSection({ isTui = false, sentinelPathreturn [notice,'',- `Your task is complete once that request succeeds. Then write a one-line summary to \`${sentinelPath}\` and stop — PortOS polls this sentinel every 2s, finalizes the run, and closes the session for you. Do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`+ `Your task is complete once that request succeeds. Then write a one-line summary to \`${sentinelPath}\` and stop — PortOS watches this sentinel and finalizes the run shortly after it appears. Do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`].join('\n');}@@ -1741,7 +1741,7 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an// both prompt paths emit byte-identical workflows. (Background: TUI owns// its own `/simplify` → `/do:pr|/do:push` → sentinel sequence because the// slashdo submodule mounts those commands at project level. Writing the- // sentinel is the done signal — PortOS finalizes via the 2s poll and kills+ // sentinel is the done signal — PortOS finalizes via the watcher and kills// the session, so the prompt does NOT ask the agent to `/quit` (it's a UI// command the agent can't invoke). See `buildTuiCompletionSection` below.)const tuiCompletionCommand = willOpenPR ? '/do:pr' : '/do:push';@@ -2387,7 +2387,7 @@ function resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, userna*/function buildSentinelWriteSteps(stepNumber, sentinelPath, sentinelTail) {return [- `${stepNumber}. Write a short markdown summary (~5–15 lines) to the completion sentinel, then stop — this sentinel is the done signal. PortOS polls it every 2s, finalizes the run, and closes the session for you. Do NOT run \`/quit\` (it's a UI command, not something you can invoke) and do NOT wait for anything after writing the sentinel.`,+ `${stepNumber}. Write a short markdown summary (~5–15 lines) to the completion sentinel, then stop — this sentinel is the done signal. PortOS watches it and finalizes the run shortly after it appears. Do NOT run \`/quit\` (it's a UI command, not something you can invoke) and do NOT wait for anything after writing the sentinel.`,'',' ```bash',` cat > "${sentinelPath}" <<'EOF'`,diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex b1a140fb99..0ec2e5cec8 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -1047,12 +1047,12 @@ describe('buildLightContextPrompt', () => {'/r', null, isTruthyMeta, { isTui: true });expect(prompt).toMatch(/Read-Only Task/);expect(prompt).not.toMatch(/## Completion Workflow/);- // A read-only TUI agent must still be told to write .agent-done — the 2s- // sentinel poll is its only clean finalize/summary path (regression: the+ // A read-only TUI agent must still be told to write .agent-done — the+ // sentinel watcher is its only clean finalize/summary path (regression: the// read-only branch used to emit the bare notice with no sentinel, so// reference-watch runs never signaled completion).expect(prompt).toMatch(/\.agent-done/);- expect(prompt).toMatch(/polls this sentinel/);+ expect(prompt).toMatch(/watches this sentinel/);});it('read-only on a non-TUI (CLI) provider gets the bare notice, no sentinel', () => {diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex eb956f2e51..949625fbc0 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -16,7 +16,7 @@ import { createOutputSpooler } from './agentTuiSpawning/outputSpooler.js';import { resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { activeAgents, userTerminatedAgents, pausedAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';-import { PATHS } from '../lib/fileUtils.js';+import { PATHS, watchForFile } from '../lib/fileUtils.js';import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';@@ -74,12 +74,11 @@ const PROVIDER_SIGNAL_POLL_MS = 5000;// RAW_TAIL_ANALYSIS_BYTES) live in// ./agentTuiSpawning/ so spawnTuiAgent stays a thin orchestrator.-// Sentinel-file polling. TUI agents write `.agent-done` in their workspace-// when they've finished /simplify + /do:pr (or /do:push) — we poll for it-// here so the agent gets cleanly finalized as soon as the work is done,-// without waiting for a shell exit.+// Sentinel-file watching. TUI agents write `.agent-done` in their workspace+// when they've finished /simplify + /do:pr (or /do:push) — watch for it here+// so the agent gets cleanly finalized as soon as the work is done, without+// waiting for a shell exit or repeatedly touching the filesystem.// The filename is per agent instance — see doneSentinelName in ../lib/agentSentinel.js.-const DONE_POLL_INTERVAL_MS = 2000;/*** Thin wrapper around `shellService.createShellSession` for the agent TUI@@ -538,7 +537,7 @@ export async function spawnTuiAgent({const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : PATHS.root;// The agent writes `.agent-done` in its workspace to signal completion (see// the sentinel watcher below) and then stops — it does NOT run `/quit` (that- // is a UI command the agent can't invoke). The 2s poll is the primary+ // is a UI command the agent can't invoke). The file watcher is the primary// finalize path; finish() also ingests the sentinel directly so the summary// is captured even if some other path (shell exit) finalizes first. Computed// up front so both the watcher AND finish() can read it (see ingestDoneSentinel).@@ -681,7 +680,7 @@ export async function spawnTuiAgent({const agentData = activeAgents.get(agentId);if (agentData?.providerSignalTimer) clearInterval(agentData.providerSignalTimer);if (agentData?.promptTimer) clearInterval(agentData.promptTimer);- if (agentData?.doneSentinelTimer) clearInterval(agentData.doneSentinelTimer);+ agentData?.doneSentinelWatcher?.();// Cancels the paste-attempt timers and releases the post-paste accumulator// even when the run ends mid-paste-window — see// createPasteRetryController's own cancel() for why each is safe to clear@@ -723,8 +722,8 @@ export async function spawnTuiAgent({// Ingest the .agent-done sentinel BEFORE draining, so its markdown summary// lands in outputBuffer/output.txt regardless of WHICH path finalized the// agent. The completion workflow writes the sentinel and stops; the 2s- // doneSentinelTimer poll is what normally calls finish(). Reading it here- // (not just in the poll) keeps the resolution captured even when shell exit+ // doneSentinelWatcher is what normally calls finish(). Reading it here+ // (not just in the watcher) keeps the resolution captured even when shell exit// finalizes first. Idempotent// via `sentinelIngested`.await ingestDoneSentinel();@@ -901,7 +900,7 @@ export async function spawnTuiAgent({* agent named in it, and requeues the task as *interrupted* — resumable, and* without charging it orphan-retry budget.*- * Sets `finalized` so every other path (provider-signal timer, sentinel poll, paste+ * Sets `finalized` so every other path (provider-signal timer, sentinel watcher, paste* retry) becomes a no-op for the rest of this process's life.*/const abandonForHostShutdown = async () => {@@ -1393,24 +1392,16 @@ export async function spawnTuiAgent({// Sentinel-file watcher. The agent's prompt instructs it to write// .agent-done in the workspace after running /simplify + /do:pr and then// stop (it does NOT `/quit` — that is a UI command it can't invoke). This- // poll is the PRIMARY finalize path: it fires finish() within DONE_POLL_- // INTERVAL_MS of the sentinel appearing, and finish()'s own cleanup kills+ // watcher is the PRIMARY finalize path: it fires finish() shortly after the+ // sentinel appears, and finish()'s own cleanup kills// the still-running TUI session. The actual sentinel READ happens in finish()// (via ingestDoneSentinel) so the resolution is captured no matter which path// finalizes. A normal shell exit or explicit provider failure handles agents// that do not write the sentinel.- const doneSentinelTimer = doneSentinelPath ? setInterval(() => {- try {- if (finalized) return;- if (!sentinelPresent()) return;- clearInterval(doneSentinelTimer);- finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId} after sentinel: ${err.message}`, { agentId });- });- } catch (err) {- console.error(`❌ doneSentinelTimer interval callback failed: ${err.message}`);- }- }, DONE_POLL_INTERVAL_MS) : null;+ const doneSentinelWatcher = doneSentinelPath ? watchForFile(doneSentinelPath, async () => {+ if (finalized) return;+ await finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' });+ }) : null;activeAgents.set(agentId, {process: ptyProcess || { kill: () => shellService.killSession(sessionId) },@@ -1424,7 +1415,7 @@ export async function spawnTuiAgent({tuiSessionId: sessionId,providerSignalTimer,promptTimer,- doneSentinelTimer+ doneSentinelWatcher});// Identify which TUI binary this session is running so consumers can gatediff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex ecb3a4c939..a1869598a8 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -113,6 +113,15 @@ vi.mock('fs', () => ({// Default: no .agent-done sentinel on disk. The completion-sentinel test// overrides this to true. Re-set in beforeEach so it can't leak between tests.existsSync: vi.fn().mockReturnValue(false),+ watch: vi.fn(() => {+ let onClose;+ return {+ once: vi.fn((event, callback) => {+ if (event === 'close') onClose = callback;+ }),+ close: vi.fn(() => onClose?.()),+ };+ }),}));vi.mock('fs/promises', () => ({@@ -1816,14 +1825,14 @@ describe('spawnTuiAgent runtime', () => {// ── 10. Completion-sentinel ingestion on the shell-exit path ─────────────────// The completion workflow has the agent write `.agent-done` and then stop- // (it does NOT `/quit`). Normally the 2s doneSentinelTimer poll finalizes the+ // (it does NOT `/quit`). Normally the doneSentinelWatcher finalizes the// agent, but the TUI process can also exit on its own (or be killed) before- // the poll ticks — when that shell-exit path wins the race, finish() MUST+ // the watcher fires — when that shell-exit path wins the race, finish() MUST// still ingest the sentinel so its markdown resolution lands in outputBuffer /// output.txt and shows up in the completed-agent details view. Regression// guard for the lost-resolution bug where the summary only got ingested by- // the poll path.- it('shell-exit after sentinel write: ingests .agent-done summary into the persisted output (process exit beats the 2s poll)', async () => {+ // the watcher path.+ it('shell-exit after sentinel write: ingests .agent-done summary into the persisted output (process exit beats the watcher)', async () => {const { appendFile } = await import('fs/promises');const sentinel = '## Summary\nImplemented the fix.\n\n## PR\nhttps://example.com/pr/42';vi.mocked(existsSync).mockReturnValue(true);