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
federate AI usage metrics as a default-on sync category
[._.]/ Adam Eivy91764551cf13
diff --git a/client/src/components/usage/FleetUsageCard.jsx b/client/src/components/usage/FleetUsageCard.jsxnew file mode 100644index 0000000000..0371a6ed71--- /dev/null+++ b/client/src/components/usage/FleetUsageCard.jsx@@ -0,0 +1,123 @@+import { Network } from 'lucide-react';+import Pill from '../ui/Pill';+import { formatCompactCountOrDash as formatNumber, formatUsd, timeAgo } from '../../utils/formatters';++/**+ * Per-instance AI usage across the federation, for the same report window the+ * rest of the page is showing.+ *+ * Renders nothing below two instances: a single-machine install has nothing to+ * compare against, and a one-row "fleet" is noise rather than information.+ *+ * A peer row is only as fresh as the last sync cycle, so each states when its+ * digest was captured rather than implying it is live.+ */+export default function FleetUsageCard({ fleet }) {+ const rows = fleet?.instances || [];+ if (rows.length < 2) return null;++ const label = (row) => (row.self+ ? <Pill tone="context" size="xs" className="ml-2">This machine</Pill>+ : row.capturedAt && (+ <span className="ml-2 text-[10px] text-gray-500" title={row.capturedAt}>+ synced {timeAgo(row.capturedAt)}+ </span>+ ));++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-3">+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2">+ <div>+ <h3 className="text-sm font-medium text-gray-400 flex items-center gap-1.5">+ <Network size={15} className="text-port-accent" />+ Across Instances+ </h3>+ <p className="text-[10px] sm:text-xs text-gray-500 mt-0.5">+ Every federated instance’s usage over this period, priced the same way.+ </p>+ </div>+ <div className="text-left sm:text-right">+ <div className="text-xl font-bold text-port-success">{formatUsd(fleet.totals?.estimatedCost)}</div>+ <div className="text-[10px] sm:text-xs text-gray-500">{rows.length} instances combined</div>+ </div>+ </div>++ {/* Mobile view (< sm): card list, so the numbers stay readable without a+ horizontal scroll — same pairing the cost report uses. */}+ <div className="block sm:hidden space-y-2">+ {rows.map((row) => (+ <div key={row.instanceId} className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center min-w-0">+ <span className="font-medium text-white text-sm truncate">{row.name}</span>+ {label(row)}+ </div>+ <span className="text-sm font-semibold text-port-success shrink-0">{formatUsd(row.totals?.estimatedCost)}</span>+ </div>+ <div className="grid grid-cols-2 gap-2 text-xs bg-port-card/50 p-2 rounded border border-port-border/50">+ <div>+ <span className="text-gray-500 block text-[10px]">Sessions</span>+ <span className="text-white font-medium">{formatNumber(row.totals?.sessions)}</span>+ </div>+ <div>+ <span className="text-gray-500 block text-[10px]">Messages</span>+ <span className="text-white font-medium">{formatNumber(row.totals?.messages)}</span>+ </div>+ <div className="col-span-2">+ <span className="text-gray-500 block text-[10px]">Tokens (In / Out)</span>+ <span className="text-white font-medium">+ {formatNumber(row.totals?.tokensIn)} / {formatNumber(row.totals?.tokensOut)}+ </span>+ </div>+ </div>+ </div>+ ))}+ <div className="bg-port-bg border border-port-border rounded-lg p-3 flex items-center justify-between text-xs font-semibold text-white">+ <span>Fleet total</span>+ <span className="text-port-success text-sm">{formatUsd(fleet.totals?.estimatedCost)}</span>+ </div>+ </div>++ {/* Desktop view (>= sm): table layout */}+ <div className="hidden sm:block overflow-x-auto">+ <table className="w-full text-sm min-w-[520px]">+ <thead>+ <tr className="text-left text-xs text-gray-500 border-b border-port-border">+ <th className="py-2 pr-2 font-medium">Instance</th>+ <th className="py-2 px-2 font-medium text-right">Sessions</th>+ <th className="py-2 px-2 font-medium text-right">Messages</th>+ <th className="py-2 px-2 font-medium text-right">Tokens In</th>+ <th className="py-2 px-2 font-medium text-right">Tokens Out</th>+ <th className="py-2 pl-2 font-medium text-right">Est. API Cost</th>+ </tr>+ </thead>+ <tbody>+ {rows.map((row) => (+ <tr key={row.instanceId} className="border-t border-port-border text-white">+ <td className="py-2 pr-2">+ <span className="font-medium truncate">{row.name}</span>+ {label(row)}+ </td>+ <td className="py-2 px-2 text-right">{formatNumber(row.totals?.sessions)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(row.totals?.messages)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(row.totals?.tokensIn)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(row.totals?.tokensOut)}</td>+ <td className="py-2 pl-2 text-right text-port-success">{formatUsd(row.totals?.estimatedCost)}</td>+ </tr>+ ))}+ </tbody>+ <tfoot>+ <tr className="border-t border-port-border font-semibold text-white">+ <td className="py-2 pr-2">Fleet total</td>+ <td className="py-2 px-2 text-right">{formatNumber(fleet.totals?.sessions)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(fleet.totals?.messages)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(fleet.totals?.tokensIn)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(fleet.totals?.tokensOut)}</td>+ <td className="py-2 pl-2 text-right text-port-success">{formatUsd(fleet.totals?.estimatedCost)}</td>+ </tr>+ </tfoot>+ </table>+ </div>+ </div>+ );+}diff --git a/client/src/components/usage/FleetUsageCard.test.jsx b/client/src/components/usage/FleetUsageCard.test.jsxnew file mode 100644index 0000000000..98610e9efb--- /dev/null+++ b/client/src/components/usage/FleetUsageCard.test.jsx@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';+import { render, screen } from '@testing-library/react';+import FleetUsageCard from './FleetUsageCard';++const row = (overrides = {}) => ({+ instanceId: 'inst-a',+ name: 'Workshop',+ self: false,+ capturedAt: '2026-08-30T09:00:00.000Z',+ totals: { sessions: 4, messages: 12, tokensIn: 1000, tokensOut: 2000, cacheReadTokens: 0, cacheWriteTokens: 0, estimatedCost: 3.5 },+ ...overrides,+});++const fleet = {+ instances: [+ row({ instanceId: 'inst-self', name: 'Workshop', self: true, capturedAt: null }),+ row({ instanceId: 'inst-peer', name: 'Studio' }),+ ],+ totals: { sessions: 8, messages: 24, tokensIn: 2000, tokensOut: 4000, cacheReadTokens: 0, cacheWriteTokens: 0, estimatedCost: 7 },+};++describe('FleetUsageCard', () => {+ it('renders a row per instance plus the combined total', () => {+ render(<FleetUsageCard fleet={fleet} />);+ // Mobile cards and the desktop table both render every row, so each label+ // legitimately appears twice.+ expect(screen.getAllByText('Studio')).toHaveLength(2);+ expect(screen.getAllByText('This machine')).toHaveLength(2);+ expect(screen.getAllByText('Fleet total')).toHaveLength(2);+ expect(screen.getByText('2 instances combined')).toBeInTheDocument();+ });++ // A single-machine install has nothing to compare against — the section is+ // noise there, so the server sends an empty list and the card must stay out+ // of the page entirely rather than rendering a one-row "fleet".+ it('renders nothing below two instances', () => {+ const { container: empty } = render(<FleetUsageCard fleet={{ instances: [], totals: null }} />);+ expect(empty).toBeEmptyDOMElement();+ const { container: single } = render(<FleetUsageCard fleet={{ instances: [row()], totals: row().totals }} />);+ expect(single).toBeEmptyDOMElement();+ const { container: absent } = render(<FleetUsageCard fleet={undefined} />);+ expect(absent).toBeEmptyDOMElement();+ });+});diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex cc859c0412..dc9a7e4635 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -7,7 +7,7 @@ import {Database, Brain, CheckCircle2, AlertCircle, Clock,RefreshCcw, Timer,Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,- Lock, Globe, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText, FolderTree, Video, Waypoints+ Lock, Globe, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText, FolderTree, Video, Waypoints, Gauge} from 'lucide-react';import toast from '../components/ui/Toast';import Pill from '../components/ui/Pill';@@ -392,6 +392,7 @@ const SYNC_CATEGORY_META = [{ key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets' },{ key: 'videoHistory', label: 'Video History', icon: Film, description: 'Generated-video metadata rows (so synced collection videos render)' },{ key: 'storyBuilder', label: 'Story Builder', icon: BookOpen, description: 'Resumable Story Builder sessions you marked for cross-machine sync' },+ { key: 'usage', label: 'AI Usage Metrics', icon: Gauge, description: 'On by default. Aggregate AI usage counters — providers, models, token counts, estimated spend — so the Usage page totals your whole federation. No prompts, transcripts, or record contents. Turning it off stops PULLING this peer\u2019s usage; disable the peer to stop every direction.' },{ key: 'fableLoom', label: 'FableLoom', icon: Waypoints, description: 'Branching stories, series plans, episode graphs, and rendered scene references' },{ key: 'authors', label: 'Authors', icon: FilePen, description: 'Author personas + headshots used as series bylines (PostgreSQL)' },{ key: 'artists', label: 'Artists', icon: Music, description: 'Music artist personas + portraits (PostgreSQL)' },@@ -465,14 +466,12 @@ function SyncCategoriesPanel({ peer, onRefresh }) {onRefresh();};+ // `syncEnabled` is NOT sent: the server derives it from the resulting category+ // map, excluding the default-ON ones. Deriving it here would read `usage: true`+ // as "something is enabled" and widen the peer's outbound push consent.const toggleCategory = async (key) => {if (fullSync) return; // categories are locked-on under full mirror- const newValue = !categories[key];- const anyCatEnabled = Object.values({ ...categories, [key]: newValue }).some(Boolean);- await updatePeer(peer.id, {- syncCategories: { [key]: newValue },- syncEnabled: anyCatEnabled- }).catch(() => null);+ await updatePeer(peer.id, { syncCategories: { [key]: !categories[key] } }).catch(() => null);onRefresh();};@@ -481,10 +480,7 @@ function SyncCategoriesPanel({ peer, onRefresh }) {for (const { key } of SYNC_CATEGORY_META) {updated[key] = enable;}- await updatePeer(peer.id, {- syncCategories: updated,- syncEnabled: enable- }).catch(() => null);+ await updatePeer(peer.id, { syncCategories: updated }).catch(() => null);onRefresh();};diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex c3d0527bb4..02391f04f3 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -5,10 +5,11 @@ import * as api from '../services/api';import BrailleSpinner from '../components/BrailleSpinner';import PageSkeleton from '../components/ui/PageSkeleton';import Pill from '../components/ui/Pill';-import { formatCompactCount, formatUsd, timeUntil } from '../utils/formatters';+import { formatCompactCount, formatCompactCountOrDash as formatNumber, formatUsd, timeUntil } from '../utils/formatters';import { useAsyncAction } from '../hooks/useAsyncAction';import { useAutoRefetch } from '../hooks/useAutoRefetch';import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';+import FleetUsageCard from '../components/usage/FleetUsageCard';// How often to re-ask while a provider's quota reading is still being taken. A// CLI/TUI scrape is a 10-20s spawn, so this is a handful of polls, not a loop.@@ -21,10 +22,6 @@ const PERIOD_OPTIONS = [{ id: 'all', label: 'All time' }];-// Preserve the em-dash empty-state; delegate K/M abbreviation to the shared helper.-const formatNumber = (num) => (num == null ? '—' : formatCompactCount(num));--// Every provider adapter normalizes its reset to ISO before it reaches here, so// this localizes and adds the relative "in 3h" that makes a reset time useful at// a glance. The raw-text fallback stays for a reading off an older peer that@@ -844,6 +841,10 @@ function InternalUsageMetrics() {</p></div>+ {/* Same window, split by machine — renders only once a peer's usage has+ synced, so a single-machine install sees no change. */}+ <FleetUsageCard fleet={usage.fleet} />+{/* Directly under the API estimate it is derived from: the estimate is theopportunity cost, this is what the quota plans actually cost to avoid it. */}<SubscriptionSavingsCard savings={usage.subscriptionSavings} onSaved={fetchUsage} />diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 09f452826b..012677dcec 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md| Module | Purpose ||---|---|-| `formatters` | Date/time/duration/byte/word formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `timeAgo`, `formatAgeDays` (age in whole DAYS — "412 days ago" — where `timeAgo` would collapse to "1y ago"; model-download lists), `localDateKey` (browser-local `YYYY-MM-DD`), `shiftISODate` (DST-safe calendar-day shifts), `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. Date display helpers anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |+| `formatters` | Date/time/duration/byte/word formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `formatCompactCountOrDash` (same, but an ABSENT count renders "—" rather than "0"), `timeAgo`, `formatAgeDays` (age in whole DAYS — "412 days ago" — where `timeAgo` would collapse to "1y ago"; model-download lists), `localDateKey` (browser-local `YYYY-MM-DD`), `shiftISODate` (DST-safe calendar-day shifts), `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. Date display helpers anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". || `cronHelpers` | Cron preset list, friendly cron parsing/building, anchored recurrence parsing/building/description, `isCronExpression` detection, `describeCron` human-readable rendering, and `JOB_INTERVAL_OPTIONS` — the interval-mode cadences for autonomous jobs, mirroring the server's `INTERVAL_OPTIONS`. Import it rather than re-declaring the list in a scheduling component. || `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. || `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex 137a2885b5..2f5feed712 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -319,6 +319,18 @@ export function formatCompactCount(n) {return String(n);}+/**+ * `formatCompactCount` for a count that may legitimately be absent: renders an+ * em-dash instead of "0", so "no data" and "measured zero" read differently on+ * a stat tile. `formatCompactCount` itself can't take this on — a real 0 must+ * still render as "0".+ * @param {number|null|undefined} n+ * @returns {string}+ */+export function formatCompactCountOrDash(n) {+ return n == null ? '—' : formatCompactCount(n);+}+/*** Round a number to `decimals` places and drop trailing zeros* (170.35000000000002 → 170.4, 170.0 → 170). Returns null fordiff --git a/docs/README.md b/docs/README.mdindex 69fb2967e9..83f472bb03 100644--- a/docs/README.md+++ b/docs/README.md@@ -51,7 +51,7 @@ Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([## Point-in-time records- **[plans/](./plans/README.md)** — dated design plans (`YYYY-MM-DD-<slug>.md`), archived on approval before implementation. Historical records, not living docs.-- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md)), and why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md).+- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md), [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md)), and why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md).- **research/** — dated investigation and incident write-ups (e.g. the [mflux GPU-watchdog panic](./research/2026-06-13-mflux-training-watchdog-panic.md) and the [local LLM performance audit](./research/2026-08-22-local-llm-performance-audit.md)).- **superpowers/** — plan/spec pairs from superpowers-driven builds: `specs/<date>-<slug>-design.md` (design) + `plans/<date>-<slug>.md` (implementation plan).diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 566bc1d434..0a06f710e6 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -109,6 +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).- 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.mdnew file mode 100644index 0000000000..91695f908b--- /dev/null+++ b/docs/decisions/2026-09-01-federated-usage-metrics.md@@ -0,0 +1,128 @@+# ADR: AI Usage Metrics Federate, On By Default++- **Date:** 2026-09-01+- **Status:** Accepted+- **Related:**+ [`server/services/peerUsage.js`](../../server/services/peerUsage.js),+ [`server/services/usage.js`](../../server/services/usage.js) (`buildUsageDigest`),+ [`server/services/dataSync.js`](../../server/services/dataSync.js) (`usage` category),+ ADR [privacy records machine-local](./2026-08-08-privacy-records-machine-local.md),+ ADR [federated visual prompts](./2026-08-20-federated-visual-prompts.md).++## Context++A single user commonly runs several PortOS installs federated as sync peers — a+desktop, a laptop, a headless render box. Every one of them records its own AI+usage into `data/usage.json`: sessions, messages, per-provider and per-model+token counts, prompt-cache tiers, and the estimated API cost the Usage page+reports.++Those counters were machine-local, so the Usage page answered "what did *this+box* spend?" — which is never the question. The question is what the **fleet**+spent, and answering it meant opening the page on each machine and adding the+numbers up by hand. Worse, the headless box that runs the most unattended+work is the one a user is least likely to open.++Two things made this non-trivial rather than "add a category and move on":++1. **Usage counters are cumulative aggregates.** Merging a peer's totals into+ the local file would double-count on the very next round trip — our own+ outbound snapshot would ship the inflated total straight back — and would+ corrupt this machine's own history irreversibly.+2. **Every sync category ships off by default.** Usage is only useful if it is+ already flowing when the user asks the question; a fleet total that requires+ per-peer opt-in on every machine is a feature nobody has turned on.++## Decision++**AI usage metrics federate as a snapshot sync category named `usage`, and it+is the one category that is ON by default.**++### Per-instance digests, never a merge++Each install publishes a *digest* of its own usage (`buildUsageDigest`) and+stores every peer's digest side by side in `data/peer-usage.json`, keyed by+origin instanceId. Nothing is ever summed into `data/usage.json`.++- Digests are replaced whole under an LWW stamp (`capturedAt`, sourced from+ `usage.json`'s `lastUpdated`), so re-applying a snapshot is a no-op.+- A node forwards the third-party digests it holds, so a chain (A↔B↔C)+ converges without A and C ever talking.+- A peer echoing a stale copy of *us* is ignored outright — this machine is the+ only authority on its own counters.+- Day buckets older than `DIGEST_DAILY_RETENTION_DAYS` (120) are folded into+ their month **for the wire only**. All-time totals stay exact; only old+ periods lose per-day granularity, which is all a fleet report needs.+- `reconciledRuns` never rides the wire: it is idempotency bookkeeping keyed by+ *local* run ids, meaningless on a peer and the largest field in the file.++### Default ON, and what "on by default" does not mean++`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+ default instead of reading as `undefined` (= off) forever. No migration needed.+- The peer-level `syncEnabled` master switch predates default-on categories and+ means *"don't replicate my content to this peer"*. It therefore masks a peer+ down to the default-on set rather than silencing it entirely.+- `syncEnabled` is **derived** from the category map and also gates per-record+ outbound pushes (`peerAllowsOutbound`). A default-on category must never flip+ it on by itself, or adding one would silently widen what every existing peer+ is allowed to receive. `hasOptedInCategory` excludes the default-on set from+ that derivation.+- The switches that still stop everything: turning the **category** off for a+ peer, or disabling the **peer** (`enabled: false`).++## Why this does not contradict the PII rule++`AGENTS.md` states that PII must not ride the federation layer, decided in the+[privacy-records ADR](./2026-08-08-privacy-records-machine-local.md). That rule+governs *records* — the user's identity, holdings, relationships, and personal+history. A usage digest is none of those. It carries:++- provider ids and model ids (`anthropic`, `claude-opus-5`)+- session / message / token / cache counts and their day+month buckets+- the publishing instance's id and name — both of which peers already exchange+ during registration (`handleAnnounce`)++It carries no prompts, no transcripts, no record contents, no file paths, and+nothing about the human. The rejected alternative — federating the raw+`usage.json` — would have shipped `reconciledRuns`, a list of local run ids;+still not PII, but machine-local bookkeeping with no meaning on a peer, so it is+excluded on both privacy and payload grounds.++## Consequences++- The Usage page gains an **Across Instances** section: one row per instance,+ priced over the same window by the same `buildUsageReport` the single-instance+ report uses, so per-instance and fleet figures can never disagree. It renders+ only once a peer digest has synced — a single-machine install sees no change.+- `data/peer-usage.json` is entirely derived, replicated state. A corrupt read+ self-heals on the next sync cycle rather than throwing on every poll, and the+ store is capped at 64 instances (oldest `capturedAt` evicted) so a peer+ forwarding a long tail of dead instance ids can't grow it without bound.+- Peer rows are as fresh as the last 60s sync cycle, so each row states when its+ digest was captured rather than implying it is live.+- `usage` is the first snapshot category that is **always dirty** — `saveUsage`+ rewrites `usage.json` on every AI run — so it transfers the whole digest map+ where every other category rests on a rarely-moving checksum. The payload is+ bounded here (120-day wire rollup, all-time `byProvider`/`byModel` dropped,+ no per-provider rows on fleet output); replacing the whole-payload transfer+ with a `capturedAt` manifest + per-slot fetch is filed as **#5759**.+- **The per-peer toggle governs the INBOUND direction.** Snapshot sync is+ pull-only, and `/api/sync/:category/snapshot` carries no per-peer category+ authorization for *any* category — the receiver-side gap that per-record pulls+ closed in #3659 and snapshots have not. Turning **AI Usage Metrics** off for a+ peer stops us pulling and storing that peer's digest; it does not stop that+ peer pulling ours, and our snapshot also forwards the third-party digests we+ hold. That asymmetry was latent while every category defaulted off — a+ default-ON category is what makes it reachable — so the honest statement is+ that a usage digest is readable by anything that can already reach the API,+ under the same posture as every other snapshot category (see the Security+ Model's trust boundary in `AGENTS.md`). Closing it properly means authorizing+ the snapshot pull path per peer and per category — the general fix already+ filed 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.diff --git a/server/lib/README.md b/server/lib/README.mdindex 99251f7bd4..ea38194a5c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -442,6 +442,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `extensionErrors.js` | `isExtensionError(payload)` — true when a client error report came from a browser extension's injected content script (extension URL scheme in `source`/`stack`/`message`, or a short list of vendor/runtime message signatures) rather than from PortOS. Consumed by `services/clientErrors.js` to keep un-actionable extension noise out of the Review Hub *and* out of the 1/sec throttle slot, where it would displace real errors. **Authoritative copy** — mirrored at `client/src/lib/extensionErrors.js`, parity enforced by `extensionErrors.mirror.test.js`. || `fetchErrorChain.js` | `describeFetchError(err)` flattens a fetch rejection's whole `cause` chain (depth-bounded, cycle-guarded) into one searchable `code: message` string — undici reports every network failure as the same opaque `TypeError: fetch failed` with the real reason nested inside, so a classifier reading only `err.message` misjudges every one of them. `isReplayableConnectionError(err)` is the narrow predicate over that string for connection-REUSE artifacts (HTTP/2 GOAWAY, reset, hang-up) that are safe to replay once via `fetchWithTimeout`'s `shouldRetry`; it deliberately EXCLUDES timeouts, which broader classifiers like `ollamaManager`'s `isTransientPullError` include. || `isoWeek.js` | ISO-8601 week identity — the single source of the `YYYY-Www` week id. `getWeekId(date)` keys on the ISO week-numbering **year** (the calendar year of that week's Thursday), not `date.getFullYear()`, so one ISO week is never split across two ids and two weeks never collide on one (#3465). Also `isoWeekParts`, `getIsoWeekNumber`, `getIsoWeekYear`, `parseWeekId` (null on garbage), and `isoWeeksInYear(year)` (52, or 53 in a leap-week year). Shared by productivity week aggregates and weekly digest filenames. |+| `snapshotChecksum.js` | The two snapshot-checksum flavours a sync category can want. `snapshotChecksum(data)` hashes `JSON.stringify` — insertion-order SENSITIVE, correct only where the getter already canonicalizes its own ordering (`dataSync.js`, `digital-twin-sync.js`). `canonicalSnapshotChecksum(data)` hashes `canonicalStringify`, so two converged machines hash identically regardless of the order they learned the data (`peerUsage.js`, whose payload is a map keyed by wire-supplied instance ids). Picking the wrong one is not a crash — it is two synced peers whose checksums never match, which the sync UI reads as "behind" forever. || `lwwTimestamp.js` | Last-writer-wins timestamp comparison for cross-instance sync merges. `parseTsMs(s)` (Date.parse → epoch ms or null), `compareNewerWins(candidate, incumbent)` (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), `compareEarlierWins(a, b)` (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by `mergeMediaCollectionsFromSync` / `mergeAuthorsFromSync` etc. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. || `markedSection.js` | Marker-delimited section replacement (pure). `buildMarkers(id)` → `{ start, end }` HTML-comment marker pair; `replaceMarkedSection(content, body, markers)` splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); `extractMarkedSection` / `hasMarkedSection` read it back. Powers the daily-log activity-digest auto-drafts (#2155) via `brainJournal.upsertAutoSection()`. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 7601121cd2..753402d707 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -11311,7 +11311,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 121+ "line": 122}]},@@ -11322,7 +11322,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 136+ "line": 137}]},@@ -11333,7 +11333,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 250+ "line": 251}]},@@ -11344,7 +11344,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 278+ "line": 279}]},@@ -11355,7 +11355,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 264+ "line": 265}]},@@ -11366,7 +11366,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 285+ "line": 286}]},@@ -11377,7 +11377,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 350+ "line": 351}]},@@ -11388,7 +11388,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 322+ "line": 323}]},@@ -11399,7 +11399,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 365+ "line": 366}]},@@ -11410,7 +11410,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 310+ "line": 311}]},@@ -11421,7 +11421,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 334+ "line": 335}]},@@ -11432,7 +11432,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 223+ "line": 224}]},@@ -11443,7 +11443,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 295+ "line": 296}]},@@ -11454,7 +11454,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 192+ "line": 193}]},@@ -11465,7 +11465,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 202+ "line": 203}]},@@ -11476,7 +11476,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 215+ "line": 216}]},@@ -11487,7 +11487,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 162+ "line": 163}]},@@ -11498,7 +11498,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 177+ "line": 178}]},@@ -18590,7 +18590,7 @@},{"source": "server/routes/providers.js",- "line": 767+ "line": 776}]},@@ -18643,6 +18643,10 @@{"source": "server/lib/aiToolkit/routes/providers.js","line": 110+ },+ {+ "source": "server/routes/providers.js",+ "line": 765}]},@@ -19908,7 +19912,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 154+ "line": 159}]},@@ -19919,7 +19923,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 218+ "line": 223}]},@@ -19930,7 +19934,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 490+ "line": 498}]},@@ -19941,7 +19945,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 231+ "line": 236}]},@@ -19952,7 +19956,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 476+ "line": 484}]},@@ -19963,7 +19967,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 278+ "line": 283}]},@@ -19974,7 +19978,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 485+ "line": 493}]},@@ -19985,7 +19989,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 455+ "line": 463}]},@@ -19996,7 +20000,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 468+ "line": 476}]},@@ -20007,7 +20011,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 336+ "line": 344}]},@@ -20018,7 +20022,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 463+ "line": 471}]},@@ -20029,7 +20033,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 286+ "line": 291}]},@@ -20040,7 +20044,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 306+ "line": 314}]},@@ -20051,7 +20055,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 322+ "line": 330}]},@@ -20062,7 +20066,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 329+ "line": 337}]},@@ -20073,7 +20077,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 314+ "line": 322}]},@@ -20084,7 +20088,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 365+ "line": 373}]},@@ -20095,7 +20099,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 358+ "line": 366}]},@@ -20106,7 +20110,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 372+ "line": 380}]},@@ -20117,7 +20121,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 381+ "line": 389}]},@@ -20128,7 +20132,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 344+ "line": 352}]},@@ -20139,7 +20143,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 414+ "line": 422}]},@@ -20150,7 +20154,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 399+ "line": 407}]},@@ -20161,7 +20165,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 423+ "line": 431}]},@@ -20172,7 +20176,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 440+ "line": 448}]},@@ -20183,7 +20187,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 407+ "line": 415}]},@@ -20194,7 +20198,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 447+ "line": 455}]},@@ -20205,7 +20209,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 390+ "line": 398}]},@@ -20216,7 +20220,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 212+ "line": 217}]},@@ -20227,7 +20231,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 183+ "line": 188}]},@@ -20238,7 +20242,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 187+ "line": 192}]},@@ -20249,7 +20253,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 198+ "line": 203}]},@@ -20260,7 +20264,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 192+ "line": 197}]},@@ -20271,7 +20275,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 226+ "line": 231}]},@@ -20282,7 +20286,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 165+ "line": 170}]},@@ -20293,7 +20297,7 @@"sources": [{"source": "server/routes/sprites.js",- "line": 171+ "line": 176}]},@@ -22163,7 +22167,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 121+ "line": 129}]},@@ -22174,7 +22178,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 20+ "line": 21}]},@@ -22185,7 +22189,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 91+ "line": 99}]},@@ -22196,7 +22200,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 95+ "line": 103}]},@@ -22207,7 +22211,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 77+ "line": 85}]},@@ -22218,7 +22222,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 107+ "line": 115}]},@@ -22229,7 +22233,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 63+ "line": 71}]},@@ -22240,7 +22244,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 84+ "line": 92}]},@@ -22251,7 +22255,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 100+ "line": 108}]},@@ -22262,7 +22266,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 43+ "line": 51}]},@@ -22273,7 +22277,7 @@"sources": [{"source": "server/routes/usage.js",- "line": 114+ "line": 122}]},@@ -23865,7 +23869,7 @@"stats": {"mounts": 147,"operations": 2153,- "declarations": 2156,+ "declarations": 2157,"sourceFiles": 229}}diff --git a/server/lib/index.js b/server/lib/index.jsindex c876349657..942b5bda63 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -419,6 +419,7 @@ export * from './extensionErrors.js';export * from './fetchErrorChain.js';export * from './isoWeek.js';export * from './lwwTimestamp.js';+export * from './snapshotChecksum.js';export * from './mapWithConcurrency.js';export * from './markedSection.js';export * from './mirrorParity.js';diff --git a/server/lib/snapshotChecksum.js b/server/lib/snapshotChecksum.jsnew file mode 100644index 0000000000..7cd5ac50a2--- /dev/null+++ b/server/lib/snapshotChecksum.js@@ -0,0 +1,34 @@+/**+ * Snapshot checksum helpers for cross-instance sync.+ *+ * A sync category's checksum is what lets the orchestrator skip the full+ * payload transfer when nothing moved, so every snapshot getter needs one.+ * These are the shared implementations — three getters had grown their own+ * byte-identical copy (`dataSync.js`, `digital-twin-sync.js`, `peerUsage.js`).+ *+ * Two variants, and the choice matters:+ *+ * - `snapshotChecksum` hashes `JSON.stringify` output, so it is sensitive to+ * key INSERTION ORDER. Correct only where the getter already canonicalizes+ * ordering itself (sorted arrays, deterministically rebuilt objects).+ * - `canonicalSnapshotChecksum` hashes `canonicalStringify`, which sorts object+ * keys recursively — so two machines holding identical data hash the same+ * regardless of the order they happened to write it in. Use this for any+ * payload whose top level is a map keyed by something arriving over the wire.+ *+ * Getting that wrong is not a crash: it is two converged peers whose checksums+ * never match, which the sync UI reads as "behind" forever.+ */++import crypto from 'crypto';+import { canonicalStringify } from './objects.js';++/** md5 of `JSON.stringify(data)` — insertion-order sensitive. */+export function snapshotChecksum(data) {+ return crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');+}++/** md5 of `canonicalStringify(data)` — stable across machines and write order. */+export function canonicalSnapshotChecksum(data) {+ return crypto.createHash('md5').update(canonicalStringify(data)).digest('hex');+}diff --git a/server/routes/dataSync.js b/server/routes/dataSync.jsindex 6a2a47fa11..dfdc3f4458 100644--- a/server/routes/dataSync.js+++ b/server/routes/dataSync.js@@ -16,7 +16,7 @@ const router = Router();// MUST stay in sync with dataSync.getSupportedCategories() — a category// registered in the service but absent here 400s before its snapshot/apply// handler can run (the latent bug #730 hit for `storyBuilder`).-const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace', 'universe', 'pipeline', 'mediaCollections', 'videoHistory', 'storyBuilder']);+const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace', 'universe', 'pipeline', 'mediaCollections', 'videoHistory', 'storyBuilder', 'usage']);// Tombstone GC manual trigger. Declared BEFORE `/:category/*` so the literal// "tombstones" segment wins Express's first-match lookup (categoryParam'sdiff --git a/server/routes/dataSync.test.js b/server/routes/dataSync.test.jsindex 08ef77ac7b..7f1c593f78 100644--- a/server/routes/dataSync.test.js+++ b/server/routes/dataSync.test.js@@ -121,7 +121,7 @@ describe('GET /api/sync/:category/checksum — forPeer scoping', () => {// is caught here.it.each(['goals', 'character', 'digitalTwin', 'meatspace',- 'universe', 'pipeline', 'mediaCollections', 'videoHistory', 'storyBuilder',+ 'universe', 'pipeline', 'mediaCollections', 'videoHistory', 'storyBuilder', 'usage',])('accepts the %s category (enum parity with getSupportedCategories)', async (category) => {const res = await request(buildApp()).get(`/api/sync/${category}/checksum`);expect(res.status).not.toBe(400);diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 79e51df9fa..169b3076cb 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -57,6 +57,7 @@ const syncCategoriesSchema = z.object({mediaCollections: z.boolean().optional(),videoHistory: z.boolean().optional(),storyBuilder: z.boolean().optional(),+ usage: z.boolean().optional(),fableLoom: z.boolean().optional(),authors: z.boolean().optional(),artists: z.boolean().optional(),diff --git a/server/routes/usage.js b/server/routes/usage.jsindex fb71d32ae4..52ecaf62ea 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -6,6 +6,7 @@ import { getAllProviders } from '../services/providers.js';import { asyncHandler } from '../lib/errorHandler.js';import { validateRequest, usageQuerySchema, usageMessagesSchema, providerUsageQuerySchema, subscriptionCostsSchema } from '../lib/validation.js';import { saveSubscriptionCosts, getSubscriptionSavings } from '../services/subscriptionCosts.js';+import { getFleetUsage } from '../services/peerUsage.js';import { resolveUsageRange } from '../lib/usageRange.js';import { WAIT } from '../lib/staleWhileRevalidate.js';import {@@ -23,19 +24,26 @@ router.get('/', asyncHandler(async (req, res) => {const result = await getAllProviders();const providers = Array.isArray(result) ? result : (result?.providers || []);const summary = usage.getUsageSummary({ from, to, providers });- // The report prices this window's usage at published API rates; the savings- // block says what the user's flat-rate plans cost over the SAME window, so- // the headline figure has something to be compared against.- const subscriptionSavings = await getSubscriptionSavings({- report: summary.report,- providers,- from,- to,- // Only an unbounded ("All time") window needs a start day inferred from- // history; every other range already has one, so don't pay the scan.- firstActivityDay: from ? null : usage.getFirstActivityDay()- });- res.json({ ...summary, subscriptionSavings });+ // Two independent reads over the same resolved window, so they overlap:+ // - savings: what the user's flat-rate plans cost over the SAME window, so+ // the headline API-rate figure has something to be compared against.+ // - fleet: the per-instance breakdown across the federation, priced over the+ // same window by the same report builder. Empty on a single-machine install+ // (or before a peer's first usage sync) — the UI hides that section rather+ // than showing a one-row "fleet".+ const [subscriptionSavings, fleet] = await Promise.all([+ getSubscriptionSavings({+ report: summary.report,+ providers,+ from,+ to,+ // Only an unbounded ("All time") window needs a start day inferred from+ // history; every other range already has one, so don't pay the scan.+ firstActivityDay: from ? null : usage.getFirstActivityDay()+ }),+ getFleetUsage({ from, to, providers }),+ ]);+ res.json({ ...summary, subscriptionSavings, fleet });}));// PUT /api/usage/subscriptions - Merge plan prices. An omitted family keeps itsdiff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex a17282a351..d4c2aa7767 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -13,6 +13,10 @@ vi.mock('../services/usage.js', () => ({resetUsage: vi.fn()}));+vi.mock('../services/peerUsage.js', () => ({+ getFleetUsage: vi.fn(async () => ({ instances: [], totals: null }))+}));+vi.mock('../services/subscriptionCosts.js', () => ({saveSubscriptionCosts: vi.fn(async (costs) => costs),getSubscriptionSavings: vi.fn(async () => ({ configured: false, families: [] }))@@ -42,6 +46,7 @@ import { getAllProviders } from '../services/providers.js';import { getProviderQuotas } from '../services/providerUsage.js';import { getHistoricalUsageBackfillStatus, startHistoricalUsageBackfill } from '../services/usageBackfill.js';import { getSubscriptionSavings, saveSubscriptionCosts } from '../services/subscriptionCosts.js';+import { getFleetUsage } from '../services/peerUsage.js';import usageRoutes from './usage.js';const buildApp = () => {@@ -64,12 +69,16 @@ describe('usage routes', () => {expect(res.body).toEqual({totalSessions: 4,providers: ['anthropic'],- subscriptionSavings: { configured: false, families: [] }+ subscriptionSavings: { configured: false, families: [] },+ fleet: { instances: [], totals: null }});const arg = usage.getUsageSummary.mock.calls[0][0];expect(arg.from).toMatch(/^\d{4}-\d{2}-\d{2}$/);expect(arg.to).toBeNull();expect(arg.providers).toEqual([]);+ // The fleet breakdown must be priced over the SAME window as the summary,+ // or a peer row would silently report a different period than its heading.+ expect(getFleetUsage).toHaveBeenCalledWith({ from: arg.from, to: null, providers: [] });});it('GET /api/usage passes an explicit from/to range through', async () => {diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex 0761362510..81d6253a0c 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -6,11 +6,11 @@* No data is ever lost — unique records from both sides are kept (union semantics).*/-import crypto from 'crypto';import { stat, readdir } from 'fs/promises';import { join } from 'path';import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';+import { snapshotChecksum } from '../lib/snapshotChecksum.js';import {PORTOS_SCHEMA_VERSIONS,RECORD_KIND_SCHEMA_CATEGORIES,@@ -34,6 +34,11 @@ import {applyDigitalTwinRemote,DIGITAL_TWIN_CHECKSUM_PATHS,} from './digital-twin-sync.js';+import {+ getUsageSnapshot,+ applyUsageRemote,+ USAGE_CHECKSUM_PATHS,+} from './peerUsage.js';// --- Category Definitions ---@@ -114,9 +119,9 @@ const MEATSPACE_FILES = {// --- Checksum Helper ----function computeChecksum(data) {- return crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');-}+// Insertion-order sensitive by design: every getter here canonicalizes its own+// ordering before hashing (see the sorted-record notes below).+const computeChecksum = snapshotChecksum;// --- Merge Helpers ---@@ -749,6 +754,10 @@ const CHECKSUM_PATHS = {// getter filters back to sync:true and the checksum is unchanged when no// synced session moved, so the orchestrator still skips the transfer.storyBuilder: [STORY_BUILDER_DIR, STORY_BUILDER_EPOCH_KEY],+ // usage invalidates on our OWN usage.json (every recorded AI run rewrites it)+ // and on the peer-digest store (a peer's newer digest changes what we forward+ // on). Both are atomicWrite'd — see peerUsage.js.+ usage: USAGE_CHECKSUM_PATHS,};const CATEGORIES = {@@ -760,7 +769,8 @@ const CATEGORIES = {pipeline: { getSnapshot: getPipelineSnapshot, applyRemote: applyPipelineRemote },mediaCollections: { getSnapshot: getMediaCollectionsSnapshot, applyRemote: applyMediaCollectionsRemote },videoHistory: { getSnapshot: getVideoHistorySnapshot, applyRemote: applyVideoHistoryRemote },- storyBuilder: { getSnapshot: getStoryBuilderSnapshot, applyRemote: applyStoryBuilderRemote }+ storyBuilder: { getSnapshot: getStoryBuilderSnapshot, applyRemote: applyStoryBuilderRemote },+ usage: { getSnapshot: getUsageSnapshot, applyRemote: applyUsageRemote }};// Map a snapshot CATEGORY to the `PORTOS_SCHEMA_VERSIONS` keys whose storage@@ -791,6 +801,9 @@ const SNAPSHOT_CATEGORY_SCHEMA_KEYS = {meatspace: [],videoHistory: [],storyBuilder: RECORD_KIND_SCHEMA_CATEGORIES.storyBuilder,+ // Per-instance digests replaced whole under an LWW stamp, with every field+ // read defensively — no versioned on-disk layout to gate on.+ usage: [],};// Exported for the boot-adjacent guard test (see dataSync.pipelineUniverse.test.js):diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.jsindex f29386a0e6..87eaa51d01 100644--- a/server/services/digital-twin-sync.js+++ b/server/services/digital-twin-sync.js@@ -55,11 +55,11 @@* account id (#3532) — see mergeSocialAccounts.*/-import crypto from 'crypto';import { join, basename } from 'path';import { readdir, readFile, unlink } from 'fs/promises';import { existsSync } from 'fs';import { atomicWrite, readJSONFile, ensureDir, PATHS } from '../lib/fileUtils.js';+import { snapshotChecksum } from '../lib/snapshotChecksum.js';import { canonicalStringify, isPlainObject } from '../lib/objects.js';import { normalizeTombstones, mergeTombstones, isTombstoned, pruneTombstones, tombstonesEqual } from '../lib/tombstones.js';import { compareNewerWins } from '../lib/lwwTimestamp.js';@@ -90,9 +90,9 @@ const SOCIAL_ACCOUNTS_FILE = join(DIR, 'social-accounts.json');// the checksum is unchanged and the orchestrator still skips the transfer).export const DIGITAL_TWIN_CHECKSUM_PATHS = [DIR];-function computeChecksum(data) {- return crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');-}+// Insertion-order sensitive by design: every getter here canonicalizes its own+// ordering before hashing (see the sorted-record notes below).+const computeChecksum = snapshotChecksum;// --- Pure merge helpers (exported for unit tests) ---diff --git a/server/services/instances.js b/server/services/instances.jsindex e20defbbda..279d36f4df 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -139,8 +139,16 @@ export function redactPeerForWire(peer) {// `hasApiKey` pattern in server/routes/providers.js. The password stays only// on the server-side record, where peerAuthHeaders reads it.export function sanitizePeerForClient(peer) {- if (!peer || typeof peer !== 'object' || !peer.auth || typeof peer.auth !== 'object') return peer;- return { ...peer, auth: { username: peer.auth.username ?? '', hasPassword: Boolean(peer.auth.password) } };+ if (!peer || typeof peer !== 'object') return peer;+ const auth = peer.auth && typeof peer.auth === 'object'+ ? { username: peer.auth.username ?? '', hasPassword: Boolean(peer.auth.password) }+ : peer.auth;+ // EFFECTIVE categories, not the raw stored map — the SAME resolution the sync+ // loop runs. Shipping the raw map would render a default-ON category's+ // 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) };}// Default data shape@@ -306,7 +314,9 @@ function validHost(str) {export { validHost };-// Default sync categories — all disabled until explicitly enabled per-peer+// Default sync categories. Everything that replicates the user's own CONTENT is+// off until explicitly enabled per-peer; the exception is `usage`, which is+// default-ON (see DEFAULT_ON_SYNC_CATEGORIES below).const DEFAULT_SYNC_CATEGORIES = {brain: false,memory: false,@@ -319,6 +329,9 @@ const DEFAULT_SYNC_CATEGORIES = {mediaCollections: false,videoHistory: false,storyBuilder: false,+ // ON by default — the only category that is. Rationale + the rules that+ // follow from it: docs/decisions/2026-09-01-federated-usage-metrics.md.+ usage: true,fableLoom: false,authors: false,artists: false,@@ -337,6 +350,58 @@ const DEFAULT_SYNC_CATEGORIES = {export { DEFAULT_SYNC_CATEGORIES };+// Categories that stay on for a peer even when the user's master `syncEnabled`+// switch is off — that switch predates them and means "don't replicate my+// content to this peer", so it must not silently retract a default-ON one.+// Turning one off is an explicit per-category act; disabling the PEER+// (`enabled: false`) still stops everything.+export const DEFAULT_ON_SYNC_CATEGORIES = Object.freeze(+ Object.entries(DEFAULT_SYNC_CATEGORIES).filter(([, on]) => on).map(([key]) => key)+);+const DEFAULT_ON_SET = new Set(DEFAULT_ON_SYNC_CATEGORIES);++/** Is this category one that ships ON? The single definition of that policy. */+export const isDefaultOnCategory = (key) => DEFAULT_ON_SET.has(key);++// Does this category map enable anything the user actually opted into?+//+// `syncEnabled` is derived from this, and it is NOT a cosmetic flag: it also+// gates per-record OUTBOUND pushes (`peerAllowsOutbound`). A default-ON category+// must therefore never flip it on by itself, or adding one would silently widen+// what every existing peer is allowed to receive.+function hasOptedInCategory(categories) {+ return Object.entries(categories || {}).some(([key, on]) => on === true && !isDefaultOnCategory(key));+}++/**+ * 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.+ *+ * Three 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.+ */+export function resolveEffectiveCategories(peer) {+ if (peer?.fullSync === true) return allSyncCategoriesOn();+ const stored = peer?.syncCategories+ ? { ...DEFAULT_SYNC_CATEGORIES, ...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;+ return Object.fromEntries(DEFAULT_ON_SYNC_CATEGORIES.map((key) => [key, stored[key] === true]));+}+// A category map with every key forced on — the effective view a full-sync// ("mirror everything") peer presents. Derived from DEFAULT_SYNC_CATEGORIES so a// newly added category is covered by full-sync peers with no per-peer change.@@ -473,7 +538,7 @@ export async function updatePeer(id, updates) {// Turning full mirror off restores the per-category selection preserved// underneath — recompute syncEnabled from it so a peer with no remaining// enabled categories doesn't read as "sync on, nothing to sync".- peer.syncEnabled = Object.values(peer.syncCategories || {}).some(Boolean);+ peer.syncEnabled = hasOptedInCategory(peer.syncCategories);}// Reciprocate the full-sync intent (and its all-on category view) to the// peer whenever we know its identity, so a node pair converges to a mutual@@ -490,6 +555,13 @@ export async function updatePeer(id, updates) {if (prev[cat] !== true && incoming[cat] === true) turnedOnKinds.push(kind);}peer.syncCategories = { ...prev, ...incoming };+ // `syncEnabled` is DERIVED from the category map — it gates per-record+ // outbound pushes (peerAllowsOutbound), so it must reflect what the user+ // opted into, not what a caller computed. Recomputing here (rather than+ // honoring `updates.syncEnabled` on this path) is what keeps a default-ON+ // category from widening outbound consent: a client that sums the whole+ // map would see `usage: true` and send `syncEnabled: true`.+ peer.syncEnabled = hasOptedInCategory(peer.syncCategories);if (turnedOnKinds.length > 0) backfillPeerInstanceId = peer.instanceId || null;// Reciprocate so the peer enables the same categories toward us. Only when// we know the peer's identity (post-handshake).@@ -1045,7 +1117,7 @@ export async function applyReciprocalSync(instanceId, categories, { fullSync } =if (needsOutboundAdopt) entry.directions = [...directions, 'outbound'];// Recompute from the (possibly preserved) stored map — a full-sync peer is// always sync-enabled; otherwise it follows the per-category selection.- entry.syncEnabled = entry.fullSync === true || Object.values(entry.syncCategories || {}).some(Boolean);+ entry.syncEnabled = entry.fullSync === true || hasOptedInCategory(entry.syncCategories);// Backfill every per-record kind whose push toward this peer just became// viable: a kind that flipped false→true, all kinds when full mirror was just// adopted, and — when we just adopted outbound on a previously inbound-onlydiff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 09df5236b4..4852f45cd2 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -451,6 +451,22 @@ describe('instances.js', () => {});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+ // with no migration. Shipping the RAW map to the client would render a+ // default-ON category's checkbox off while the server actively syncs it.+ it('resolves the effective category map so the UI matches what actually syncs', () => {+ const sanitized = sanitizePeerForClient({ id: 'p1', syncCategories: { brain: true } });+ expect(sanitized.syncCategories.brain).toBe(true);+ expect(sanitized.syncCategories.usage).toBe(true); // default-ON, absent from the stored map+ expect(sanitized.syncCategories.goals).toBe(false);+ });++ it('lets an explicit opt-out survive the default merge', () => {+ const sanitized = sanitizePeerForClient({ id: 'p1', syncCategories: { usage: false } });+ expect(sanitized.syncCategories.usage).toBe(false);+ });+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);@@ -462,9 +478,11 @@ describe('instances.js', () => {expect(peer.auth.password).toBe('secret');});- it('leaves a credential-less peer untouched', () => {+ it('leaves a credential-less peer\'s credential alone', () => {const peer = { id: 'peer-1', name: 'host', auth: null };- expect(sanitizePeerForClient(peer)).toBe(peer);+ const sanitized = sanitizePeerForClient(peer);+ expect(sanitized.auth).toBeNull();+ expect(sanitized.id).toBe('peer-1');});});@@ -704,6 +722,35 @@ describe('instances.js', () => {expect(changed).toBe(false);});+ // `usage` is the one default-ON category. `syncEnabled` is derived from the+ // category map AND gates per-record outbound pushes (peerAllowsOutbound), so+ // a default-ON category must never flip it on by itself — otherwise adding+ // one would silently widen what every existing peer may receive.+ // The client used to compute syncEnabled itself by summing the whole category+ // map — which reads a default-ON category as "something is enabled" and+ // widens the peer's outbound push consent (peerAllowsOutbound). syncEnabled+ // is DERIVED, so a syncCategories edit recomputes it and ignores the value+ // a caller sent alongside.+ it('recomputes syncEnabled from the categories, ignoring a caller-sent value', async () => {+ const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true, usage: true }, syncEnabled: true }];+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });++ const peer = await updatePeer('p1', { syncCategories: { brain: false }, syncEnabled: true });++ expect(peer.syncCategories.usage).toBe(true);+ expect(peer.syncEnabled).toBe(false);+ });++ it('a default-ON category alone does not flip syncEnabled on', async () => {+ const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true }, syncEnabled: true }];+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });++ const { peer } = await applyReciprocalSync('inst-A', { brain: false, usage: true });++ expect(peer.syncCategories.usage).toBe(true);+ expect(peer.syncEnabled).toBe(false); // no CONTENT category left enabled+ });+it('applies an all-false map to clear a stale enabled category (the offline-disable recovery path)', async () => {const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true }, syncEnabled: true }];readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });diff --git a/server/services/peerUsage.js b/server/services/peerUsage.jsnew file mode 100644index 0000000000..654687119c--- /dev/null+++ b/server/services/peerUsage.js@@ -0,0 +1,237 @@+/**+ * Federated AI-usage metrics.+ *+ * PortOS installs are commonly several machines federated as sync peers, and+ * "how much AI did I burn?" is a question about the FLEET, not about whichever+ * box the user happens to have open. This service is the `usage` sync+ * category's store: each instance publishes a digest of its own+ * `data/usage.json` (aggregate counters only — see `buildUsageDigest`) and+ * keeps every peer's digest side by side under `data/peer-usage.json`.+ *+ * Two invariants make that safe to run continuously:+ *+ * - **Never merged into local usage.** A peer's counters live in their own+ * per-instance slot. Summing them into `usage.json` would double-count on+ * the very next round trip (our snapshot would ship the inflated total back)+ * and would corrupt this machine's own history irreversibly.+ * - **Idempotent, per-instance LWW.** A digest is replaced whole, keyed by its+ * origin instanceId and stamped with `capturedAt`. Re-applying the same+ * snapshot is a no-op, and a node forwards what it knows about third+ * instances, so a chain (A↔B↔C) converges without A and C ever talking.+ *+ * Privacy: the digest carries provider ids, model ids, token/session/message+ * counts, day+month buckets and an instance name. No prompts, no transcripts,+ * no record contents, no PII — see+ * `docs/decisions/2026-09-01-federated-usage-metrics.md`.+ */++import { join } from 'path';+import { atomicWrite, readJSONFile, 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 { canonicalSnapshotChecksum } from '../lib/snapshotChecksum.js';+import { roundCents } from '../lib/subscriptionSavings.js';+import { buildUsageDigest, buildUsageReport, getUsage, USAGE_FILE } from './usage.js';++const PEER_USAGE_FILE = join(PATHS.data, 'peer-usage.json');++// Upper bound on stored peer digests. A home federation runs a handful of+// machines; the cap only stops an unbounded file if a peer ever forwards a long+// tail of instance ids that no longer exist. Oldest `capturedAt` is evicted.+const MAX_INSTANCES = 64;++const withLock = createMutex();++const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;++/**+ * This machine's federation identity. Dynamically imported so `dataSync` →+ * `peerUsage` doesn't drag `services/instances.js` (peer socket relay,+ * federated-media consumer, tailscale) into dataSync's module-load path — the+ * same reason dataSync defers `sharing/peerSync.js`.+ */+async function readSelfIdentity() {+ const { getSelf, UNKNOWN_INSTANCE_ID } = await import('./instances.js');+ const self = await getSelf().catch(() => null);+ const instanceId = isNonEmptyStr(self?.instanceId) && self.instanceId !== UNKNOWN_INSTANCE_ID+ ? self.instanceId+ : null;+ return { instanceId, name: isNonEmptyStr(self?.name) ? self.name : null };+}++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 };+}++/**+ * 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.+ */+function sanitizeEntry(entry, expectedId) {+ if (!isPlainObject(entry) || !isPlainObject(entry.usage)) return null;+ // A digest may omit its own id (the key is authoritative), but it may never+ // claim a DIFFERENT one — that would let a peer smuggle a digest in under our+ // id, or overwrite a third instance's slot.+ if (isNonEmptyStr(entry.instanceId) && entry.instanceId !== expectedId) return null;+ if (parseTsMs(entry.capturedAt) === null) return null;+ return {+ instanceId: expectedId,+ name: isNonEmptyStr(entry.name) ? entry.name.slice(0, 120) : expectedId,+ capturedAt: entry.capturedAt,+ usage: entry.usage,+ };+}++// The self digest is a pure function of (usage counters, today's date) — the+// date because the wire rollup's cutoff moves at midnight. `saveUsage` stamps+// `lastUpdated` on every write, so it doubles as the cache key. Without this+// memo the deep clone + rollup re-ran on every checksum-cache miss AND once per+// probing peer, all producing the identical byte-for-byte digest.+let digestMemo = null;+function selfDigest(usageData) {+ const key = `${usageData?.lastUpdated ?? ''}|${new Date().toISOString().slice(0, 10)}`;+ if (digestMemo?.key !== key) digestMemo = { key, digest: buildUsageDigest(usageData) };+ return digestMemo.digest;+}++/** This instance's own live entry, rebuilt from `usage.json` on every read. */+async function buildSelfEntry() {+ const { instanceId, name } = await readSelfIdentity();+ if (!instanceId) return null;+ const usage = selfDigest(getUsage());+ return { instanceId, name: name || instanceId, capturedAt: usage.lastUpdated, usage };+}++/**+ * Every instance we can report on: the peer digests we hold, plus our own live+ * entry. Our own slot is always regenerated — a stale copy of us that came back+ * from a peer never wins. A digest with no activity yet has a null+ * `lastUpdated` and is dropped from the wire rather than shipped unorderable.+ */+async function entriesWithSelf() {+ const [store, self] = await Promise.all([readStore(), buildSelfEntry()]);+ const peers = Object.values(store.instances).filter((e) => isPlainObject(e) && isPlainObject(e.usage));+ const publishable = self && isNonEmptyStr(self.capturedAt) ? self : null;+ return {+ self: publishable,+ peers: peers.filter((e) => e.instanceId !== self?.instanceId),+ };+}++/**+ * dataSync `getSnapshot` for the `usage` category: our own live digest plus+ * every peer digest we hold, so a third instance reachable only through us+ * still propagates.+ */+export async function getUsageSnapshot() {+ const { self, peers } = await entriesWithSelf();+ const instances = Object.fromEntries(peers.map((e) => [e.instanceId, e]));+ if (self) instances[self.instanceId] = self;+ const data = { instances };+ // 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+ // "behind" forever.+ return { data, checksum: canonicalSnapshotChecksum(data) };+}++/**+ * dataSync `applyRemote` for the `usage` category. Per-instance LWW on+ * `capturedAt`; our own slot is skipped outright (we are the authority on our+ * own counters), and nothing is ever summed into `data/usage.json`.+ */+export async function applyUsageRemote(remoteData) {+ const incoming = isPlainObject(remoteData?.instances) ? remoteData.instances : null;+ if (!incoming) return { applied: false, count: 0 };++ const { instanceId: selfId } = await readSelfIdentity();++ return withLock(async () => {+ const store = await readStore();+ 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;+ if (!compareNewerWins(entry.capturedAt, store.instances[key]?.capturedAt)) continue;+ store.instances[key] = entry;+ changed++;+ }++ if (changed === 0) return { applied: false, count: 0 };++ const ids = Object.keys(store.instances);+ if (ids.length > MAX_INSTANCES) {+ const oldestFirst = ids.sort((a, b) => (parseTsMs(store.instances[a].capturedAt) ?? 0) - (parseTsMs(store.instances[b].capturedAt) ?? 0));+ for (const id of oldestFirst.slice(0, ids.length - MAX_INSTANCES)) delete store.instances[id];+ }++ await atomicWrite(PEER_USAGE_FILE, store);+ console.log(`🔄 Usage sync: updated ${changed} instance digest${changed === 1 ? '' : 's'}`);+ return { applied: true, count: changed };+ });+}++/**+ * Fleet-wide usage for a report window: one row per known instance plus the+ * combined totals.+ *+ * Every row goes through the SAME pure `buildUsageReport` the single-instance+ * page uses, so per-instance and fleet figures are priced identically — and+ * THIS machine's row reads the live activity maps, not its own wire digest. The+ * digest folds days past the wire-retention window into whole months, and+ * `buildUsageReport` includes a month bucket whole whenever its month overlaps+ * the window; routing our own row through it would make the "This machine" row+ * disagree with the headline directly above it on a narrow historical range.+ *+ * 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.+ */+export async function getFleetUsage({ from = null, to = null, providers = [] } = {}) {+ const { self, peers } = await entriesWithSelf();+ if (peers.length === 0) return { instances: [], totals: null };++ const row = ({ instanceId, name, capturedAt, activity, isSelf }) => {+ const report = buildUsageReport(activity.dailyActivity || {}, {+ from,+ to,+ providers,+ monthlyActivity: activity.monthlyActivity || {},+ // 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.+ totalTokens: from || to ? null : activity.totalTokens,+ });+ return { instanceId, name: name || instanceId, self: isSelf, capturedAt, totals: report.totals };+ };++ const rows = peers.map((e) => row({ ...e, activity: e.usage, isSelf: false }));+ if (self) rows.unshift(row({ ...self, activity: getUsage(), isSelf: true }));++ rows.sort((a, b) => (b.self ? 1 : 0) - (a.self ? 1 : 0) || b.totals.estimatedCost - a.totals.estimatedCost);++ // Derived from the report's own totals rather than a second hardcoded field+ // list, so a field added to `buildUsageReport` can't silently sum to zero here.+ const totals = rows.reduce((acc, r) => {+ for (const [field, value] of Object.entries(r.totals)) {+ if (typeof value === 'number') acc[field] = (acc[field] || 0) + value;+ }+ return acc;+ }, {});+ totals.estimatedCost = roundCents(totals.estimatedCost || 0);++ return { instances: rows, totals };+}++// Files whose fingerprint invalidates the category's checksum cache.+export const USAGE_CHECKSUM_PATHS = [USAGE_FILE, PEER_USAGE_FILE];++export { PEER_USAGE_FILE };diff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.jsnew file mode 100644index 0000000000..6ac1cf1ffb--- /dev/null+++ b/server/services/peerUsage.test.js@@ -0,0 +1,236 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { readFile } from 'fs/promises';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++const { makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-peer-usage-' });+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++// peerUsage resolves this machine's identity through a dynamic import of+// instances.js (kept off dataSync's module graph); the digest itself is+// whatever usage.js currently holds.+const self = { instanceId: 'inst-self', name: 'Workshop' };+// importActual so UNKNOWN_INSTANCE_ID stays the REAL sentinel — a hand-written+// copy here would let the real one drift and silently stop being filtered.+vi.mock('./instances.js', async () => ({+ ...(await vi.importActual('./instances.js')),+ getSelf: vi.fn(async () => self),+}));++let localUsage;+vi.mock('./usage.js', async () => {+ const actual = await vi.importActual('./usage.js');+ return { ...actual, getUsage: () => localUsage };+});++const { buildUsageDigest, getUsage } = await import('./usage.js');+const {+ getUsageSnapshot,+ applyUsageRemote,+ getFleetUsage,+ PEER_USAGE_FILE,+} = await import('./peerUsage.js');++afterAll(cleanup);++// A minimal but realistic usage shape: one provider/model day bucket plus the+// all-time totals the report folds in on an unbounded window.+const usageFixture = ({ day = '2026-08-30', tokensOut = 1000, lastUpdated = '2026-08-30T12:00:00.000Z' } = {}) => ({+ totalSessions: 2,+ totalMessages: 5,+ totalToolCalls: 7,+ totalTokens: { input: 500, output: tokensOut },+ byProvider: { anthropic: { name: 'Anthropic', sessions: 2, messages: 5, tokens: tokensOut } },+ byModel: { 'claude-opus-5': { sessions: 2, messages: 5, tokens: tokensOut } },+ dailyActivity: {+ [day]: {+ sessions: 2,+ messages: 5,+ tokens: tokensOut,+ byProvider: {+ anthropic: {+ name: 'Anthropic',+ sessions: 2,+ messages: 5,+ tokensIn: 500,+ tokensOut,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: 'measured',+ byModel: {+ 'claude-opus-5': {+ sessions: 2, messages: 5, tokensIn: 500, tokensOut,+ cacheReadTokens: 0, cacheWriteTokens: 0, source: 'measured',+ },+ },+ },+ },+ },+ },+ monthlyActivity: {},+ hourlyActivity: Array(24).fill(0),+ earliestActivityDay: day,+ lastUpdated,+ // Machine-local idempotency bookkeeping keyed by LOCAL run ids — meaningless+ // on a peer, and the largest field in the file.+ reconciledRuns: { 'run-1': '2026-08-30T12:00:00.000Z' },+});++const peerEntry = (overrides = {}) => ({+ instanceId: 'inst-peer',+ name: 'Studio',+ capturedAt: '2026-08-30T09:00:00.000Z',+ usage: buildUsageDigest(usageFixture({ tokensOut: 4000 })),+ ...overrides,+});++const readStoreFile = async () => JSON.parse(await readFile(PEER_USAGE_FILE, 'utf8'));++beforeEach(async () => {+ localUsage = usageFixture();+ // Reset the store between cases — every test starts with no peer digests.+ const { atomicWrite } = await import('../lib/fileUtils.js');+ await atomicWrite(PEER_USAGE_FILE, { instances: {} });+});++describe('federated usage digest', () => {+ // The wire shape is an allowlist. `reconciledRuns` is local run-id bookkeeping+ // (meaningless on a peer, and the biggest field in the file); all-time+ // byProvider/byModel are a coarser restatement of the day buckets that already+ // ride along. Both would otherwise be pure recurring wire weight.+ it('ships an allowlist, not the whole usage file', () => {+ const digest = buildUsageDigest(usageFixture());+ expect(Object.keys(digest).sort()).toEqual([+ 'dailyActivity', 'earliestActivityDay', 'hourlyActivity', 'lastUpdated',+ 'monthlyActivity', 'totalMessages', 'totalSessions', 'totalTokens', 'totalToolCalls',+ ]);+ });++ it('folds days past the wire retention window into their month, preserving counts', () => {+ const source = usageFixture({ day: '2026-01-05' });+ const digest = buildUsageDigest(source, { retentionDays: 30, now: new Date('2026-08-30T00:00:00Z') });+ expect(digest.dailyActivity['2026-01-05']).toBeUndefined();+ expect(digest.monthlyActivity['2026-01'].byProvider.anthropic.tokensOut).toBe(1000);+ // Pure: the rollup runs over a shallow copy, so the caller's maps survive.+ expect(source.dailyActivity['2026-01-05']).toBeTruthy();+ expect(source.monthlyActivity).toEqual({});+ });+});++describe('usage sync category', () => {+ it('publishes this instance under its own id', async () => {+ const { data } = await getUsageSnapshot();+ expect(Object.keys(data.instances)).toEqual(['inst-self']);+ expect(data.instances['inst-self'].name).toBe('Workshop');+ expect(data.instances['inst-self'].capturedAt).toBe('2026-08-30T12:00:00.000Z');+ });++ it('keeps the checksum stable while local usage has not moved', async () => {+ const a = await getUsageSnapshot();+ const b = await getUsageSnapshot();+ expect(b.checksum).toBe(a.checksum);+ });++ it('stores a peer digest side by side instead of summing it into local usage', async () => {+ const result = await applyUsageRemote({ instances: { 'inst-peer': peerEntry() } });+ expect(result).toEqual({ applied: true, count: 1 });++ const store = await readStoreFile();+ expect(store.instances['inst-peer'].usage.totalTokens.output).toBe(4000);+ // The local file's own counters are untouched — summing them would+ // double-count on the very next round trip.+ expect(localUsage.totalTokens.output).toBe(1000);+ const { data } = await getUsageSnapshot();+ expect(data.instances['inst-self'].usage.totalTokens.output).toBe(1000);+ });++ it('re-applying the same snapshot is a no-op', async () => {+ const snapshot = { instances: { 'inst-peer': peerEntry() } };+ await applyUsageRemote(snapshot);+ expect(await applyUsageRemote(snapshot)).toEqual({ applied: false, count: 0 });+ });++ it('replaces a peer digest only when the incoming one is newer', async () => {+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry() } });++ const stale = peerEntry({+ capturedAt: '2026-08-29T00:00:00.000Z',+ usage: buildUsageDigest(usageFixture({ tokensOut: 1 })),+ });+ expect(await applyUsageRemote({ instances: { 'inst-peer': stale } })).toEqual({ applied: false, count: 0 });+ expect((await readStoreFile()).instances['inst-peer'].usage.totalTokens.output).toBe(4000);++ const fresh = peerEntry({+ capturedAt: '2026-08-31T00:00:00.000Z',+ usage: buildUsageDigest(usageFixture({ tokensOut: 9000 })),+ });+ expect(await applyUsageRemote({ instances: { 'inst-peer': fresh } })).toEqual({ applied: true, count: 1 });+ expect((await readStoreFile()).instances['inst-peer'].usage.totalTokens.output).toBe(9000);+ });++ it('ignores a peer echoing a stale copy of US back', async () => {+ const echo = peerEntry({+ instanceId: 'inst-self',+ name: 'Workshop',+ capturedAt: '2099-01-01T00:00:00.000Z',+ usage: buildUsageDigest(usageFixture({ tokensOut: 999999 })),+ });+ expect(await applyUsageRemote({ instances: { 'inst-self': echo } })).toEqual({ applied: false, count: 0 });+ const { data } = await getUsageSnapshot();+ expect(data.instances['inst-self'].usage.totalTokens.output).toBe(1000);+ });++ it('rejects an entry whose instanceId does not match the key it arrived under', async () => {+ const spoofed = peerEntry({ instanceId: 'inst-self' });+ expect(await applyUsageRemote({ instances: { 'inst-peer': spoofed } })).toEqual({ applied: false, count: 0 });+ });++ it('forwards known peer digests so a third instance propagates through us', async () => {+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry() } });+ const { data } = await getUsageSnapshot();+ expect(Object.keys(data.instances).sort()).toEqual(['inst-peer', 'inst-self']);+ });+});++describe('fleet report', () => {+ it('is empty until a peer digest has synced', async () => {+ expect(await getFleetUsage({ providers: [] })).toEqual({ instances: [], totals: null });+ });++ it('reports one row per instance plus the combined totals', async () => {+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry() } });+ const fleet = await getFleetUsage({ providers: [] });++ expect(fleet.instances.map((i) => i.instanceId)).toEqual(['inst-self', 'inst-peer']);+ expect(fleet.instances[0].self).toBe(true);+ expect(fleet.instances[1].capturedAt).toBe('2026-08-30T09:00:00.000Z');+ expect(fleet.totals.tokensOut).toBe(5000);+ expect(fleet.totals.sessions).toBe(4);+ });++ // The wire digest folds days past its retention window into WHOLE months, and+ // buildUsageReport includes a month bucket whole whenever its month overlaps+ // the range. Routing this machine's own row through the digest therefore made+ // the "This machine" row report a whole month where the headline above it+ // reported ten days — measured at 10x. The self row must read the live maps.+ it('prices this machine from live usage, not from its own wire digest', async () => {+ localUsage = usageFixture({ day: '2026-01-05', tokensOut: 1000 });+ localUsage.dailyActivity['2026-01-15'] = { sessions: 1, messages: 1, tokens: 100, byProvider: {+ anthropic: { name: 'Anthropic', sessions: 1, messages: 1, tokensIn: 50, tokensOut: 100, cacheReadTokens: 0, cacheWriteTokens: 0, source: 'measured', byModel: {} },+ } };+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry() } });++ const fleet = await getFleetUsage({ from: '2026-01-10', to: '2026-01-20', providers: [] });+ const selfRow = fleet.instances.find((i) => i.self);+ // Only the 2026-01-15 bucket is in range; the 2026-01-05 one is not.+ expect(selfRow.totals.tokensOut).toBe(100);+ });++ 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: [] });+ expect(outside.totals.tokensOut).toBe(0);+ });+});diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex d746f49d13..2b2a8ea80f 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -11,7 +11,7 @@ import { join } from 'path';import { readJSONFile, ensureDir, PATHS, dataPath, atomicWrite } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { instanceEvents } from './instanceEvents.js';-import { getPeers, DEFAULT_SYNC_CATEGORIES, allSyncCategoriesOn, updatePeer, getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';+import { getPeers, resolveEffectiveCategories, updatePeer, getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';import { peerBaseUrl } from '../lib/peerUrl.js';import { peerAuthHeaders } from '../lib/peerHttpClient.js';import * as brainSync from './brainSync.js';@@ -444,25 +444,10 @@ function detectCursorReset(cursor, peer) {return corrected;}-/**- * Resolve effective sync categories for a peer.- * Returns object with boolean flags for each category.- * Falls back to legacy behavior: if syncCategories is absent but syncEnabled is true,- * enable brain + memory for backward compatibility with older peers.- */-function getEffectiveCategories(peer) {- // A full-sync ("mirror everything") peer pulls EVERY snapshot category from- // its mirror, regardless of the stored per-category map — including a category- // added in a later version (allSyncCategoriesOn derives off- // DEFAULT_SYNC_CATEGORIES, so it stays current automatically).- if (peer.fullSync === true) return allSyncCategoriesOn();- if (peer.syncCategories) return peer.syncCategories;- // Legacy fallback: peers without syncCategories but with syncEnabled get brain+memory- if (peer.syncEnabled !== false) {- return { ...DEFAULT_SYNC_CATEGORIES, brain: true, memory: true };- }- return { ...DEFAULT_SYNC_CATEGORIES };-}+// The effective category map lives in instances.js, next to the defaults it+// resolves against, so the sync loop and the client-facing peer payload+// (sanitizePeerForClient) can't drift apart on what "on" means for a peer.+const getEffectiveCategories = resolveEffectiveCategories;/*** Sync a snapshot-based data category from a peer.@@ -818,7 +803,9 @@ export async function syncWithPeer(peer) {* Check if a peer has any sync category enabled*/function hasAnySyncEnabled(peer) {- if (peer.syncEnabled === false) return false;+ // 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.const cats = getEffectiveCategories(peer);return Object.values(cats).some(Boolean);}diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 6424790406..6371a9c76d 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -1,18 +1,17 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Mock all dependencies-vi.mock('./instances.js', () => ({+vi.mock('./instances.js', async () => ({+ // Keep the REAL resolveEffectiveCategories (and the default map it resolves+ // against): a hand-written stand-in would let the shipped defaults drift from+ // what these tests assert the sync loop does with them.+ ...(await vi.importActual('./instances.js')),getPeers: vi.fn(),updatePeer: vi.fn().mockResolvedValue(undefined),// forPeer scoping resolves our own instanceId; the orchestrator catches a// throw/UNKNOWN and just omits the query param, so the default mock returns// a stable id to exercise the scoped path.getInstanceId: vi.fn().mockResolvedValue('our-inst-id'),- UNKNOWN_INSTANCE_ID: 'unknown',- DEFAULT_SYNC_CATEGORIES: {- brain: false, memory: false, goals: false,- character: false, digitalTwin: false, meatspace: false, catalog: false- }}));vi.mock('./brainSyncLog.js', () => ({getChangesSince: vi.fn(),@@ -779,6 +778,53 @@ describe('syncOrchestrator', () => {});});+ // AI usage metrics are the one DEFAULT-ON sync category: a fresh peer syncs+ // them without the user enabling anything, and the peer-level `syncEnabled`+ // master switch (which predates default-on categories and means "don't+ // replicate my content here") must not silently retract them.+ describe('default-ON categories', () => {+ const categoryUrls = () => mockFetch.mock.calls+ .map((c) => c[0])+ .filter((url) => url.includes('/api/sync/'));++ beforeEach(async () => {+ const dataSync = await import('./dataSync.js');+ dataSync.getSupportedCategories.mockReturnValue(['usage', 'goals']);+ dataSync.getChecksum.mockResolvedValue({ checksum: 'local' });+ mockFetch.mockImplementation(async (url) => {+ if (url.includes('/checksum')) return { ok: true, json: async () => ({ checksum: 'remote' }) };+ if (url.includes('/snapshot')) return { ok: true, json: async () => ({ data: { instances: {} }, checksum: 'remote' }) };+ return { ok: true, json: async () => ({}) };+ });+ dataSync.applyRemote.mockResolvedValue({ applied: true, count: 1 });+ });++ it('pulls usage from a peer whose stored map predates the category', async () => {+ // A peer record written before `usage` existed has no key for it — it must+ // pick up the shipped default rather than reading as off forever.+ await syncWithPeer({ ...mockPeer, syncEnabled: true, syncCategories: { goals: false } });+ expect(categoryUrls().some((url) => url.includes('/api/sync/usage/'))).toBe(true);+ });++ it('keeps pulling usage — and only usage — when the master switch is off', async () => {+ await syncWithPeer({ ...mockPeer, syncEnabled: false, syncCategories: { goals: true } });+ const urls = categoryUrls();+ expect(urls.some((url) => url.includes('/api/sync/usage/'))).toBe(true);+ expect(urls.some((url) => url.includes('/api/sync/goals/'))).toBe(false);+ });++ it('honors an explicit opt-out of the category itself', async () => {+ await syncWithPeer({ ...mockPeer, syncEnabled: true, syncCategories: { usage: false } });+ expect(categoryUrls().some((url) => url.includes('/api/sync/usage/'))).toBe(false);+ });++ it('still syncs nothing for a disabled peer', async () => {+ getPeers.mockResolvedValue([{ ...mockPeer, enabled: false, syncCategories: { usage: true } }]);+ await syncAllPeers();+ expect(categoryUrls()).toHaveLength(0);+ });+ });+describe('syncAllPeers', () => {it('iterates online peers with instanceId', async () => {const onlinePeer = { ...mockPeer };diff --git a/server/services/usage.js b/server/services/usage.jsindex 63df5db013..fa4db4914a 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -5,7 +5,7 @@ import { familyForProvider } from '../lib/providerFamilies.js';import { roundCents } from '../lib/subscriptionSavings.js';const DATA_DIR = PATHS.data;-const USAGE_FILE = join(DATA_DIR, 'usage.json');+export const USAGE_FILE = join(DATA_DIR, 'usage.json');// Day buckets older than this are rolled up into monthly buckets at load time so// dailyActivity (and therefore the whole-file rewrite on every AI run) stops growing@@ -1010,3 +1010,60 @@ export async function resetUsage() {await saveUsage();return true;}++/**+ * How many days of PER-DAY granularity ride the federated usage digest. Older+ * days are folded into their month bucket for the WIRE ONLY — the local file+ * keeps its own (much longer) `ROLLUP_RETENTION_DAYS` window untouched, and a+ * local report always reads the live maps.+ *+ * The cap exists because the digest is re-fetched by every peer whenever local+ * usage moves (which is every AI run). All-time totals stay exact either way —+ * folding a day into its month preserves every count, just at coarser+ * granularity, which is all a fleet-level report needs for old periods.+ */+const DIGEST_DAILY_RETENTION_DAYS = 120;++/**+ * Build the federated wire shape for this instance's usage: aggregate counters+ * only — provider ids, model ids, token counts, timestamps. No prompts, no+ * transcripts, no record contents, no PII.+ *+ * Two fields of `usageData` are deliberately absent. `reconciledRuns` is+ * idempotency bookkeeping keyed by LOCAL run ids — meaningless on a peer and+ * the largest field in the file. All-time `byProvider`/`byModel` are a coarser+ * restatement of what the day buckets already carry, which is what a fleet+ * report actually aggregates.+ *+ * Pure: only the buckets that survive the wire rollup are copied, so the+ * caller's `usageData` is untouched and old days aren't cloned to be discarded.+ */+export function buildUsageDigest(source = getUsage(), { retentionDays = DIGEST_DAILY_RETENTION_DAYS, now = new Date() } = {}) {+ // Shallow copy first: the rollup DELETES the days it folds away, so it runs+ // over our own map of references while only READING the buckets themselves.+ // Deep-cloning afterwards therefore copies just the days that survived,+ // instead of copying the whole history to throw most of it away.+ const surviving = { ...(source?.dailyActivity || {}) };+ const monthlyActivity = structuredClone(source?.monthlyActivity || {});+ rollupOldDailyActivity(surviving, monthlyActivity, { retentionDays, now });+ const dailyActivity = structuredClone(surviving);++ const hourly = Array.isArray(source?.hourlyActivity) ? source.hourlyActivity : [];+ return {+ totalSessions: source?.totalSessions || 0,+ totalMessages: source?.totalMessages || 0,+ totalToolCalls: source?.totalToolCalls || 0,+ totalTokens: {+ input: source?.totalTokens?.input || 0,+ output: source?.totalTokens?.output || 0+ },+ dailyActivity,+ monthlyActivity,+ hourlyActivity: Array.from({ length: 24 }, (_, i) => hourly[i] || 0),+ earliestActivityDay: findEarliestActivityDay(dailyActivity, monthlyActivity),+ // The instant this instance last recorded usage. Doubles as the digest's+ // LWW stamp on the wire — it moves on every `saveUsage`, and NOT on a mere+ // re-read, so a peer's checksum stays stable while nothing has happened.+ lastUpdated: source?.lastUpdated ?? null+ };+}