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(cos): count skipped improvement runs once (#12570)

[._.]/ Adam Eivy538594497c84
diff --git a/server/services/cosTaskGenerator.execution.test.js b/server/services/cosTaskGenerator.execution.test.js
new file mode 100644
index 0000000000..d25836d6ad
--- /dev/null
+++ b/server/services/cosTaskGenerator.execution.test.js
@@ -0,0 +1,59 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ app: { id: 'cadence-app', name: 'Cadence app', repoPath: '/fixture/app' },
+ type: 'mobile-responsive',
+ recordExecution: vi.fn(async () => {}),
+ updateAppActivity: vi.fn(async () => {}),
+ emitLog: vi.fn(),
+ applicable: false,
+}));
+vi.mock('./apps.js', async (actual) => ({
+ ...await actual(), getActiveApps: async () => [mocks.app], getAppTaskTypeOverrides: async () => ({}),
+}));
+vi.mock('./appActivity.js', async (actual) => ({
+ ...await actual(), getNextAppForReview: async () => mocks.app,
+ markIdleReviewStarted: async () => {}, markAppReviewCooldown: async () => {}, bindAppReviewAgent: async () => {},
+ updateAppActivity: (...args) => mocks.updateAppActivity(...args),
+}));
+vi.mock('./cosState.js', async (actual) => ({
+ ...await actual(), withStateLock: async (fn) => fn(), loadState: async () => ({ stats: {} }), saveState: async () => {},
+}));
+vi.mock('./cosEvents.js', async (actual) => ({ ...await actual(), emitLog: (...args) => mocks.emitLog(...args) }));
+vi.mock('./taskSchedule.js', async (actual) => ({
+ ...await actual(), getOnDemandRequests: async () => [],
+ getNextTaskType: async () => ({ taskType: mocks.type, reason: 'scheduled' }),
+ getTaskInterval: async () => ({ taskMetadata: {}, prompt: 'Review {appName}' }),
+ recordExecution: (...args) => mocks.recordExecution(...args),
+}));
+vi.mock('./appQualitySchedule.js', () => ({ resolveAuditApplicability: async () => ({ applicable: mocks.applicable, reason: 'No mobile app' }) }));
+vi.mock('./taskTypeHooks.js', () => ({ getTaskInputHook: async () => null }));
+vi.mock('./prWatcher.js', () => ({
+ checkPullRequests: async () => ({ ok: true, firstRun: false, newPrs: [], repoFullName: 'fixture/app', defaultBranch: 'main' }),
+ persistPrWatcherState: async () => {},
+}));
+vi.mock('./taskPromptService.js', async (actual) => ({ ...await actual(), getTaskPrompt: async () => 'Review {appName}' }));
+
+import { generateIdleReviewTask } from './cosTaskGenerator.js';
+
+const state = { config: { improvementEnabled: true, idleReviewPriority: 'MEDIUM', requireApproval: true, confidenceAutoApproval: { enabled: false } }, stats: {} };
+describe('idle-review execution ownership (#12570)', () => {
+ beforeEach(() => { vi.clearAllMocks(); mocks.applicable = false; });
+ it.each(['mobile-responsive', 'pr-watcher'])('records %s skip once without announcing generation', async (type) => {
+ mocks.type = type;
+ const result = await generateIdleReviewTask(state);
+ expect(result.task).toBeNull();
+ expect(mocks.recordExecution).toHaveBeenCalledExactlyOnceWith(type, mocks.app.id);
+ expect(mocks.updateAppActivity).not.toHaveBeenCalled();
+ expect(mocks.emitLog.mock.calls.filter(([, message]) => message.startsWith('Generating improvement task'))).toHaveLength(0);
+ });
+ it('records and announces a successfully prepared task once', async () => {
+ mocks.type = 'code-quality';
+ mocks.applicable = true;
+ const result = await generateIdleReviewTask(state);
+ expect(result.task).toBeTruthy();
+ expect(mocks.recordExecution).toHaveBeenCalledExactlyOnceWith('task:code-quality', mocks.app.id);
+ expect(mocks.updateAppActivity).toHaveBeenCalledExactlyOnceWith(mocks.app.id, { lastImprovementType: 'code-quality' });
+ expect(mocks.emitLog.mock.calls.filter(([, message]) => message.startsWith('Generating improvement task'))).toHaveLength(1);
+ });
+});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 9d1822a8d5..45d5e0a856 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1106,7 +1106,6 @@ export async function generateIdleReviewTask(state, { ignoreTaskId = null, isApp
await saveState(s);
});
- emitLog('info', `Generating improvement task for ${nextApp.name}`, { appId: nextApp.id });
const { task: idleTask, pendingPerpetualDispatch, preflightCardId } = await generateManagedAppImprovementTask(nextApp, state, { ignoreTaskId });
// Only bind the active marker once a real task exists.
if (idleTask) {
@@ -1765,7 +1764,6 @@ export function applyAppWorktreeDefault(metadata, app) {
}
async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = null } = {}) {
- const { updateAppActivity } = await import('./appActivity.js');
const taskSchedule = await import('./taskSchedule.js');
// First, check for any on-demand task requests for this app
@@ -1826,24 +1824,14 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu
selectionReason = nextTypeResult.reason;
}
- // Record execution in the schedule service
- await taskSchedule.recordExecution(`task:${nextType}`, app.id);
-
- // Update app activity with new type
- await updateAppActivity(app.id, {
- lastImprovementType: nextType
- });
-
- emitLog('info', `Generating improvement task for ${app.name}: ${nextType} (${selectionReason})`, { appId: app.id, analysisType: nextType });
-
// Delegate the actual task build to the per-type generator so the dynamic
// blocks run on the idle-review path too: pr-watcher's PR poll +
// {prData}/{repoFullName}/{defaultBranch} injection, and reference-watch's
// {referenceData} injection. Without delegation this path replaced only the
// generic placeholders, so a watcher type selected here would spawn a prompt
// with the literal {prData}/{referenceData} markers and never poll. The
- // recordExecution + activity bump above already accounted for the idle
- // spawn; the per-type generator does not record execution itself.
+ // preparer owns skip cadence and success activity/logging; this caller
+ // records execution only when preparation produces a task.
const prepared = await prepareManagedAppImprovementTask(nextType, app, state, {
ignoreTaskId,
targetPullRequest,
@@ -1856,6 +1844,7 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu
preflightCardId: stolenCardId
});
const { task, pendingPerpetualDispatch } = prepared;
+ if (task) await taskSchedule.recordExecution(`task:${nextType}`, app.id);
// Idle-review can steal a queued on-demand request for this app. That
// request is still a user Run — apply the same consent as Priority 0.
if (stolenRequest) {
diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.js
index 2d45919cba..e234150357 100644
--- a/server/services/onDemandDrain.js
+++ b/server/services/onDemandDrain.js
@@ -249,7 +249,6 @@ export async function drainOnDemandRequests(ctx, adapter) {
await markAppReviewCooldown(targetApp.id);
reviewStartedApps.add(targetApp.id);
}
- await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);
const prepared = await prepareManagedAppImprovementTask(request.taskType, targetApp, state, {
skipPreconditions: true,
onDemand: true,
@@ -272,6 +271,7 @@ export async function drainOnDemandRequests(ctx, adapter) {
pendingPerpetualDispatch = prepared.pendingPerpetualDispatch;
skip = prepared.skip;
if (task) {
+ await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);
await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
}
} else {
diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.js
index c620752215..5f04e3a247 100644
--- a/server/services/onDemandDrain.test.js
+++ b/server/services/onDemandDrain.test.js
@@ -675,7 +675,7 @@ describe('atomic on-demand preparation ownership', () => {
// A late loser must not close or reset a card while the winner is working.
expect(mocks.prepareManagedAppImprovementTask).toHaveBeenCalledTimes(1);
expect(mocks.applyOnDemandRunResets).toHaveBeenCalledTimes(1);
- expect(mocks.recordExecution).toHaveBeenCalledTimes(1);
+ expect(mocks.recordExecution).not.toHaveBeenCalled();
expect(mocks.startPreflightCard).toHaveBeenCalledTimes(1);
expect(mocks.reportPreflightStep).toHaveBeenCalledTimes(1);
expect(mocks.finishPreflightCard).not.toHaveBeenCalled();
@@ -683,6 +683,7 @@ describe('atomic on-demand preparation ownership', () => {
preparationRelease.resolve();
await Promise.all(drains);
+ expect(mocks.recordExecution).toHaveBeenCalledTimes(1);
expect(mocks.addTask).toHaveBeenCalledTimes(1);
expect(engines[winner].spawned).toHaveLength(1);
expect(engines[1 - winner].spawned).toEqual([]);
@@ -778,3 +779,20 @@ describe.each(ENGINES)('%s — historical queued Deep compatibility', (_name, ma
expect(spawned).toHaveLength(1);
});
});
+
+
+describe.each(ENGINES)('%s — preparation owns skipped execution cadence (#12570)', (_name, makeAdapter) => {
+ it.each(['input-hook', 'pr-watcher'])('does not charge %s twice', async (gate) => {
+ const taskType = gate === 'pr-watcher' ? 'pr-watcher' : 'code-quality';
+ mocks.loadSchedule.mockResolvedValue({ tasks: { [taskType]: { enabled: true } } });
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest({ taskType })]);
+ mocks.prepareManagedAppImprovementTask.mockImplementation(async (_type, app) => {
+ // The preparer's cadence-bearing skip already records this run.
+ await mocks.recordExecution(taskType, app.id);
+ return { task: null, pendingPerpetualDispatch: null, skip: { gate } };
+ });
+ await drainOnDemandRequests({ state: STATE }, makeAdapter().adapter);
+ expect(mocks.recordExecution).toHaveBeenCalledExactlyOnceWith(taskType, APP.id);
+ expect(mocks.addTask).not.toHaveBeenCalled();
+ });
+});