Skip to content

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

stamp the quota slot on write so a corrected reading still reaches peers

[._.]/ Adam Eivy2aee2cf673b5
diff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.js
index 97043a932f..c7610323a6 100644
--- a/server/services/peerUsage.test.js
+++ b/server/services/peerUsage.test.js
@@ -455,7 +455,29 @@ describe('federated subscription-quota readings', () => {
expect(self.quotas).toEqual([expect.objectContaining({ family: 'claude', plan: 'subscription' })]);
// A quota refresh with no new AI runs must still move the slot, or no peer
// would ever pull it: `capturedAt` is both the LWW stamp and the manifest.
- expect(self.capturedAt).toBe('2026-08-31T00:00:00.000Z');
+ expect(Date.parse(self.capturedAt)).toBeGreaterThanOrEqual(Date.parse('2026-08-31T00:00:00.000Z'));
+ });
+
+ // `capturedAt` is the manifest fingerprint, so it has to move whenever the
+ // entry does. Deriving it from the freshest card's `fetchedAt` only worked
+ // while every adapter stamped its read clock: a Codex card carries the
+ // timestamp of the turn that produced it, so a corrected Codex reading can
+ // sit behind a sibling card's stamp and — without a write clock — leave the
+ // slot pinned, so no peer ever pulls the correction.
+ it('moves the LWW stamp when a card changes behind a newer sibling card', async () => {
+ await recordLocalQuotaCards([
+ quotaCard({ fetchedAt: '2026-08-31T12:00:00.000Z' }),
+ quotaCard({ family: 'codex', label: 'Codex', fetchedAt: '2026-08-30T08:00:00.000Z' }),
+ ]);
+ const before = (await readLocalQuotaCards()).capturedAt;
+
+ // New Codex telemetry, still older than the claude card's stamp.
+ const spent = [{ key: 'week', label: 'Current week', percentUsed: 100, percentRemaining: 0, resetsAt: null, timezone: null }];
+ const write = await recordLocalQuotaCards([
+ quotaCard({ family: 'codex', label: 'Codex', fetchedAt: '2026-08-30T09:00:00.000Z', limits: spent }),
+ ]);
+ expect(write.changed).toBe(true);
+ expect(Date.parse(write.capturedAt)).toBeGreaterThan(Date.parse(before));
});
it('re-records only what changed, so a repeated read is not a new slot to pull', async () => {
diff --git a/server/services/providerQuotaShare.js b/server/services/providerQuotaShare.js
index dc9d500277..b9c2817add 100644
--- a/server/services/providerQuotaShare.js
+++ b/server/services/providerQuotaShare.js
@@ -19,18 +19,35 @@ 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 { compareNewerWins } from '../lib/lwwTimestamp.js';
+import { compareNewerWins, parseTsMs } from '../lib/lwwTimestamp.js';
+import { isNonBlankStr } from '../lib/textUtils.js';
export const PROVIDER_QUOTAS_FILE = join(PATHS.data, 'provider-quotas.json');
const withLock = createMutex();
-/** The cards this instance last read, newest-known per family. Never throws. */
+/**
+ * The cards this instance last read, newest-known per family, plus WHEN THIS
+ * STORE LAST CHANGED. Never throws.
+ *
+ * `capturedAt` is the federated slot's LWW stamp and manifest fingerprint (see
+ * `buildSelfEntry` in services/peerUsage.js), so it has to move whenever
+ * anything in the entry does. It is therefore the WRITE clock, not the freshest
+ * card's `fetchedAt` — those coincide only while every adapter stamps its read
+ * clock, and an adapter that honestly reports older telemetry (Codex, stamped
+ * with the turn that produced it) breaks the equivalence: a corrected Codex
+ * reading whose timestamp sits behind a sibling card's stamp would leave
+ * `capturedAt` pinned, and no peer would ever pull the correction.
+ *
+ * A store written before `capturedAt` existed falls back to the old derivation,
+ * which is exactly what those installs already published.
+ */
export async function readLocalQuotaCards() {
// Read-only projection; this fallback is never used by the merge writer below.
const raw = await readJSONFile(PROVIDER_QUOTAS_FILE, null);
const quotas = sanitizeQuotaCards(isPlainObject(raw) ? raw.quotas : null);
- return { quotas, capturedAt: latestFetchedAt(quotas) };
+ const capturedAt = isNonBlankStr(raw?.capturedAt) ? raw.capturedAt : latestFetchedAt(quotas);
+ return { quotas, capturedAt };
}
/**
@@ -55,6 +72,17 @@ const claimOf = ({ fetchedAt, ...rest }) => JSON.stringify(rest);
*/
const isOlderReading = (card, incumbent) => compareNewerWins(incumbent?.fetchedAt, card?.fetchedAt);
+/**
+ * The next strictly-increasing write stamp after `prior` — the current clock,
+ * nudged a millisecond past `prior` when the clock has not moved (or has gone
+ * backwards, as it can across an NTP correction).
+ */
+function nextStamp(prior) {
+ const nowMs = Date.now();
+ const priorMs = parseTsMs(prior);
+ return new Date(priorMs !== null && nowMs <= priorMs ? priorMs + 1 : nowMs).toISOString();
+}
+
/**
* Merge a batch of freshly-read cards into the store, keyed by family.
*
@@ -88,8 +116,15 @@ export async function recordLocalQuotaCards(cards) {
changed = true;
}
const quotas = [...byFamily.values()];
- if (!changed) return { quotas, changed: false };
- await atomicWrite(PROVIDER_QUOTAS_FILE, { quotas });
- return { quotas, changed: true };
+ const storedAt = isNonBlankStr(raw?.capturedAt) ? raw.capturedAt : latestFetchedAt(quotas);
+ if (!changed) return { quotas, capturedAt: storedAt, changed: false };
+ // Stamped on the WRITE, so the slot moves whenever its contents do — see
+ // readLocalQuotaCards for why the freshest card's `fetchedAt` can't serve.
+ // Forced STRICTLY forward: peers compare this stamp newer-wins, so two
+ // writes inside one millisecond would stamp the same instant and the second
+ // reading would never be pulled.
+ const capturedAt = nextStamp(storedAt);
+ await atomicWrite(PROVIDER_QUOTAS_FILE, { capturedAt, quotas });
+ return { quotas, capturedAt, changed: true };
});
}