Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
fix(auth): retain credential ownership and background cooldown gates
wyt751f1bfd4f6d
diff --git a/src/main/features/auth.ts b/src/main/features/auth.tsindex c7a35c8e..38f6191c 100644--- a/src/main/features/auth.ts+++ b/src/main/features/auth.ts@@ -59,6 +59,7 @@import { normalizeAnthropicBaseUrl } from '../model/custom-model-url';import * as fs from 'node:fs';+import { createHash } from 'node:crypto';import * as path from 'node:path';import { shell } from 'electron';@@ -1134,6 +1135,19 @@ export function getConfiguredModelCooldown(): {return best;}+/** Read-only background gate; provider selection and cooldown policy stay unchanged. */+export function allConfiguredModelsCooledDown(): boolean {+ const store = loadProfiles();+ let configured = 0;+ for (const entry of store.entries) {+ if (!isEntryAllowed(store, entry)) continue;+ if (!store.profiles[entry.profileId]) continue;+ configured += 1;+ if (!getCooldown(entry.profileId)) return false;+ }+ return configured > 0;+}+export function getConfiguredModelOAuthExpiredMessage(): string | null {const store = loadProfiles();const now = Date.now();@@ -1145,7 +1159,7 @@ export function getConfiguredModelOAuthExpiredMessage(): string | null {clearOAuthRefreshFailure(entry.profileId);continue;}- if (!oauthRefreshFailures.has(entry.profileId) && prof.refresh) continue;+ if (!oauthRefreshFailures.has(oauthProfileKey(getActiveUserId(), entry.profileId)) && prof.refresh) continue;return t('errors.model_oauth_expired', { provider: providerLabel(prof.provider) });}return null;@@ -2259,11 +2273,11 @@ async function resolveEntryApiKey(store: ProfilesFile, entry: Entry, userId: strtry {const refreshed = await refreshOAuthProfile(entry.profileId, userId);if (!isActiveAuthOwner(userId)) return undefined;- if (!refreshed) rememberOAuthRefreshFailure(entry.profileId, prof);+ if (!refreshed) rememberOAuthRefreshFailure(entry.profileId, prof, userId);return refreshed;} catch (err) {if (!isActiveAuthOwner(userId)) return undefined;- rememberOAuthRefreshFailure(entry.profileId, prof);+ rememberOAuthRefreshFailure(entry.profileId, prof, userId);log.warn('OAuth refresh failed', { profileId: entry.profileId, error: logErrorSummary(err) });return undefined;}@@ -2463,21 +2477,52 @@ export async function pickRotationKey(providerId: string): Promise<{return null;}-async function refreshOAuthProfile(profileId: string, userId = getActiveUserId()): Promise<string | undefined> {- const store = loadProfiles({ userId });- const prof = store.profiles[profileId];- if (!prof || prof.type !== 'oauth') return undefined;+// A rotating credential is shared by chat and connection probes. Keep one+// exchange per exact owner/credential; reauthorization supersedes older grants.+const oauthRefreshInFlight = new Map<string, Promise<string | undefined>>();++function oauthCredentialFingerprint(prof: OAuthProfile): string {+ return createHash('sha256').update(JSON.stringify([+ prof.provider, prof.access, prof.refresh, prof.expires,+ ])).digest('hex');+}+function isSameOAuthCredential(target: StoredProfile | undefined, expected: OAuthProfile): target is OAuthProfile {+ return target?.type === 'oauth'+ && oauthCredentialFingerprint(target) === oauthCredentialFingerprint(expected);+}++function refreshOAuthProfile(profileId: string, userId = getActiveUserId()): Promise<string | undefined> {+ if (!isActiveAuthOwner(userId)) return Promise.resolve(undefined);+ const prof = loadProfiles({ userId }).profiles[profileId];+ if (!prof || prof.type !== 'oauth') return Promise.resolve(undefined);+ const key = JSON.stringify([userId, profileId, oauthCredentialFingerprint(prof)]);+ const existing = oauthRefreshInFlight.get(key);+ if (existing) return existing;+ const pending = performOAuthProfileRefresh(profileId, userId, prof);+ oauthRefreshInFlight.set(key, pending);+ const clearPending = () => {+ if (oauthRefreshInFlight.get(key) === pending) oauthRefreshInFlight.delete(key);+ };+ pending.then(clearPending, clearPending);+ return pending;+}++async function performOAuthProfileRefresh(+ profileId: string,+ userId: string,+ prof: OAuthProfile,+): Promise<string | undefined> {let oauth: PiOauthModule;try {oauth = await piOauth();} catch (err) {- if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof);+ if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof, userId);throw err;}const provider = await oauth.getOAuthProvider(prof.provider);if (!provider) {- if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof);+ if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof, userId);return undefined;}@@ -2491,26 +2536,29 @@ async function refreshOAuthProfile(profileId: string, userId = getActiveUserId()),),};+ if (!isActiveAuthOwner(userId)) return undefined;+ if (!isSameOAuthCredential(loadProfiles({ userId }).profiles[profileId], prof)) return undefined;let newCreds: any;try {newCreds = await provider.refreshToken(creds as any);} catch (err) {- if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof);+ if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof, userId);throw err;}const fresh = loadProfiles({ throwOnInvalidExisting: true, userId });const target = fresh.profiles[profileId];- if (target && target.type === 'oauth') {- target.access = newCreds.access;- target.refresh = newCreds.refresh;- target.expires = newCreds.expires;- for (const [k, v] of Object.entries(newCreds)) {- if (!['access', 'refresh', 'expires'].includes(k)) {- (target as OAuthProfile)[k] = v;- }+ // An admitted rotating grant still settles only to its original owner.+ // Removal or reauthorization must not be undone by its delayed response.+ if (!isSameOAuthCredential(target, prof)) return undefined;+ target.access = newCreds.access;+ target.refresh = newCreds.refresh;+ target.expires = newCreds.expires;+ for (const [k, v] of Object.entries(newCreds)) {+ if (!['access', 'refresh', 'expires'].includes(k)) {+ target[k] = v;}- saveProfiles(fresh, userId);}+ saveProfiles(fresh, userId);if (isActiveAuthOwner(userId)) clearOAuthRefreshFailure(profileId);return provider.getApiKey(newCreds);}@@ -2692,10 +2740,15 @@ export const saveApiKey = (providerId: string, apiKey: string, label?: string) =addApiKey(providerId, apiKey, label);const oauthRefreshFailures = new Set<string>();-function rememberOAuthRefreshFailure(profileId: string, prof: OAuthProfile): void {+function oauthProfileKey(userId: string, profileId: string): string {+ return JSON.stringify([userId, profileId]);+}+function rememberOAuthRefreshFailure(profileId: string, prof: OAuthProfile, userId = getActiveUserId()): void {if (!profileId || Date.now() < prof.expires) return;- oauthRefreshFailures.add(profileId);+ // A superseded grant is not a failed attempt for its replacement credential.+ if (!isSameOAuthCredential(loadProfiles({ userId }).profiles[profileId], prof)) return;+ oauthRefreshFailures.add(oauthProfileKey(userId, profileId));}-function clearOAuthRefreshFailure(profileId: string): void {- if (profileId) oauthRefreshFailures.delete(profileId);+function clearOAuthRefreshFailure(profileId: string, userId = getActiveUserId()): void {+ if (profileId) oauthRefreshFailures.delete(oauthProfileKey(userId, profileId));}diff --git a/src/main/features/reflection-orchestrator.ts b/src/main/features/reflection-orchestrator.tsindex e98bab08..ff00a79e 100644--- a/src/main/features/reflection-orchestrator.ts+++ b/src/main/features/reflection-orchestrator.ts@@ -60,6 +60,7 @@ import { getLocaleMeta } from '../i18n';import { scheduleBootBackground, isBootAdmissionIdle, type ScheduledBootBackgroundTask } from '../util/boot_init';import { registerUserSwitchHook } from './user-switch-hooks';import { getActiveUserId } from './users';+import { allConfiguredModelsCooledDown } from './auth';type ReflectionErrorCode =| 'transcript_unavailable'| 'empty_response'@@ -597,9 +598,13 @@ async function runCycle(uid: string, opts: RunCycleOpts): Promise<number> {// backoff) for nothing, after paying the dirty scan and runner build. Skip// without touching any window; the cooldown is short next to the 14h// cadence. Nothing configured at all is left to `buildRunner`'s own gate.- // Managed-provider cooldown inspection is private. Orkas still honors- // the injectable gate used by deterministic tests and host integrations.- const isModelUsable = opts.isModelUsable ?? (() => true);+ const isModelUsable = opts.isModelUsable ?? (() => {+ try { return !allConfiguredModelsCooledDown(); }+ catch (err) {+ log.warn('model availability probe failed; running the cycle anyway', { error: logErrorSummary(err) });+ return true;+ }+ });if (!isModelUsable()) {log.info('cycle: every configured model candidate is cooling down, skipping');return 0;diff --git a/test/main/features/auth.test.ts b/test/main/features/auth.test.tsindex 00b29d54..7beba24f 100644--- a/test/main/features/auth.test.ts+++ b/test/main/features/auth.test.ts@@ -1114,6 +1114,52 @@ describe('auth › pickChatEntryGroup + 冷却联动', () => {});});+describe('auth › background model cooldown availability', () => {+ it('leaves an unconfigured store to the normal runner gate', async () => {+ const auth = await import('../../../src/main/features/auth');+ expect(auth.allConfiguredModelsCooledDown()).toBe(false);+ });++ it('reports all configured API-key entries cooling down without mutating credentials', async () => {+ const auth = await import('../../../src/main/features/auth');+ const cooldown = await import('../../../src/main/model/core-agent/profile-cooldown');+ const first = await auth.addApiKeyEntry('anthropic', 'claude-opus-4-8', 'fixture-first-key-xxxxxxxx', 'first');+ const second = await auth.addApiKeyEntry('openai', 'gpt-5.5', 'fixture-second-key-xxxxxxxx', 'second');+ cooldown.markCooldown(first.profileId, 'rate_limit', 'fixture 429');+ cooldown.markCooldown(second.profileId, 'auth', 'fixture 401');+ const paths = await import('../../../src/main/paths');+ const file = paths.userAuthProfilesFile(TEST_UID);+ const original = fs.readFileSync(file);+ expect(auth.allConfiguredModelsCooledDown()).toBe(true);+ expect(fs.readFileSync(file)).toEqual(original);+ });++ it('keeps the cycle usable when one API-key entry is not cooling down', async () => {+ const auth = await import('../../../src/main/features/auth');+ const cooldown = await import('../../../src/main/model/core-agent/profile-cooldown');+ const first = await auth.addApiKeyEntry('anthropic', 'claude-opus-4-8', 'fixture-first-key-xxxxxxxx', 'first');+ const second = await auth.addApiKeyEntry('openai', 'gpt-5.5', 'fixture-second-key-xxxxxxxx', 'second');+ cooldown.markCooldown(first.profileId, 'balance', 'fixture 402');+ expect(auth.allConfiguredModelsCooledDown()).toBe(false);+ cooldown.markCooldown(second.profileId, 'permission', 'fixture 403');+ expect(auth.allConfiguredModelsCooledDown()).toBe(true);+ cooldown.clearCooldown(first.profileId);+ expect(auth.allConfiguredModelsCooledDown()).toBe(false);+ });++ it('ignores disabled entries rather than treating them as usable fallback', async () => {+ const auth = await import('../../../src/main/features/auth');+ const cooldown = await import('../../../src/main/model/core-agent/profile-cooldown');+ const allowed = await auth.addApiKeyEntry('anthropic', 'claude-opus-4-8', 'fixture-allowed-key-xxxxxxxx', 'allowed');+ await auth.addApiKeyEntry('deepseek', 'deepseek-v4-flash', 'fixture-disabled-key-xxxxxxxx', 'disabled');+ cooldown.markCooldown(allowed.profileId, 'auth', 'fixture 401');+ await setDeepSeekEnabled(false);+ expect(auth.allConfiguredModelsCooledDown()).toBe(true);+ await setDeepSeekEnabled(true);+ expect(auth.allConfiguredModelsCooledDown()).toBe(false);+ });+});+describe('auth › hasConfiguredModel', () => {it('reports not-configured on a fresh store', async () => {const a = await import('../../../src/main/features/auth');@@ -1845,6 +1891,186 @@ describe('auth › OAuth login ownership and cancellation', () => {});+describe('auth › rotating OAuth credential ownership', () => {+ async function fixture() {+ const grants: Array<{ resolve: (value: any) => void; reject: (error: Error) => void }> = [];+ const refreshToken = vi.fn(() => new Promise<any>((resolve, reject) => grants.push({ resolve, reject })));+ const provider = { id: 'openai-codex', name: 'Controlled OAuth fixture', refreshToken, getApiKey: (value: any) => value.access };+ const lookup = vi.fn(() => provider);+ vi.doMock('@earendil-works/pi-ai/oauth', () => ({+ getOAuthProvider: lookup, getOAuthProviders: () => [provider], registerOAuthProvider: vi.fn(),+ }));+ const auth = await import('../../../src/main/features/auth');+ const paths = await import('../../../src/main/paths');+ const secrets = await import('../../../src/main/util/local-secret-store');+ const file = paths.userAuthProfilesFile(TEST_UID);+ const write = async (access: string, refresh: string, expires = Date.now() - 1000) => {+ await writeExpiredOAuthEntry({+ providerId: provider.id, model: 'gpt-5.6-sol', access, refresh, expires,+ });+ // The legacy v4 fixture is normalized by the real public reader before+ // capturing exact replacement bytes; migration is not a stale-grant write.+ expect(auth.hasConfiguredModel()).toEqual({ configured: true });+ };+ await write('fixture-original-access', 'fixture-original-refresh');+ const read = () => JSON.parse(secrets.decryptLocalSecret({ namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json' }, fs.readFileSync(file, 'utf8')));+ const next = (access: string) => ({ access, refresh: access + '-refresh', expires: Date.now() + 3_600_000 });+ return { auth, file, write, read, next, grants, refreshToken, lookup, provider };+ }++ it('coalesces concurrent refreshes for the same credential into one grant', async () => {+ const f = await fixture();+ const first = f.auth.pickRotationKey('openai-codex');+ const second = f.auth.pickRotationKey('openai-codex');+ try {+ await vi.waitFor(() => expect(f.grants.length).toBeGreaterThan(0));+ const credentials = f.next('fixture-rotated');+ for (const grant of f.grants) grant.resolve(credentials);+ const results = await Promise.all([first, second]);+ expect(f.refreshToken).toHaveBeenCalledOnce();+ expect(results.map(result => result?.apiKey)).toEqual([credentials.access, credentials.access]);+ expect(f.read().profiles['openai-codex:default']).toMatchObject(credentials);+ } finally {+ for (const grant of f.grants) grant.resolve(f.next('fixture-cleanup'));+ await Promise.all([first, second]);+ }+ });++ it.each(['reauthorize', 'remove'] as const)('does not let an admitted old grant overwrite %s', async action => {+ const f = await fixture();+ const pending = f.auth.pickRotationKey('openai-codex');+ try {+ await vi.waitFor(() => expect(f.grants).toHaveLength(1));+ if (action === 'remove') await f.auth.removeCredential('openai-codex:default');+ else await f.write('fixture-reauthorized', 'fixture-reauthorized-refresh', Date.now() + 3_600_000);+ const expected = fs.readFileSync(f.file);+ f.grants[0].resolve(f.next('fixture-obsolete-grant'));+ expect(await pending).toBeNull();+ expect(fs.readFileSync(f.file)).toEqual(expected);+ } finally { f.grants[0]?.resolve(f.next('fixture-cleanup')); await pending; }+ });++ it('does not start a grant when provider discovery finds a superseded credential', async () => {+ const f = await fixture();+ let release!: () => void;+ let entered = false;+ const gate = new Promise<void>(resolve => { release = resolve; });+ f.lookup.mockImplementation((async () => { entered = true; await gate; return f.provider; }) as any);+ const pending = f.auth.pickRotationKey('openai-codex');+ try {+ await vi.waitFor(() => expect(entered).toBe(true));+ await f.write('fixture-new-login', 'fixture-new-refresh');+ const expected = fs.readFileSync(f.file);+ // An eager resolution keeps the unfixed path bounded while preserving+ // the independent oracle that it must never invoke refreshToken.+ f.refreshToken.mockResolvedValue(f.next('fixture-obsolete-grant'));+ release();+ expect(await pending).toBeNull();+ expect(f.refreshToken).not.toHaveBeenCalled();+ expect(fs.readFileSync(f.file)).toEqual(expected);+ } finally { release(); await pending; }+ });++ it('keeps a newer credential grant pending after the obsolete grant settles', async () => {+ const f = await fixture();+ const first = f.auth.pickRotationKey('openai-codex');+ let second: ReturnType<typeof f.auth.pickRotationKey> | undefined;+ let third: ReturnType<typeof f.auth.pickRotationKey> | undefined;+ try {+ await vi.waitFor(() => expect(f.grants).toHaveLength(1));+ await f.write('fixture-new-login', 'fixture-new-refresh');+ second = f.auth.pickRotationKey('openai-codex');+ await vi.waitFor(() => expect(f.grants).toHaveLength(2));+ f.grants[0].resolve(f.next('fixture-obsolete-grant'));+ const obsoleteResult = await first;+ third = f.auth.pickRotationKey('openai-codex');+ // Both real calls cross provider lookup microtasks before observation.+ await new Promise<void>(resolve => setImmediate(resolve));+ const credentials = f.next('fixture-current-grant');+ for (const grant of f.grants.slice(1)) grant.resolve(credentials);+ const results = await Promise.all([second, third]);+ expect(obsoleteResult).toBeNull();+ expect(f.refreshToken).toHaveBeenCalledTimes(2);+ expect(results.map(result => result?.apiKey)).toEqual([credentials.access, credentials.access]);+ expect(f.read().profiles['openai-codex:default']).toMatchObject(credentials);+ } finally {+ for (const grant of f.grants) grant.resolve(f.next('fixture-cleanup'));+ await Promise.all([first, second, third]);+ }+ });++ it('keeps failure hints private to the account that attempted refresh', async () => {+ const f = await fixture();+ const pending = f.auth.pickRotationKey('openai-codex');+ await vi.waitFor(() => expect(f.grants).toHaveLength(1));+ f.grants[0].reject(new Error('controlled owner A failure'));+ expect(await pending).toBeNull();+ expect(f.auth.getConfiguredModelOAuthExpiredMessage()).toBeTruthy();+ const users = await import('../../../src/main/features/users');+ users.activateUser('oauth-hint-owner-b');+ await writeExpiredOAuthEntry({ providerId: 'openai-codex', model: 'gpt-5.6-sol', uid: 'oauth-hint-owner-b' });+ expect(f.auth.getConfiguredModelOAuthExpiredMessage()).toBeNull();+ });++ it('keeps the original account failure hint after another account refresh succeeds', async () => {+ const f = await fixture();+ const pending = f.auth.pickRotationKey('openai-codex');+ await vi.waitFor(() => expect(f.grants).toHaveLength(1));+ f.grants[0].reject(new Error('controlled owner A failure'));+ expect(await pending).toBeNull();+ const originalHint = f.auth.getConfiguredModelOAuthExpiredMessage();+ expect(originalHint).toBeTruthy();+ const users = await import('../../../src/main/features/users');+ users.activateUser('oauth-hint-owner-b');+ await writeExpiredOAuthEntry({ providerId: 'openai-codex', model: 'gpt-5.6-sol', uid: 'oauth-hint-owner-b' });+ f.refreshToken.mockResolvedValue(f.next('fixture-owner-b-current'));+ expect(await f.auth.pickRotationKey('openai-codex')).toMatchObject({ apiKey: 'fixture-owner-b-current' });+ expect(f.auth.getConfiguredModelOAuthExpiredMessage()).toBeNull();+ users.activateUser(TEST_UID);+ expect(f.auth.getConfiguredModelOAuthExpiredMessage()).toBe(originalHint);+ });++ it('does not record an obsolete grant as a failure of replacement credentials', async () => {+ // This case owns credential state; use a local metadata-only SDK seam.+ vi.doMock('#core-agent', () => ({+ getPiModel: (provider: string, model: string) => ({ id: model, provider,+ api: 'openai-codex-responses', contextWindow: 131072, maxTokens: 32768,+ input: ['text'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }),+ }));+ const f = await fixture();+ const pending = f.auth.pickChatEntryGroup();+ try {+ await vi.waitFor(() => expect(f.grants).toHaveLength(1));+ await f.write('fixture-new-login', 'fixture-new-refresh');+ f.refreshToken.mockResolvedValue(f.next('fixture-unexpected-second-grant'));+ f.grants[0].resolve(f.next('fixture-obsolete-grant'));+ expect(await pending).toEqual([]);+ expect(f.refreshToken).toHaveBeenCalledOnce();+ expect(f.read().profiles['openai-codex:default']).toMatchObject({ access: 'fixture-new-login', refresh: 'fixture-new-refresh' });+ expect(f.auth.getConfiguredModelOAuthExpiredMessage()).toBeNull();+ } finally { f.grants[0]?.resolve(f.next('fixture-cleanup')); await pending; }+ });++ it('releases a failed in-flight refresh so an explicit retry can succeed', async () => {+ const f = await fixture();+ const first = f.auth.pickRotationKey('openai-codex');+ await vi.waitFor(() => expect(f.grants).toHaveLength(1));+ const original = fs.readFileSync(f.file);+ f.grants[0].reject(new Error('controlled refresh failure'));+ expect(await first).toBeNull();+ expect(fs.readFileSync(f.file)).toEqual(original);+ const retry = f.auth.pickRotationKey('openai-codex');+ try {+ await vi.waitFor(() => expect(f.grants).toHaveLength(2));+ const credentials = f.next('fixture-retry-success');+ f.grants[1].resolve(credentials);+ expect(await retry).toMatchObject({ apiKey: credentials.access });+ expect(f.refreshToken).toHaveBeenCalledTimes(2);+ expect(f.read().profiles['openai-codex:default']).toMatchObject(credentials);+ } finally { f.grants[1]?.resolve(f.next('fixture-cleanup')); await retry; }+ });+});+describe('auth › interrupted connection and rotation ownership', () => {const probes = ['metadata', 'refresh', 'discovery', 'factory', 'stream'].flatMap(stage => ['explicit', 'rotation'].flatMap(mode =>['same-account', 'different-account', 'anonymous'].map(destination => [stage, mode, destination]),diff --git a/test/main/features/reflection-orchestrator.test.ts b/test/main/features/reflection-orchestrator.test.tsindex 61834eb8..ac702a0d 100644--- a/test/main/features/reflection-orchestrator.test.ts+++ b/test/main/features/reflection-orchestrator.test.ts@@ -622,6 +622,32 @@ describe('reflection-orchestrator › runOneCycle', () => {expect(mod.readReflectionState(TEST_UID)).toEqual({ lastReflectedAt: {} });});+ it('uses configured API-key cooldowns by default without consuming reflection windows', async () => {+ const auth = await import('../../../src/main/features/auth');+ const cooldown = await import('../../../src/main/model/core-agent/profile-cooldown');+ const first = await auth.addApiKeyEntry('anthropic', 'claude-opus-4-8', 'fixture-first-key-xxxxxxxx', 'first');+ const second = await auth.addApiKeyEntry('openai', 'gpt-5.5', 'fixture-second-key-xxxxxxxx', 'second');+ cooldown.markCooldown(first.profileId, 'rate_limit', 'fixture 429');+ cooldown.markCooldown(second.profileId, 'auth', 'fixture 401');+ const mod = await loadModule();+ const reflect = vi.fn(async () => 'nothing_to_save' as const);+ const isDirty = vi.fn(async () => true);+ const stateFile = path.join(tmpDir, TEST_UID, 'local', 'config', 'reflection-state.json');+ expect(fs.existsSync(stateFile)).toBe(false);+ expect(await mod.runOneCycle(TEST_UID, { now: () => NOW, reflect, isDirty })).toBe(0);+ expect(isDirty).not.toHaveBeenCalled();+ expect(reflect).not.toHaveBeenCalled();+ expect(fs.existsSync(stateFile)).toBe(false);+ expect(mod.readReflectionState(TEST_UID)).toEqual({ lastReflectedAt: {} });++ // A usable credential opens the same production default gate again.+ cooldown.clearCooldown(second.profileId);+ await mod.runOneCycle(TEST_UID, { now: () => NOW, reflect, isDirty });+ expect(isDirty).toHaveBeenCalled();+ expect(reflect).toHaveBeenCalledOnce();+ expect(fs.existsSync(stateFile)).toBe(true);+ });+it('passes model-safe capacity into transcript selection', async () => {const observeBudget = vi.fn();const mod = await loadModuleWithRunner({ writes: 0, inputBudget: 43210, observeBudget });