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

fix: hand a held mission task's sub-task back to pending instead of stranding it (#4858)

[._.]/ Adam Eivydcfbc24089fe
diff --git a/server/services/missions.js b/server/services/missions.js
index 28aaa442a4..0cf62df020 100644
--- a/server/services/missions.js
+++ b/server/services/missions.js
@@ -314,6 +314,44 @@ async function generateMissionTask(missionId) {
return null
}
+/**
+ * Return a sub-task `generateMissionTask` claimed as `in_progress` to `pending`.
+ *
+ * Mission tasks are never written to `COS-TASKS.md` — the in-memory object
+ * `generateMissionTask` emits as `task:ready` is the only copy. The flip it
+ * saves first exists purely to stop the next generation cycle re-picking the
+ * same sub-task, so any path that declines to spawn the emitted task strands it:
+ * the object is gone, and `generateMissionTask` only ever selects `pending`
+ * sub-tasks, so nothing re-picks it. The mission silently stops advancing, one
+ * sub-task burned per occurrence (issue #4858).
+ *
+ * Reverting the flip is what makes the dispatch holds mean for a mission task
+ * what they already mean for a persisted task: still queued, re-picked when the
+ * condition clears. The caller is `holdTask` in `subAgentSpawner.js`, the one
+ * chokepoint every hold funnels through.
+ *
+ * A sub-task that is no longer `in_progress` is left alone — `completeSubTask`
+ * may have landed a real result between dispatch and release, and resurrecting
+ * that as pending work would re-run finished work.
+ *
+ * @param {string} missionId - Mission ID
+ * @param {string} subTaskId - Sub-task ID
+ * @returns {Promise<Object|null>} - Updated mission, or null when nothing was released
+ */
+async function releaseMissionSubTask(missionId, subTaskId) {
+ const mission = await getMission(missionId)
+ if (!mission) return null
+
+ const subTask = mission.subTasks.find(t => t.id === subTaskId)
+ if (!subTask || subTask.status !== 'in_progress') return null
+
+ subTask.status = 'pending'
+ mission.updatedAt = new Date().toISOString()
+ await saveMission(mission)
+
+ return mission
+}
+
/**
* Generate proactive tasks from all active missions
* @param {Object} options - Generation options
@@ -448,6 +486,7 @@ export {
addSubTask,
completeSubTask,
generateMissionTask,
+ releaseMissionSubTask,
generateProactiveTasks,
recordMissionReview,
getStats,
diff --git a/server/services/missions.test.js b/server/services/missions.test.js
index cd837717f0..664c162d00 100644
--- a/server/services/missions.test.js
+++ b/server/services/missions.test.js
@@ -43,6 +43,7 @@ const {
addSubTask,
completeSubTask,
generateMissionTask,
+ releaseMissionSubTask,
generateProactiveTasks,
recordMissionReview,
getStats,
@@ -285,6 +286,80 @@ describe('Missions Service', () => {
});
});
+ // Issue #4858: `generateMissionTask` saves the `in_progress` flip before it
+ // returns, but the task it returns is never persisted. Any dispatch path that
+ // declines to spawn it must hand the sub-task back, or generation — which only
+ // selects `pending` — never sees it again.
+ describe('releaseMissionSubTask', () => {
+ const seedGenerated = async (id) => {
+ await createMission({ id, appId: 'test-app', name: 'Release Test' });
+ await addSubTask(id, { description: 'Held task', priority: 'high' });
+ const task = await generateMissionTask(id);
+ return task.metadata.subTaskId;
+ };
+
+ it('returns an in_progress sub-task to pending', async () => {
+ const subTaskId = await seedGenerated('test-release-mission');
+
+ const mission = await releaseMissionSubTask('test-release-mission', subTaskId);
+
+ expect(mission.subTasks.find(t => t.id === subTaskId).status).toBe('pending');
+
+ await deleteMission('test-release-mission');
+ });
+
+ // The acceptance criterion the whole fix exists for: the next generation
+ // cycle re-picks it, so the mission keeps advancing after the hold clears.
+ it('makes the sub-task re-generatable, so the mission resumes', async () => {
+ const subTaskId = await seedGenerated('test-regenerate-mission');
+ // Already claimed — generation correctly refuses to hand it out twice.
+ expect(await generateMissionTask('test-regenerate-mission')).toBeNull();
+
+ await releaseMissionSubTask('test-regenerate-mission', subTaskId);
+ const task = await generateMissionTask('test-regenerate-mission');
+
+ expect(task).not.toBeNull();
+ expect(task.metadata.subTaskId).toBe(subTaskId);
+
+ await deleteMission('test-regenerate-mission');
+ });
+
+ // A release that lands after the agent finished must not resurrect the
+ // sub-task and re-run completed work.
+ it('leaves a completed sub-task alone', async () => {
+ const subTaskId = await seedGenerated('test-release-completed');
+ await completeSubTask('test-release-completed', subTaskId, { success: true });
+
+ expect(await releaseMissionSubTask('test-release-completed', subTaskId)).toBeNull();
+
+ const mission = await getMission('test-release-completed');
+ expect(mission.subTasks.find(t => t.id === subTaskId).status).toBe('completed');
+
+ await deleteMission('test-release-completed');
+ });
+
+ it('leaves a failed sub-task alone', async () => {
+ const subTaskId = await seedGenerated('test-release-failed');
+ await completeSubTask('test-release-failed', subTaskId, { success: false });
+
+ expect(await releaseMissionSubTask('test-release-failed', subTaskId)).toBeNull();
+
+ const mission = await getMission('test-release-failed');
+ expect(mission.subTasks.find(t => t.id === subTaskId).status).toBe('failed');
+
+ await deleteMission('test-release-failed');
+ });
+
+ it('returns null for an unknown mission or sub-task', async () => {
+ await createMission({ id: 'test-release-unknown', appId: 'test-app', name: 'Unknown Test' });
+
+ expect(await releaseMissionSubTask('no-such-mission', 'sub-1')).toBeNull();
+ expect(await releaseMissionSubTask('test-release-unknown', 'no-such-sub')).toBeNull();
+
+ await deleteMission('test-release-unknown');
+ });
+ });
+
describe('generateProactiveTasks', () => {
it('should generate tasks from active missions', async () => {
await createMission({
diff --git a/server/services/subAgentSpawner.dispatchHolds.test.js b/server/services/subAgentSpawner.dispatchHolds.test.js
index 4bbfd7aa1d..b6692efa16 100644
--- a/server/services/subAgentSpawner.dispatchHolds.test.js
+++ b/server/services/subAgentSpawner.dispatchHolds.test.js
@@ -16,9 +16,10 @@
*
* The holds live in that listener, not inside `runAgentSpawn`, because a hold
* below the spawn body's entry returns past `releaseAppReviewMarker` and strands
- * the synthetic "in review" marker for the whole outage (issue #989). The two
- * side effects the dequeue tiers already committed — that marker and the
- * scheduler's `spawningJobIds` reservation — are released here instead.
+ * the synthetic "in review" marker for the whole outage (issue #989). The side
+ * effects the dequeue tiers already committed — that marker, the scheduler's
+ * `spawningJobIds` reservation, and a mission sub-task's `in_progress` flip —
+ * are released here instead.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -49,6 +50,7 @@ vi.mock('./agentManagement.js', () => ({ cleanupOrphanedAgents: vi.fn().mockReso
vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn() }));
vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./updateChecker.js', () => ({ isUpdateInProgress: vi.fn().mockReturnValue(false) }));
+vi.mock('./missions.js', () => ({ releaseMissionSubTask: vi.fn().mockResolvedValue(null) }));
vi.mock('./agentOrchestrator.js', () => ({
completeAgent: vi.fn(),
spawnAgentForTask: vi.fn().mockResolvedValue('agent-1'),
@@ -64,6 +66,7 @@ import { isRunnerReachable } from './cosRunnerClient.js';
import { spawnAgentForTask } from './agentOrchestrator.js';
import { releaseAppReviewMarker } from './appActivity.js';
import { isUpdateInProgress } from './updateChecker.js';
+import { releaseMissionSubTask } from './missions.js';
import { setUseRunner } from './agentState.js';
const dispatch = (task) => taskHandlers.get('task:ready')(task);
@@ -185,6 +188,99 @@ describe('subAgentSpawner — self-update hold (#4124)', () => {
});
});
+/**
+ * A mission task is the one dispatch shape with NO persisted record, so "leave
+ * the task queued" cannot mean "do nothing" for it (issue #4858).
+ *
+ * `generateMissionTask` flips the selected sub-task to `in_progress` and saves
+ * the mission before returning — the flip is what stops the next generation
+ * cycle re-picking it. The task object it returns is the only copy; nothing
+ * writes it to `COS-TASKS.md`. So a hold that skipped the revert would burn one
+ * sub-task per occurrence: no queued record to re-dispatch, and generation only
+ * ever selects `pending` sub-tasks, so the mission just stops advancing.
+ *
+ * The revert lives in `holdTask` rather than in any single hold branch, for the
+ * same reason `job:spawn-failed` does — that is the one chokepoint every hold
+ * funnels through, so a fourth hold inherits it for free.
+ */
+describe('subAgentSpawner — mission sub-task release (#4858)', () => {
+ const missionTask = (id) => ({
+ id,
+ metadata: { missionId: 'mission-1', subTaskId: 'sub-3', isMissionTask: true },
+ });
+
+ beforeEach(async () => {
+ await initSpawner();
+ vi.clearAllMocks();
+ vi.useRealTimers();
+ setUseRunner(true);
+ isRunnerReachable.mockResolvedValue(true);
+ isUpdateInProgress.mockReturnValue(false);
+ releaseMissionSubTask.mockResolvedValue(null);
+ });
+
+ it('returns the sub-task to pending when the runner is down', async () => {
+ isRunnerReachable.mockResolvedValue(false);
+
+ await dispatch(missionTask('cos-m1'));
+
+ expect(spawnAgentForTask).not.toHaveBeenCalled();
+ expect(releaseMissionSubTask).toHaveBeenCalledWith('mission-1', 'sub-3');
+ });
+
+ // The whole point of releasing in holdTask: every hold gets it, not just the
+ // one whose branch happened to be written first.
+ it('returns the sub-task to pending during a self-update too', async () => {
+ isUpdateInProgress.mockReturnValue(true);
+
+ await dispatch(missionTask('cos-m2'));
+
+ expect(releaseMissionSubTask).toHaveBeenCalledWith('mission-1', 'sub-3');
+ });
+
+ it('leaves the flip alone on a successful dispatch — the agent owns it now', async () => {
+ await dispatch(missionTask('cos-m3'));
+
+ expect(spawnAgentForTask).toHaveBeenCalledTimes(1);
+ expect(releaseMissionSubTask).not.toHaveBeenCalled();
+ });
+
+ it('does not touch missions for a held task that is not a mission task', async () => {
+ isRunnerReachable.mockResolvedValue(false);
+
+ await dispatch({ id: 'cos-m4', metadata: { jobId: 'job-2' } });
+
+ expect(releaseMissionSubTask).not.toHaveBeenCalled();
+ });
+
+ // Both halves identify the record; a missionId alone can't address a sub-task,
+ // and passing undefined through would make the helper scan for `undefined`.
+ it('skips the release when the sub-task id is missing', async () => {
+ isRunnerReachable.mockResolvedValue(false);
+
+ await dispatch({ id: 'cos-m5', metadata: { missionId: 'mission-1' } });
+
+ expect(releaseMissionSubTask).not.toHaveBeenCalled();
+ });
+
+ // holdTask runs outside the request lifecycle (a cosEvents listener), so a
+ // rejected release must not escape as an unhandled rejection or swallow the
+ // releases queued before it.
+ it('logs and continues when the release fails', async () => {
+ isRunnerReachable.mockResolvedValue(false);
+ releaseMissionSubTask.mockRejectedValue(new Error('disk full'));
+
+ await expect(dispatch({
+ id: 'cos-m6',
+ metadata: { missionId: 'mission-1', subTaskId: 'sub-3', app: 'some-app' },
+ })).resolves.not.toThrow();
+
+ expect(releaseAppReviewMarker).toHaveBeenCalledWith('some-app');
+ const warnings = emitLog.mock.calls.filter(([level]) => level === 'warn');
+ expect(warnings.some(([, message]) => /release mission sub-task sub-3/.test(message))).toBe(true);
+ });
+});
+
describe('subAgentSpawner — runner connection events', () => {
beforeEach(async () => {
await initSpawner();
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index ea984b4b9b..f79ba3a1e5 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -46,6 +46,7 @@ import { appendRunEvent } from './agentRunEventLog.js';
import { runnerAgents, setUseRunner, useRunner } from './agentState.js';
import { releaseAppReviewMarker } from './appActivity.js';
import { isUpdateInProgress } from './updateChecker.js';
+import { releaseMissionSubTask } from './missions.js';
// This module's own event wiring drives three LIFECYCLE TRANSITIONS, so it takes
// them from the facade rather than from the three separate leaves that happen to
// implement them (#3450). It can: nothing the facade imports imports this module
@@ -76,9 +77,14 @@ let runnerRecovery = Promise.resolve();
* which also re-registers the cron schedule. Without it an autonomous job
* sits wedged until the scheduler's 5-minute spawn timeout — per job, per
* outage.
+ * - a mission sub-task's `in_progress` flip (issue #4858). `generateMissionTask`
+ * writes that flip before returning, and a mission task is never persisted to
+ * `COS-TASKS.md` — the emitted object is the only copy. Held without the
+ * revert, the sub-task is stranded for good: there is no record left queued,
+ * and generation only ever re-picks `pending` sub-tasks.
*
- * Shared by both hold conditions (self-update in progress, runner down) so a
- * third one can't ship with only half the releases.
+ * Shared by every hold condition (self-update in progress, runner down, and any
+ * that follow) so a new one can't ship with only half the releases.
*/
async function holdTask(task, reason) {
emitLog('debug', `⏸️ Holding task ${task.id} — ${reason}`, { taskId: task.id });
@@ -88,6 +94,11 @@ async function holdTask(task, reason) {
if (task.metadata?.jobId) {
cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });
}
+ if (task.metadata?.missionId && task.metadata?.subTaskId) {
+ await releaseMissionSubTask(task.metadata.missionId, task.metadata.subTaskId).catch(err =>
+ emitLog('warn', `Failed to release mission sub-task ${task.metadata.subTaskId}: ${err.message}`, { taskId: task.id })
+ );
+ }
}
/**