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: retire queued review tasks after PR completion
[._.]/ Adam Eivy5d94dd11158e
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 17c432fdef..7975e68a67 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -505,11 +505,14 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore* via `completeAgent` — which takes the same non-reentrant `withStateLock`, so* running either inside would deadlock. Resolving first is also what keeps the task* from ever being `pending` (spawnable) without its pointer.+ *+ * `expectedStatus`, when supplied, is checked under the task-file lock. A mismatch+ * returns `{ statusChanged: true }` without writing or retiring pause state.*/-export async function updateTask(taskId, updates, taskType = 'user', { now = Date.now(), suppressDequeue = false } = {}) {+export async function updateTask(taskId, updates, taskType = 'user', { now = Date.now(), suppressDequeue = false, expectedStatus = null } = {}) {const release = await preparePauseRelease(taskId, updates);- const result = await writeTaskUpdate(taskId, release ? { ...updates, metadata: release.metadata } : updates, taskType, { now, suppressDequeue });- if (release && !result?.error) {+ const result = await writeTaskUpdate(taskId, release ? { ...updates, metadata: release.metadata } : updates, taskType, { now, suppressDequeue, expectedStatus });+ if (release && !result?.error && !result?.statusChanged) {await retirePausedAgent(release.agentId, taskId, resolveTaskTargetBranch(result?.metadata));}return result;@@ -613,7 +616,7 @@ function mergeUpdateMetadata(existingMetadata, updates) {return merged;}-async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue = false }) {+async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue = false, expectedStatus = null }) {return withStateLock(async () => {const state = await loadState();const filePath = taskType === 'user'@@ -633,6 +636,13 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeuereturn { error: 'Task not found' };}+ // Deterministic sweepers can retire a queued task only while it is still+ // pending. Check under the same lock as the write so a concurrent dequeue or+ // user action cannot be overwritten by a stale queue snapshot.+ if (expectedStatus && tasks[taskIndex].status !== expectedStatus) {+ return { statusChanged: true, task: tasks[taskIndex] };+ }+const updatedMetadata = mergeUpdateMetadata(tasks[taskIndex].metadata, updates);// Ask "what status transition is this?" ONCE. Every lifecycle rule below reads adiff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 7a6e48ec5e..5cc4e0a854 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -164,6 +164,22 @@ describe('cosTaskStore.firstLine', () => {});});+describe('cosTaskStore.updateTask expectedStatus', () => {+ it('does not apply a stale terminal update after a task has been claimed', async () => {+ const task = await addTask({ id: 'sys-rl-cas', description: 'Resolve a PR' }, 'internal');+ await updateTask(task.id, { status: 'in_progress' }, 'internal');+ mock.events = [];++ const result = await updateTask(task.id, {+ status: 'completed', metadata: { reviewLoopRetiredReason: 'pull-request-merged-before-follow-up' },+ }, 'internal', { expectedStatus: 'pending' });++ expect(result).toMatchObject({ statusChanged: true, task: { status: 'in_progress' } });+ expect((await getTaskById(task.id)).status).toBe('in_progress');+ expect(mock.events).toEqual([]);+ });+});+describe('cosTaskStore.getUserTasks / getCosTasks', () => {it('returns an empty, non-existent result when the file is missing', async () => {const result = await getUserTasks();diff --git a/server/services/developmentWatchdog.js b/server/services/developmentWatchdog.jsindex 9022638086..b7804d49f3 100644--- a/server/services/developmentWatchdog.js+++ b/server/services/developmentWatchdog.js@@ -12,6 +12,27 @@ const tasksFrom = data => [...data.user.tasks, ...data.cos.tasks];const ownershipTask = (app, pr) => ({ metadata: { app: app.id, reviewLoopPRUrl: pr.url } });const parseGithubJson = value => safeJSONParse(value, null, { allowArray: false });+function reviewFollowUpPrNumber(task, target) {+ const metadata = task?.metadata || {};+ if (metadata.reviewLoopFollowUp !== true && metadata.reviewLoopFollowUp !== 'true') return null;+ let url;+ try { url = new URL(metadata.reviewLoopPRUrl || metadata.prUrl); } catch { return null; }+ const match = url.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:\/|$)/);+ if (!match || !['https:', 'http:'].includes(url.protocol)) return null;+ const host = url.hostname.toLowerCase();+ const expectedHost = String(target.webHost || target.apiHost || '').toLowerCase();+ if (expectedHost && host !== expectedHost) return null;+ if (metadata.reviewLoopPRHost && String(metadata.reviewLoopPRHost).toLowerCase() !== host) return null;+ const fullName = `${match[1]}/${match[2]}`.toLowerCase();+ const expectedName = String(target.fullName || '').toLowerCase();+ if (expectedName && fullName !== expectedName) return null;+ const urlNumber = Number(match[3]);+ const metadataNumber = Number(metadata.reviewLoopPRNumber);+ if (metadata.reviewLoopPRNumber != null && metadata.reviewLoopPRNumber !== ''+ && (!Number.isSafeInteger(metadataNumber) || metadataNumber !== urlNumber)) return null;+ return Number.isSafeInteger(urlNumber) && urlNumber > 0 ? urlNumber : null;+}+function authorized(state, appId, write = false) {const role = normalizePersistentMindMaintainer(state.config?.persistentMindMaintainer);const caps = normalizePersistentMindCapabilities(state.config?.persistentMindCapabilities);@@ -52,7 +73,7 @@ async function participatingPeerTasks() {return { tasks, blockers };}-async function inspectApp(app, tasks) {+async function inspectApp(app, tasks, localReviewTasks = [], activeAgentTaskIds = new Set()) {const { resolveAppForgeTarget } = await import('../lib/workTracker.js');const { listAppPullRequests } = await import('./appPullRequests.js');const { detectActionableWork, listConfiguredForgeIssues, issueNumberFromRef } = await import('./perpetualWork.js');@@ -62,7 +83,10 @@ async function inspectApp(app, tasks) {const { createGithubActorTrust } = await import('./forgeActorTrust.js');const { execGit } = await import('../lib/execGit.js');const { tracker, target } = await resolveAppForgeTarget(app);- const row = { appId: app.id, repository: target?.fullName || null, complete: false, blockers: [], pullRequests: [], issues: [], eligibleCount: 0 };+ const row = {+ appId: app.id, repository: target?.fullName || null, complete: false, blockers: [],+ pullRequests: [], issues: [], terminalReviewFollowUps: [], retiredReviewFollowUps: [], eligibleCount: 0,+ };// Other forge support remains explicit rather than silently using GitHub semantics.if (tracker !== 'github' || !target?.repoSpec) { row.blockers.push('unsupported-forge'); return row; }const account = target.fullName?.split('/')[0]?.toLowerCase() === 'atomantic' ? 'atomantic' : app.forgeAccount;@@ -109,6 +133,26 @@ async function inspectApp(app, tasks) {row.pullRequests.push({ number: pr.number, headSha: pr.headSha, fingerprint: JSON.stringify([pr.headSha, pr.reviewDecision, pr.mergeStateStatus, pr.checks, pr.labels]), disposition, taskId: owner?.id || null,reason: owner?.metadata?.blockedCategory || (disposition === 'unknown' ? 'external-claim-owner-unverified' : null), url: pr.url, headBranch: pr.headBranch, forkHead: pr.forkHead });}+ if (localReviewTasks.length) {+ const { getPullRequestState } = await import('./github.js');+ const openNumbers = new Set(row.pullRequests.map(pr => Number(pr.number)));+ const candidates = localReviewTasks.filter(task => task.status === 'pending'+ && task.metadata?.app === app.id && !activeAgentTaskIds.has(task.id))+ .map(task => ({ task, number: reviewFollowUpPrNumber(task, target) }))+ .filter(candidate => candidate.number && !openNumbers.has(candidate.number));+ const states = new Map();+ for (const candidate of candidates) {+ if (!states.has(candidate.number)) {+ states.set(candidate.number, await getPullRequestState(String(candidate.number), {+ cwd: app.repoPath, env: exec.env,+ }).catch(() => null));+ }+ const state = states.get(candidate.number);+ if (state?.status === 'known' && ['MERGED', 'CLOSED'].includes(state.state)) {+ row.terminalReviewFollowUps.push({ taskId: candidate.task.id, prNumber: candidate.number, prState: state.state });+ }+ }+ }row.eligibleCount = backlog.count || 0;const externalClaims = new Set([...branches.stdout.split('\n').map(line => line.trim().split(/\s+/).at(-1)?.replace(/^refs\/heads\//, '')),@@ -128,6 +172,24 @@ async function inspectApp(app, tasks) {return row;}+async function retireTerminalReviewFollowUps(app, row) {+ if (!row.terminalReviewFollowUps?.length) return;+ const { updateTask } = await import('./cosTaskStore.js');+ const activeAgentStatuses = new Set(['running', 'queued', 'finalizing', 'paused']);+ for (const followUp of row.terminalReviewFollowUps) {+ const current = await loadState();+ if (!authorized(current, app.id, true)) return;+ const hasAgent = Object.values(current.agents || {}).some(agent => agent.taskId === followUp.taskId+ && activeAgentStatuses.has(agent.status));+ if (hasAgent) continue;+ const reason = followUp.prState === 'MERGED' ? 'pull-request-merged-before-follow-up' : 'pull-request-closed-before-follow-up';+ const result = await updateTask(followUp.taskId, {+ status: 'completed', metadata: { reviewLoopRetiredReason: reason },+ }, 'internal', { expectedStatus: 'pending', suppressDequeue: true });+ if (result?.status === 'completed') row.retiredReviewFollowUps.push({ ...followUp, reason });+ }+}+async function dispatch(app, decision) {// Refresh grant, pause and ownership through the durable queue immediately// before a write. The queue's shared work-key admission is authoritative.@@ -226,12 +288,18 @@ async function scan({ dryRun = false, force = false, source = 'scheduled' } = {}} else {const { getActiveApps } = await import('./apps.js');const { getAllTasks } = await import('./cosTaskStore.js');- const tasks = tasksFrom(await getAllTasks());+ const taskSources = await getAllTasks();+ const tasks = tasksFrom(taskSources);+ const localReviewTasks = taskSources.cos?.tasks || [];const peers = await participatingPeerTasks();const allTasks = [...tasks, ...peers.tasks];const agents = Object.values(state.agents || {});// Include finalization and queued ownership, not only live subprocesses.const activeAgents = agents.filter(agent => ['running', 'queued', 'finalizing', 'paused'].includes(agent.status));+ const activeAgentTaskIds = new Set([+ ...activeAgents.map(agent => agent.taskId),+ ...allTasks.filter(task => ['queued', 'running', 'in_progress', 'finalizing', 'paused'].includes(task.status)).map(task => task.id),+ ].filter(Boolean));for (const agent of activeAgents) {const task = tasks.find(t => t.id === agent.taskId);if (task) allTasks.push({ ...task, status: 'running' });@@ -249,8 +317,13 @@ async function scan({ dryRun = false, force = false, source = 'scheduled' } = {}const app = apps.find(item => item.id === id);if (!app || !authorized(state, id)) { receipt.apps.push({ appId: id, complete: false, blockers: ['app-unavailable-or-not-granted'], pullRequests: [], issues: [] }); continue; }let row;- try { row = await inspectApp(app, allTasks); }+ try { row = await inspectApp(app, allTasks, localReviewTasks, activeAgentTaskIds); }catch { row = { appId: id, complete: false, blockers: ['source-unavailable'], pullRequests: [], issues: [] }; }+ if (row.complete && !dryRun && !peers.blockers.length && authorized(state, id, true)) {+ await retireTerminalReviewFollowUps(app, row).catch(err => {+ console.error(`❌ Development watchdog could not retire a completed PR follow-up: ${err.message}`);+ });+ }for (const pr of row.pullRequests) {const previous = state.developmentWatchdog?.dispatches?.[`${id}:pr:${pr.number}`];if (pr.disposition === 'eligible' && previous?.fingerprint === pr.fingerprint) {diff --git a/server/services/developmentWatchdog.test.js b/server/services/developmentWatchdog.test.jsindex a7b9b13124..122fc5a632 100644--- a/server/services/developmentWatchdog.test.js+++ b/server/services/developmentWatchdog.test.js@@ -1,8 +1,15 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-const m = vi.hoisted(() => ({ state: null, tasks: [], prs: [], backlog: [], peers: [], adds: [], save: vi.fn(), branch: '', account: 'atomantic', nextPrs: null, prReads: 0, dependencies: [], dependencyOpen: false, execGhFailureOn: null, invalidGhJsonOn: null, issueTruncated: false, readiness: { shouldRun: true }, requests: [], duplicate: false, prepare: vi.fn(), record: vi.fn(), execution: vi.fn(), metadata: vi.fn() }));+const m = vi.hoisted(() => ({ state: null, tasks: [], prs: [], backlog: [], peers: [], adds: [], updates: [], save: vi.fn(), branch: '', account: 'atomantic', nextPrs: null, prReads: 0, prStates: {}, dependencies: [], dependencyOpen: false, execGhFailureOn: null, invalidGhJsonOn: null, issueTruncated: false, readiness: { shouldRun: true }, requests: [], duplicate: false, prepare: vi.fn(), record: vi.fn(), execution: vi.fn(), metadata: vi.fn() }));vi.mock('./cosState.js', () => ({ loadState: async () => m.state, saveState: m.save, withStateLock: async fn => fn(), isImprovementEnabled: state => state.config.improvementEnabled }));vi.mock('./apps.js', () => ({ getActiveApps: async () => [{ id: 'app', name: 'Example', repoPath: '/example' }] }));-vi.mock('./cosTaskStore.js', () => ({ getAllTasks: async () => ({ user: { tasks: [] }, cos: { tasks: m.tasks } }), addTask: async task => { if (m.duplicate) return { id: 'existing', duplicate: true }; const result = { ...task, id: 'queued', status: 'pending' }; m.tasks.push(result); m.adds.push(result); return result; } }));+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: async () => ({ user: { tasks: [] }, cos: { tasks: m.tasks } }), updateTask: async (id, updates, type, options) => {+ m.updates.push({ id, updates, type, options });+ const task = m.tasks.find(item => item.id === id);+ if (!task) return { error: 'Task not found' };+ if (options?.expectedStatus && task.status !== options.expectedStatus) return { statusChanged: true, task };+ Object.assign(task, updates, { metadata: { ...task.metadata, ...updates.metadata } });+ return task;+}, addTask: async task => { if (m.duplicate) return { id: 'existing', duplicate: true }; const result = { ...task, id: 'queued', status: 'pending' }; m.tasks.push(result); m.adds.push(result); return result; } }));vi.mock('./instances.js', () => ({ getPeers: async () => m.peers }));vi.mock('../lib/workTracker.js', () => ({ resolveAppForgeTarget: async () => ({ tracker: 'github', target: { fullName: 'atomantic/example', repoSpec: 'github.com/atomantic/example', apiHost: 'github.com' } }) }));vi.mock('./appPullRequests.js', () => ({ listAppPullRequests: async () => ({ pullRequests: ++m.prReads > 1 && m.nextPrs ? m.nextPrs : m.prs, transient: false }) }));@@ -23,7 +30,7 @@ vi.mock('./github.js', () => ({ execGh: async args => {if (args[0] === m.execGhFailureOn) throw new Error('forge unavailable');if (args[0] === m.invalidGhJsonOn) return 'not json';return JSON.stringify({ body: '', state: m.dependencyOpen ? 'OPEN' : 'CLOSED', labels: m.dependencyOpen ? [{ name: 'in-progress' }] : [] });-} }));+}, getPullRequestState: async number => m.prStates[String(number)] || { status: 'unavailable', state: null } }));vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async () => ({}) }));vi.mock('./forgeActorTrust.js', () => ({ createGithubActorTrust: async () => ({ isTrusted: async () => true }) }));vi.mock('../lib/execGit.js', () => ({ execGit: async () => ({ stdout: m.branch }) }));@@ -41,7 +48,7 @@ import { readPersistentMindMaintenanceContext } from './persistentMindMaintenancbeforeEach(() => {m.state = { config: { improvementEnabled: true, persistentMindMaintainer: { enabled: true, appIds: ['app'] }, persistentMindCapabilities: { readPortos: true, createTasks: true }, maxConcurrentAgents: 3 }, agents: {} };- m.tasks = []; m.prs = []; m.backlog = []; m.peers = []; m.adds = []; m.branch = ''; m.account = 'atomantic'; m.save.mockClear(); m.nextPrs = null; m.prReads = 0; m.dependencies = []; m.dependencyOpen = false; m.execGhFailureOn = null; m.invalidGhJsonOn = null; m.issueTruncated = false;+ m.tasks = []; m.prs = []; m.backlog = []; m.peers = []; m.adds = []; m.updates = []; m.branch = ''; m.account = 'atomantic'; m.save.mockClear(); m.nextPrs = null; m.prReads = 0; m.prStates = {}; m.dependencies = []; m.dependencyOpen = false; m.execGhFailureOn = null; m.invalidGhJsonOn = null; m.issueTruncated = false;m.readiness = { shouldRun: true }; m.requests = []; m.duplicate = false;m.metadata.mockReset().mockResolvedValue({ metadata: {} });m.prepare.mockReset().mockResolvedValue({@@ -109,6 +116,49 @@ it('queues abandoned claim PRs through review-then-merge and withholds changed hm.adds = []; m.state.developmentWatchdog = null; m.prReads = 0; m.nextPrs = [{ ...orphan, headSha: 'changed' }];expect((await runDevelopmentWatchdog({ force: true })).decisions[0].reason).toBe('evidence-changed'); expect(m.adds).toEqual([]);});++it('retires a pending review follow-up when the forge confirms its PR is already merged', async () => {+ const task = {+ id: 'sys-rl-merged', status: 'pending',+ metadata: {+ app: 'app', reviewLoopFollowUp: true, reviewLoopPRNumber: '5', reviewLoopPRHost: 'github.com',+ reviewLoopPROwner: 'atomantic', reviewLoopPRRepo: 'example',+ reviewLoopPRUrl: 'https://github.com/atomantic/example/pull/5',+ },+ };+ m.tasks = [task];+ m.prStates['5'] = { status: 'known', state: 'MERGED' };++ const receipt = await runDevelopmentWatchdog({ force: true });++ expect(m.updates).toEqual([expect.objectContaining({+ id: task.id,+ updates: { status: 'completed', metadata: { reviewLoopRetiredReason: 'pull-request-merged-before-follow-up' } },+ type: 'internal', options: { expectedStatus: 'pending', suppressDequeue: true },+ })]);+ expect(task.status).toBe('completed');+ expect(receipt.apps[0].retiredReviewFollowUps).toEqual([{+ taskId: task.id, prNumber: 5, prState: 'MERGED', reason: 'pull-request-merged-before-follow-up',+ }]);+});++it('keeps a pending review follow-up when the PR state is unavailable', async () => {+ const task = {+ id: 'sys-rl-unavailable', status: 'pending',+ metadata: {+ app: 'app', reviewLoopFollowUp: true, reviewLoopPRNumber: 6, reviewLoopPRHost: 'github.com',+ reviewLoopPROwner: 'atomantic', reviewLoopPRRepo: 'example',+ reviewLoopPRUrl: 'https://github.com/atomantic/example/pull/6',+ },+ };+ m.tasks = [task];++ const receipt = await runDevelopmentWatchdog({ force: true });++ expect(task.status).toBe('pending');+ expect(m.updates).toEqual([]);+ expect(receipt.apps[0].retiredReviewFollowUps).toEqual([]);+});it('keeps explicit live claim and open dependency evidence out of dispatch', async () => {m.prs = [orphan]; m.dependencyOpen = true;let receipt = await runDevelopmentWatchdog({ force: true });