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
address review (claude): gate default-on sync to approved peers, tombstone retired digests
[._.]/ Adam Eivy3c86a5ff406f
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 0a06f710e6..663f996e09 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -109,7 +109,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- CoS event ledgers — ordinary diagnostics use `data/cos/run-events.jsonl` + `run-events.1.jsonl`; persistent-mind trajectory uses the separate `mind-events.jsonl` + `mind-events.1.jsonl` pair (`server/services/agentRunEventLog.js`, #4540, #5082). Both are append-only, machine-local `ephemeral-file` replay aids with no federation cursor, tombstone, or `PORTOS_SCHEMA_VERSIONS` entry. The durable ordinary run record remains `data/runs/{id}/metadata.json`; mind rollups remain in their own bounded cache. Ordinary generations rotate at 5000 events and additionally expire after 30 days. Mind generations rotate at 10000 events without an age cutoff so a stopped mind keeps its unsummarized window, while high-volume mind chatter cannot evict ordinary run diagnostics. Migration 301 moves existing `mind.*` lines out of the shared files and stamps predecessor sequence provenance used to distinguish a legitimate timestamp jump from lost retained events. Payloads are redacted at append time, and both bounded pairs are backed up with the rest of `data/cos/`.- Remote-API metadata cache — `data/cache/huggingface-repos.json` (`server/services/huggingFaceRepoCache.js`). Hugging Face per-repo records (file sizes, native context window) backing the local-LLM catalog's quant pickers. `ephemeral-file` rather than `db-primary` because it is a pure projection of someone else's API with no queries, no relationships, and no sync cursor — and because it is *machine-local by construction*: it exists to spare THIS install's cold-start requests, so federating it would be pure noise. Long TTL (7 days) since published GGUF file sizes are immutable, but bounded because a repo can gain a new quant. Non-overridable backup exclude — regenerable on demand, and stale by restore time anyway. Purgeable from Data Manager (`cache` category).- Rapid Reader's Accelerando source cache — `data/cache/accelerando.html` (`server/services/rapidReader.js`). The official author-hosted HTML edition is fetched only when the user asks to load it, then retained locally for repeat and offline reads. `ephemeral-file` rather than `db-primary`: it is a machine-local copy of a separately licensed remote work, has no PortOS records or queries, and can be re-downloaded or purged without data loss. It is not bundled, federated, or backed up; Data Manager purges it with the `cache` category.-- Peer AI-usage digests — `data/peer-usage.json` (`server/services/peerUsage.js`). One aggregate usage digest per FEDERATED instance, keyed by origin `instanceId` and replaced whole under an LWW `capturedAt` stamp. `ephemeral-file`: it is entirely derived, replicated state whose authority is each peer's own `data/usage.json`, so a corrupt or missing file self-heals on the next 60s sync cycle. It is deliberately NOT merged into local `usage.json` — summing peer counters into our own file would double-count on the very next round trip and corrupt this machine's history irreversibly. Federated by the default-ON `usage` snapshot category (no per-record sequence cursor or tombstone: a digest is replaced, never appended to or deleted); capped at 64 instances, oldest `capturedAt` evicted. Backed up with the rest of `data/` — harmless either way, since a restore is re-converged on the next cycle. See ADR [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md).+- Peer AI-usage digests — `data/peer-usage.json` (`server/services/peerUsage.js`). One aggregate usage digest per FEDERATED instance, keyed by origin `instanceId` and replaced whole under an LWW `capturedAt` stamp. `ephemeral-file`: it is entirely derived, replicated state whose authority is each peer's own `data/usage.json`, so a corrupt or missing file self-heals on the next 60s sync cycle. It is deliberately NOT merged into local `usage.json` — summing peer counters into our own file would double-count on the very next round trip and corrupt this machine's history irreversibly. Federated by the default-ON `usage` snapshot category: no per-record sequence cursor (a digest is replaced whole under an LWW `capturedAt`), but it DOES carry tombstones (`server/lib/tombstones.js`, keyed on `instanceId`) — removing a peer must retire its digest everywhere, since our own snapshot forwards every digest we hold and a surviving peer would otherwise hand a deleted row straight back. Capped at 64 instances (oldest `capturedAt` evicted), and each arriving digest is rebuilt to the known wire shape rather than stored as it came. Backed up with the rest of `data/` — harmless either way, since a restore is re-converged on the next cycle. See ADR [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md).- Rapid Reader shelf — `data/rapid-reader-library/{id}/index.json` (collectionStore). Durable user-curated prose is `file-primary`: it is machine-local, never federated, and included in normal filesystem backups. It has no relationship graph or full-text search requirement that justifies Postgres.---diff --git a/docs/decisions/2026-09-01-federated-usage-metrics.md b/docs/decisions/2026-09-01-federated-usage-metrics.mdindex 91695f908b..744377af04 100644--- a/docs/decisions/2026-09-01-federated-usage-metrics.md+++ b/docs/decisions/2026-09-01-federated-usage-metrics.md@@ -61,9 +61,19 @@ origin instanceId. Nothing is ever summed into `data/usage.json`.`DEFAULT_SYNC_CATEGORIES.usage` is `true`, and `DEFAULT_ON_SYNC_CATEGORIES`names the default-on set so the rest of the system can reason about it:-- `getEffectiveCategories` layers a peer's stored map **over** the defaults, so- a peer record written before this category existed picks up the shipped+- `resolveEffectiveCategories` layers a peer's stored map **over** the defaults,+ so a peer record written before this category existed picks up the shippeddefault instead of reading as `undefined` (= off) forever. No migration needed.+ It is the single resolver, used by both the sync loop and the client-facing+ peer payload — two would drift, and the UI would show something the loop+ doesn't do.+- **A default reaches only a peer the user established here.** `handleAnnounce`+ auto-creates an inbound-only peer record for any host that can reach the port,+ with no approval step and (by default) no auth, so a default-ON category that+ applied there would mean announcing is enough to get a stranger's numbers+ pulled into this install's fleet report. `directions` is the discriminator, the+ same signal `peerAllowsOutbound` reads. An explicit stored `true` still wins:+ ticking the box for an inbound peer is a decision, not a default.- The peer-level `syncEnabled` master switch predates default-on categories andmeans *"don't replicate my content to this peer"*. It therefore masks a peerdown to the default-on set rather than silencing it entirely.@@ -71,7 +81,12 @@ names the default-on set so the rest of the system can reason about it:outbound pushes (`peerAllowsOutbound`). A default-on category must never flipit on by itself, or adding one would silently widen what every existing peeris allowed to receive. `hasOptedInCategory` excludes the default-on set from- that derivation.+ that derivation, and `updatePeer` recomputes it on any category edit rather+ than honoring a caller-supplied value.+- The **settings UI** reads the configured map, not the masked one+ (`masterSwitch: false`) — masking there would render every box on a+ `syncEnabled: false` peer unchecked, and ticking one would silently reactivate+ every other category still true underneath it.- The switches that still stop everything: turning the **category** off for apeer, or disabling the **peer** (`enabled: false`).@@ -125,4 +140,19 @@ excluded on both privacy and payload grounds.the snapshot pull path per peer and per category — the general fix alreadyfiled as #3659, not a usage-specific one.- A user who wants a machine's spend out of the federation entirely disables the- peer (`enabled: false`), which stops every direction.+ peer (`enabled: false`), which stops every direction — checked in+ `hasAnySyncEnabled`, so it holds on the `peer:online` path too, not only in+ the polling loop.+- **Removing a peer retires its digest via a tombstone**, not a plain delete.+ Our snapshot forwards every digest we hold, so a surviving peer would hand a+ deleted row straight back on the next cycle and a decommissioned machine's+ spend would sit in the fleet total forever. The tombstone rides the same+ snapshot (`server/lib/tombstones.js`, keyed on `instanceId`) so the removal+ propagates; a digest captured *after* it supersedes it, so re-adding the+ machine later works.+- A peer's digest is **rebuilt to the known wire shape on arrival**, not stored+ as it came. The shape is fixed and shallow (day → provider → model), and this+ category's checksum uses `canonicalStringify` — a recursive JS function with a+ far smaller depth budget than native `JSON.stringify` — so a digest deep+ enough to pass `atomicWrite` but blow that recursion would otherwise 500 the+ snapshot endpoint for every peer, permanently and across restarts.diff --git a/server/services/instances.js b/server/services/instances.jsindex 279d36f4df..03967db7e8 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -148,7 +148,12 @@ export function sanitizePeerForClient(peer) {// checkbox off while the server is actively syncing it (and make turning it// off take two clicks), and a second, subtly different resolver here would// put the UI and the sync loop back out of step on the legacy no-map peer.- return { ...peer, auth, syncCategories: resolveEffectiveCategories(peer) };+ // `masterSwitch: false` — show what the user has CONFIGURED, not what the+ // master switch currently lets through. The UI renders `peer.syncEnabled`+ // separately, so masking here would hide the stored selection: every box on a+ // `syncEnabled: false` peer would read unchecked, and ticking one would+ // silently reactivate every other category still true underneath it.+ return { ...peer, auth, syncCategories: resolveEffectiveCategories(peer, { masterSwitch: false }) };}// Default data shape@@ -373,32 +378,56 @@ function hasOptedInCategory(categories) {return Object.entries(categories || {}).some(([key, on]) => on === true && !isDefaultOnCategory(key));}+/**+ * Did the USER establish this peer relationship from this machine? Mirrors+ * `peerAllowsOutbound`'s reading of `directions`: an absent/empty array is a+ * legacy record (permissive), `['outbound']` is a peer the user added here, and+ * `['inbound']` is one that merely ANNOUNCED itself to us and was auto-created+ * by `handleAnnounce` — never approved by anyone.+ */+function peerUserEstablished(peer) {+ const directions = Array.isArray(peer?.directions) ? peer.directions : [];+ return directions.length === 0 || directions.includes('outbound');+}+/*** The effective sync-category map for a peer — the single resolution of "what- * actually syncs with this peer", used by BOTH the sync loop (syncOrchestrator)- * and the client-facing peer payload (sanitizePeerForClient). Two resolvers- * would drift, and the UI would then show something the loop doesn't do.+ * syncs with this peer", used by BOTH the sync loop (syncOrchestrator) and the+ * client-facing peer payload (sanitizePeerForClient). Two resolvers would drift,+ * and the UI would then show something the loop doesn't do.*- * Three rules, in order:+ * The rules, in order:* - A full-sync ("mirror everything") peer implies every current AND future* category on, whatever its stored map says.* - The shipped defaults sit UNDER the stored map, so a category added after* this peer record was written picks up its default instead of reading as* `undefined` (= off) forever. No migration needed; a key the user actually* toggled is present in the stored map and always wins.- * - `syncEnabled: false` — the master "don't replicate my content here" switch- * — masks the result down to the default-ON categories rather than silencing- * the peer outright. Disabling the PEER (`enabled: false`) still stops- * everything.+ * - **A default-ON category defaults on only for a peer the user established.**+ * `handleAnnounce` auto-creates an inbound-only record for any host that can+ * reach the port, with no approval step — so letting a default reach those+ * would start pulling an unknown machine's data into this install the moment+ * it announced itself. An explicit stored `true` still wins there: if the+ * user ticked the box for an inbound peer, that is a decision, not a default.+ * - `masterSwitch` (default true) applies `syncEnabled: false` — the user's+ * "don't replicate my content to this peer" switch — by masking the result+ * down to the default-ON categories rather than silencing the peer outright.+ * Pass `false` to read what the user has CONFIGURED, independent of that+ * switch (what the settings UI renders). Disabling the PEER+ * (`enabled: false`) always stops everything, in either mode.*/-export function resolveEffectiveCategories(peer) {+export function resolveEffectiveCategories(peer, { masterSwitch = true } = {}) {if (peer?.fullSync === true) return allSyncCategoriesOn();+ const defaults = { ...DEFAULT_SYNC_CATEGORIES };+ if (!peerUserEstablished(peer)) {+ for (const key of DEFAULT_ON_SYNC_CATEGORIES) defaults[key] = false;+ }const stored = peer?.syncCategories- ? { ...DEFAULT_SYNC_CATEGORIES, ...peer.syncCategories }+ ? { ...defaults, ...peer.syncCategories }// Legacy fallback: a peer with no stored map but sync on gets brain+memory,// the pre-per-category behavior.- : { ...DEFAULT_SYNC_CATEGORIES, ...(peer?.syncEnabled !== false ? { brain: true, memory: true } : {}) };- if (peer?.syncEnabled !== false) return stored;+ : { ...defaults, ...(peer?.syncEnabled !== false ? { brain: true, memory: true } : {}) };+ if (!masterSwitch || peer?.syncEnabled !== false) return stored;return Object.fromEntries(DEFAULT_ON_SYNC_CATEGORIES.map((key) => [key, stored[key] === true]));}@@ -490,14 +519,24 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, aexport async function removePeer(id) {disconnectFromPeer(id);- return withData(async (data) => {+ const removed = await withData(async (data) => {const idx = data.peers.findIndex(p => p.id === id);if (idx === -1) return null;- const [removed] = data.peers.splice(idx, 1);- console.log(`🌐 Peer removed: ${removed.name}`);+ const [entry] = data.peers.splice(idx, 1);+ console.log(`🌐 Peer removed: ${entry.name}`);instanceEvents.emit('peers:updated', data.peers);- return removed;+ return entry;});+ // Retire that instance's federated usage digest. Without this the row stays in+ // the fleet report forever: our own snapshot forwards every digest we hold, so+ // a surviving peer would hand it straight back on the next cycle. Dynamic+ // import keeps peerUsage (and its usage.js graph) off this module's load path.+ if (removed?.instanceId) {+ const { forgetInstanceUsage } = await import('./peerUsage.js');+ await forgetInstanceUsage(removed.instanceId)+ .catch((err) => console.log(`⚠️ instances: retiring usage digest failed: ${err.message}`));+ }+ return removed;}export async function updatePeer(id, updates) {diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 4852f45cd2..1778fb212e 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -75,6 +75,7 @@ import {handleAnnounce,redactPeerForWire,sanitizePeerForClient,+ resolveEffectiveCategories,applyReciprocalSync,requestReciprocalSync,enqueueReciprocalSync,@@ -450,6 +451,28 @@ describe('instances.js', () => {});});+ // handleAnnounce auto-creates an inbound-only peer for ANY host that can reach+ // the port — no approval step, and auth is off by default. A default-ON+ // category must not reach those, or announcing would be enough to get a+ // stranger's numbers pulled into this install's fleet report.+ describe('resolveEffectiveCategories — default-ON scope', () => {+ it('does not default a category on for an unapproved announce peer', () => {+ const announced = { id: 'p1', directions: ['inbound'], syncEnabled: false };+ expect(resolveEffectiveCategories(announced).usage).toBe(false);+ });++ it('does default it on for a peer the user added here', () => {+ expect(resolveEffectiveCategories({ id: 'p1', directions: ['outbound'] }).usage).toBe(true);+ // A legacy record with no directions array stays permissive.+ expect(resolveEffectiveCategories({ id: 'p2' }).usage).toBe(true);+ });++ it('honors an explicit opt-IN on an announce peer — that is a user decision', () => {+ const announced = { id: 'p1', directions: ['inbound'], syncCategories: { usage: true } };+ expect(resolveEffectiveCategories(announced).usage).toBe(true);+ });+ });+describe('sanitizePeerForClient', () => {// The sync path layers DEFAULT_SYNC_CATEGORIES *under* the stored map so a// peer record written before a category existed picks up its shipped default@@ -467,6 +490,17 @@ describe('instances.js', () => {expect(sanitized.syncCategories.usage).toBe(false);});+ // The UI renders syncEnabled separately, so the payload shows what the user+ // CONFIGURED. Masking here would render every box on a syncEnabled:false peer+ // unchecked, and ticking one would silently reactivate the rest.+ it('shows the configured selection on a peer whose master switch is off', () => {+ const sanitized = sanitizePeerForClient({+ id: 'p1', syncEnabled: false, syncCategories: { brain: true, universe: true },+ });+ expect(sanitized.syncCategories.brain).toBe(true);+ expect(sanitized.syncCategories.universe).toBe(true);+ });+it('redacts the password to a hasPassword marker but keeps the username', () => {const peer = { id: 'peer-1', name: 'host', auth: { username: 'alice', password: 'secret' }, status: 'online' };const sanitized = sanitizePeerForClient(peer);diff --git a/server/services/peerUsage.js b/server/services/peerUsage.jsindex 654687119c..18858ded76 100644--- a/server/services/peerUsage.js+++ b/server/services/peerUsage.js@@ -26,10 +26,11 @@*/import { join } from 'path';-import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { atomicWrite, readJSONFile, dataPath, PATHS } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';import { createMutex } from '../lib/asyncMutex.js';import { compareNewerWins, parseTsMs } from '../lib/lwwTimestamp.js';+import { mergeTombstones, normalizeTombstones, recordTombstone, isTombstoned } from '../lib/tombstones.js';import { canonicalSnapshotChecksum } from '../lib/snapshotChecksum.js';import { roundCents } from '../lib/subscriptionSavings.js';import { buildUsageDigest, buildUsageReport, getUsage, USAGE_FILE } from './usage.js';@@ -41,9 +42,101 @@ const PEER_USAGE_FILE = join(PATHS.data, 'peer-usage.json');// tail of instance ids that no longer exist. Oldest `capturedAt` is evicted.const MAX_INSTANCES = 64;-const withLock = createMutex();+// Structural bounds on ONE peer-supplied digest. The wire shape is fixed and+// shallow (day → provider → model), so it is normalized field-by-field rather+// than stored as it arrived: `canonicalStringify` (used for this category's+// checksum) is a recursive JS function with a far smaller depth budget than+// native JSON.stringify, so a digest nested deeply enough to pass `atomicWrite`+// but blow that recursion would 500 the snapshot endpoint for every peer,+// permanently and across restarts. The caps also stop one peer from growing+// `peer-usage.json` without bound inside its single slot.+const MAX_DAY_BUCKETS = 800;+const MAX_MONTH_BUCKETS = 400;+const MAX_PROVIDERS_PER_BUCKET = 100;+const MAX_MODELS_PER_PROVIDER = 400;++const DAY_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;+const MONTH_KEY_RE = /^\d{4}-\d{2}$/;const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;+const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);+const str = (v, max) => (isNonEmptyStr(v) ? v.slice(0, max) : null);++const COUNT_FIELDS = ['sessions', 'messages', 'tokens', 'tokensIn', 'tokensOut', 'cacheReadTokens', 'cacheWriteTokens'];++function takeCounts(source, target) {+ for (const field of COUNT_FIELDS) {+ if (typeof source?.[field] === 'number') target[field] = num(source[field]);+ }+ return target;+}++function sanitizeModelBucket(raw) {+ const out = takeCounts(raw, {});+ const source = str(raw?.source, 20);+ if (source) out.source = source;+ return out;+}++function sanitizeProviderBucket(raw) {+ const out = takeCounts(raw, {});+ const name = str(raw?.name, 120);+ if (name) out.name = name;+ const source = str(raw?.source, 20);+ if (source) out.source = source;+ if (isPlainObject(raw?.byModel)) {+ out.byModel = {};+ for (const [model, mRaw] of Object.entries(raw.byModel).slice(0, MAX_MODELS_PER_PROVIDER)) {+ if (!isNonEmptyStr(model)) continue;+ out.byModel[model.slice(0, 200)] = sanitizeModelBucket(mRaw);+ }+ }+ return out;+}++function sanitizeActivityBucket(raw) {+ const out = takeCounts(raw, {});+ if (isPlainObject(raw?.byProvider)) {+ out.byProvider = {};+ for (const [pid, pRaw] of Object.entries(raw.byProvider).slice(0, MAX_PROVIDERS_PER_BUCKET)) {+ if (!isNonEmptyStr(pid)) continue;+ out.byProvider[pid.slice(0, 200)] = sanitizeProviderBucket(pRaw);+ }+ }+ return out;+}++function sanitizeActivityMap(raw, keyRe, limit) {+ const out = {};+ if (!isPlainObject(raw)) return out;+ for (const [key, bucket] of Object.entries(raw).slice(0, limit)) {+ if (!keyRe.test(key)) continue;+ out[key] = sanitizeActivityBucket(bucket);+ }+ return out;+}++/**+ * Rebuild a peer's digest to the known wire shape, dropping anything else. Depth+ * is therefore fixed by construction — see the bounds above for why that+ * matters more than it looks.+ */+function sanitizeDigest(raw) {+ const hourly = Array.isArray(raw?.hourlyActivity) ? raw.hourlyActivity : [];+ return {+ totalSessions: num(raw?.totalSessions),+ totalMessages: num(raw?.totalMessages),+ totalToolCalls: num(raw?.totalToolCalls),+ totalTokens: { input: num(raw?.totalTokens?.input), output: num(raw?.totalTokens?.output) },+ dailyActivity: sanitizeActivityMap(raw?.dailyActivity, DAY_KEY_RE, MAX_DAY_BUCKETS),+ monthlyActivity: sanitizeActivityMap(raw?.monthlyActivity, MONTH_KEY_RE, MAX_MONTH_BUCKETS),+ hourlyActivity: Array.from({ length: 24 }, (_, i) => num(hourly[i])),+ earliestActivityDay: str(raw?.earliestActivityDay, 10),+ lastUpdated: str(raw?.lastUpdated, 40),+ };+}++const withLock = createMutex();/*** This machine's federation identity. Dynamically imported so `dataSync` →@@ -64,15 +157,16 @@ async function readStore() {// Non-strict: this file is entirely derived, replicated state. A corrupt read// self-heals on the next sync cycle, which beats throwing on every poll.const raw = await readJSONFile(PEER_USAGE_FILE, null);- const instances = isPlainObject(raw?.instances) ? raw.instances : {};- return { instances };+ return {+ instances: isPlainObject(raw?.instances) ? raw.instances : {},+ tombstones: normalizeTombstones(raw?.tombstones, 'instanceId'),+ };}/*** Coerce one wire entry into a stored entry, or null when it can't be trusted.- * The digest itself is read defensively downstream (every field is optional to- * `buildUsageReport`), so this only pins identity and orderability: the entry- * must belong to the map key it arrived under, and carry a parseable stamp.+ * Pins identity (the entry must belong to the map key it arrived under),+ * orderability (a parseable stamp), and shape (`sanitizeDigest`).*/function sanitizeEntry(entry, expectedId) {if (!isPlainObject(entry) || !isPlainObject(entry.usage)) return null;@@ -85,7 +179,7 @@ function sanitizeEntry(entry, expectedId) {instanceId: expectedId,name: isNonEmptyStr(entry.name) ? entry.name.slice(0, 120) : expectedId,capturedAt: entry.capturedAt,- usage: entry.usage,+ usage: sanitizeDigest(entry.usage),};}@@ -122,6 +216,7 @@ async function entriesWithSelf() {return {self: publishable,peers: peers.filter((e) => e.instanceId !== self?.instanceId),+ tombstones: store.tombstones,};}@@ -131,10 +226,12 @@ async function entriesWithSelf() {* still propagates.*/export async function getUsageSnapshot() {- const { self, peers } = await entriesWithSelf();+ const { self, peers, tombstones } = await entriesWithSelf();const instances = Object.fromEntries(peers.map((e) => [e.instanceId, e]));if (self) instances[self.instanceId] = self;- const data = { instances };+ // Tombstones ride the snapshot so a retirement propagates: an add-only merge+ // alone would let any peer that still holds the digest hand it straight back.+ const data = { instances, tombstones };// CANONICAL: the payload is a map keyed by instance ids arriving over the// wire, so two converged peers would otherwise hash differently purely from// the order they happened to learn each other — which the sync UI reads as@@ -155,18 +252,39 @@ export async function applyUsageRemote(remoteData) {return withLock(async () => {const store = await readStore();+ // Union the deletion list in BOTH directions, so retiring an instance on one+ // machine retires it everywhere instead of being undone by the next peer that+ // still forwards it.+ const { merged, changed: tombstonesChanged } = mergeTombstones(store.tombstones, remoteData?.tombstones, { keyField: 'instanceId' });+ store.tombstones = merged;let changed = 0;for (const [key, rawEntry] of Object.entries(incoming)) {if (!isNonEmptyStr(key) || key === selfId) continue;const entry = sanitizeEntry(rawEntry, key);if (!entry) continue;+ // A digest CAPTURED after the deletion is a machine that came back, and+ // supersedes the tombstone. An older one is the retired machine echoing+ // back via a peer that hasn't seen the removal yet.+ if (isTombstoned(store.tombstones, key, entry.capturedAt, 'instanceId')) continue;if (!compareNewerWins(entry.capturedAt, store.instances[key]?.capturedAt)) continue;store.instances[key] = entry;changed++;}- if (changed === 0) return { applied: false, count: 0 };+ // Adopting a peer's tombstone also retires the local digest it covers.+ for (const key of Object.keys(store.instances)) {+ if (!isTombstoned(store.tombstones, key, store.instances[key]?.capturedAt, 'instanceId')) continue;+ delete store.instances[key];+ changed++;+ }++ if (changed === 0) {+ // A tombstone learned from a peer is still state worth persisting, even+ // when it retired nothing here — otherwise we re-learn it every cycle.+ if (tombstonesChanged) await atomicWrite(PEER_USAGE_FILE, store);+ return { applied: false, count: 0 };+ }const ids = Object.keys(store.instances);if (ids.length > MAX_INSTANCES) {@@ -195,6 +313,30 @@ export async function applyUsageRemote(remoteData) {* Peer rows are as fresh as the last sync, so `capturedAt` is surfaced for the* UI to age them rather than implying they are live.*/+/**+ * Keep only month buckets the window covers END TO END. `buildUsageReport`+ * includes an overlapping month whole, so a month the range only clips would+ * contribute days outside it. Unbounded on a side means that side covers+ * everything, so a bucket is dropped only where the given bound cuts into it.+ */+function dropPartiallyCoveredMonths(monthlyActivity, from, to) {+ if (!isPlainObject(monthlyActivity)) return {};+ if (!from && !to) return monthlyActivity;+ const out = {};+ for (const [month, bucket] of Object.entries(monthlyActivity)) {+ // A month is fully covered when the window starts on or before its 1st and+ // ends on or after its last day.+ if (from && from > month + '-01') continue;+ if (to) {+ const [y, m] = month.split('-').map(Number);+ const lastDay = new Date(Date.UTC(y, m, 0)).toISOString().slice(0, 10);+ if (to < lastDay) continue;+ }+ out[month] = bucket;+ }+ return out;+}+export async function getFleetUsage({ from = null, to = null, providers = [] } = {}) {const { self, peers } = await entriesWithSelf();if (peers.length === 0) return { instances: [], totals: null };@@ -204,7 +346,14 @@ export async function getFleetUsage({ from = null, to = null, providers = [] } =from,to,providers,- monthlyActivity: activity.monthlyActivity || {},+ // A month bucket is folded in WHOLE whenever its month overlaps the window+ // — fine locally, where months only exist past the 400-day daily retention+ // and so can't land inside a range anyone asks for. A peer's digest rolls+ // up at 120 days, well inside a reachable range, so an explicit narrow+ // from/to over a rolled-up month would silently count days outside it.+ // Drop the partially-covered months rather than over-report; the row's+ // whole-month periods are unaffected.+ monthlyActivity: dropPartiallyCoveredMonths(activity.monthlyActivity, from, to),// Same rule as the single-instance summary: the all-time (unbounded)// window folds in legacy totals no bucket represents; a bounded window// must not, or it attributes all-time residue to the range.@@ -231,7 +380,32 @@ export async function getFleetUsage({ from = null, to = null, providers = [] } =return { instances: rows, totals };}-// Files whose fingerprint invalidates the category's checksum cache.-export const USAGE_CHECKSUM_PATHS = [USAGE_FILE, PEER_USAGE_FILE];+/**+ * Retire an instance's usage digest — called when the user removes that peer.+ *+ * A plain delete is not enough: our snapshot forwards every digest we hold, so a+ * surviving peer would hand the row straight back on the next cycle and a+ * decommissioned machine's spend would sit in the fleet total forever. The+ * tombstone rides the same snapshot and propagates the removal instead. A digest+ * captured AFTER the tombstone still wins, so re-adding the machine later works.+ */+export async function forgetInstanceUsage(instanceId) {+ if (!isNonEmptyStr(instanceId)) return { removed: false };+ return withLock(async () => {+ const store = await readStore();+ store.tombstones = recordTombstone(store.tombstones, instanceId, { keyField: 'instanceId' });+ const removed = Object.hasOwn(store.instances, instanceId);+ delete store.instances[instanceId];+ await atomicWrite(PEER_USAGE_FILE, store);+ console.log(`🔄 Usage sync: retired digest for instance ${instanceId}`);+ return { removed };+ });+}++// Files whose fingerprint invalidates the category's checksum cache. The+// instances file is in the set because the snapshot embeds this instance's NAME+// — without it a rename never reaches peers and their fleet table keeps showing+// the old one until an AI run happens to move usage.json.+export const USAGE_CHECKSUM_PATHS = [USAGE_FILE, PEER_USAGE_FILE, dataPath('instances.json')];export { PEER_USAGE_FILE };diff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.jsindex 6ac1cf1ffb..a25f37ff48 100644--- a/server/services/peerUsage.test.js+++ b/server/services/peerUsage.test.js@@ -30,6 +30,7 @@ const {getUsageSnapshot,applyUsageRemote,getFleetUsage,+ forgetInstanceUsage,PEER_USAGE_FILE,} = await import('./peerUsage.js');@@ -194,6 +195,72 @@ describe('usage sync category', () => {});});+describe('untrusted digest handling', () => {+ // canonicalStringify (this category's checksum) recurses in JS, with a far+ // smaller depth budget than native JSON.stringify — so a digest that survives+ // atomicWrite but blows that recursion would 500 the snapshot endpoint for+ // every peer, permanently and across restarts. The digest is rebuilt to the+ // known shallow shape rather than stored as it arrived, so depth is fixed.+ it('rebuilds a hostile digest to the wire shape instead of storing it', async () => {+ let deep = { tokensOut: 1 };+ for (let i = 0; i < 5000; i++) deep = { nested: deep };+ const hostile = peerEntry({ usage: { ...buildUsageDigest(usageFixture()), evil: deep } });++ expect(await applyUsageRemote({ instances: { 'inst-peer': hostile } })).toEqual({ applied: true, count: 1 });+ expect((await readStoreFile()).instances['inst-peer'].usage.evil).toBeUndefined();+ // The checksum must still be computable — this is the failure being pinned.+ await expect(getUsageSnapshot()).resolves.toMatchObject({ checksum: expect.any(String) });+ });++ it('drops junk bucket keys and coerces non-numeric counts', async () => {+ const junk = peerEntry({ usage: {+ ...buildUsageDigest(usageFixture()),+ dailyActivity: { 'not-a-day': { tokensOut: 5 }, '2026-08-30': { tokensOut: '900', sessions: 2 } },+ } });+ await applyUsageRemote({ instances: { 'inst-peer': junk } });++ const stored = (await readStoreFile()).instances['inst-peer'].usage.dailyActivity;+ expect(stored['not-a-day']).toBeUndefined();+ expect(stored['2026-08-30']).toEqual({ sessions: 2 }); // the string count is dropped, not NaN'd+ });+});++describe('retiring an instance', () => {+ // Our snapshot forwards every digest we hold, so a plain delete is undone by+ // the next peer that still has it — the decommissioned machine's spend would+ // sit in the fleet total forever.+ it('tombstones a removed instance so a peer cannot hand it back', async () => {+ const entry = peerEntry();+ await applyUsageRemote({ instances: { 'inst-peer': entry } });+ await forgetInstanceUsage('inst-peer');+ expect((await readStoreFile()).instances['inst-peer']).toBeUndefined();++ // A peer that hasn't seen the removal re-forwards the same digest.+ expect(await applyUsageRemote({ instances: { 'inst-peer': entry } })).toEqual({ applied: false, count: 0 });+ expect((await readStoreFile()).instances['inst-peer']).toBeUndefined();+ });++ it('propagates the retirement to a peer that still holds the digest', async () => {+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry() } });+ const { data } = await getUsageSnapshot();+ expect(data.instances['inst-peer']).toBeTruthy();++ // The remote retired it; its snapshot carries the tombstone.+ const result = await applyUsageRemote({ instances: {}, tombstones: [{ instanceId: 'inst-peer', deletedAt: '2026-08-31T00:00:00.000Z' }] });+ expect(result.count).toBe(1);+ expect((await readStoreFile()).instances['inst-peer']).toBeUndefined();+ });++ it('lets a machine that comes back supersede its own tombstone', async () => {+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry() } });+ await forgetInstanceUsage('inst-peer');++ const returned = peerEntry({ capturedAt: '2099-01-01T00:00:00.000Z' });+ expect(await applyUsageRemote({ instances: { 'inst-peer': returned } })).toEqual({ applied: true, count: 1 });+ expect((await readStoreFile()).instances['inst-peer']).toBeTruthy();+ });+});+describe('fleet report', () => {it('is empty until a peer digest has synced', async () => {expect(await getFleetUsage({ providers: [] })).toEqual({ instances: [], totals: null });@@ -228,6 +295,28 @@ describe('fleet report', () => {expect(selfRow.totals.tokensOut).toBe(100);});+ // buildUsageReport folds an OVERLAPPING month bucket in whole. Locally that is+ // safe (months only exist past the 400-day daily retention, far outside any+ // range anyone asks for), but a peer's digest rolls up at 120 days — well+ // inside a reachable window — so a narrow explicit from/to over a rolled-up+ // month would silently count days outside it.+ it('does not count a rolled-up month the window only clips', async () => {+ const rolledUp = peerEntry({+ usage: buildUsageDigest(usageFixture({ day: '2026-05-02', tokensOut: 7000 }), {+ retentionDays: 30, now: new Date('2026-09-01T00:00:00Z'),+ }),+ });+ await applyUsageRemote({ instances: { 'inst-peer': rolledUp } });+ expect(rolledUp.usage.monthlyActivity['2026-05']).toBeTruthy();++ const clipped = await getFleetUsage({ from: '2026-05-10', to: '2026-05-15', providers: [] });+ expect(clipped.totals.tokensOut).toBe(0);++ // A window that covers the whole month still reports it.+ const whole = await getFleetUsage({ from: '2026-05-01', to: '2026-05-31', providers: [] });+ expect(whole.totals.tokensOut).toBe(7000);+ });+it('scopes every instance to the same report window', async () => {await applyUsageRemote({ instances: { 'inst-peer': peerEntry() } });const outside = await getFleetUsage({ from: '2026-09-01', to: '2026-09-30', providers: [] });diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 2b2a8ea80f..1a7f76fc49 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -803,9 +803,13 @@ export async function syncWithPeer(peer) {* Check if a peer has any sync category enabled*/function hasAnySyncEnabled(peer) {- // No `syncEnabled === false` short-circuit: getEffectiveCategories already- // masks such a peer down to its default-ON categories. `peer.enabled === false`- // remains the switch that stops everything — syncAllPeers filters on it.+ // `enabled: false` is the switch that stops everything, and it is checked HERE+ // rather than only in syncAllPeers: the `peer:online` handler gates solely on+ // this function, and a default-ON category makes it truthy for almost every+ // peer — so without this a disabled peer would still sync the moment a manual+ // Connect flipped its status. No `syncEnabled === false` short-circuit though:+ // getEffectiveCategories already masks that peer down to its default-ON set.+ if (peer.enabled === false) return false;const cats = getEffectiveCategories(peer);return Object.values(cats).some(Boolean);}diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 6371a9c76d..0fb97f2828 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -823,6 +823,22 @@ describe('syncOrchestrator', () => {await syncAllPeers();expect(categoryUrls()).toHaveLength(0);});++ // The peer:online handler gates only on hasAnySyncEnabled, and a default-ON+ // category makes that truthy for nearly every peer — so `enabled: false`+ // has to be checked there too, or a manual Connect on a disabled peer would+ // start syncing it.+ it('a disabled peer is not eligible even when its status flips online', async () => {+ const disabled = { ...mockPeer, enabled: false, syncCategories: { usage: true } };+ getPeers.mockResolvedValue([disabled]);+ initSyncOrchestrator();+ // instanceEvents is mocked, so invoke the handler the orchestrator just+ // registered rather than relying on a real emit.+ const [, onPeerOnline] = instanceEvents.on.mock.calls.find(([event]) => event === 'peer:online');+ await onPeerOnline(disabled);+ await vi.runOnlyPendingTimersAsync();+ expect(categoryUrls()).toHaveLength(0);+ });});describe('syncAllPeers', () => {