Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
fix(brain): refresh a brain's rules from upkeep, so one empty pull is not forever (#343)
anirudhkumar-nanonetscf954d0acf8f
diff --git a/src/brain/link.ts b/src/brain/link.tsindex c4d786ea..f23b75a3 100644--- a/src/brain/link.ts+++ b/src/brain/link.ts@@ -18,9 +18,21 @@ import { join } from 'node:path';/** Default API host. Overridden by GRAFT_BRAIN_URL, for staging and self-hosted. */const DEFAULT_BRAIN_BASE_URL = 'https://agents.nanonets.com';-/** How long a cached rule set is served before `ask` refreshes it in the background. */+/** How long a cached rule set is served before upkeep refreshes it. */export const RULES_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours+/**+ * The TTL used while the cache holds NO rules.+ *+ * A brain is connected during onboarding while it is still being mined, so the+ * first pull legitimately returns nothing. Six hours of that is the difference+ * between the feature working and the user concluding it does not: they wired+ * graft up, got an empty rulebook, and nothing would go back for the real one+ * until tomorrow. Two minutes costs one cheap request per session until the+ * rules land, and then the normal TTL takes over.+ */+export const EMPTY_RULES_TTL_MS = 2 * 60 * 1000;+/** One rule from the brain, anchored to a symbol in this repo. */export interface BrainRule {ruleId: string;@@ -38,6 +50,11 @@ export interface RulesCache {brainId: string;fetchedAt: number;rules: BrainRule[];+ /** When a refresh was last ATTEMPTED, successful or not. Separate from+ * `fetchedAt`, which records when rules last actually arrived: without the+ * distinction, a brain that is still building would be re-checked on every+ * single command, because its `fetchedAt` never advances. */+ checkedAt?: number;}/** The persisted brain link. */@@ -89,9 +106,24 @@ export function writeRulesCache(dir: string, cache: RulesCache): void {writeJsonAtomic(rulesCachePath(dir), cache, true);}-/** Whether a cached set is old enough to refetch. */+/**+ * Whether a cached set is old enough to refetch.+ *+ * Keyed off the last ATTEMPT, not the last success, and with a much shorter+ * window while the cache is empty — see EMPTY_RULES_TTL_MS for why that case+ * is the one that matters.+ */export function cacheIsStale(cache: RulesCache | null, now = Date.now()): boolean {- return !cache || now - cache.fetchedAt > RULES_TTL_MS;+ if (!cache) return true;+ const ttl = cache.rules.length === 0 ? EMPTY_RULES_TTL_MS : RULES_TTL_MS;+ return now - (cache.checkedAt ?? cache.fetchedAt) > ttl;+}++/** Record that a refresh was attempted, without claiming rules arrived. */+export function markRulesChecked(dir: string, now = Date.now()): void {+ const cache = readRulesCache(dir);+ if (!cache) return;+ writeRulesCache(dir, { ...cache, checkedAt: now });}/**diff --git a/src/cli.ts b/src/cli.tsindex 27b50689..f4a81366 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -208,7 +208,7 @@ function parseTabs(raw: string | undefined): VizTab[] | undefined {* not editorialize on stderr at startup (`mcp` runs its own upkeep at boot, and* `_update-check` IS the fetch).*/-const UPKEEP_SKIP = new Set(["version", "upgrade", "_update-check", "mcp"]);+const UPKEEP_SKIP = new Set(["version", "upgrade", "_update-check", "_brain-refresh", "mcp"]);/*** Every other command: top up the cached registry answer in the background and,@@ -242,6 +242,21 @@ program.hook("postAction", (_parent, action) => {});// Hidden from --help: only ever spawned detached by maybeRefreshInBackground.+program+ .command("_brain-refresh", { hidden: true })+ .description("internal: re-pull the attached brain's rules and rewrite the agent files")+ .argument("[dir]", "target repo directory", ".")+ .action(async (dir: string) => {+ // Spawned detached by upkeep, so nothing here is user-visible and nothing+ // may throw: a failure means the cached rules keep serving, which is the+ // correct outcome for a brain that is momentarily unreachable.+ try {+ await pullBrain(resolve(dir), { home: homedir() });+ } catch {+ /* the next session tries again */+ }+ });+program.command("_update-check", { hidden: true }).description("internal: refresh the cached latest-version answer")diff --git a/src/upkeep-run.ts b/src/upkeep-run.tsindex 7c64afa5..fd60065d 100644--- a/src/upkeep-run.ts+++ b/src/upkeep-run.ts@@ -11,6 +11,7 @@ import { graftCliPath } from './claude/paths.js';import {formatUpdateNudge,formatWiringRefresh,+ maybeRefreshBrainRules,maybeRefreshInBackground,readUpdateCache,reconcileWiring,@@ -66,6 +67,11 @@ export function runUpkeep(const refreshLine = formatWiringRefresh(refreshed);if (refreshLine) lines.push(refreshLine);} catch { /* fail-soft: wiring refresh is never worth breaking a session for */ }+ try {+ // Rules the attached brain has gained since the last pull. Detached, so it+ // never delays the session it runs in.+ if (opts.background !== false) maybeRefreshBrainRules(repo);+ } catch { /* same */ }try {if (opts.background !== false) maybeRefreshInBackground(opts.home);const nudge = formatUpdateNudge(current, readUpdateCache(opts.home)?.latest);diff --git a/src/upkeep.ts b/src/upkeep.tsindex b573b3e4..5856f61c 100644--- a/src/upkeep.ts+++ b/src/upkeep.ts@@ -32,6 +32,7 @@ import { readJson, writeJsonAtomic, cacheDir } from './util/state.js';import { HOSTS } from './hosts/registry.js';import { START } from './hosts/sections.js';import { getNpmViewVersion, readCurrentVersion } from './cli-meta.js';+import { cacheIsStale, markRulesChecked, readLink, readRulesCache } from './brain/link.js';import { graftCliPath } from './claude/paths.js';/**@@ -143,6 +144,41 @@ export function maybeRefreshInBackground(home?: string, now = Date.now()): boole}}+/**+ * Refresh the attached brain's rules in a detached child, when they are stale.+ *+ * The same shape as the update check above, and for the same reason: this runs+ * inside session-start hooks and MCP boot, where waiting on the network is a+ * stalled first turn. So nothing here blocks — the child does the fetch and+ * this call returns immediately.+ *+ * Without it a brain is pulled exactly once, at `graft brain connect`, and+ * never again. That was survivable when connecting happened after the brain+ * finished building; it is not survivable now that onboarding connects DURING+ * the build, because the one pull returns an empty rulebook and nothing would+ * ever go back for the real one.+ *+ * The attempt is stamped before spawning, so a brain that is still building+ * costs one request per TTL window rather than one per command.+ */+export function maybeRefreshBrainRules(repo: string, now = Date.now()): boolean {+ try {+ if (!readLink(repo)) return false;+ const cache = readRulesCache(repo);+ if (!cacheIsStale(cache, now)) return false;+ markRulesChecked(repo, now);+ const child = spawn(process.execPath, [graftCliPath(), '_brain-refresh', repo], {+ detached: true,+ stdio: 'ignore',+ windowsHide: true,+ });+ child.unref();+ return true;+ } catch {+ return false; // no spawn, or an unreadable repo — the cached rules still serve+ }+}+/** One line, or nothing. Nothing is the common case — don't spend context on* "you're up to date". */export function formatUpdateNudge(current: string, latest: string | null | undefined): string | null {