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
rank quota readings by the one shared LWW rule instead of three hand-rolled ones
[._.]/ Adam Eivy8adc3630ba29
diff --git a/server/lib/fleetQuotas.js b/server/lib/fleetQuotas.jsindex 50a743a993..45c53f97cc 100644--- a/server/lib/fleetQuotas.js+++ b/server/lib/fleetQuotas.js@@ -24,7 +24,7 @@* (`"3 renders · 24h"`), not addends, so there is nothing to unify honestly.*/-import { parseTsMs } from './lwwTimestamp.js';+import { compareNewerWins, parseTsMs } from './lwwTimestamp.js';import { isNonBlankStr } from './textUtils.js';// Structural bounds on ONE peer-supplied quota payload. Same reasoning as the@@ -115,11 +115,9 @@ function unifyLimits(contributions) {for (const limit of c.limits || []) {const incumbent = best.get(limit.key);if (!incumbent) order.push(limit.key);- const incumbentMs = incumbent ? parseTsMs(incumbent.fetchedAt) : null;- const candidateMs = parseTsMs(c.fetchedAt);- // Unparseable-loses, tie → incumbent: same polarity as every other- // cross-instance merge, so the local reading (always first) holds a tie.- if (!incumbent || (candidateMs !== null && (incumbentMs === null || candidateMs > incumbentMs))) {+ // Unparseable-loses, tie → incumbent: the shared LWW polarity, so the+ // local reading (always first) holds a tie.+ if (!incumbent || compareNewerWins(c.fetchedAt, incumbent.fetchedAt)) {best.set(limit.key, { limit, fetchedAt: c.fetchedAt, instanceId: c.instanceId, name: c.name });}}diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex a1fae2ad29..199d19a829 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -465,7 +465,14 @@ describe('deferred imports stay deferred (#6156)', () => {// origin is carded" policy — is free: onDemandDrain.js already reached that// leaf directly, and gave up its own edge to the same shared helper. Nothing to// narrow — a deferred import IS the narrow form.-const MAX_STATIC_INSTANTIATIONS = 103521;+// The Codex quota-freshness fix measures +4: providerUsage.js and+// providerQuotaShare.js stop hand-rolling "which reading is newer" and reach for+// lwwTimestamp.js (the canonical LWW polarity) plus singleFlight.js. Both are+// dependency-free leaves, so the delta is the two modules themselves across the+// handful of closures that reach these services — there is no subtree behind+// them to narrow, and deferring a compare used on every passive quota read+// would trade the whole point of the shared rule for four instantiations.+const MAX_STATIC_INSTANTIATIONS = 103525;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/staleWhileRevalidate.js b/server/lib/staleWhileRevalidate.jsindex 69c40c7288..8cf1643f8e 100644--- a/server/lib/staleWhileRevalidate.js+++ b/server/lib/staleWhileRevalidate.js@@ -125,26 +125,11 @@ export function createStaleWhileRevalidate({return settled.value;}- /**- * The last successful reading for `key`, or `undefined` — without producing- * one, and WITHOUT applying the TTL.- *- * For a caller that has a cheaper second source and wants to pick between- * them by the readings' own `fetchedAt` rather than by this cache's clock: an- * expensive reading taken an hour ago can still be the more current of the- * two, and `read` would either hide it (TTL lapsed → produce) or pay for a- * spawn to re-confirm it. Since values carry their own age, the caller can- * judge staleness itself; what it cannot do is afford the production.- */- function peek(key) {- return entries.get(key)?.value;- }-/** Test seam / explicit invalidation. Omit `key` to clear everything. */function clear(key) {if (key === undefined) entries.clear();else entries.delete(key);}- return { read, peek, clear };+ return { read, clear };}diff --git a/server/lib/staleWhileRevalidate.test.js b/server/lib/staleWhileRevalidate.test.jsindex 165a803533..d83d5b6ba4 100644--- a/server/lib/staleWhileRevalidate.test.js+++ b/server/lib/staleWhileRevalidate.test.js@@ -126,25 +126,6 @@ describe('createStaleWhileRevalidate', () => {expect(await cache.read('k', produce)).toBe('full'); // …and revalidated});- // For a caller that has a second, cheap source and picks between them by the- // readings' own `fetchedAt`: the expensive reading is still the answer long- // after the TTL lapses, and paying for a respawn to re-confirm it is the cost- // `read` cannot avoid.- it('peeks the last reading without producing one, and without applying the TTL', async () => {- vi.useFakeTimers();- const cache = createStaleWhileRevalidate({ ttlMs: TTL });- const produce = vi.fn().mockResolvedValue('reading');- expect(cache.peek('k')).toBeUndefined(); // cold: nothing to hand back-- await cache.read('k', produce);- vi.advanceTimersByTime(TTL * 10);- expect(cache.peek('k')).toBe('reading');- expect(produce).toHaveBeenCalledTimes(1);-- cache.clear('k');- expect(cache.peek('k')).toBeUndefined();- });-it('keys entries independently and clears them', async () => {const cache = createStaleWhileRevalidate({ ttlMs: TTL });await cache.read('a', () => Promise.resolve(1));diff --git a/server/services/providerQuotaShare.js b/server/services/providerQuotaShare.jsindex 4bcb2d7003..dc9d500277 100644--- a/server/services/providerQuotaShare.js+++ b/server/services/providerQuotaShare.js@@ -19,7 +19,7 @@ import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';import { createMutex } from '../lib/asyncMutex.js';import { sanitizeQuotaCards, latestFetchedAt } from '../lib/fleetQuotas.js';-import { parseTsMs } from '../lib/lwwTimestamp.js';+import { compareNewerWins } from '../lib/lwwTimestamp.js';export const PROVIDER_QUOTAS_FILE = join(PATHS.data, 'provider-quotas.json');@@ -45,16 +45,15 @@ export async function readLocalQuotaCards() {const claimOf = ({ fetchedAt, ...rest }) => JSON.stringify(rest);/**- * Is `card` a reading taken BEFORE `incumbent`?+ * Is `card` a reading taken STRICTLY BEFORE `incumbent`? The shared LWW+ * predicate, asked the other way round — so this guard and the federated merge+ * that consumes the result (`lib/fleetQuotas.js`) rank by one rule.*- * Unparseable on either side is "can't tell", which answers false — the caller- * then falls through to its normal last-write-wins, exactly as before.+ * Only "strictly older" is rejected, not "not newer": two readings stamped the+ * same instant with different claims are a correction, and the later write+ * should still apply.*/-function isOlderReading(card, incumbent) {- const cardMs = parseTsMs(card?.fetchedAt);- const incumbentMs = parseTsMs(incumbent?.fetchedAt);- return cardMs !== null && incumbentMs !== null && cardMs < incumbentMs;-}+const isOlderReading = (card, incumbent) => compareNewerWins(incumbent?.fetchedAt, card?.fetchedAt);/*** Merge a batch of freshly-read cards into the store, keyed by family.@@ -78,13 +77,12 @@ export async function recordLocalQuotaCards(cards) {for (const card of incoming) {const incumbent = byFamily.get(card.family);if (incumbent && claimOf(incumbent) === claimOf(card)) continue;- // A reading taken EARLIER than the one on file is not an update. Adapters- // differ in how stale their source can be — a Codex card derived from- // rollout-log telemetry is stamped with the turn that produced it and can- // be days old, while the same install's live account reading is minutes- // old — so an older card arriving second must not retire a newer one.- // Federation merges these by `fetchedAt`, so letting it through would- // hand every peer a reading this machine already knows is superseded.+ // A reading taken EARLIER than the one on file is not an update: a card+ // stamps when its READING was taken, so a source that lags (Codex rollout+ // telemetry, stamped with the turn that produced it) can arrive after a+ // current one while describing an older moment. Federation ranks these by+ // `fetchedAt`, so letting it through would hand every peer a reading this+ // machine already knows is superseded.if (incumbent && isOlderReading(card, incumbent)) continue;byFamily.set(card.family, card);changed = true;diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex ba32b22879..0eadd8a200 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -7,7 +7,9 @@ import { commandBasename } from '../lib/providerModels.js';import { PROVIDER_FAMILIES } from '../lib/providerFamilies.js';import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';-import { parseHumanReset } from '../lib/quotaReset.js';+import { parseHumanReset, normalizeResetAt } from '../lib/quotaReset.js';+import { compareNewerWins, parseTsMs } from '../lib/lwwTimestamp.js';+import { createSingleFlight } from '../lib/singleFlight.js';import { readFileTail } from '../lib/fileUtils.js';import { codexHomeDir, readCodexRoutingOverride } from '../lib/codexUserConfig.js';import { getSettings } from './settings.js';@@ -34,6 +36,13 @@ import { enabledCloudImageModes } from './imageGen/modes.js';* degraded panel) — in both cases it is the sentence to show in place of* meters, so consumers must not word it as a failure.*+ * `fetchedAt` is WHEN THE READING WAS TAKEN, never when it was served — an+ * adapter reading a log of past events stamps that log's own timestamp, not its+ * clock. Every consumer ranks cards by it: the federated merge takes the+ * freshest reading per limit key (`lib/fleetQuotas.js`), the shared store keeps+ * the newest card per family (`services/providerQuotaShare.js`), and the UI+ * ages what it shows. A card that overstates its freshness wins all three.+ ** `metrics[]` is for a backend whose quota cannot be queried at all: it renders* as labelled stat tiles instead of a meter, so an adapter never has to invent* a percentage to have something to show. `burnable: false` marks a card the@@ -49,9 +58,10 @@ import { enabledCloudImageModes } from './imageGen/modes.js';* Caching: the claude adapter carries its own 60s cache + single-flight inside* claudeCodeUsage.js; the codex adapter is a bounded local-file tail read (1-2* leaf dirs on a typical layout) plus a retained copy of the last LIVE account- * reading, which a passive read serves whenever it is the newer of the two; the Antigravity/Grok adapters carry a 5-min- * cache + single-flight here (`cachedScrape`) because each TUI scrape costs- * ~10-15s (spawn + sign-in + render), too slow to repeat per page poll.+ * reading, served whenever it is the fresher of the two; the Antigravity/Grok+ * adapters carry a 5-min cache + single-flight here (`cachedScrape`) because+ * each TUI scrape costs ~10-15s (spawn + sign-in + render), too slow to repeat+ * per page poll.*/// --- Codex: parse rate-limit telemetry out of local session logs -----------@@ -216,21 +226,19 @@ export function mapCodexQuota(rateLimits, timestamp, {routingOverridden ? CODEX_ROUTING_CAVEAT : null,].filter(Boolean).join(' '),...(limits.length ? {} : { error: codexNoWindowsMessage(rateLimits, now) }),- // The TELEMETRY's own timestamp, not the clock we read it at. Codex only- // emits `rate_limits` while a turn is running, so this reading can be days- // old — and `fetchedAt` is what every consumer ages it by: the federated- // merge picks the freshest reading per limit key, and the quota store keeps- // the newest card per family. Stamping "now" on a stale log tail made it- // win both, so a machine that had not run Codex since Tuesday kept- // overwriting a peer's (and this machine's own) current account reading.+ // The TELEMETRY's own timestamp, not the clock we read it at: Codex emits+ // `rate_limits` only while a turn runs, so this reading can be days old and+ // `fetchedAt` is the card contract every consumer ranks by (see the card+ // shape above). Stamping "now" here let a stale log tail outrank both a+ // peer's current reading and this machine's own live account reading.fetchedAt: telemetryIso(timestamp) || new Date().toISOString()};}/** An ISO string for a telemetry timestamp, or null when it isn't a usable date. */function telemetryIso(timestamp) {- const ms = timestamp == null ? NaN : Date.parse(timestamp);- return Number.isFinite(ms) ? new Date(ms).toISOString() : null;+ const ms = parseTsMs(timestamp);+ return ms === null ? null : new Date(ms).toISOString();}/**@@ -275,29 +283,25 @@ async function listCodexRolloutFiles(codexHome) {}/**- * The last live account reading, kept so a passive page load can serve it.+ * The last live account reading, retained so a passive page load can serve it.*- * `codexAppServer` caches readiness for 15s — long enough to coalesce one- * render, far too short to survive navigating away and back, which is exactly- * when the user sees the number regress. A live reading is retained here until- * something more current replaces it, and `peek` hands it back without ever- * spawning the app-server on a passive read.+ * NOT a TTL cache: `codexAppServer` already caches readiness for 15s, and a+ * reading's usefulness here is decided by its own `fetchedAt` against the+ * rollout log's, never by how long this module has held it. So the pair is+ * exactly "retain the last reading" plus "coalesce concurrent live reads" —+ * a single-flight and a variable, which is what the code does.*/-const codexLiveCache = createStaleWhileRevalidate({- ttlMs: 60 * 1000,- isComplete: (card) => Boolean(card?.limits?.length),-});-const CODEX_LIVE_KEY = 'codex:account';+let retainedLiveCodexCard = null;+const codexLiveFlight = createSingleFlight();/** Test-only: forget the retained live Codex account reading. */export function __resetCodexLiveQuotaCache() {- codexLiveCache.clear();+ retainedLiveCodexCard = null;}/*** Query the signed-in ChatGPT account's quota through the Codex app-server.- * Starts no turn and spends no tokens. Throws when the account can't answer, so- * the stale-while-revalidate cache backs off instead of respawning per request.+ * Starts no turn and spends no tokens. Throws when the account can't answer.*/async function readLiveCodexQuota() {const { getCodexAccountReadiness } = await import('./codexAppServer.js');@@ -314,12 +318,13 @@ async function readLiveCodexQuota() {plan_type: readiness.account?.planType,}, null);const checkedAt = Number.isFinite(readiness.checkedAt) ? readiness.checkedAt : Date.now();- return {+ retainedLiveCodexCard = {...quota,approximate: false,fetchedAt: new Date(checkedAt).toISOString(),note: ['Live Codex account quota.', readCodexRoutingOverride()?.overridden === true ? CODEX_ROUTING_CAVEAT : null].filter(Boolean).join(' '),};+ return retainedLiveCodexCard;}/**@@ -327,11 +332,15 @@ async function readLiveCodexQuota() {** A retained reading whose every metered window has since reset is describing a* spent allowance, the same way `codexWindowExpired` rules out a rolled-over- * log entry. A card with no meters at all has nothing to have expired, so it- * never outranks a reading that does.+ * log entry. A window whose reset time can't be resolved hasn't been shown to+ * have passed, so it counts as live; a card with no meters at all has nothing+ * to have expired, and so never outranks a reading that does.*/const codexCardUnexpired = (card, now) =>- (card?.limits || []).some((limit) => !limit.resetsAt || Date.parse(limit.resetsAt) > now);+ (card?.limits || []).some((limit) => {+ const { epochMs } = normalizeResetAt(limit, { now });+ return epochMs === null || epochMs > now;+ });/*** Passive reads stay local; a fresh request queries the account without@@ -341,23 +350,21 @@ const codexCardUnexpired = (card, now) =>* current state, while the rollout logs only know what the last Codex TURN was* told — which may be days stale. Serving the log tail unconditionally on* passive reads is what made the card snap back to an old percentage as soon as- * the user navigated away from an explicit Refresh, so a retained live reading- * wins whenever it is genuinely the newer of the two.+ * the user navigated away from an explicit Refresh, so the retained live+ * reading holds unless the log is genuinely fresher.*/async function fetchCurrentCodexQuota({ wait = WAIT.CACHED } = {}) {if (wait === WAIT.FRESH) {- const live = await codexLiveCache.read(CODEX_LIVE_KEY, readLiveCodexQuota, { wait }).catch(() => null);+ const live = await codexLiveFlight.run('codex:account', readLiveCodexQuota).catch(() => null);if (live) return live;const quota = await fetchCodexQuota();return { ...quota, note: `Live Codex quota refresh unavailable; showing local telemetry. ${quota.note || ''}`.trim() };}const now = Date.now();- const live = codexLiveCache.peek(CODEX_LIVE_KEY);+ const live = retainedLiveCodexCard;const quota = await fetchCodexQuota({ now });if (!live || !codexCardUnexpired(live, now)) return quota;- const liveMs = Date.parse(live.fetchedAt);- const logMs = Date.parse(quota.fetchedAt);- return Number.isFinite(liveMs) && (!Number.isFinite(logMs) || liveMs >= logMs) ? live : quota;+ return compareNewerWins(quota.fetchedAt, live.fetchedAt) ? quota : live;}/** Exported for tests (which point `codexHome` at a fixture tree). */