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 a queued autopilot gap task when the series run resumes
[._.]/ Adam Eivycba2f1e3697d
diff --git a/.changelog/next/fixed-main.md b/.changelog/next/fixed-main.mdindex 8d31522e56..63696c4425 100644--- a/.changelog/next/fixed-main.md+++ b/.changelog/next/fixed-main.md@@ -1,3 +1,4 @@- Windows: the update script aborted before building the client and restarting, because Node refuses to spawn npm.cmd without a shell (EINVAL) — leaving the UI permanently reporting a stale client build- Windows: git worktree add for CoS agents timed out at 30s on a full checkout, blocking tasks with worktree-failed while git actually completed the worktree- Windows: orphaned and merged CoS worktrees were never cleaned up, because git reports POSIX paths while PortOS built Windows ones+- Series Autopilot retires a queued gap task when a new run starts, so CoS stops dispatching agents against findings the resumed run has already repaireddiff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex b0885fb664..faddcfae99 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -326,6 +326,12 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore// speech layer can announce its completion (see voice/proactiveTriggers.js).if (taskData.voiceDispatch === true) metadata.voiceDispatch = true;if (taskData.isRecovery === true) metadata.isRecovery = true;+ // Series Autopilot gap tasks (seriesAutopilot/session.js `fileGap`) carry the+ // series they were filed for so a later run can retire the ones it has moved+ // past. Without this the only handle is the description prefix, which is+ // stable by construction but a fragile thing to key a status flip on.+ if (taskData.autopilotGapSeriesId) metadata.autopilotGapSeriesId = taskData.autopilotGapSeriesId;+ if (taskData.autopilotGapKind) metadata.autopilotGapKind = taskData.autopilotGapKind;// Investigation-task guards (#2615): the durable fingerprint dedupes repeat// failures of the same cause; the marker blocks investigations-of-investigations;// affectedTasks names every task blocked on the cause (later dedup hits union in).diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex d9d48ec75e..b781506394 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -137,7 +137,18 @@ vi.mock('./visualStages.js', () => visualSpies);let nextTaskId = 0;const addTask = vi.fn(async () => ({ id: `task-gap-${++nextTaskId}` }));-vi.mock('../cosTaskStore.js', () => ({ addTask }));+// Backing store for the gap-task retirement path (clearGapTasks). Tests seed+// `userTasks` with whatever the queue should already hold when a run starts.+let userTasks = [];+const getUserTasks = vi.fn(async () => ({ tasks: userTasks }));+const updateTask = vi.fn(async (taskId, updates) => {+ const task = userTasks.find(t => t.id === taskId);+ if (!task) return { error: 'Task not found' };+ Object.assign(task, updates, { metadata: { ...task.metadata, ...updates.metadata } });+ return task;+});+const firstLine = (s) => (s || '').split('\n').map(l => l.trim()).find(l => l) || '';+vi.mock('../cosTaskStore.js', () => ({ addTask, getUserTasks, updateTask, firstLine }));let scriptVerifyFindings = [];const verifyComicScript = vi.fn(async () => ({ issues: scriptVerifyFindings }));@@ -271,6 +282,7 @@ beforeEach(() => {editorialChecksPerCheck = [];editorialChecksFindings = [];nextTaskId = 0;+ userTasks = [];modelRecommendations = {};autopilot.__testing.runs.clear();vi.clearAllMocks();@@ -4115,6 +4127,61 @@ describe('autopilot conductor', () => {expect(last?.reason).toMatch(/comicScript/);});+ it('tags a filed gap task with the series so a later run can find it', async () => {+ const { seriesId } = await seedComplete({ script: 'just prose, no comic pages here' });+ await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true, includeVisual: false });+ await waitFor(runFinished(seriesId));+ const tagged = addTask.mock.calls.map((c) => c[0]).find((t) => /script-unparseable/.test(t.description));+ expect(tagged.autopilotGapSeriesId).toBe(seriesId);+ expect(tagged.autopilotGapKind).toBe('script-unparseable');+ });++ it('retires a PENDING gap task for this series when a new run starts', async () => {+ const { seriesId } = await seedComplete();+ userTasks = [{+ id: 'task-stale', status: 'pending',+ description: `Autopilot foundationGate-stalled gap — series ${seriesId}\n\npaused`,+ metadata: { autopilotGapSeriesId: seriesId },+ }];+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });+ await waitFor(runFinished(seriesId));+ expect(userTasks[0].status).toBe('completed');+ expect(userTasks[0].metadata.resolution).toBe('auto-expired');+ expect(userTasks[0].metadata.autoExpiredReason).toBe('autopilot-resumed');+ });++ it('retires a legacy gap task that predates the autopilotGapSeriesId tag', async () => {+ const { seriesId } = await seedComplete();+ userTasks = [{+ id: 'task-legacy', status: 'pending',+ description: `Autopilot foundationGate-stalled gap — series ${seriesId}\n\npaused`,+ metadata: {},+ }];+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });+ await waitFor(runFinished(seriesId));+ expect(userTasks[0].status).toBe('completed');+ });++ it('leaves in-progress gap tasks and other series alone', async () => {+ const { seriesId } = await seedComplete();+ userTasks = [+ {+ id: 'task-running', status: 'in_progress',+ description: `Autopilot foundationGate-stalled gap — series ${seriesId}\n\npaused`,+ metadata: { autopilotGapSeriesId: seriesId },+ },+ {+ id: 'task-other', status: 'pending',+ description: 'Autopilot foundationGate-stalled gap — series ser-somebody-else\n\npaused',+ metadata: { autopilotGapSeriesId: 'ser-somebody-else' },+ },+ { id: 'task-unrelated', status: 'pending', description: 'Fix the login page', metadata: {} },+ ];+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });+ await waitFor(runFinished(seriesId));+ expect(userTasks.map((t) => t.status)).toEqual(['in_progress', 'pending', 'pending']);+ });+it('does not file gap tasks when fileGaps is off', async () => {const { seriesId } = await seedComplete({ script: 'just prose, no comic pages here' });await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.jsindex 8c9adac504..c19501a7f9 100644--- a/server/services/pipeline/seriesAutopilot/orchestrator.js+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js@@ -27,7 +27,7 @@ import { getModelPerformanceReport } from './modelPerformance.js';import { runSelfImproveDiagnosis } from './selfImprove.js';import { observerEnabled, runObserverPass, summarizeObserver } from './observer.js';import { VISUAL_DRAFT_ENABLED, summarizePlanCost } from './convergence.js';-import { broadcast, broadcastStart, persistMarker, clearPauseNotice, notifyPause, fileGap, scheduleCleanup, roleLlm } from './session.js';+import { broadcast, broadcastStart, persistMarker, clearPauseNotice, clearGapTasks, notifyPause, fileGap, scheduleCleanup, roleLlm } from './session.js';import { resolveNextStep } from './stepResolver.js';import { editorialSubsetIds } from './editorialSteps.js';import { dispatchStep } from './dispatch.js';@@ -349,6 +349,11 @@ export async function startSeriesAutopilot(sId, options = {}) {// A resume is a fresh start: drop any stale pause banner up front so a run// that completes/errors without re-pausing doesn't leave a dead resume link.await clearPauseNotice(sId);+ // Same reasoning for the CoS gap task the pause filed — and higher stakes:+ // a queued gap task dispatches an agent to hand-edit the very fields this+ // run is about to repair itself. Re-filed with fresh findings if the gate+ // still fails.+ await clearGapTasks(sId).catch(() => {});if (runOptions.includeVisual && !VISUAL_DRAFT_ENABLED) {broadcast(sId, { type: 'note', message: 'Draft visual rendering is not enabled in this build — running to text-ready + editorial review.' });}diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.jsindex 3953c3f941..a32975286c 100644--- a/server/services/pipeline/seriesAutopilot/session.js+++ b/server/services/pipeline/seriesAutopilot/session.js@@ -171,7 +171,12 @@ export async function fileGap(record, sId, { gapKind, issueId = null, summary, cif (!record.options.fileGaps || record.mode !== 'execute') return;const idTag = `series ${sId}${issueId ? ` issue ${issueId}` : ''}`;const description = `Autopilot ${gapKind} gap — ${idTag}\n\n${summary}`;- const result = await cosTaskStore.addTask({ description, context }, 'user')+ const result = await cosTaskStore.addTask({+ description,+ context,+ autopilotGapSeriesId: sId,+ autopilotGapKind: gapKind,+ }, 'user').catch((err) => { console.log(`⚠️ autopilot: fileGap (${gapKind}) failed: ${err.message}`); return null; });if (result && !result.duplicate) {broadcast(sId, { type: 'gap:filed', gapKind, issueId, taskId: result.id });@@ -196,6 +201,58 @@ export async function clearPauseNotice(sId) {await removeByMetadata('autopilotPauseSeriesId', sId).catch(() => {});}+// The gap task's counterpart to clearPauseNotice: retire any gap task still+// QUEUED for this series when a fresh execute run starts.+//+// A gap task is a snapshot of one pause ("needs human review of the residual+// findings before it can continue"). Once a run is moving again that premise is+// void, but nothing used to retire the task — so CoS kept dispatching agents+// against findings the run had already repaired. On this install that burned ten+// agent sessions across two series, each re-fixing what the previous one fixed.+//+// Worse than waste: the resumed run OWNS the fields those findings name (the+// foundation gate repairs worldbuilding/character/craft itself, and the arc gate+// rewrites `arc.summary` + `season.synopsis`), so an agent hand-editing them+// concurrently clobbers the run's own repair.+//+// Self-correcting by construction: the gate re-judges from live content on the+// way past, and re-files a gap with FRESH findings if it still fails. Clearing+// early can only drop a task whose findings are about to be re-derived.+//+// Scoped to `pending` on purpose — an `in_progress` task has an agent attached,+// and flipping it mid-run would strand that agent and re-open the dedup slot.+// Status flip, never deletion, so the retirement federates (the #2619 precedent+// in cosTaskStore.sweepResolvedFailureTasks). Best-effort: this must never+// abort a run.+export async function clearGapTasks(sId) {+ const { tasks = [] } = await cosTaskStore.getUserTasks().catch(() => ({ tasks: [] }));+ // Legacy gap tasks (filed before `autopilotGapSeriesId` existed — every+ // install upgrading into this has some) carry no metadata handle, so fall back+ // to the first line, which fileGap builds deterministically above.+ const isGapFor = (t) => {+ if (t.metadata?.autopilotGapSeriesId) return t.metadata.autopilotGapSeriesId === sId;+ const line = cosTaskStore.firstLine(t.description);+ return line.startsWith('Autopilot ') && line.includes(` gap — series ${sId}`);+ };+ const stale = tasks.filter((t) => t.status === 'pending' && isGapFor(t));+ let retired = 0;+ for (const task of stale) {+ const updated = await cosTaskStore.updateTask(task.id, {+ status: 'completed',+ metadata: {+ resolution: 'auto-expired',+ autoExpiredReason: 'autopilot-resumed',+ autoExpiredAt: new Date().toISOString(),+ },+ }, 'user').catch(() => null);+ if (updated && !updated.error) retired++;+ }+ if (retired > 0) {+ console.log(`🧹 autopilot: retired ${retired} stale gap task(s) for ${sId.slice(0, 12)} on resume`);+ }+ return retired;+}+export async function notifyPause(record, sId, { reason, pauseKind = null, currentStep = null }) {if (record.options.notifyOnPause === false || record.mode !== 'execute') return;const series = await getSeries(sId).catch(() => null);