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

feat: skip automatic upgrade-rehearsal launches when no input changed since the last clean run (#12907)

Adam Eivy62a81249bcac
diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.js b/client/src/components/cos/tabs/schedule/scheduleConstants.js
index 39b938e53c..f97381e0d2 100644
--- a/client/src/components/cos/tabs/schedule/scheduleConstants.js
+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.js
@@ -178,6 +178,7 @@ export const TASK_READINESS_REASON_RENDERING = Object.freeze({
[TASK_READINESS_REASON.CRON_COOLDOWN]: 'cadence',
[TASK_READINESS_REASON.FAILURE_COOLDOWN]: 'cadence',
[TASK_READINESS_REASON.WAITING_ON_DEPENDENCIES]: 'waiting',
+ [TASK_READINESS_REASON.INPUTS_UNCHANGED]: 'cadence',
});
// Classify a task config into one status group (mutually exclusive).
diff --git a/server/lib/taskReadinessReasons.js b/server/lib/taskReadinessReasons.js
index aa0217a870..9041955589 100644
--- a/server/lib/taskReadinessReasons.js
+++ b/server/lib/taskReadinessReasons.js
@@ -16,6 +16,7 @@ export const TASK_READINESS_REASON = Object.freeze({
CRON_COOLDOWN: 'cron-cooldown',
FAILURE_COOLDOWN: 'failure-cooldown',
WAITING_ON_DEPENDENCIES: 'waiting-on-dependencies',
+ INPUTS_UNCHANGED: 'inputs-unchanged',
});
export const TASK_READINESS_REASONS = Object.freeze(Object.values(TASK_READINESS_REASON));
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index a4fa117625..08d4054220 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -2055,6 +2055,27 @@ async function publishAppSnapshotFileAfterAudit(appId) {
* back to the task's repoPath; a recovery run trusts only the persisted
* workspace — without it there is nothing safe to read, so no payload.
*/
+// A run is a clean baseline only when it succeeded, recorded its assessment and
+// that assessment verified no material finding (worstSeverity 0) from a real
+// scan; anything else drops the baseline so the next launch runs.
+async function recordInputGateBaseline({ task, taskType, agentId, success, auditAssessment, workspacePath }) {
+ const appId = task?.metadata?.app;
+ const { TASK_INPUT_PATHS } = await import('./taskScheduleRegistry.js');
+ if (!appId || !TASK_INPUT_PATHS[taskType]) return;
+ const { doneSentinelPath, parseSentinelPayload } = await import('../lib/agentSentinel.js');
+ const { parseAuditQualityReport } = await import('../lib/auditQuality.js');
+ const path = workspacePath ? doneSentinelPath(workspacePath, agentId) : null;
+ const report = success && auditAssessment.status === 'recorded' && path
+ ? parseAuditQualityReport(parseSentinelPayload(await tryReadFile(path)).summary, taskType) : null;
+ const clean = report?.worstSeverity === 0 && report.scannedFiles > 0;
+ const { readHead } = await import('./taskInputGate.js');
+ const { recordCleanInputBaseline } = await import('./taskSchedule.js');
+ const head = clean ? await readHead(workspacePath) : null;
+ await recordCleanInputBaseline(taskType, appId, head).catch(err => {
+ emitLog('warn', `⚠️ Input-gate baseline was not saved for ${taskType}: ${err.message}`, { taskType, agentId });
+ });
+}
+
function hookPayloadDir({ task, workspacePath, recovery }) {
return recovery
? (workspacePath || null)
@@ -2159,6 +2180,8 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, a
return { status: 'persistence-failed' };
});
const recorded = auditAssessment.status === 'recorded';
+ await recordInputGateBaseline({ task, taskType, agentId, success, auditAssessment, workspacePath: hookPayloadDir({ task, workspacePath, recovery }) })
+ .catch(err => emitLog('warn', `⚠️ Input-gate baseline failed for ${agentId}: ${err.message}`, { agentId }));
// A review-only run must not land a separate snapshot behind the user's back.
if (!isLegacyDeepAudit(task.metadata) && recorded === true && resolvePrCompletion(task?.metadata) !== PR_COMPLETIONS.LEAVE_OPEN) {
await publishAppSnapshotFileAfterAudit(task?.metadata?.app);
diff --git a/server/services/taskInputGate.js b/server/services/taskInputGate.js
new file mode 100644
index 0000000000..d2bde29b46
--- /dev/null
+++ b/server/services/taskInputGate.js
@@ -0,0 +1,22 @@
+// Git half of the `inputs-unchanged` scheduler gate (#12907): HEAD capture for a
+// clean-run baseline and the "did any declared input change since it" question.
+import { execGit } from '../lib/execGit.js';
+
+const SHA_RE = /^[0-9a-f]{40}$/;
+
+export async function readHead(repoPath, git = execGit) {
+ const head = await git(['rev-parse', 'HEAD'], repoPath).then(r => r.stdout.trim(), () => '');
+ return SHA_RE.test(head) ? head : null;
+}
+
+/**
+ * True only on positive proof that no input changed. Any doubt (no baseline, no
+ * repo, an unknown commit after a force-push, a git failure) answers false so
+ * the audit runs.
+ */
+export async function inputsUnchangedSince({ repoPath, lastCleanHead, inputPaths, git = execGit }) {
+ if (!repoPath || !SHA_RE.test(lastCleanHead || '') || !inputPaths?.length) return false;
+ const changed = await git(['diff', '--name-only', lastCleanHead, 'HEAD', '--', ...inputPaths], repoPath)
+ .then(r => r.stdout.trim(), () => null);
+ return changed === '';
+}
diff --git a/server/services/taskInputGate.test.js b/server/services/taskInputGate.test.js
new file mode 100644
index 0000000000..0c11595b95
--- /dev/null
+++ b/server/services/taskInputGate.test.js
@@ -0,0 +1,40 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execGit } from '../lib/execGit.js';
+import { inputsUnchangedSince, readHead } from './taskInputGate.js';
+
+// Real git on a scratch repo: the pathspec and the failure-means-run contract
+// are what the scheduler gate relies on.
+describe('taskInputGate', () => {
+ let repo;
+ const commit = async (file, body) => {
+ mkdirSync(join(repo, file, '..'), { recursive: true });
+ writeFileSync(join(repo, file), body);
+ await execGit(['add', '-A'], repo);
+ await execGit(['-c', 'user.name=t', '-c', '[email protected]', 'commit', '-q', '-m', file], repo);
+ return readHead(repo);
+ };
+ const paths = ['scripts/migrations/', 'server/services/backupRestore*'];
+
+ beforeAll(async () => {
+ repo = mkdtempSync(join(tmpdir(), 'input-gate-'));
+ await execGit(['init', '-q'], repo);
+ });
+ afterAll(() => rmSync(repo, { recursive: true, force: true }));
+
+ it('is unchanged only while no declared path differs from the baseline', async () => {
+ const base = await commit('scripts/migrations/001.js', 'a');
+ await commit('docs/unrelated.md', 'x');
+ expect(await inputsUnchangedSince({ repoPath: repo, lastCleanHead: base, inputPaths: paths })).toBe(true);
+ await commit('server/services/backupRestoreFoo.js', 'y');
+ expect(await inputsUnchangedSince({ repoPath: repo, lastCleanHead: base, inputPaths: paths })).toBe(false);
+ });
+
+ it('answers false (run the audit) on a missing, malformed or unknown baseline', async () => {
+ for (const lastCleanHead of [null, '--output=x', 'f'.repeat(40)]) {
+ expect(await inputsUnchangedSince({ repoPath: repo, lastCleanHead, inputPaths: paths })).toBe(false);
+ }
+ });
+});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 22b20e0729..c584c9923a 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -48,6 +48,7 @@ import {
} from './taskScheduleConstants.js';
import {
DEFAULT_TASK_INTERVALS,
+ TASK_INPUT_PATHS,
INSTALL_WIDE_TASK_TYPES,
MANAGED_APP_TARGET_TASK_TYPES,
MANAGED_AGENT_OPTIONS,
@@ -60,6 +61,7 @@ import {
enforceManagedAgentOptions
} from './taskScheduleRegistry.js';
import { loadSchedule, updateSchedule } from './taskScheduleStore.js';
+import { inputsUnchangedSince } from './taskInputGate.js';
import { isInstanceFeatureEnabled } from './instanceFeatures.js';
import { recordUserAction } from './userActions.js';
import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';
@@ -370,6 +372,31 @@ export async function recordRecommendedAudits(taskType, appId, items) {
});
}
+/**
+ * Baseline for the `inputs-unchanged` gate: the repo HEAD of the last clean run
+ * of an input-gated task. A failed or finding-producing run passes `null`, which
+ * drops the baseline so the next automatic launch runs.
+ */
+export async function recordCleanInputBaseline(taskType, appId, head) {
+ if (!TASK_INPUT_PATHS[taskType] || !appId) return false;
+ return updateSchedule(async (schedule) => {
+ const record = ensureExecutionRecord(schedule, taskType, appId);
+ if ((record.lastCleanHead ?? null) === (head ?? null)) return { result: false, changed: false };
+ if (head) record.lastCleanHead = head;
+ else delete record.lastCleanHead;
+ return { result: true, changed: true };
+ });
+}
+
+// True when the task declares input paths and none changed since its last clean run.
+async function inputsUnchangedForTask(taskType, appId, schedule) {
+ const inputPaths = TASK_INPUT_PATHS[taskType];
+ const lastCleanHead = inputPaths && appId ? resolveExecutionRecord(schedule, taskType, appId)?.lastCleanHead : null;
+ if (!lastCleanHead) return false;
+ const app = await getAppById(appId).catch(() => null);
+ return inputsUnchangedSince({ repoPath: app?.repoPath, lastCleanHead, inputPaths });
+}
+
// ============================================================
// Perpetual (drain-until-done) park state
// ============================================================
@@ -1217,6 +1244,10 @@ async function evaluateTaskReadiness(taskType, appId, { featureEnabled, continui
}
}
+ if (result.shouldRun && await inputsUnchangedForTask(taskType, appId, schedule)) {
+ return { shouldRun: false, reason: TASK_READINESS_REASON.INPUTS_UNCHANGED };
+ }
+
return result;
}
@@ -1327,6 +1358,11 @@ export async function triggerOnDemandTask(taskType, appId = null, {
// the schedule interval and the app's own per-app override.
const providerOverride = (provider || model || effort) ? { provider, model, effort } : null;
const manual = isManualOnDemandRequest({ origin, burn: burnProvenance });
+ // Unattended launches (burn, refill) of an input-gated audit are declined while
+ // nothing it reads changed since its last clean run; a human Run always goes.
+ if (!manual && await inputsUnchangedForTask(taskType, appId, await loadSchedule())) {
+ return { error: `Task type '${taskType}' inputs are unchanged since its last clean run`, reason: TASK_READINESS_REASON.INPUTS_UNCHANGED };
+ }
const request = await updateSchedule(async (schedule) => {
const tasks = schedule.tasks || {};
const config = Object.prototype.hasOwnProperty.call(tasks, taskType) ? tasks[taskType] : null;
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index b714d57124..e648ee6bbe 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -71,6 +71,8 @@ vi.mock('./apps.js', () => ({
clearAllIssueWatcherState: vi.fn().mockResolvedValue({ changed: false })
}))
+vi.mock('./taskInputGate.js', () => ({ inputsUnchangedSince: vi.fn().mockResolvedValue(false), readHead: vi.fn() }))
+
vi.mock('./instanceFeatures.js', () => ({
isInstanceFeatureEnabled: vi.fn().mockResolvedValue(true),
}))
@@ -203,6 +205,8 @@ import { getAdaptiveCooldownMultiplier } from './taskLearning.js'
import { parseCronToNextRun } from './eventScheduler.js'
import { addNotification, exists as notificationExists, removeByMetadata } from './notifications.js'
import { isInstanceFeatureEnabled } from './instanceFeatures.js'
+import { inputsUnchangedSince } from './taskInputGate.js'
+import { getAppById } from './apps.js'
const mockSchedule = ({ tasks = {}, executions = {}, templates = [], onDemandRequests = [] } = {}) => {
readJSONFile.mockResolvedValue({ version: 2, tasks, executions, templates, onDemandRequests })
@@ -2157,6 +2161,48 @@ describe('taskSchedule', () => {
loadState.mockResolvedValue({ config: { improvementEnabled: true } })
})
+ describe('inputs-unchanged gate (#12907)', () => {
+ const HEAD = 'a'.repeat(40)
+ const gated = (lastCleanHead) => mockSchedule({
+ tasks: { 'upgrade-rehearsal': { type: 'on-demand', enabled: true } },
+ executions: { 'task:upgrade-rehearsal': { perApp: { 'app-1': { lastRun: null, count: 0, ...(lastCleanHead ? { lastCleanHead } : {}) } } } }
+ })
+ beforeEach(() => {
+ getAppById.mockResolvedValue({ id: 'app-1', repoPath: '/repo' })
+ isTaskTypeEnabledForApp.mockResolvedValue(true)
+ inputsUnchangedSince.mockReset().mockResolvedValue(true)
+ })
+
+ it('declines unattended launches while no declared input changed since the clean baseline, but never a user Run', async () => {
+ gated(HEAD)
+ const refill = await triggerOnDemandTask('upgrade-rehearsal', 'app-1', { origin: ON_DEMAND_ORIGINS.REFILL })
+ expect(refill).toMatchObject({ reason: 'inputs-unchanged' })
+ expect(inputsUnchangedSince).toHaveBeenCalledWith(expect.objectContaining({ repoPath: '/repo', lastCleanHead: HEAD }))
+ expect(await triggerOnDemandTask('upgrade-rehearsal', 'app-1')).toMatchObject({ taskType: 'upgrade-rehearsal', origin: ON_DEMAND_ORIGINS.USER })
+ })
+
+ it('launches when an input changed or no clean baseline exists', async () => {
+ gated(HEAD)
+ inputsUnchangedSince.mockResolvedValue(false)
+ expect(await triggerOnDemandTask('upgrade-rehearsal', 'app-1', { origin: ON_DEMAND_ORIGINS.REFILL })).toMatchObject({ taskType: 'upgrade-rehearsal' })
+ gated(null)
+ inputsUnchangedSince.mockClear()
+ expect(await triggerOnDemandTask('upgrade-rehearsal', 'app-1', { origin: ON_DEMAND_ORIGINS.REFILL })).toMatchObject({ taskType: 'upgrade-rehearsal' })
+ expect(inputsUnchangedSince).not.toHaveBeenCalled()
+ })
+
+ it('reports inputs-unchanged from readiness instead of a due cron slot', async () => {
+ mockSchedule({
+ tasks: { 'upgrade-rehearsal': { type: 'cron', enabled: true, cronExpression: '* * * * *' } },
+ executions: { 'task:upgrade-rehearsal': { perApp: { 'app-1': { lastRun: null, count: 0, lastCleanHead: HEAD } } } }
+ })
+ parseCronToNextRun.mockReturnValue(new Date(Date.now() - 1000))
+ expect(await shouldRunTask('upgrade-rehearsal', 'app-1')).toMatchObject({ shouldRun: false, reason: 'inputs-unchanged' })
+ inputsUnchangedSince.mockResolvedValue(false)
+ expect(await shouldRunTask('upgrade-rehearsal', 'app-1')).toMatchObject({ shouldRun: true, reason: 'cron-due' })
+ })
+ })
+
it('keeps model research global for both scheduled and manual dispatch', async () => {
mockSchedule({ tasks: { 'model-comparison-refresh': { type: INTERVAL_TYPES.CRON, cronExpression: '* * * * *', enabled: true } } })
parseCronToNextRun.mockReturnValue(new Date(Date.now() - 1000))
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
index e6a10fa2b3..d3a6654f44 100644
--- a/server/services/taskScheduleRegistry.js
+++ b/server/services/taskScheduleRegistry.js
@@ -495,6 +495,23 @@ export const DEFAULT_TASK_INTERVALS = Object.fromEntries(
])
);
+// Repo paths whose change makes a repeat of an expensive executed audit worth
+// buying. An automatic launch is skipped (`inputs-unchanged`) while none differ
+// from the HEAD of the last clean run (#12907); a user-origin launch always runs.
+// Git pathspecs relative to the app's repo root. The prompt version stands in
+// for the prompt body: a body change requires a bump.
+export const TASK_INPUT_PATHS = Object.freeze({
+ 'upgrade-rehearsal': Object.freeze([
+ 'scripts/run-migrations.js',
+ 'scripts/lib/',
+ 'scripts/migrations/',
+ 'data.reference/',
+ 'server/services/backup.js',
+ 'server/services/backupRestore*',
+ 'server/services/taskPromptDefaults/versions.js',
+ ]),
+});
+
// Agent-options that a task manages internally — UI locks the toggle, and
// loadSchedule/updateTaskInterval enforce the default value regardless of
// what's persisted or POSTed. The reasoning lives next to each task above