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
keep the sentinel when finalize threw before recording an outcome
[._.]/ Adam Eivyc0961b29d6c7
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 90e07cf71b..5bc5c758a5 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -792,7 +792,6 @@ 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.jsindex d3be827f36..0aeb441f5b 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -34,7 +34,7 @@ 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, rmGuarded, tryReadFile } from '../lib/fileUtils.js';-import { doneSentinelPath as resolveDoneSentinelPath } from '../lib/agentSentinel.js';+import { DONE_SENTINEL_NAME, doneSentinelName, doneSentinelPath as resolveDoneSentinelPath } from '../lib/agentSentinel.js';import * as jiraService from './jira.js';import * as git from './git.js';import { isTruthyMeta } from './agentState.js';@@ -327,8 +327,20 @@ async function runCompletionCleanupSteps(context) {// 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 }));+ //+ // Gated on the record actually reaching an outcome. `finalizeAgent` runs+ // `persistSimplifySummaries` and `resolveFailedTaskUpdate` BEFORE it+ // dispatches the output hook and calls `completeAgent`; a throw in either+ // leaves the record `running`, and the orphan sweep's recovery hook is then+ // what salvages the run — for a programmatic-I/O type the sentinel IS the+ // deliverable it reads (an LI proposal, an issue-filing payload). Both+ // spawners run this from a `finally`, so they reach here on exactly that+ // path. An unreadable record counts as not-over: leaving the file for the+ // stale sweep is the recoverable direction, destroying a deliverable is not.+ if (context.agentState?.status === 'completed') {+ await removeCompletionSentinel(context)+ .catch(err => emitLog('warn', `Completion sentinel removal failed for ${context.agentId}: ${err.message}`, { agentId: context.agentId }));+ }}function resolveRunnerPrOwnership({ task, agent, agentState }) {@@ -494,17 +506,18 @@ async function advanceCreativeDirectorIfNeeded({ agentId, task, effectiveSuccess* 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.+ * The workspace comes from the agent record — the cwd stamped at registration,+ * which is the directory the run wrote its sentinel into (a worktree run+ * records its worktree here).*/-export async function removeCompletionSentinel({ agentId, agent, agentState, workspacePath }) {- // A missing id makes `doneSentinelName` fall back to the bare, unscoped- // `.agent-done` — which belongs to no run and may be a legacy agent's live- // signal. The sweep protects it with an age floor for exactly that reason, so- // never let a resolution failure here aim at it.- if (typeof agentId !== 'string' || !agentId.trim()) return;- const workspace = workspacePath || agentState?.metadata?.workspacePath || agent?.workspacePath || null;+export async function removeCompletionSentinel({ agentId, agent, agentState }) {+ // An id that yields no usable slug makes `doneSentinelName` fall back to the+ // bare, unscoped `.agent-done` — which belongs to no run and may be a legacy+ // agent's live signal (the sweep protects it with an age floor for exactly+ // that reason). Ask the producer rather than re-deriving its rule: the+ // fallback fires on a blank id AND on one whose sanitized slug is empty.+ if (typeof agentId !== 'string' || doneSentinelName(agentId) === DONE_SENTINEL_NAME) return;+ const workspace = 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 });@@ -557,22 +570,19 @@ 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, workspacePath = null }) {+export async function runSpawnerCompletionCleanup({ agentId, task, success, prOwnership, prClaimVerified = false, noChangesToShip = false, outputBuffer }) {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, workspacePath, continueOnError: true,+ prClaimVerified, noChangesToShip, outputBuffer, continueOnError: true,});} finally {await releaseRetryHold({ agentId, task, success })diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex 2f7c6c1c19..f3398abefd 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -623,7 +623,7 @@ describe.each(['runner', 'spawner'])('%s completion side effects', (path) => {beforeEach(async () => {workspace = await mkdtemp(join(tmpdir(), 'completion-test-'));- getAgent.mockResolvedValue({ metadata: { workspacePath: workspace, sourceWorkspace: '/example/repo' }, result: { success: true } });+ getAgent.mockResolvedValue({ status: 'completed', metadata: { workspacePath: workspace, sourceWorkspace: '/example/repo' }, result: { success: true } });git.push.mockResolvedValue({});git.getRepoBranches.mockResolvedValue({ baseBranch: 'main', devBranch: 'develop' });git.generatePRDescription.mockResolvedValue('Example changes');@@ -699,34 +699,47 @@ describe.each(['runner', 'spawner'])('%s completion side effects', (path) => {});});-// 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');+// `finalizeAgent` runs persistSimplifySummaries and resolveFailedTaskUpdate+// BEFORE it dispatches the output hook and calls completeAgent, and both+// spawners run cleanup from a `finally` — so a throw in either lands here with+// the record still `running`. The orphan sweep's recovery hook is what salvages+// that run, and for a programmatic-I/O type the sentinel IS the deliverable it+// reads, so retiring it here would destroy an LI proposal or filing payload.+describe('completion sentinel survives a finalize that recorded no outcome', () => {+ let workspace;+ beforeEach(async () => { workspace = await mkdtemp(join(tmpdir(), 'completion-unfinalized-')); });+ afterEach(async () => { await rm(workspace, { recursive: true, force: true }); });- await runSpawnerCompletionCleanup({- agentId: 'a1', task: { id: 't', metadata: {} }, success: true, outputBuffer: '',+ const cleanupWithStatus = (status) => {+ getAgent.mockResolvedValue({ status, metadata: { workspacePath: workspace } });+ return runSpawnerCompletionCleanup({+ agentId: 'a1', task: { id: 't', metadata: {} }, success: false, outputBuffer: '',prOwnership: { taskOpenPR: false, agentOpensOwnPr: false },- workspacePath: workspace,});+ };+ it('keeps the sentinel while the record is still running', async () => {+ await writeFile(join(workspace, '.agent-done-a1'), '{"summary":"x","payload":{"title":"proposal"}}');+ await cleanupWithStatus('running');+ expect(await readFile(join(workspace, '.agent-done-a1'), 'utf8')).toContain('proposal');+ });++ it('removes it once the record reached an outcome', async () => {+ await writeFile(join(workspace, '.agent-done-a1'), '{"summary":"x","payload":{"title":"proposal"}}');+ await cleanupWithStatus('completed');await expect(readFile(join(workspace, '.agent-done-a1'))).rejects.toMatchObject({ code: 'ENOENT' });- await rm(workspace, { recursive: true, force: true });});});-// `doneSentinelName` falls back to the bare, unscoped `.agent-done` for a-// missing id — a file that belongs to no run and that the stale sweep protects-// with an age floor precisely because it can never be matched to one.+// `doneSentinelName` falls back to the bare, unscoped `.agent-done` whenever the+// SANITIZED slug is empty — not only for a blank id. That file belongs to no run+// and the stale sweep protects it with an age floor for exactly that reason.describe('completion sentinel removal never targets the unscoped sentinel', () => {- it('does nothing when the run has no agent id', async () => {+ it.each([[' '], ['/'], ['...']])('does nothing for an id with no usable slug (%j)', async (agentId) => {const workspace = await mkdtemp(join(tmpdir(), 'completion-unscoped-'));await writeFile(join(workspace, '.agent-done'), '## Summary\nA legacy run still going');- await removeCompletionSentinel({ agentId: ' ', workspacePath: workspace });+ await removeCompletionSentinel({ agentId, agentState: { metadata: { workspacePath: workspace } } });expect(await readFile(join(workspace, '.agent-done'), 'utf8')).toContain('still going');await rm(workspace, { recursive: true, force: true });diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex aba364ab0b..fdb88c367c 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -1042,7 +1042,6 @@ export async function spawnTuiAgent({await runSpawnerCompletionCleanup({agentId,task,- workspacePath: cwd,success: cleanupSuccess,prOwnership,prClaimVerified,