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
separate the repair-dispatch gate from the update cooldown
[._.]/ Adam Eivy063c35d517ac
diff --git a/server/services/autoUpdateScheduler.js b/server/services/autoUpdateScheduler.jsindex 842e529e35..9804acdafc 100644--- a/server/services/autoUpdateScheduler.js+++ b/server/services/autoUpdateScheduler.js@@ -65,21 +65,39 @@ let ioRef = null;* `lastRunAt` first (this scheduler's own last launch), then the last recorded* update result — which covers an update the USER ran, so a manual update also* resets the interval rather than leaving an automatic one queued behind it.- * `repairQueuedAt` covers the OTHER thing this scheduler dispatches: a repo- * repair agent that stands down without fixing anything never produces a- * `lastRunAt`, so without this the cooldown would never re-arm and the next- * tick would queue a second agent immediately — repeating every 5 minutes- * forever (#7468). `armedAt` is the fallback for an install that has never- * updated: without it the interval would be measured from the epoch and the- * first tick after enabling would fire immediately.+ * `armedAt` is the fallback for an install that has never updated: without it+ * the interval would be measured from the epoch and the first tick after+ * enabling would fire immediately.+ *+ * Deliberately does NOT fold in a repair-agent dispatch (`repairQueuedAt`,+ * see `repairDispatchDue` below): this baseline gates the WHOLE tick,+ * including the update itself, before the checkout is even read. Blending+ * the two would mean a checkout the repair agent fixed in five minutes still+ * could not update for the rest of the interval — breaking the documented+ * promise that PortOS resumes automatically once the checkout is clean.*/export function updateBaselineAt(runtime, lastUpdateResult, now = Date.now()) {- const candidates = [runtime?.lastRunAt, runtime?.repairQueuedAt, lastUpdateResult?.completedAt, runtime?.armedAt]+ const candidates = [runtime?.lastRunAt, lastUpdateResult?.completedAt, runtime?.armedAt].map((value) => (typeof value === 'string' ? Date.parse(value) : NaN)).filter((value) => Number.isFinite(value));return candidates.length ? Math.max(...candidates) : now;}+/**+ * Whether enough time has passed since the last repair-agent DISPATCH to+ * queue another one. A separate gate from `updateBaselineAt` on purpose+ * (#7468): this one only throttles re-queueing a repair agent for a checkout+ * it could not fix, so it must never hold back the update tick itself once+ * the checkout is actually clean. Reuses the same `minIntervalMs` the update+ * cooldown uses — there is no separate configured interval for this, and+ * reusing it keeps "one dispatch per cooldown window" in one place.+ */+export function repairDispatchDue(runtime, minIntervalMs, now = Date.now()) {+ const queuedAt = typeof runtime?.repairQueuedAt === 'string' ? Date.parse(runtime.repairQueuedAt) : NaN;+ if (!Number.isFinite(queuedAt)) return true;+ return now - queuedAt >= minIntervalMs;+}+/*** Is the only thing standing between this checkout and readiness something* `prepareUpdateRepo` can mechanically fix? Those are not worth waking an agent@@ -172,16 +190,20 @@ export async function runAutoUpdateTick({ io = ioRef } = {}) {const read = await checkUpdateRepoReadiness({ fetch: true }).catch((err) => ({ ready: false, needsAgent: false, reasons: ['git-unreadable'], summary: err.message, repairable: [] }));if (!read.ready && !isRepairableOnly(read)) {- if (read.needsAgent && config.resolveBlockersWithAgent) {- await queueRepoRepairTask(read);- // Stamp the cooldown baseline at DISPATCH, not only when an update- // itself runs. `addTask`'s dedup (cosTaskStore.js) only collapses- // repeat ticks onto one task while that task stays open — once the- // agent completes (fixed or not), the task flips to `completed` and the- // very next tick would queue a fresh one with nothing else to stop it.- // This makes a stand-down cost one dispatch per cooldown window instead- // of one per 5-minute tick.- await updateChecker.recordAutoUpdateRuntime({ repairQueuedAt: new Date().toISOString() }).catch(() => undefined);+ if (read.needsAgent && config.resolveBlockersWithAgent && repairDispatchDue(runtime, config.minIntervalMs, now)) {+ const task = await queueRepoRepairTask(read);+ // Stamp only on a REAL dispatch. `addTask`'s dedup (cosTaskStore.js)+ // only collapses repeat ticks onto one task while that task stays open+ // — once the agent completes (fixed or not), the task flips to+ // `completed` and the very next tick would queue a fresh one with+ // nothing else to stop it. `repairDispatchDue` above makes a stand-down+ // cost one dispatch per cooldown window instead of one per 5-minute+ // tick; stamping unconditionally here (including on a failed enqueue,+ // where `task` is null) would lock out every retry for the same+ // window while nothing was actually queued.+ if (task?.id) {+ await updateChecker.recordAutoUpdateRuntime({ repairQueuedAt: new Date().toISOString() }).catch(() => undefined);+ }}return standDown('repo-not-ready', read.summary);}diff --git a/server/services/autoUpdateScheduler.test.js b/server/services/autoUpdateScheduler.test.jsindex 6d838df5c5..772952ee71 100644--- a/server/services/autoUpdateScheduler.test.js+++ b/server/services/autoUpdateScheduler.test.js@@ -34,7 +34,7 @@ vi.mock('./updateChecker.js', () => ({recordAutoUpdateRuntime: deps.recordRuntime,}));-const { runAutoUpdateTick, syncAutoUpdateSchedule, updateBaselineAt, __resetAutoUpdateSchedulerForTests } =+const { runAutoUpdateTick, syncAutoUpdateSchedule, updateBaselineAt, repairDispatchDue, __resetAutoUpdateSchedulerForTests } =await import('./autoUpdateScheduler.js');const HOUR = 60 * 60 * 1000;@@ -226,8 +226,9 @@ describe('checkout readiness gate', () => {// fixing the tree must not be re-queued every 5-minute tick forever.// `addTask`'s dedup only holds while that task stays open, and// `agentFinalization` marks it `completed` regardless of whether the- // checkout ended up clean — so nothing but the cooldown baseline can bound- // the re-dispatch.+ // checkout ended up clean — so nothing but the `repairQueuedAt` gate can+ // bound the re-dispatch. Still `repo-not-ready`, not `cooldown` — the+ // update-cooldown reason must not be reused here (see next test).it('does not queue a second repair agent on the tick after the first one completed', async () => {deps.readRepo.mockResolvedValue(notReady);deps.queueRepair.mockResolvedValue({ id: 'task-1' });@@ -240,7 +241,8 @@ describe('checkout readiness gate', () => {// The repair task is done by the next tick (whether or not it fixed// anything, same as agentFinalization marking it `completed` either way),- // but the baseline stamped above is what the cooldown reads now.+ // but the checkout is STILL not ready, so the repair-dispatch gate above+ // is what has to hold, not the update cooldown.deps.queueRepair.mockClear();deps.gateState.mockResolvedValue({runtime: { armedAt: iso(Date.now() - 48 * HOUR), lastRunAt: null, repairQueuedAt },@@ -249,9 +251,36 @@ describe('checkout readiness gate', () => {});const result = await runAutoUpdateTick({ io: {} });- expect(result).toMatchObject({ ran: false, reason: 'cooldown' });+ expect(result).toMatchObject({ ran: false, reason: 'repo-not-ready' });+ expect(deps.queueRepair).not.toHaveBeenCalled();+ });++ // The bug the reviewer of the first draft of this fix caught: folding the+ // repair-dispatch timestamp into the UPDATE cooldown would mean a checkout+ // the repair agent fixes in minutes still can't update for the rest of the+ // interval. It must update on the very next idle tick instead.+ it('updates on the next tick once the repair agent actually fixed the checkout', async () => {+ deps.gateState.mockResolvedValue({+ runtime: { armedAt: iso(Date.now() - 48 * HOUR), lastRunAt: null, repairQueuedAt: iso(Date.now() - 60_000) },+ lastUpdateResult: null,+ updateInProgress: false,+ });+ deps.readRepo.mockResolvedValue(readyVerdict);++ await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: true });expect(deps.queueRepair).not.toHaveBeenCalled();});++ // A failed enqueue (`queueRepoRepairTask` returns null on its own caught+ // error) must not stamp the gate — otherwise one failed dispatch locks out+ // every retry for the whole cooldown window while nothing was queued.+ it('does not stamp the repair gate when the enqueue itself failed', async () => {+ deps.readRepo.mockResolvedValue(notReady);+ deps.queueRepair.mockResolvedValue(null);++ await runAutoUpdateTick({ io: {} });+ expect(deps.recordRuntime).not.toHaveBeenCalledWith(expect.objectContaining({ repairQueuedAt: expect.any(String) }));+ });});describe('poll registration', () => {@@ -290,15 +319,43 @@ describe('interval baseline', () => {expect(updateBaselineAt({}, null, now)).toBe(now);});- // A repair-agent DISPATCH also resets the clock (#7468) — without this, a- // stand-down agent (no lastRunAt, since no update ever ran) would leave the- // baseline stuck at armedAt forever and every tick would re-queue.- it('also measures the interval from a repair-agent dispatch', () => {+ // #7468: a repair-agent dispatch must NOT feed this baseline. A fixed+ // checkout has to update on the very next tick, not wait out the same+ // interval a second time — that throttling lives in `repairDispatchDue`.+ it('ignores a repair-agent dispatch entirely', () => {const now = Date.parse('2026-01-02T00:00:00Z');expect(updateBaselineAt(- { repairQueuedAt: '2026-01-01T18:00:00Z', armedAt: '2025-12-01T00:00:00Z' },+ { repairQueuedAt: '2026-01-01T23:59:00Z', armedAt: '2025-12-01T00:00:00Z' },null,now,- )).toBe(Date.parse('2026-01-01T18:00:00Z'));+ )).toBe(Date.parse('2025-12-01T00:00:00Z'));+ });+});++describe('repair-dispatch cooldown', () => {+ const MIN_INTERVAL_MS = 6 * HOUR;++ // The regression this whole fix targets: a repair agent that stands down+ // must cost one dispatch per window, not one per 5-minute tick.+ it('refuses a re-dispatch before the interval has elapsed', () => {+ const now = Date.parse('2026-01-02T00:00:00Z');+ expect(repairDispatchDue(+ { repairQueuedAt: iso(now - HOUR) },+ MIN_INTERVAL_MS,+ now,+ )).toBe(false);+ });++ it('allows a re-dispatch once the interval has elapsed', () => {+ const now = Date.parse('2026-01-02T00:00:00Z');+ expect(repairDispatchDue(+ { repairQueuedAt: iso(now - 7 * HOUR) },+ MIN_INTERVAL_MS,+ now,+ )).toBe(true);+ });++ it('allows the first dispatch when nothing has ever been queued', () => {+ expect(repairDispatchDue({}, MIN_INTERVAL_MS, Date.now())).toBe(true);});});diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex 849e2343a6..ad772857f1 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -373,10 +373,12 @@ function normalizeAutoUpdateRuntime(raw) {lastOutcome: typeof source.lastOutcome === 'string' ? source.lastOutcome : null,lastSkip: isPlainObject(source.lastSkip) ? source.lastSkip : null,// When a repo-repair agent was last DISPATCHED (queued), not when it- // finished — `autoUpdateScheduler.updateBaselineAt` folds this into the- // cooldown baseline so a repair agent that stands down without fixing- // anything costs one dispatch per cooldown window, not one per 5-minute- // tick. See root AGENTS.md "AI Provider Usage Policy".+ // finished — `autoUpdateScheduler.repairDispatchDue` reads this to bound+ // a stand-down repair agent to one dispatch per cooldown window instead+ // of one per 5-minute tick. Kept OUT of `updateBaselineAt` on purpose: a+ // checkout the repair agent fixes must still update on the very next+ // idle tick, not wait out the same interval a second time. See root+ // AGENTS.md "AI Provider Usage Policy".repairQueuedAt: typeof source.repairQueuedAt === 'string' ? source.repairQueuedAt : null,};}diff --git a/server/services/updateRepoReadiness.js b/server/services/updateRepoReadiness.jsindex 06b7c21c84..5f5e0a65e1 100644--- a/server/services/updateRepoReadiness.js+++ b/server/services/updateRepoReadiness.js@@ -244,12 +244,14 @@ export async function prepareUpdateRepo({ repoPath = PATHS.root } = {}) {* every subsequent tick onto the one open task ONLY WHILE THAT TASK STAYS* OPEN — once the agent finishes (fixed or not) the task flips to `completed`* and the dedup no longer matches. What actually bounds re-dispatch after that- * is the caller: `autoUpdateScheduler.runAutoUpdateTick` stamps the cooldown- * baseline (`repairQueuedAt`) right after this call returns, so a stand-down- * agent costs one dispatch per cooldown window rather than one per poll- * (#7468). The task store is imported lazily — this module is on the update- * path, the repair branch is rare, and a static import would pull the whole- * CoS state graph into that closure.+ * is the caller: `autoUpdateScheduler.repairDispatchDue` gates a call to this+ * function on a `repairQueuedAt` timestamp stamped right after a successful+ * enqueue, so a stand-down agent costs one dispatch per cooldown window+ * rather than one per poll (#7468). That gate is deliberately separate from+ * the update cooldown, so a checkout this agent fixes still updates on the+ * very next idle tick. The task store is imported lazily — this module is on+ * the update path, the repair branch is rare, and a static import would pull+ * the whole CoS state graph into that closure.** Never rejects: a failed enqueue must not mask the readiness refusal itself.*