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: recover truncated TUI completion sentinels
Adam Eivyeb15d44fd792
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 70037dcc7c..5dd8c66326 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -18,7 +18,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, watchForFile } from '../lib/fileUtils.js';+import { ensureDir, PATHS } from '../lib/fileUtils.js';import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { prepareCliPrompt } from '../lib/cliProviderArgs.js';@@ -41,6 +41,7 @@ import { createHttpDrain } from '../lib/httpDrain.js';import { PORTS } from '../lib/ports.js';import { setupProcessErrorHandlers } from '../lib/errorHandler.js';import { parseSentinelPayload } from '../lib/agentSentinel.js';+import { createAgentSentinelAccess } from '../services/agentSentinelWatcher.js';import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';// Process-level safety net (defense-in-depth, see issue #1878). The main server@@ -326,6 +327,13 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {exited: false,};activeAgents.set(agentId, agent);+ const sentinelAccess = createAgentSentinelAccess({+ workspacePath: cwd,+ agentId,+ sentinelPath: doneSentinelPath,+ startedAt,+ getActiveAgentIds: () => activeAgents.keys(),+ });tuiProcess.onData((data) => {const current = activeAgents.get(agentId);@@ -343,12 +351,12 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {})));if (doneSentinelPath) {- agent.doneWatcher = watchForFile(doneSentinelPath, () => {+ agent.doneWatcher = sentinelAccess.watch(() => {agent.sentinelWork = lifecycle.trackWork(async () => {const current = activeAgents.get(agentId);if (!current) return;current.completedBySentinel = true;- const contents = await readFile(doneSentinelPath, 'utf8').catch(err => {+ const contents = await sentinelAccess.read().catch(err => {console.error(`❌ TUI agent ${agentId} sentinel read failed: ${err.message}`);return '';});diff --git a/server/lib/README.md b/server/lib/README.mdindex 17264e8476..c6653965ae 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -59,7 +59,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. || `agentRegistrationRecord.js` | The `registerAgent` payload one spawn writes, projected from its task — `buildAgentRegistration({ task, provider, … })` plus `resolveExecutionMode({ spawnHeadless, useRunner })` (`direct` / `runner` / `tui` / `runner-tui`, replacing a nested ternary chain). `agent.metadata` is a HAND-PICKED projection of `task.metadata`, never a spread: every downstream reader (run cards, `perpetualRefillPlan`, `declaresNoCommitCriterion`, the quota-burn continuation, `featureAgents`) sees the agent record alone, so an unlisted field does not survive the spawn — which is how `quotaBurnStepId` shipped persisted but unprojected (#6406) while this list was maintained inline in a 900-line orchestrator. Pure and synchronous: `primaryCheckoutBaseline` and `providerEndpoint` arrive as VALUES (both were `await`/service calls inline) and `isTruthyMetaFn` is injected the way `inlinePrLifecycleSection` takes it, keeping this leaf out of the agent-state and local-endpoint graphs. || `agentScratchPaths.js` | Runtime scratch PortOS itself writes into an agent worktree and never commits — `PUBLIC_REVIEW_INPUT_FILENAME` / `PUBLIC_REVIEW_PATCH_DIRNAME` (the public-review bundle materialized by `services/modelAbuseGuard.js`), the `AGENT_SCRATCH_PATHS` list, prefix-aware `matchesScratchRoot(path, roots)` and `isAgentScratchPath(path)`. `classifyWorktreeDirt` (`services/worktreeManager.js`) subtracts these for EVERY caller and uses the same matcher for its per-call `ignoredPaths`, so a worktree holding only scratch reads as clean end to end — before this, it was preserved by `removeWorktree`, held by `reapMergedWorktrees`, filed as a repo-state recovery task, and dispatched to a branch-reconcile coordinator, forever. Only STATIC names live here; a run-scoped name like `.agent-done-<agentId>` (`agentSentinel.js`) is passed per call instead. |-| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, `doneSentinelAgentId(filename)` → its inverse (`''` for the bare unscoped name, `null` for a non-sentinel), so the stale-sentinel sweep in `services/agentSentinelSweep.js` matches leftovers to runs the same way the producer named them, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. |+| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelCandidateNames(agentId)` → the canonical name plus the bounded one-character truncation recovery candidate for generated ids, `doneSentinelPath(workspacePath, agentId)` → the canonical path every producer resolves, `doneSentinelAgentId(filename)` → its inverse (`''` for the bare unscoped name, `null` for a non-sentinel), so the stale-sentinel sweep in `services/agentSentinelSweep.js` matches leftovers to runs the same way the producer named them, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. || `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. || `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). || `cosAgentListProjection.js` | What a CoS agent LIST response may carry. `toAgentListItem` / `toAgentListItems` drop the transcript and bound `metadata.taskDescription` to `AGENT_LIST_DESCRIPTION_CHARS` (2000, on a clause boundary via `textUtils.clampToCharLimit`), stamping `taskDescriptionTruncated` + the original `taskDescriptionLength` so the UI can hydrate the rest from `GET /api/cos/agents/:id`. That one field was 68% of the Agents tab payload — p50 is 75 characters but a pasted-prompt description runs past 50 KB, and `GET /api/cos/agents` sits on the first-paint critical path of every `/cos/*` tab and re-reads every 30s. Applied at the ROUTE layer only: `getAgents`/`getAgentsByDate` also feed the weekly digest and CoS reports, which need the whole text. |diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.jsindex 64c064ad31..b8e2990fd1 100644--- a/server/lib/agentSentinel.js+++ b/server/lib/agentSentinel.js@@ -61,6 +61,24 @@ export function doneSentinelName(agentId) {return slug ? `${DONE_SENTINEL_NAME}-${slug}` : DONE_SENTINEL_NAME;}+/**+ * The names a run-scoped watcher may inspect, in canonical-first order.+ *+ * Producers have exactly one name: `doneSentinelName(agentId)`. The second+ * name is a deliberately narrow recovery for a generated agent id whose final+ * hexadecimal character was dropped while a terminal copied the path. It is+ * not a second producer contract: runtime consumers must still require a+ * fresh, unambiguous file before accepting it.+ */+export function doneSentinelCandidateNames(agentId) {+ const canonical = doneSentinelName(agentId);+ const normalizedId = typeof agentId === 'string' ? agentId.trim() : '';+ if (!/^agent-[0-9a-f]{8}$/.test(normalizedId)) return [canonical];++ const truncated = doneSentinelName(normalizedId.slice(0, -1));+ return truncated === canonical ? [canonical] : [canonical, truncated];+}+/*** The agent id encoded in a done-sentinel filename.*@@ -80,18 +98,6 @@ export function doneSentinelAgentId(name) {return name.startsWith(prefix) && name.length > prefix.length ? name.slice(prefix.length) : null;}-/**- * 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 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 "did- * this run finish", which is the failure the scoped name exists to remove.- *- * Pure: callers do their own `existsSync` / read.- */const STARTUP_SENTINEL_REASONS = new Set(['paste-not-rendered', 'tui-not-ready', 'command-not-found']);/**@@ -111,6 +117,14 @@ export function missingSentinelLogMessage({ agentId, reason, sentinelPath, mergereturn `${agentId} finalized (${reason}) with no completion sentinel — expected ${sentinelPath}`;}+/**+ * The one canonical path this run's sentinel lives at — `null` without a+ * workspace. Producers and normal consumers resolve it here: the prompt the+ * agent is given, the canonical TUI watcher, the CLI exit check, and the+ * output-hook payload read. The TUI runtime may additionally use+ * `doneSentinelCandidateNames` for its bounded terminal-copy recovery; this+ * function remains the producer's one canonical path and is pure.+ */export function doneSentinelPath(workspacePath, agentId) {if (!workspacePath || typeof workspacePath !== 'string') return null;return join(workspacePath, doneSentinelName(agentId));diff --git a/server/lib/agentSentinel.test.js b/server/lib/agentSentinel.test.jsindex 19aa714703..c41e8faa00 100644--- a/server/lib/agentSentinel.test.js+++ b/server/lib/agentSentinel.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import { join } from 'path';-import { DONE_SENTINEL_NAME, doneSentinelAgentId, doneSentinelName, doneSentinelPath, extractSentinelPayloadFromTranscript, missingSentinelLogMessage, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';+import { DONE_SENTINEL_NAME, doneSentinelAgentId, doneSentinelCandidateNames, doneSentinelName, doneSentinelPath, extractSentinelPayloadFromTranscript, missingSentinelLogMessage, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';describe('missingSentinelLogMessage', () => {it('names a startup failure as the reason the sentinel was never written', () => {@@ -59,6 +59,21 @@ describe('agentSentinel', () => {});});+ describe('doneSentinelCandidateNames', () => {+ it('keeps the canonical name first and bounds recovery to one dropped hex suffix', () => {+ expect(doneSentinelCandidateNames('agent-ded2dccb')).toEqual([+ '.agent-done-agent-ded2dccb',+ '.agent-done-agent-ded2dcc',+ ]);+ });++ it('does not broaden recovery for non-generated or non-hex ids', () => {+ expect(doneSentinelCandidateNames('agent-1a2b3c')).toEqual(['.agent-done-agent-1a2b3c']);+ expect(doneSentinelCandidateNames('agent-1234567g')).toEqual(['.agent-done-agent-1234567g']);+ expect(doneSentinelCandidateNames(null)).toEqual(['.agent-done']);+ });+ });+describe('doneSentinelPath', () => {it('resolves the run-scoped file inside the workspace', () => {// Worktree-less agents share the primary checkout: a bare `.agent-done`diff --git a/server/lib/fileCore.js b/server/lib/fileCore.jsindex bc76ebe3ed..14cb8b4ddc 100644--- a/server/lib/fileCore.js+++ b/server/lib/fileCore.js@@ -66,8 +66,23 @@ export function parseFilesystemStats(stats) {};}-/** Watch for a file to appear without repeatedly stat'ing its parent directory. */-export function watchForFile(filePath, onDetected, { settleMs = 50, pollMs = FILE_WATCH_FALLBACK_POLL_MS } = {}) {+/**+ * Watch for a file to appear without repeatedly stat'ing its parent directory.+ *+ * `shouldDetect` is a run-specific acceptance gate for callers watching a+ * compatibility name. It is evaluated only after the target exists, so a+ * rejected stale/ambiguous file remains watchable and can be accepted if a+ * later write makes it valid.+ */+export function watchForFile(+ filePath,+ onDetected,+ {+ settleMs = 50,+ pollMs = FILE_WATCH_FALLBACK_POLL_MS,+ shouldDetect = () => true,+ } = {},+) {const targetName = basename(filePath);const targetDir = dirname(filePath);let closed = false;@@ -89,7 +104,7 @@ export function watchForFile(filePath, onDetected, { settleMs = 50, pollMs = FILwatcher.close();};const detect = (settle = true) => {- if (closed || detected || !existsSync(filePath)) return;+ if (closed || detected || !existsSync(filePath) || !shouldDetect(filePath)) return;detected = true;if (!settle) {close(notify);diff --git a/server/services/agentSentinelWatcher.js b/server/services/agentSentinelWatcher.jsnew file mode 100644index 0000000000..bbe158087e--- /dev/null+++ b/server/services/agentSentinelWatcher.js@@ -0,0 +1,170 @@+/**+ * Run-scoped completion-sentinel access for TUI agents.+ *+ * The producer contract is the canonical `.agent-done-<agentId>` path. A+ * terminal/model can occasionally lose the final character while copying that+ * path, though, leaving a completion file that the exact watcher will never+ * see. This module accepts only the one-character truncation that can occur for+ * generated agent ids, and only when the file is fresh for this run and no+ * active sibling owns the same prefix.+ */++import * as fs from 'fs';+import { readFile, rm, writeFile } from 'fs/promises';+import { basename, join } from 'path';+import { watchForFile } from '../lib/fileUtils.js';+import { doneSentinelAgentId, doneSentinelCandidateNames, doneSentinelPath } from '../lib/agentSentinel.js';++function activeIds(getActiveAgentIds) {+ try {+ const source = getActiveAgentIds?.() ?? [];+ const iterable = source instanceof Map ? source.keys() : source;+ return [...iterable].filter((id) => typeof id === 'string');+ } catch {+ // A registry read must never turn a completion signal into a crash. The+ // fallback is fail-closed below, so an uncertain sibling set cannot steal+ // another run's sentinel.+ return null;+ }+}++function isFreshFile(filePath, startedAt) {+ try {+ const info = fs.statSync?.(filePath, { throwIfNoEntry: false });+ return !!info?.isFile?.() && Number.isFinite(info.mtimeMs) && info.mtimeMs >= startedAt;+ } catch {+ return false;+ }+}++/**+ * Build the sentinel access used by a live TUI run.+ *+ * The returned `path` is always the canonical path. `resolvedPath()` changes+ * to the accepted recovery path only after a watcher or presence check has+ * validated it. That lets the controller promote a recovered file back to the+ * canonical name before finalization reads structured payloads. A caller may+ * pass `sentinelPath` when the transport already supplied the canonical path;+ * custom paths deliberately disable truncation recovery.+ */+export function createAgentSentinelAccess({+ workspacePath,+ agentId,+ sentinelPath = null,+ startedAt = Date.now(),+ getActiveAgentIds = () => [],+} = {}) {+ const canonicalPath = sentinelPath || doneSentinelPath(workspacePath, agentId);+ const defaultCanonicalPath = doneSentinelPath(workspacePath, agentId);+ const candidatePaths = canonicalPath+ ? canonicalPath === defaultCanonicalPath+ ? doneSentinelCandidateNames(agentId).map((name) => join(workspacePath, name))+ : [canonicalPath]+ : [];+ const fallbackPaths = candidatePaths.slice(1);+ const blockedFallbacks = new Set();+ let detectedPath = null;+ let callbackDelivered = 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;+ }+ return isFreshFile(filePath, startedAt);+ };++ const resolvePath = () => {+ if (!canonicalPath) return null;+ if (fs.existsSync(canonicalPath)) {+ detectedPath ??= canonicalPath;+ return canonicalPath;+ }+ const recoveredPath = fallbackPaths.find((filePath) =>+ fs.existsSync(filePath) && fallbackIsUnambiguous(filePath)+ );+ if (recoveredPath) {+ detectedPath ??= recoveredPath;+ return recoveredPath;+ }+ return null;+ };++ const notify = (watchedPath, onDetected) => {+ const resolved = resolvePath();+ if (!resolved || (watchedPath !== canonicalPath && resolved !== watchedPath)) return;+ detectedPath = resolved;+ if (callbackDelivered) return;+ callbackDelivered = true;+ return onDetected(resolved);+ };++ const watch = (onDetected, watchOptions = {}) => {+ if (!canonicalPath || typeof onDetected !== 'function') return null;+ 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 resolvedPath = () => detectedPath || resolvePath();++ const read = async () => {+ const filePath = resolvedPath() || canonicalPath;+ if (!filePath) throw new Error('No workspace available for completion sentinel');+ return readFile(filePath, 'utf8');+ };++ const remove = async () => {+ const paths = new Set();+ if (canonicalPath) paths.add(canonicalPath);+ if (detectedPath && detectedPath !== canonicalPath) paths.add(detectedPath);+ await Promise.all([...paths].map((filePath) => rm(filePath, { force: true }).catch(() => {})));+ detectedPath = null;+ callbackDelivered = 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 (err?.code !== 'EEXIST') throw err;+ });+ };++ // 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 (detectedPath && detectedPath !== canonicalPath) {+ await rm(detectedPath, { force: true }).catch(() => {});+ }+ detectedPath = null;+ };++ return {+ path: canonicalPath,+ candidatePaths,+ exists: () => !!resolvePath(),+ resolvedPath,+ read,+ remove,+ promote,+ cleanup,+ watch,+ };+}diff --git a/server/services/agentSentinelWatcher.test.js b/server/services/agentSentinelWatcher.test.jsnew file mode 100644index 0000000000..1f8ce89200--- /dev/null+++ b/server/services/agentSentinelWatcher.test.js@@ -0,0 +1,89 @@+import { describe, expect, it } from 'vitest';+import { mkdtemp, readFile, rm, utimes, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { createAgentSentinelAccess } from './agentSentinelWatcher.js';++const AGENT_ID = 'agent-ded2dccb';++async function makeWorkspace() {+ return mkdtemp(join(tmpdir(), 'portos-sentinel-'));+}++describe('createAgentSentinelAccess', () => {+ it('accepts and promotes only a fresh one-character truncation', async () => {+ const workspace = await makeWorkspace();+ try {+ const access = createAgentSentinelAccess({+ workspacePath: workspace,+ agentId: AGENT_ID,+ startedAt: Date.now() - 1000,+ getActiveAgentIds: () => [AGENT_ID],+ });+ const recoveredPath = join(workspace, '.agent-done-agent-ded2dcc');+ const contents = '## Summary\nRecovered completion.';+ await writeFile(recoveredPath, contents);++ expect(access.exists()).toBe(true);+ expect(access.resolvedPath()).toBe(recoveredPath);+ expect(await access.read()).toBe(contents);++ await access.promote(contents);+ expect(await readFile(join(workspace, '.agent-done-agent-ded2dccb'), 'utf8')).toBe(contents);+ await access.cleanup();+ await expect(readFile(recoveredPath, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' });+ } finally {+ await rm(workspace, { recursive: true, force: true });+ }+ });++ it('rejects a stale recovery file and a live sibling prefix collision', async () => {+ const workspace = await makeWorkspace();+ try {+ const recoveredPath = join(workspace, '.agent-done-agent-ded2dcc');+ await writeFile(recoveredPath, 'stale');+ const old = new Date(Date.now() - 60_000);+ await utimes(recoveredPath, old, old);++ const staleAccess = createAgentSentinelAccess({+ workspacePath: workspace,+ agentId: AGENT_ID,+ startedAt: Date.now() - 1000,+ getActiveAgentIds: () => [AGENT_ID],+ });+ expect(staleAccess.exists()).toBe(false);++ await writeFile(recoveredPath, 'sibling');+ const siblingAccess = createAgentSentinelAccess({+ workspacePath: workspace,+ agentId: AGENT_ID,+ startedAt: Date.now() - 1000,+ getActiveAgentIds: () => [AGENT_ID, 'agent-ded2dcc'],+ });+ expect(siblingAccess.exists()).toBe(false);+ } 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 {+ const access = createAgentSentinelAccess({+ workspacePath: workspace,+ agentId: AGENT_ID,+ startedAt: Date.now() - 1000,+ getActiveAgentIds: () => [AGENT_ID],+ });+ const detected = new Promise((resolve) => access.watch(resolve, { settleMs: 0, pollMs: 10 }));+ await writeFile(join(workspace, '.agent-done-agent-ded2dcc'), 'done');+ await expect(Promise.race([+ detected,+ new Promise((_, reject) => setTimeout(() => reject(new Error('sentinel was not detected')), 1000)),+ ])).resolves.toBe(join(workspace, '.agent-done-agent-ded2dcc'));+ } finally {+ await rm(workspace, { recursive: true, force: true });+ }+ });+});+diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex c20a42f882..b7e91f846d 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -24,8 +24,6 @@*/import { join } from 'path';-import { existsSync } from 'fs';-import { readFile, rm } from 'fs/promises';import * as shellService from './shell.js';import { emitLog } from './cosEvents.js';import { updateAgent } from './cosAgentLifecycle.js';@@ -36,9 +34,10 @@ import { buildTuiSpawnConfig } from './agentTuiSpawning/spawnConfig.js';import { finalizeAgent } from './agentFinalization.js';import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';import { activeAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';-import { PATHS, watchForFile } from '../lib/fileUtils.js';+import { PATHS } from '../lib/fileUtils.js';import { resolveAgentCliCwd } from '../lib/spawnCwd.js';import { doneSentinelPath as resolveDoneSentinelPath } from '../lib/agentSentinel.js';+import { createAgentSentinelAccess } from './agentSentinelWatcher.js';import { PTY_UNAVAILABLE_PREFIX } from '../lib/ptySpawnDiagnostics.js';import { finalizeAgentRunCommon, shouldAbandonAgentRun } from './agentRunFinalize.js';import { leavesPrForHuman } from '../lib/prDisposition.js';@@ -304,6 +303,12 @@ export async function spawnTuiAgent({// exit) finalizes first. Resolved from the shared helper, so this is// byte-identical to the path the prompt told the agent to write.const doneSentinelPath = resolveDoneSentinelPath(cwd, agentId);+ const sentinelAccess = createAgentSentinelAccess({+ workspacePath: cwd,+ agentId,+ startedAt: Date.now(),+ getActiveAgentIds: () => activeAgents.keys(),+ });// Every TUI that is a real coding harness drives its own push → PR → review// → merge, whether or not it can type `/do:pr` (#3733) — a Claude TUI runs// the slashdo command (`prOpenedBy: 'agent-slashdo'`),@@ -381,10 +386,13 @@ export async function spawnTuiAgent({},sentinel: {path: doneSentinelPath,- exists: () => !!doneSentinelPath && existsSync(doneSentinelPath),- read: () => readFile(doneSentinelPath, 'utf8'),- remove: () => (doneSentinelPath ? rm(doneSentinelPath).catch(() => {}) : Promise.resolve()),- watch: (onDetect) => (doneSentinelPath ? watchForFile(doneSentinelPath, onDetect) : null),+ exists: sentinelAccess.exists,+ resolvedPath: sentinelAccess.resolvedPath,+ read: () => sentinelAccess.read(),+ remove: () => sentinelAccess.remove(),+ promote: (contents) => sentinelAccess.promote(contents),+ cleanup: () => sentinelAccess.cleanup(),+ watch: (onDetect) => sentinelAccess.watch(onDetect),},finalization: {finalizeAgent,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex c2b0e95de0..c364d651b1 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -147,6 +147,7 @@ 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),+ statSync: vi.fn().mockReturnValue({ isFile: () => true, mtimeMs: Date.now() }),watch: vi.fn(() => {let onClose;return {@@ -238,7 +239,7 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => {return { ...actual, execFile: vi.fn((_file, _args, _opts, cb) => cb(new Error('not mocked'))) };});-import { existsSync } from 'fs';+import { existsSync, statSync } from 'fs';import { readFile, rm } from 'fs/promises';import { execFile } from '../lib/childProcess.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';@@ -808,6 +809,7 @@ describe('spawnTuiAgent runtime', () => {// completion-sentinel test overrides both. clearAllMocks keeps the factory// implementation, so re-set explicitly to prevent cross-test leakage.vi.mocked(existsSync).mockReturnValue(false);+ vi.mocked(statSync).mockReturnValue({ isFile: () => true, mtimeMs: Date.now() });vi.mocked(readFile).mockResolvedValue('');});@@ -2925,6 +2927,36 @@ describe('spawnTuiAgent runtime', () => {expect(outputTxtWrites).toContain('https://example.com/pr/42');});+ it('finalizes a one-character-truncated sentinel and stops the idle nudge loop', async () => {+ const truncatedName = '.agent-done-agent-ded2dcc';+ const sentinel = '## Summary\nRecovered after a terminal path truncation.';+ vi.mocked(existsSync).mockImplementation((filePath) =>+ filePath === '/tmp/ws' || (typeof filePath === 'string' && filePath.endsWith(truncatedName))+ );+ vi.mocked(readFile).mockImplementation(async (filePath) =>+ typeof filePath === 'string' && filePath.endsWith(truncatedName) ? sentinel : ''+ );++ const spawnPromise = runSpawn({ agentId: 'agent-ded2dccb', workspacePath: '/tmp/ws' });+ await flushMicrotasks();+ await capturedOnExit({ exitCode: 0, killed: false });+ await spawnPromise;+ await vi.advanceTimersByTimeAsync(1000);+ await flushMicrotasks();++ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-ded2dccb',+ success: true,+ completionReason: 'agent-signaled-done',+ }),+ );++ const pasteCount = vi.mocked(shellService.pasteToSession).mock.calls.length;+ await vi.advanceTimersByTimeAsync(STALL_NUDGE_IDLE_MS * (STALL_NUDGE_MAX_ATTEMPTS + 1));+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(pasteCount);+ });+// ── 11. A PortOS host restart is an interruption, never a completion ─────────//// Reported in #3202: `pm2 restart portos-server` TreeKills the agent's PTY.diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.jsindex e5b6c1ddf8..88be0f1ad5 100644--- a/server/services/agentTuiSpawning/sessionController.js+++ b/server/services/agentTuiSpawning/sessionController.js@@ -699,6 +699,16 @@ export function createTuiSessionController({console.error(`❌ ingestDoneSentinel readFile failed: ${err.message}`);return '';});+ // A terminal-copy recovery name is accepted only by the run-scoped+ // 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?.();+ if (sentinel.promote && sentinelSourcePath && sentinelSourcePath !== sentinel.path) {+ await sentinel.promote(contents).catch(err => {+ console.error(`❌ ingestDoneSentinel canonical promotion failed: ${err.message}`);+ });+ }// A programmatic-I/O task type writes a JSON `{ summary, payload }` sentinel;// append only the human `summary` to the agent output (the structured// `payload` is consumed separately by the task type's processTaskOutput hook,@@ -817,6 +827,9 @@ export function createTuiSessionController({noChangesToShip,outputBuffer: getOutputBuffer(),}).catch(err => emitLog('warn', `TUI completion cleanup failed for ${agentId}: ${err.message}`, { agentId }));+ if (sentinel.cleanup) {+ await sentinel.cleanup().catch(err => emitLog('warn', `TUI recovery sentinel cleanup failed for ${agentId}: ${err.message}`, { agentId }));+ }persistence.releaseRunRecord(agentData?.pid ?? null);if (sessionId && session.isAlive(sessionId)) session.kill(sessionId);diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 94821a4165..b02bbc60de 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -13,7 +13,7 @@ import { existsSync, realpathSync } from 'fs';import { lstat, readlink, readdir, rm, stat, symlink, unlink } from 'fs/promises';import { dirname, isAbsolute, join, resolve } from 'path';import { ensureDir, isPathInsideDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';-import { DONE_SENTINEL_NAME, doneSentinelName } from '../lib/agentSentinel.js';+import { DONE_SENTINEL_NAME, doneSentinelCandidateNames } from '../lib/agentSentinel.js';import { AGENT_SCRATCH_PATHS, matchesScratchRoot } from '../lib/agentScratchPaths.js';import { execGit } from '../lib/execGit.js';import { clearStaleGitLock } from '../lib/gitStaleLock.js';@@ -970,10 +970,11 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio// by finalizeAgent before this cleanup runs. Ignore it for the preservation// decision, while still preserving the tree if any real change remains; the// eventual forced worktree removal discards it with the rest of the completed- // checkout. Both names — THIS run's `.agent-done-<agentId>` and the legacy- // shared one a pre-upgrade run may have left — and no other agent's.+ // checkout. The run's canonical name and its bounded truncation-recovery+ // name, plus the legacy shared one a pre-upgrade run may have left — and no+ // other agent's.const dirt = classifyWorktreeDirt(dirtyFiles, {- ignoredPaths: [DONE_SENTINEL_NAME, doneSentinelName(agentId)]+ ignoredPaths: [DONE_SENTINEL_NAME, ...doneSentinelCandidateNames(agentId)]});if (!dirt.clean && options.discardDirt) {// Throwaway posture: the caller has already established that nothing in this