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: cache findInProgressIds git/gh lookups behind a short TTL (#3499)
[._.]/ Adam Eivy94db61ffdd52
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e4f686f412..c34bbbed2b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -103,3 +103,5 @@- **[issue-3506] Typing in the ⌘K search bar no longer re-reads every Brain record off disk.** Brain keeps one file per record — people, projects, ideas, admin items, memory entries, links and inbox captures each live in their own directory — and unified search was opening and parsing all of them, across all seven stores, for every single character typed. On a Brain that has been in use for a while that is thousands of file reads per keystroke, which is exactly why the palette got slower the more you put into it. Search now reads a small in-memory projection of just the fields it matches on, refreshed as records change rather than rebuilt per query, so the disk is touched once per store instead of once per character. A store that is legitimately empty counts as read — otherwise the one case with nothing to cache would have kept re-scanning forever. Records arriving from a sync peer, which deliberately land without firing the usual change events so they cannot echo back around the network, now raise a local-only signal so the projection refreshes for them too; without it an inbound sync would have left search answering from a stale snapshot indefinitely. The old cap that only ever searched your 200 most recent inbox captures is gone with it — it existed solely to bound the disk cost that no longer exists.- **[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.diff --git a/server/lib/planIds.js b/server/lib/planIds.jsindex 0b22d93057..07b7e27bf6 100644--- a/server/lib/planIds.js+++ b/server/lib/planIds.js@@ -9,6 +9,7 @@* - assignMissingIds(markdown, extraIds)→ { content, assigned[] }* - extractAllIds(markdown) → string[] (every `[slug]` in PLAN.md)* - findInProgressIds(repoPath, ids) → Set<string> (subset present in branch/PR names)+ * - resetInProgressScanCache(repoPath?) → void (evict the TTL-cached ref scan)* - pickFirstAvailable(items, takenIds) → PlanItem | null** @typedef {Object} PlanItem@@ -298,26 +299,39 @@ export function extractSlugFromRef(ref) {}/**- * Find which of `knownIds` are currently in flight, as evidenced by an open- * git branch (local or remote) or open PR with the slug encoded into a- * documented claim ref pattern (`claim/<slug>` or `cos/<task>/<slug>/<agent>`).- *- * `repoPath` is the repository to query. Git refs (local + freshly fetched- * `origin/*`) are the primary evidence and cover every documented claim pattern;- * the open-PR head refs are a secondary net for a claim whose branch was pruned.+ * How long a claim-ref scan stays reusable. The scan costs a network+ * `git fetch --prune`, a `git branch -a`, and a `gh pr list` child process, and+ * the background scheduler re-evaluates plan-task dispatch far more often than+ * claim branches actually appear (#3499). One minute is short enough that a+ * freshly pushed claim branch is seen on the next tick or two, and long enough+ * that a burst of evaluation ticks costs one scan instead of one each.+ */+export const IN_PROGRESS_SCAN_TTL_MS = 60_000;++/** repoPath → { expiresAt:number, promise:Promise<Set<string>> } */+const inProgressScanCache = new Map();++/**+ * Drop cached claim-ref scans. Call with a `repoPath` to evict one repo, or+ * with no argument to clear every entry.*- * When `gh` cannot be reached the PR net is UNAVAILABLE, not empty (#3358) — the- * degradation is logged once so a run that later double-claims an item has a- * visible cause, rather than the forge outage passing as "no PRs are open".+ * Tests MUST call this in `beforeEach` — the cache is module-level, so without+ * a reset one test's scan result leaks into the next one's assertions.*- * @param {string} repoPath- * @param {string[]|Set<string>} knownIds- * @returns {Promise<Set<string>>}+ * @param {string} [repoPath]*/-export async function findInProgressIds(repoPath, knownIds) {- const known = knownIds instanceof Set ? knownIds : new Set(knownIds);- if (known.size === 0) return new Set();+export function resetInProgressScanCache(repoPath) {+ if (typeof repoPath === 'string') inProgressScanCache.delete(repoPath);+ else inProgressScanCache.clear();+}+/**+ * The uncached scan: every claim slug currently evidenced by a git ref or an+ * open PR head ref in `repoPath`. Returns ALL slugs found, not just the ones a+ * particular caller asked about, so one scan can serve callers with different+ * `knownIds` sets.+ */+async function scanClaimedSlugs(repoPath) {// Best-effort fetch so remote branches are currentawait execGit(['fetch', '--prune'], repoPath).catch(() => {});@@ -339,10 +353,73 @@ export async function findInProgressIds(repoPath, knownIds) {...(prHeadRefs || [])].map(s => s.trim()).filter(Boolean);- const inFlight = new Set();+ const slugs = new Set();for (const ref of refs) {const slug = extractSlugFromRef(ref);- if (slug && known.has(slug)) inFlight.add(slug);+ if (slug) slugs.add(slug);+ }+ return slugs;+}++/**+ * TTL-cached wrapper around `scanClaimedSlugs`. Concurrent callers share the+ * one in-flight promise; the TTL is stamped again when it settles so a slow+ * scan doesn't immediately look stale. A rejected scan is evicted so the next+ * call retries rather than caching the failure.+ */+function claimedSlugs(repoPath, { force = false } = {}) {+ const cached = inProgressScanCache.get(repoPath);+ if (!force && cached && cached.expiresAt > Date.now()) return cached.promise;++ const entry = { expiresAt: Date.now() + IN_PROGRESS_SCAN_TTL_MS, promise: null };+ entry.promise = scanClaimedSlugs(repoPath).then(+ slugs => {+ entry.expiresAt = Date.now() + IN_PROGRESS_SCAN_TTL_MS;+ return slugs;+ },+ err => {+ if (inProgressScanCache.get(repoPath) === entry) inProgressScanCache.delete(repoPath);+ throw err;+ }+ );+ inProgressScanCache.set(repoPath, entry);+ return entry.promise;+}++/**+ * Find which of `knownIds` are currently in flight, as evidenced by an open+ * git branch (local or remote) or open PR with the slug encoded into a+ * documented claim ref pattern (`claim/<slug>` or `cos/<task>/<slug>/<agent>`).+ *+ * `repoPath` is the repository to query. Git refs (local + freshly fetched+ * `origin/*`) are the primary evidence and cover every documented claim pattern;+ * the open-PR head refs are a secondary net for a claim whose branch was pruned.+ *+ * When `gh` cannot be reached the PR net is UNAVAILABLE, not empty (#3358) — the+ * degradation is logged once so a run that later double-claims an item has a+ * visible cause, rather than the forge outage passing as "no PRs are open".+ *+ * The underlying ref scan is cached per `repoPath` for `IN_PROGRESS_SCAN_TTL_MS`+ * so back-to-back scheduler evaluation ticks reuse it instead of respawning+ * `git fetch` / `git branch` / `gh pr list` every time (#3499). What's cached is+ * the full slug set, so a caller passing a different `knownIds` still gets a+ * correct intersection. Pass `{ force: true }` to bypass the cache when a caller+ * is about to act on the result rather than merely gate on it.+ *+ * @param {string} repoPath+ * @param {string[]|Set<string>} knownIds+ * @param {{ force?: boolean }} [options]+ * @returns {Promise<Set<string>>}+ */+export async function findInProgressIds(repoPath, knownIds, options = {}) {+ const known = knownIds instanceof Set ? knownIds : new Set(knownIds);+ if (known.size === 0) return new Set();++ const claimed = await claimedSlugs(repoPath, options);++ const inFlight = new Set();+ for (const slug of claimed) {+ if (known.has(slug)) inFlight.add(slug);}return inFlight;}diff --git a/server/lib/planIds.test.js b/server/lib/planIds.test.jsindex ba1e07a92f..64afb7b6e7 100644--- a/server/lib/planIds.test.js+++ b/server/lib/planIds.test.js@@ -1,4 +1,12 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';++const execGitMock = vi.hoisted(() => vi.fn());+const spawnMock = vi.hoisted(() => vi.fn());++vi.mock('./execGit.js', () => ({ execGit: (...args) => execGitMock(...args) }));+vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));+import {slugify,parsePlanItems,@@ -6,7 +14,10 @@ import {extractAllIds,pickFirstAvailable,diagnoseUnpickablePlan,- extractSlugFromRef+ extractSlugFromRef,+ findInProgressIds,+ resetInProgressScanCache,+ IN_PROGRESS_SCAN_TTL_MS} from './planIds.js';describe('planIds.js', () => {@@ -320,4 +331,136 @@ describe('planIds.js', () => {expect(extractSlugFromRef('claim/foo/bar')).toBe('foo/bar');});});++ describe('findInProgressIds TTL cache', () => {+ // A fake `gh pr list` child: emits its stdout then closes clean.+ const fakeGhChild = (stdout) => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.kill = () => {};+ setImmediate(() => {+ if (stdout) child.stdout.emit('data', Buffer.from(stdout));+ child.emit('close', 0);+ });+ return child;+ };++ // Per-repo branch listings, so a leaked cache entry shows up as the wrong+ // repo's slugs rather than merely as a missing process spawn.+ const branchesByRepo = {+ '/repo/a': 'main\nclaim/alpha\n',+ '/repo/b': 'main\ncos/task-7/beta/agent-1\n'+ };+ const KNOWN = ['alpha', 'beta', 'gamma'];++ let now;++ beforeEach(() => {+ resetInProgressScanCache();+ execGitMock.mockReset();+ spawnMock.mockReset();+ now = 1_700_000_000_000;+ vi.spyOn(Date, 'now').mockImplementation(() => now);+ execGitMock.mockImplementation((args, repoPath) =>+ args[0] === 'branch'+ ? Promise.resolve({ stdout: branchesByRepo[repoPath] ?? '' })+ : Promise.resolve({ stdout: '' })+ );+ spawnMock.mockImplementation(() => fakeGhChild(''));+ });++ afterEach(() => {+ vi.restoreAllMocks();+ resetInProgressScanCache();+ });++ const scanCount = () => spawnMock.mock.calls.length;++ it('reuses the scan for a second call inside the TTL window', async () => {+ const first = await findInProgressIds('/repo/a', KNOWN);+ expect([...first]).toEqual(['alpha']);+ expect(scanCount()).toBe(1);++ now += IN_PROGRESS_SCAN_TTL_MS - 1;+ const second = await findInProgressIds('/repo/a', KNOWN);+ expect([...second]).toEqual(['alpha']);+ // No second `git fetch` / `git branch` / `gh pr list` round-trip.+ expect(scanCount()).toBe(1);+ expect(execGitMock).toHaveBeenCalledTimes(2);+ });++ it('dedupes concurrent callers onto one in-flight scan', async () => {+ const [a, b] = await Promise.all([+ findInProgressIds('/repo/a', KNOWN),+ findInProgressIds('/repo/a', KNOWN)+ ]);+ expect([...a]).toEqual(['alpha']);+ expect([...b]).toEqual(['alpha']);+ expect(scanCount()).toBe(1);+ });++ it('re-scans after the TTL expires and picks up the newer refs', async () => {+ expect([...await findInProgressIds('/repo/a', KNOWN)]).toEqual(['alpha']);+ expect(scanCount()).toBe(1);++ branchesByRepo['/repo/a'] = 'main\nclaim/alpha\nclaim/gamma\n';+ now += IN_PROGRESS_SCAN_TTL_MS + 1;++ const after = await findInProgressIds('/repo/a', KNOWN);+ expect([...after].sort()).toEqual(['alpha', 'gamma']);+ expect(scanCount()).toBe(2);++ branchesByRepo['/repo/a'] = 'main\nclaim/alpha\n';+ });++ it('caches per repoPath — one repo\'s scan never answers for another', async () => {+ expect([...await findInProgressIds('/repo/a', KNOWN)]).toEqual(['alpha']);+ expect([...await findInProgressIds('/repo/b', KNOWN)]).toEqual(['beta']);+ expect(scanCount()).toBe(2);++ // Still isolated on the cached path.+ expect([...await findInProgressIds('/repo/a', KNOWN)]).toEqual(['alpha']);+ expect([...await findInProgressIds('/repo/b', KNOWN)]).toEqual(['beta']);+ expect(scanCount()).toBe(2);++ const repoArgs = execGitMock.mock.calls.map(([, repoPath]) => repoPath);+ expect(new Set(repoArgs)).toEqual(new Set(['/repo/a', '/repo/b']));+ });++ it('intersects the cached slug set against each caller\'s own knownIds', async () => {+ // The cache holds every claimed slug, not one caller's filtered answer —+ // otherwise a second caller with a different id set would read a subset.+ branchesByRepo['/repo/a'] = 'claim/alpha\nclaim/gamma\n';+ expect([...await findInProgressIds('/repo/a', ['alpha'])]).toEqual(['alpha']);+ expect([...await findInProgressIds('/repo/a', ['gamma'])]).toEqual(['gamma']);+ expect(scanCount()).toBe(1);++ branchesByRepo['/repo/a'] = 'main\nclaim/alpha\n';+ });++ it('bypasses the cache with { force: true }', async () => {+ await findInProgressIds('/repo/a', KNOWN);+ expect(scanCount()).toBe(1);++ await findInProgressIds('/repo/a', KNOWN, { force: true });+ expect(scanCount()).toBe(2);+ });++ it('resetInProgressScanCache evicts one repo without clearing the rest', async () => {+ await findInProgressIds('/repo/a', KNOWN);+ await findInProgressIds('/repo/b', KNOWN);+ expect(scanCount()).toBe(2);++ resetInProgressScanCache('/repo/a');+ await findInProgressIds('/repo/a', KNOWN);+ await findInProgressIds('/repo/b', KNOWN);+ expect(scanCount()).toBe(3);+ });++ it('never scans when there are no known ids to match', async () => {+ expect([...await findInProgressIds('/repo/a', [])]).toEqual([]);+ expect(scanCount()).toBe(0);+ expect(execGitMock).not.toHaveBeenCalled();+ });+ });});