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

delete the .agent-done sentinel on every completion path, not just the TUI one

[._.]/ Adam Eivy5880b2965228
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 5bc5c758a5..90e07cf71b 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -792,6 +792,7 @@ export async function spawnDirectly({
await runSpawnerCompletionCleanup({
agentId,
task,
+ workspacePath: cwd,
success: cleanupSuccess,
prOwnership,
prClaimVerified,
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index 6229b39675..2354006ebb 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -33,7 +33,8 @@ import { emitLog } from './cosEvents.js';
import { updateAgent } from './cosAgentLifecycle.js';
import { updateTask, addTask, reviveBlockedTask, checkStagePrecondition } from './cos.js';
import { PIPELINE_STAGE_BEHAVIOR_FLAGS, normalizeReviewers } from '../lib/validation.js';
-import { PATHS, tryReadFile } from '../lib/fileUtils.js';
+import { PATHS, rmGuarded, tryReadFile } from '../lib/fileUtils.js';
+import { doneSentinelPath as resolveDoneSentinelPath } from '../lib/agentSentinel.js';
import * as jiraService from './jira.js';
import * as git from './git.js';
import { isTruthyMeta } from './agentState.js';
@@ -323,6 +324,11 @@ async function runCompletionCleanupSteps(context) {
await runStep('Creative Director completion', () => advanceCreativeDirectorIfNeeded(context));
const cleanupWarnings = await runStep('Worktree cleanup', () => completeWorktreeCleanup(context));
await runStep('Cleanup warning reporting', () => reportWorktreeCleanupWarnings({ ...context, cleanupWarnings }));
+ // Last, and never fatal: `runStep` RETHROWS on the runner path
+ // (`continueOnError` is unset there), so a janitorial `rm` that hits EPERM
+ // must not be able to abort the worktree cleanup and pipeline hand-off above.
+ await removeCompletionSentinel(context)
+ .catch(err => emitLog('warn', `Completion sentinel removal failed for ${context.agentId}: ${err.message}`, { agentId: context.agentId }));
}
function resolveRunnerPrOwnership({ task, agent, agentState }) {
@@ -474,6 +480,31 @@ async function advanceCreativeDirectorIfNeeded({ agentId, task, effectiveSuccess
}
}
+/**
+ * Delete the run's own `.agent-done-<agentId>` completion sentinel.
+ *
+ * The sentinel is a runtime signal, not a work product: once a run has an
+ * outcome nothing reads it again, and a worktree-LESS run (the issue-filing,
+ * reasoning and read-only audit task types) executes in a real checkout — this
+ * repo, or a managed app's own — where it would otherwise sit in the user's
+ * `git status` as untracked dirt, one file per run, forever.
+ *
+ * Pause and host-shutdown abandon both return before any completion cleanup
+ * runs (`finalizeAgentRunCommon`), and a run is abandoned only when it wrote no
+ * sentinel at all (`shouldAbandonForHostShutdown`) — so this never eats a
+ * signal a resume still needs.
+ *
+ * `workspacePath` is the spawner's own cwd, authoritative for the run it is
+ * finalizing; the runner-event path has none and falls back to the workspace
+ * the agent record stamped at registration.
+ */
+export async function removeCompletionSentinel({ agentId, agent, agentState, workspacePath }) {
+ const workspace = workspacePath || agentState?.metadata?.workspacePath || agent?.workspacePath || null;
+ if (!workspace) return;
+ // `rmGuarded`, like the stale-sentinel sweep that deletes these same files.
+ await rmGuarded(resolveDoneSentinelPath(workspace, agentId), { force: true });
+}
+
async function completeWorktreeCleanup({ agentId, task, agent, agentState, effectiveSuccess, prOwnership, outputBuffer, prClaimVerified, noChangesToShip }) {
if (task?.metadata?.jiraBranch) return;
const ownership = prOwnership ?? resolveRunnerPrOwnership({ task, agent, agentState });
@@ -521,19 +552,22 @@ async function reportWorktreeCleanupWarnings({ agentId, task, cleanupWarnings })
* Retry-hold release remains in a `finally`: even a skipped JIRA worktree or
* a failed hand-off must release the task with the resume pointer cleanup left.
*
+ * `workspacePath` is the spawner's own cwd, so sentinel removal still works
+ * when the persisted record cannot be read.
+ *
* `prOwnership` is `resolvePrOwnership`'s answer for this run;
* `prClaimVerified` / `noChangesToShip` are read off finalize's return.
* `success` is the verdict finalize actually persisted — a PR-claim downgrade
* must reach cleanup, or a run that opened no PR is cleaned up as a success and
* loses its retry state (#3358).
*/
-export async function runSpawnerCompletionCleanup({ agentId, task, success, prOwnership, prClaimVerified = false, noChangesToShip = false, outputBuffer }) {
+export async function runSpawnerCompletionCleanup({ agentId, task, success, prOwnership, prClaimVerified = false, noChangesToShip = false, outputBuffer, workspacePath = null }) {
try {
const { getAgent } = await import('./cos.js');
const agentState = await getAgent(agentId).catch(() => null);
await runCompletionCleanupSteps({
agentId, task, agentState, effectiveSuccess: success, prOwnership,
- prClaimVerified, noChangesToShip, outputBuffer, continueOnError: true,
+ prClaimVerified, noChangesToShip, outputBuffer, workspacePath, continueOnError: true,
});
} finally {
await releaseRetryHold({ agentId, task, success })
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
index 7a0a0d4a87..d061f86fe7 100644
--- a/server/services/agentCompletionCleanup.test.js
+++ b/server/services/agentCompletionCleanup.test.js
@@ -672,6 +672,19 @@ describe.each(['runner', 'spawner'])('%s completion side effects', (path) => {
expect(spawnMergeRecoveryTask).toHaveBeenCalledWith(warnings, 'a1', expect.objectContaining({ id: 't' }), 'Example App', '/example/repo');
});
+ // Only the TUI spawner used to delete it, so every direct-CLI and
+ // runner-owned run left one untracked file behind — in a REAL checkout, for a
+ // worktree-less run (issue-filing, reasoning, read-only audits).
+ it("removes this run's completion sentinel and leaves a concurrent sibling's alone", async () => {
+ await writeFile(join(workspace, '.agent-done-a1'), '## Summary\nDid the example work');
+ await writeFile(join(workspace, '.agent-done-a2'), '## Summary\nStill working');
+
+ await complete({});
+
+ await expect(readFile(join(workspace, '.agent-done-a1'))).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(await readFile(join(workspace, '.agent-done-a2'), 'utf8')).toContain('Still working');
+ });
+
it('turns the plan-question marker into a notification and consumes it before cleanup', async () => {
const marker = '# Plan Question: Choose the example scope\nPlease clarify the example.';
await writeFile(join(workspace, '.plan-questions.md'), marker);
@@ -685,3 +698,22 @@ describe.each(['runner', 'spawner'])('%s completion side effects', (path) => {
expect(addNotification.mock.invocationCallOrder[0]).toBeLessThan(cleanupAgentWorktree.mock.invocationCallOrder[0]);
});
});
+
+// The spawner passes its own cwd, so a run whose persisted record cannot be read
+// still has its sentinel removed rather than leaking one into a real checkout.
+describe('spawner sentinel removal without a persisted record', () => {
+ it('falls back to the cwd the spawner ran in', async () => {
+ const workspace = await mkdtemp(join(tmpdir(), 'completion-sentinel-'));
+ getAgent.mockResolvedValue(null);
+ await writeFile(join(workspace, '.agent-done-a1'), '## Summary\nDone');
+
+ await runSpawnerCompletionCleanup({
+ agentId: 'a1', task: { id: 't', metadata: {} }, success: true, outputBuffer: '',
+ prOwnership: { taskOpenPR: false, agentOpensOwnPr: false },
+ workspacePath: workspace,
+ });
+
+ await expect(readFile(join(workspace, '.agent-done-a1'))).rejects.toMatchObject({ code: 'ENOENT' });
+ await rm(workspace, { recursive: true, force: true });
+ });
+});
diff --git a/server/services/agentCompletionRouting.test.js b/server/services/agentCompletionRouting.test.js
index 7810203b86..6c7cd596bb 100644
--- a/server/services/agentCompletionRouting.test.js
+++ b/server/services/agentCompletionRouting.test.js
@@ -55,6 +55,7 @@ vi.mock('./agentWorktreeCleanup.js', () => ({
vi.mock('./agentCompletionCleanup.js', () => ({
runAgentCompletionCleanup: vi.fn().mockResolvedValue(undefined),
+ removeCompletionSentinel: vi.fn().mockResolvedValue(undefined),
}));
import { handleAgentCompletion } from './agentLifecycle.js';
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 0977d08ffd..dfb41d0a8f 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -750,6 +750,11 @@ export function dispatchTaskOutputHookOnce({
* Recovery paths try the agent's persisted workspace when it still exists.
* When it does not, only hooks whose registry contract says they are
* payload-independent may run with null output.
+ *
+ * Returns the deduped dispatch promise ITSELF — concurrent normal/recovery
+ * completions must share one, and a timed-out hook stays recoverable until that
+ * original settles — so this stays a pass-through with no side effects of its
+ * own. Sentinel retirement lives at the two recovery call sites, after the read.
*/
export function dispatchRecoveredTaskOutputHook({ agentId, task, success, workspacePath = null }) {
return dispatchTaskOutputHookOnce({
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 93543b4bd2..93db28be80 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -91,7 +91,7 @@ import { cloudSwarmThreadCapacity, localEndpointOfProvider, providerBaseUrl } fr
import { describeLocalPromptBudget, planLocalPromptBudget } from '../lib/localPromptBudget.js';
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
import { releaseRetryHold } from './agentWorktreeCleanup.js';
-import { runAgentCompletionCleanup } from './agentCompletionCleanup.js';
+import { runAgentCompletionCleanup, removeCompletionSentinel } from './agentCompletionCleanup.js';
import { dispatchRecoveredTaskOutputHook, finalizeAgent, releaseAgentLane, stampLiExecutionVerdict } from './agentFinalization.js';
import { extractFinalSummary } from './agentSummaryExtraction.js';
import { handleOrphanedTask } from './agentManagement.js';
@@ -1204,6 +1204,11 @@ async function completeUntrackedAgentFromCosState(agentId, exitCode, success, du
success,
workspacePath: cosAgent.metadata?.workspacePath || null,
});
+ // Recovery retires the run without reaching finalizeAgent's completion
+ // cleanup, so the sentinel has no other owner — and the hook above was the
+ // last thing to read it. Mirrored in agentManagement's orphan sweep.
+ await removeCompletionSentinel({ agentId, agentState: cosAgent })
+ .catch(err => emitLog('warn', `Completion sentinel removal failed for ${agentId}: ${err.message}`, { agentId }));
await completeAgent(agentId, {
success,
exitCode,
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 4b2186af30..fc8d847b54 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -39,6 +39,7 @@ import { completeAgentRun } from './agentRunTracking.js';
import { appendRunEvent } from './agentRunEventLog.js';
import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';
import { dispatchRecoveredTaskOutputHook } from './agentFinalization.js';
+import { removeCompletionSentinel } from './agentCompletionCleanup.js';
import { fileInvestigationTask } from './investigationTaskProducer.js';
import { buildInvestigationFingerprint } from '../lib/investigationTasks.js';
import { PATHS, tryReadFile } from '../lib/fileUtils.js';
@@ -1285,6 +1286,12 @@ async function runCleanupOrphanedAgents() {
success: false,
workspacePath: agent.metadata?.workspacePath || null,
});
+ // Same reason as the post-restart recovery in agentLifecycle.js: this
+ // sweep retires the run without reaching completion cleanup, and the hook
+ // above was the last sentinel read. A hard kill (`pm2 restart`, reboot)
+ // lands here, so this is the path that leaves dirt in a managed app repo.
+ await removeCompletionSentinel({ agentId: agent.id, agentState: agent })
+ .catch(err => emitLog('warn', `Completion sentinel removal failed for ${agent.id}: ${err.message}`, { agentId: agent.id }));
if (agent.metadata?.runId) {
const bufferedOutput = Array.isArray(agent.output)
? agent.output.map((entry) => typeof entry === 'string' ? entry : entry?.line).filter(Boolean).join('\n')
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 49255d1af8..cb639bb465 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -29,6 +29,8 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ChildProcess } from '../lib/childProcess.js';
import { readFileSync } from 'fs';
+import { mkdtemp, writeFile, readFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
@@ -247,6 +249,32 @@ describe('cleanupOrphanedAgents — startup recovery coordination', () => {
}));
});
+ // A hard kill (`pm2 restart`, SIGKILL, reboot) never reaches completion
+ // cleanup, so this sweep is the path that retires the run — and a
+ // worktree-less run executes in a REAL checkout (the PortOS repo or a managed
+ // app's own), where a skipped sentinel is untracked dirt in the user's repo.
+ it("removes the reaped run's completion sentinel from its workspace", async () => {
+ const workspace = await mkdtemp(join(tmpdir(), 'orphan-sentinel-'));
+ await writeFile(join(workspace, '.agent-done-agent-stale'), '## Summary\nDied mid-run');
+ getAgents.mockResolvedValueOnce([{
+ id: 'agent-stale',
+ status: 'running',
+ pid: 2147483646,
+ taskId: 'task-1',
+ metadata: { useRunner: true, executionMode: 'runner', workspacePath: workspace },
+ }]);
+ getActiveAgentsFromRunner.mockResolvedValueOnce([{
+ id: 'agent-stale', pid: 2147483646, kind: 'cli', processActive: false, liveness: 'pid',
+ }]);
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });
+
+ await cleanupOrphanedAgents();
+
+ await expect(readFile(join(workspace, '.agent-done-agent-stale')))
+ .rejects.toMatchObject({ code: 'ENOENT' });
+ await rm(workspace, { recursive: true, force: true });
+ });
+
it('does not reap a live runner-owned TUI advertised via onExit liveness', async () => {
getAgents.mockResolvedValueOnce([{
id: 'agent-tui',
diff --git a/server/services/agentSentinelSweep.js b/server/services/agentSentinelSweep.js
index daa1fd4375..2d316a6ae4 100644
--- a/server/services/agentSentinelSweep.js
+++ b/server/services/agentSentinelSweep.js
@@ -1,15 +1,19 @@
/**
* Stale `.agent-done-*` sentinel sweep.
*
- * A run's own finalize path deletes its sentinel (`releaseRunResources` in
- * agentTuiSpawning, and the CLI/finalization equivalents), so in the happy case
- * nothing is left behind. Three paths deliberately or unavoidably skip that:
+ * A run that reaches an outcome deletes its own sentinel: every completion path
+ * — the TUI spawner, the direct-CLI spawner, and the runner-event path — funnels
+ * through `removeCompletionSentinel` in agentCompletionCleanup.js, and the
+ * post-restart recovery in agentLifecycle.js removes it too. So in the happy
+ * case nothing is left behind. What still can be:
*
- * - a host shutdown ABANDONS the run and preserves the sentinel on purpose,
- * because the resume needs it (#3202);
* - a hard kill (`pm2 restart`, SIGKILL, a machine reboot) never reaches any
* cleanup at all;
- * - the file only vanishes with the worktree for worktree-backed runs.
+ * - a host shutdown ABANDONS the run rather than finalizing it (#3202), so no
+ * completion cleanup runs — the abandon gate only fires when the run wrote
+ * NO sentinel, but a race can still strand one;
+ * - a completion whose sentinel removal failed (an unreadable agent record,
+ * a transient I/O error).
*
* Worktree-less agents share a real checkout — the PortOS repo, or a managed
* app's own repo — so for them a skipped cleanup leaves an untracked file in the
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 74be91f0c1..aba364ab0b 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -1035,17 +1035,14 @@ export async function spawnTuiAgent({
* the shell session on disk.
*/
const releaseRunResources = async ({ agentData, cleanupSuccess, prOwnership, prClaimVerified, noChangesToShip }) => {
- // This run's sentinel only — a sibling agent sharing this workspace owns
- // its own file and may still be running.
- if (doneSentinelPath) await rm(doneSentinelPath).catch(() => {});
-
// Pipeline progression → worktree cleanup with the PR disposition →
- // retry-hold release, in the one owner both in-process spawners share.
- // Caught so a throw there cannot skip the in-memory teardown below — this
- // runs off a PTY exit, outside any request lifecycle.
+ // sentinel removal → retry-hold release, in the one owner every completion
+ // path shares. Caught so a throw there cannot skip the in-memory teardown
+ // below — this runs off a PTY exit, outside any request lifecycle.
await runSpawnerCompletionCleanup({
agentId,
task,
+ workspacePath: cwd,
success: cleanupSuccess,
prOwnership,
prClaimVerified,