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
perf: walk each CoS blocked queue separately so orphan-cooldown revival is linear, not O(N^2) (#3500)
[._.]/ Adam Eivy4d444ba88a6e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9da8782152..dc0cfb927d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -109,3 +109,5 @@- **[issue-3498] Opening a long-running agent's transcript no longer loads the entire log into memory.** A completed agent's `output.txt` has no size ceiling — a multi-hour TUI run writes tens of megabytes — and every request for that agent's details read the whole file and turned each of its 50,000+ lines into its own object, spiking memory and churning the garbage collector for a view that only ever shows the end of the log. The agent detail now hydrates the tail: at most the last 1,000 lines, and never more than 512KB read off disk. Both caps are needed, not just the line one — a repaint-heavy TUI transcript spools as effectively a single enormous line with no newlines in it, so a line count alone bounds nothing. When the log is longer than that, the view says so and reports the full size on disk rather than presenting a clipped transcript as the whole thing. The bounded tail read is now one shared helper instead of the two near-identical private copies that had grown up in the TUI failure analyzer and the Codex usage scan.- **[issue-3499] Background scheduler ticks no longer fire a network `git fetch` and a `gh` process at GitHub every time they check whether a plan item is claimable.** Deciding whether a PLAN.md item is already in flight means reading the repo's claim branches and open PRs, which costs a `git fetch --prune`, a `git branch -a`, and a spawned `gh pr list` — and the evaluation loop runs far more often than claim branches actually appear, so the same three processes were being spawned over and over for an answer that had not changed. The scan result is now reused for a minute per repository, which is short enough that a newly pushed claim branch is still seen within a tick or two and long enough that a burst of checks costs one scan instead of one each. What gets cached is every claimed slug in the repo rather than one caller's filtered answer, so a second caller asking about a different set of items still gets a correct result off the same scan, and callers that overlap in time share a single in-flight scan instead of racing three more processes into the same repo.++- **[issue-3500] The Chief of Staff's cooldown sweep no longer re-scans its whole blocked backlog once per blocked task.** Tasks that get parked with an orphan-retry cooldown are revived by a pass that walks both task queues — the user queue and the internal one — and each revived task has to be written back to the queue it came from. That queue was being re-derived per task by searching the user queue for the task itself, a linear scan inside a linear loop, so the work grew with the square of the backlog on every scheduler tick. The two queues are now walked separately, which hands each task its origin for free and makes the sweep linear. Behavior is unchanged, including that a task carrying an explicit type still wins over the queue it was found in.diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 1a0868fdf9..bc3b6b0b93 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -644,35 +644,44 @@ export function isWithinProjectLimit(task, agentsByProject, perProjectLimit) {return current < perProjectLimit;}+/**+ * Unblock every expired `orphan-cooldown` task in ONE queue's blocked group.+ * `defaultTaskType` names the store the array came from, so a task that carries+ * no explicit `taskType` is routed back to the queue it was read from — no+ * membership scan needed.+ */+async function unblockExpiredCooldownsInQueue(blocked, defaultTaskType) {+ for (const task of blocked || []) {+ if (task.metadata?.blockedCategory !== 'orphan-cooldown' || !task.metadata?.cooldownUntil) continue;+ if (new Date(task.metadata.cooldownUntil).getTime() > Date.now()) continue;+ emitLog('info', `⏰ Orphan cooldown expired for task ${task.id}, unblocking`, { taskId: task.id });+ await updateTask(task.id, {+ status: 'pending',+ metadata: {+ ...task.metadata,+ blockedReason: undefined,+ blockedCategory: undefined,+ blockedAt: undefined,+ cooldownUntil: undefined+ }+ }, task.taskType || defaultTaskType);+ }+}+/*** Unblock tasks whose orphan-retry cooldown has expired. Walks the blocked* groups of both task stores and flips any `orphan-cooldown` task back to* pending once its `cooldownUntil` has passed. Extracted from `evaluateTasks`* so the cooldown-unblock pass is independently testable.+ *+ * Each store is walked separately rather than concatenated: the old single-pass+ * version re-derived the queue of origin with `userBlocked.includes(task)` per+ * task, an O(N) scan inside an O(N) loop (#3500). Passing the origin down makes+ * classification O(1) and the whole pass linear.*/-async function unblockExpiredOrphanCooldowns(userTaskData, cosTaskData) {- const allBlocked = [- ...(userTaskData.grouped?.blocked || []),- ...(cosTaskData.grouped?.blocked || [])- ];- for (const task of allBlocked) {- if (task.metadata?.blockedCategory === 'orphan-cooldown' && task.metadata?.cooldownUntil) {- if (new Date(task.metadata.cooldownUntil).getTime() <= Date.now()) {- const taskType = task.taskType || (userTaskData.grouped?.blocked?.includes(task) ? 'user' : 'internal');- emitLog('info', `⏰ Orphan cooldown expired for task ${task.id}, unblocking`, { taskId: task.id });- await updateTask(task.id, {- status: 'pending',- metadata: {- ...task.metadata,- blockedReason: undefined,- blockedCategory: undefined,- blockedAt: undefined,- cooldownUntil: undefined- }- }, taskType);- }- }- }+export async function unblockExpiredOrphanCooldowns(userTaskData, cosTaskData) {+ await unblockExpiredCooldownsInQueue(userTaskData.grouped?.blocked, 'user');+ await unblockExpiredCooldownsInQueue(cosTaskData.grouped?.blocked, 'internal');}/**diff --git a/server/services/cosTaskGenerator.orphanCooldown.test.js b/server/services/cosTaskGenerator.orphanCooldown.test.jsnew file mode 100644index 0000000000..121fdc9331--- /dev/null+++ b/server/services/cosTaskGenerator.orphanCooldown.test.js@@ -0,0 +1,121 @@+/**+ * `unblockExpiredOrphanCooldowns` — expired orphan-cooldown revival (#3500).+ *+ * The pass walks BOTH task stores' blocked groups and flips any+ * `orphan-cooldown` task whose `cooldownUntil` has passed back to `pending`.+ * Each revived task has to be written back to the store it came from, and the+ * pre-fix version re-derived that origin per task with+ * `userTaskData.grouped.blocked.includes(task)` — an O(N) scan inside the O(N)+ * loop. These tests pin the classification results AND that no membership scan+ * happens, so a future edit can't quietly reintroduce the quadratic lookup.+ *+ * Isolated file so the `cosTaskStore` mock can't leak into the shared+ * cosTaskGenerator suite.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++const updateTaskMock = vi.fn(async () => ({}));+vi.mock('./cosTaskStore.js', async (importActual) => ({+ ...(await importActual()),+ updateTask: (...args) => updateTaskMock(...args),+}));++import { unblockExpiredOrphanCooldowns } from './cosTaskGenerator.js';++const EXPIRED = new Date(Date.now() - 60_000).toISOString();+const PENDING = new Date(Date.now() + 60 * 60_000).toISOString();++const cooldownTask = (id, cooldownUntil, extra = {}) => ({+ id,+ status: 'blocked',+ metadata: { blockedCategory: 'orphan-cooldown', blockedReason: 'orphaned', blockedAt: EXPIRED, cooldownUntil },+ ...extra,+});++/**+ * A blocked-group array that counts every membership scan performed against it.+ * The own `includes` property shadows `Array.prototype.includes`, so the+ * pre-fix `blocked.includes(task)` classification is directly observable.+ */+const scanCountingArray = (tasks) => {+ const arr = [...tasks];+ arr.scans = 0;+ arr.includes = function (...args) {+ arr.scans += 1;+ return Array.prototype.includes.apply(this, args);+ };+ return arr;+};++const store = (blocked) => ({ grouped: { blocked } });++beforeEach(() => {+ updateTaskMock.mockClear();+});++describe('unblockExpiredOrphanCooldowns', () => {+ it('routes each revived task back to the store it was read from', async () => {+ await unblockExpiredOrphanCooldowns(+ store([cooldownTask('u1', EXPIRED)]),+ store([cooldownTask('c1', EXPIRED)])+ );++ expect(updateTaskMock).toHaveBeenCalledTimes(2);+ expect(updateTaskMock.mock.calls.map(([id, , taskType]) => [id, taskType])).toEqual([+ ['u1', 'user'],+ ['c1', 'internal'],+ ]);+ });++ it('classifies queue origin without any membership scan (no O(N^2) lookup)', async () => {+ // Enough tasks that a per-task scan is unmistakable in the counter.+ const userBlocked = scanCountingArray(+ Array.from({ length: 25 }, (_, i) => cooldownTask(`u${i}`, EXPIRED))+ );+ const cosBlocked = scanCountingArray(+ Array.from({ length: 25 }, (_, i) => cooldownTask(`c${i}`, EXPIRED))+ );++ await unblockExpiredOrphanCooldowns(store(userBlocked), store(cosBlocked));++ expect(updateTaskMock).toHaveBeenCalledTimes(50);+ expect(userBlocked.scans).toBe(0);+ expect(cosBlocked.scans).toBe(0);+ });++ it('honors an explicit taskType over the queue default', async () => {+ // A user-typed task parked in the CoS store still writes back as 'user'.+ await unblockExpiredOrphanCooldowns(+ store([]),+ store([cooldownTask('c1', EXPIRED, { taskType: 'user' })])+ );++ expect(updateTaskMock).toHaveBeenCalledWith('c1', expect.anything(), 'user');+ });++ it('clears the block fields and flips status to pending', async () => {+ await unblockExpiredOrphanCooldowns(store([cooldownTask('u1', EXPIRED)]), store([]));++ const [, update] = updateTaskMock.mock.calls[0];+ expect(update.status).toBe('pending');+ expect(update.metadata.blockedCategory).toBeUndefined();+ expect(update.metadata.blockedReason).toBeUndefined();+ expect(update.metadata.blockedAt).toBeUndefined();+ expect(update.metadata.cooldownUntil).toBeUndefined();+ });++ it('leaves unexpired cooldowns, other block categories, and missing groups alone', async () => {+ await unblockExpiredOrphanCooldowns(+ store([+ cooldownTask('u1', PENDING),+ { id: 'u2', metadata: { blockedCategory: 'max-spawns', cooldownUntil: EXPIRED } },+ { id: 'u3', metadata: { blockedCategory: 'orphan-cooldown' } },+ { id: 'u4' },+ ]),+ {}+ );++ expect(updateTaskMock).not.toHaveBeenCalled();+ });+});