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: address review (claude): preserve on-demand reconcile behavior
[._.]/ Adam Eivya747179cadb9
diff --git a/scripts/migrations/170-branch-reconcile-to-cos-task.js b/scripts/migrations/170-branch-reconcile-to-cos-task.jsindex f2e0760c20..59b696fabb 100644--- a/scripts/migrations/170-branch-reconcile-to-cos-task.js+++ b/scripts/migrations/170-branch-reconcile-to-cos-task.js@@ -69,6 +69,10 @@ export default {if (isObject(schedule) && isObject(schedule.tasks)) {const task = isObject(schedule.tasks['branch-reconcile']) ? schedule.tasks['branch-reconcile'] : {};task.enabled = true;+ // The legacy enabled flag was explicit consent to an automatic drain.+ // A missing/new default is now on-demand, so retain that old behavior+ // when the migration has no previously selected cadence to preserve.+ if (!task.type || task.type === 'on-demand') task.type = 'perpetual';if (typeof old.cron === 'string' && old.cron.trim().split(/\s+/).length === 5) {task.recheckCron = old.cron;}diff --git a/scripts/migrations/170-branch-reconcile-to-cos-task.test.js b/scripts/migrations/170-branch-reconcile-to-cos-task.test.jsindex 61a5a31e67..0c2c67c3ef 100644--- a/scripts/migrations/170-branch-reconcile-to-cos-task.test.js+++ b/scripts/migrations/170-branch-reconcile-to-cos-task.test.js@@ -78,6 +78,16 @@ describe('migration 170 — branch reconciler → per-app CoS task', () => {expect(meta).toMatchObject({ cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true });});+ it('preserves the legacy automatic drain when the new task entry is absent', async () => {+ writeJson(settingsPath, { branchReconcile: { enabled: true } });+ writeJson(schedulePath, { tasks: {} });++ await migration.up({ rootDir });++ expect(readJson(schedulePath).tasks['branch-reconcile'].type).toBe('perpetual');+ expect(readJson(schedulePath).tasks['branch-reconcile'].enabled).toBe(true);+ });+it('preserves PortOS-only scope by disabling the task on other managed apps', async () => {writeJson(settingsPath, { branchReconcile: { enabled: true } });writeJson(schedulePath, { tasks: { 'branch-reconcile': {} } });diff --git a/server/services/cos.js b/server/services/cos.jsindex 5e70cefd44..bd73cb1931 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -21,6 +21,7 @@ import { join } from 'path';import { getActiveProvider } from './providers.js';import { isInternalTaskId } from '../lib/taskParser.js';import { isAutoApprovableInvestigation } from '../lib/investigationTasks.js';+import { INTERVAL_TYPES, isReconcileDrainTaskType } from './taskScheduleConstants.js';import { isRetryHeld, isStaleRetryHold } from '../lib/taskRetryHold.js';import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, clearStaleActiveAgents } from './appActivity.js';import { getActiveApps } from './apps.js';@@ -1425,17 +1426,18 @@ async function dequeueNextTask({ ignoreTaskId = null } = {}) {}/**- * Pure gate: did the just-completed agent belong to an *enabled perpetual*- * schedule (e.g. claim-issue)? Perpetual tasks are documented as "drain- * actionable work back-to-back (re-queue on completion)" (taskSchedule.js), but- * `dequeueNextTask` above only drains already-queued tasks — it never- * regenerates perpetual work. Without an explicit refill on completion the next- * run waits for the ~hourly `cos-improvement-check` timer (a "ready" perpetual- * task doesn't even shorten that timer — cosJobScheduler gates the delay on- * `status:'scheduled'` tasks only). This gate lets the completion handler decide- * whether to refill the perpetual queue immediately instead of idling. Reads- * the analysis type the same way `queueEligibleImprovementTasks` /- * `isDisabledAnalysisType` do, and never throws on partial inputs.+ * Pure gate: did the just-completed agent belong to an enabled drain schedule+ * (e.g. claim-issue)? Perpetual tasks and the detector-driven+ * reconciliation tasks are documented as draining actionable work back-to-back+ * (re-queue on completion) (taskSchedule.js), but `dequeueNextTask` above only+ * drains already-queued tasks — it never regenerates work. Without an explicit+ * refill on completion the next run waits for the ~hourly+ * `cos-improvement-check` timer (a "ready" task doesn't even shorten that timer+ * — cosJobScheduler gates the delay on `status:'scheduled'` tasks only). This+ * gate lets the completion handler decide whether to refill the drain immediately+ * instead of idling. Reads the analysis type the same way+ * `queueEligibleImprovementTasks` / `isDisabledAnalysisType` do, and never throws+ * on partial inputs.*//*** The scheduled task type a completed agent belongs to, if any — the key@@ -1453,14 +1455,19 @@ export function isPerpetualRefillCandidate(agent, schedule) {const analysisType = agentScheduledType(agent);if (!analysisType) return false;const taskDef = schedule?.tasks?.[analysisType];- return Boolean(taskDef?.enabled) && taskDef.type === 'perpetual';+ const isPerpetual = taskDef?.type === INTERVAL_TYPES.PERPETUAL;+ const isOnDemandReconcile = taskDef?.type === INTERVAL_TYPES.ON_DEMAND+ && isReconcileDrainTaskType(analysisType);+ // Reconciliation keeps its drain semantics even though its fresh-install+ // interval is on-demand; all other on-demand tasks remain single-run actions.+ return Boolean(taskDef?.enabled) && (isPerpetual || isOnDemandReconcile);}/**- * Decide which "lane" a completed perpetual run's drain must continue in. Pure,- * so the branch is unit-testable without a live daemon.+ * Decide which "lane" a completed drain run must continue in. Pure, so the+ * branch is unit-testable without a live daemon.*- * - `'skip'` — not a perpetual refill candidate (disabled/non-perpetual/no+ * - `'skip'` — not a drain refill candidate (disabled/non-draining/no* analysis type); nothing to refill.* - `'onDemand'` — the completed run was a MANUAL "Run Now" drain, marked by* the on-demand spawn engines (`metadata.onDemand`, projecteddiff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 3da4d1b6c5..85ea9638ba 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -2145,6 +2145,7 @@ describe('isPerpetualRefillCandidate — perpetual drain on completion', () => {tasks: {'claim-issue': { type: 'perpetual', enabled: true },'claim-issue-disabled': { type: 'perpetual', enabled: false },+ 'branch-reconcile': { type: 'on-demand', enabled: true },'plan-task': { type: 'daily', enabled: true },},};@@ -2164,6 +2165,10 @@ describe('isPerpetualRefillCandidate — perpetual drain on completion', () => {expect(isPerpetualRefillCandidate(agentFor('plan-task'), schedule)).toBe(false);});+ it('is true for an enabled on-demand reconciliation drain', () => {+ expect(isPerpetualRefillCandidate(agentFor('branch-reconcile'), schedule)).toBe(true);+ });+it('is false for an unknown / unscheduled type', () => {expect(isPerpetualRefillCandidate(agentFor('ghost-type'), schedule)).toBe(false);});@@ -2193,6 +2198,7 @@ describe('perpetualRefillPlan — manual vs scheduled drain lane', () => {tasks: {'claim-issue': { type: 'perpetual', enabled: true },'claim-issue-disabled': { type: 'perpetual', enabled: false },+ 'branch-reconcile': { type: 'on-demand', enabled: true },'plan-task': { type: 'daily', enabled: true },},};@@ -2210,6 +2216,13 @@ describe('perpetualRefillPlan — manual vs scheduled drain lane', () => {)).toEqual({ lane: 'onDemand', taskType: 'claim-issue', appId: 'app-42' });});+ it('routes an on-demand reconciliation drain to the on-demand lane', () => {+ expect(perpetualRefillPlan(+ agent({ taskAnalysisType: 'branch-reconcile', taskOnDemand: true, taskApp: 'app-1' }),+ schedule,+ )).toEqual({ lane: 'onDemand', taskType: 'branch-reconcile', appId: 'app-1' });+ });+it('a manual run with no app resolves appId to null (global on-demand re-issue)', () => {expect(perpetualRefillPlan(agent({ taskAnalysisType: 'claim-issue', taskOnDemand: true }),diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 4745d01517..b91637ed8a 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -54,6 +54,7 @@ import {applyAuditModeWrapper,} from '../lib/auditCatalog.js';import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';+import { isReconcileDrainTaskType } from './taskScheduleConstants.js';import {appendClaimOverrideContext,appendPrefetchedIssueContext,@@ -2155,9 +2156,9 @@ function takePerpetualTransient(taskType, appId) {* Surface WHY a user-initiated on-demand "Run" produced no task, so the trigger* isn't a silent no-op the user only discovers in the pm2 logs. Emits* `schedule:on-demand-empty` (which the client toasts) with an `outcome`:- * - 'parked' → a perpetual detector re-checked and found no actionable work;+ * - 'parked' → a detector-driven task re-checked and found no actionable work;* carries the reason + open/in-flight/filtered breakdown.- * - 'transient' → a perpetual task that did NOT park — a gh/glab probe+ * - 'transient' → a detector-driven task that did NOT park — a gh/glab probe* failure — so the check didn't actually complete. Carries a* `forge` block naming the real fault when the CLI is broken* in a way that will NOT clear on its own.@@ -2174,8 +2175,9 @@ function takePerpetualTransient(taskType, appId) {export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig }) {const appId = targetApp?.id || null;const parkInfo = await taskScheduleMod.getPerpetualParkInfo(request.taskType, appId).catch(() => null);- const isPerpetual = taskConfig?.type === taskScheduleMod.INTERVAL_TYPES.PERPETUAL;- const outcome = parkInfo ? 'parked' : (isPerpetual ? 'transient' : 'idle');+ const isDetectorDriven = taskConfig?.type === taskScheduleMod.INTERVAL_TYPES.PERPETUAL+ || isReconcileDrainTaskType(request.taskType);+ const outcome = parkInfo ? 'parked' : (isDetectorDriven ? 'transient' : 'idle');// Layered Intelligence skips (e.g. a provider that can't drive an agent) record// an actionable last-run reason. Surface it so a manual "Run" toasts WHY it@@ -2419,8 +2421,9 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i}/**- * The ONE consecutive-dispatch cap for every perpetual drain, checked at the- * choke point all four spawn engines funnel through.+ * The ONE consecutive-dispatch cap for every perpetual or on-demand+ * reconciliation drain, checked at the choke point all four spawn engines funnel+ * through.** Every perpetual drain re-issues itself the moment its run completes, so* "keeps finding work" and "is stuck in a loop" look identical one cycle at a@@ -2439,7 +2442,10 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i* @returns {Promise<{skip:boolean}>}*/export async function applyPerpetualDrainCap(app, taskType, interval, taskSchedule) {- if (interval.type !== taskSchedule.INTERVAL_TYPES.PERPETUAL) return { skip: false };+ const isPerpetual = interval.type === taskSchedule.INTERVAL_TYPES.PERPETUAL;+ const isOnDemandReconcile = interval.type === taskSchedule.INTERVAL_TYPES.ON_DEMAND+ && isReconcileDrainTaskType(taskType);+ if (!isPerpetual && !isOnDemandReconcile) return { skip: false };// Coerce before validating: this key is not on the schedule route's allowlist, so// the only way it arrives non-numeric is a hand-edited schedule.json, where `"5"`// is the likeliest shape and reading it as "no cap" would silently unbound thediff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 235e0cf6f6..8bc3742891 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -1110,7 +1110,7 @@ describe('emitOnDemandEmpty', () => {// and the INTERVAL_TYPES enum the perpetual check reads.const stubMod = {getPerpetualParkInfo: async () => null,- INTERVAL_TYPES: { PERPETUAL: 'perpetual' }+ INTERVAL_TYPES: { ON_DEMAND: 'on-demand', PERPETUAL: 'perpetual' }};it("emits an 'idle' event with reason null for a non-LI task type", async () => {@@ -1161,6 +1161,24 @@ describe('emitOnDemandEmpty', () => {expect(await emitTransient('claim-issue')).toMatchObject({ outcome: 'transient', forge: null });});+ it('treats on-demand reconciliation as detector-driven for transient feedback', async () => {+ recordPerpetualTransient('branch-reconcile', 'app-1', { cli: null, reason: 'probe-failed' });+ const events = [];+ const handler = (data) => events.push(data);+ cosEvents.on('schedule:on-demand-empty', handler);+ try {+ await emitOnDemandEmpty({+ taskScheduleMod: stubMod,+ request: { id: 'req-reconcile', taskType: 'branch-reconcile' },+ targetApp: { id: 'app-1', name: 'App One' },+ taskConfig: { type: 'on-demand' }+ });+ } finally {+ cosEvents.off('schedule:on-demand-empty', handler);+ }+ expect(events[0]).toMatchObject({ taskType: 'branch-reconcile', outcome: 'transient' });+ });+it('skips the gh probe for a non-gh transient verdict, so a glab/git fault never toasts a gh remedy', async () => {// branch-reconcile and quota-burn go transient over git / provider faults with// no forge at all (cli: null); claim-issue-gitlab fails on glab. None of them@@ -1555,7 +1573,7 @@ describe('resolveReconcileDrainGate', () => {*/describe('applyPerpetualDrainCap', () => {const fakeSchedule = (dispatchCount = 0) => ({- INTERVAL_TYPES: { PERPETUAL: 'perpetual' },+ INTERVAL_TYPES: { ON_DEMAND: 'on-demand', PERPETUAL: 'perpetual' },getPerpetualDrainState: vi.fn(async () => ({ signature: null, dispatchCount })),parkPerpetual: vi.fn(async () => {})});@@ -1597,9 +1615,14 @@ describe('applyPerpetualDrainCap', () => {it('ignores non-perpetual intervals entirely', async () => {const ts = fakeSchedule(500);- expect(await applyPerpetualDrainCap(app, 'branch-reconcile', { type: 'daily', drainDispatchCap: 5 }, ts)).toEqual({ skip: false });+ expect(await applyPerpetualDrainCap(app, 'security', { type: 'daily', drainDispatchCap: 5 }, ts)).toEqual({ skip: false });expect(ts.getPerpetualDrainState).not.toHaveBeenCalled();});++ it('applies the cap to the on-demand reconciliation drain', async () => {+ const ts = fakeSchedule(5);+ expect(await applyPerpetualDrainCap(app, 'branch-reconcile', { type: 'on-demand', drainDispatchCap: 5 }, ts)).toEqual({ skip: true });+ });});/**diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 069b68c240..996ddd20dc 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -713,8 +713,9 @@ export async function applyOnDemandRunResets(request, appId = null) {* Returns { satisfied, pending } where pending lists unfinished dependency task types.** Dependencies that are disabled — either globally (missing from the schedule or- * `enabled: false`) or disabled for the requesting app — are skipped, since they- * will never run and would otherwise block the dependent task indefinitely.+ * `enabled: false`) — or use an on-demand interval are skipped, since they will+ * not run automatically and would otherwise block the dependent task indefinitely.+ * A scheduled per-app override keeps its dependency gate active.*/async function checkRunAfterDeps(schedule, taskType, appId = null) {const interval = schedule.tasks[taskType];@@ -730,6 +731,8 @@ async function checkRunAfterDeps(schedule, taskType, appId = null) {const depConfig = schedule.tasks[dep];if (!depConfig || !depConfig.enabled) continue;if (appId && !(await isTaskTypeEnabledForApp(appId, dep))) continue;+ const depPerAppInterval = appId ? await getAppTaskTypeInterval(appId, dep) : null;+ if ((depPerAppInterval || depConfig.type) === INTERVAL_TYPES.ON_DEMAND) continue;const depKey = `task:${dep}`;const depExec = schedule.executions[depKey] || { lastRun: null, perApp: {} };diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex d44643efc1..768d212d95 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -381,6 +381,16 @@ describe('taskSchedule', () => {expect(schedule.tasks['security'].providerId).toBe('p1')})+ it('preserves an existing paused cadence when loading new defaults', async () => {+ mockSchedule({+ tasks: { security: { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null } }+ })++ const schedule = await loadSchedule()++ expect(schedule.tasks.security).toMatchObject({ type: INTERVAL_TYPES.WEEKLY, enabled: false })+ })+it('should merge defaults for missing task types', async () => {mockSchedule({tasks: { 'security': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null } }@@ -1104,6 +1114,22 @@ describe('taskSchedule', () => {}})+ it('feature-ideas ignores an enabled on-demand do-replan dependency', async () => {+ const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()++ mockSchedule({+ tasks: {+ 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null },+ 'do-replan': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null }+ },+ executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }+ })++ const result = await shouldRunTask('feature-ideas')+ expect(result.shouldRun).toBe(true)+ expect(result.reason).toContain('daily-due')+ })+it('feature-ideas runs when do-replan has run since its last run', async () => {const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()diff --git a/server/services/taskScheduleConstants.js b/server/services/taskScheduleConstants.jsindex 13fc64037c..5c60f9d2c5 100644--- a/server/services/taskScheduleConstants.js+++ b/server/services/taskScheduleConstants.js@@ -21,3 +21,5 @@ export const FAILURE_BACKOFF_CAP_MS = DAY_MS;export const FAILURE_PARK_THRESHOLD = 5;export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill' };export const isRefillRequest = (request) => request?.origin === ON_DEMAND_ORIGINS.REFILL;+const RECONCILE_DRAIN_TASK_TYPES = new Set(['branch-reconcile', 'issue-reconcile']);+export const isReconcileDrainTaskType = (taskType) => RECONCILE_DRAIN_TASK_TYPES.has(taskType);diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.jsindex b6e052b532..12f8d93134 100644--- a/server/services/taskScheduleRegistry.js+++ b/server/services/taskScheduleRegistry.js@@ -201,10 +201,11 @@ export const DEFAULT_TASK_INTERVALS = {// branch-reconcile first removes fully-merged, clean orphaned worktrees and// branches, then finishes THIS machine's remaining in-flight LOCAL branches// per app (open a PR for pushed-but-unopened work, resolve merge conflicts,- // drive the review loop, auto-merge when green). PERPETUAL (drain-until-done):- // the generator runs the deterministic reconcile every dispatch, and dispatches- // the coordinator agent only while actionable in-flight branches remain — then- // PARKS on the daily recheckCron. The action toggles (cleanupMerged / openPr /+ // drive the review loop, auto-merge when green). Detector-driven drain behavior:+ // the generator runs the deterministic reconcile every manual/on-demand+ // dispatch (or selected perpetual dispatch), and dispatches the coordinator+ // agent only while actionable in-flight branches remain — then PARKS on the+ // daily recheckCron. The action toggles (cleanupMerged / openPr /// resolveConflicts / autoMerge / finishAbandoned) are per-app taskMetadata// booleans (each ON unless explicitly false); `finishAbandoned` covers the work// a dead agent left UNCOMMITTED in its worktree — commit + ship it, or report it@@ -222,10 +223,11 @@ export const DEFAULT_TASK_INTERVALS = {// issue-reconcile heals ZOMBIE issues: open + `in-progress` (claimed) yet with// their PR already MERGED and no live claim anywhere — a partial ship left the// claim marker on, so the queue (which skips `in-progress`) never re-picks the- // remaining scope. PERPETUAL (drain-until-done): the generator runs the- // deterministic gh/git scan every dispatch and dispatches the coordinator agent- // only while zombies remain — then PARKS on the daily recheckCron (offset an- // hour after branch-reconcile so merged-branch cleanup lands first). The+ // remaining scope. Detector-driven drain behavior: the generator runs the+ // deterministic gh/git scan every manual/on-demand dispatch (or selected+ // perpetual dispatch) and dispatches the coordinator agent only while zombies+ // remain — then PARKS on the daily recheckCron (offset an hour after+ // branch-reconcile so merged-branch cleanup lands first). The// coordinator applies the partial-ship hybrid per zombie (close + file a scoped// follow-up when the remainder is separable, else comment "done/remaining" +// release the claim). `autoClose` (ON unless explicitly false) is the only