Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (release gate): carry the quota-burn dispatch ledger across the window-key change
[._.]/ Adam Eivyadedc442f921
diff --git a/.changelog/v2.38.0.md b/.changelog/v2.38.0.mdindex bce02d46ab..e2ee72cdff 100644--- a/.changelog/v2.38.0.md+++ b/.changelog/v2.38.0.md@@ -83,6 +83,11 @@ Released: 2026-08-04- **"Open in Xcode" opens the actual project instead of guessing its filename.** The button built `<display name>.xcodeproj` on the client and navigated to an `xcode://` URL, so any app whose display name wasn't byte-identical to its project on disk ("My Client" → `MyClient.xcodeproj`) got a path that doesn't exist — and a custom-scheme navigation reports nothing either way, so the click was a silent no-op, doubly so from a phone where the scheme isn't registered at all. The new `POST /api/apps/:id/open-xcode` resolves the real target the same way the Xcode script generators do (`deriveProjectInfo`: `project.yml` `name:` → the `*.xcodeproj` on disk → the sanitized app name), prefers a `.xcworkspace` over the `.xcodeproj` it wraps, and opens it on the machine Xcode is installed on. A `swift` SPM package — which has no `.xcodeproj` at all — falls back to its `Package.swift`, and a repo with none of the three comes back as a 404 naming everything it looked for, so the click always ends in a visible toast. (#3438)- **Each provider card on the Usage page refreshes on its own.** Every family's reading is an independent 10-20s CLI/TUI scrape, so the single "Refresh" button made re-checking one provider cost a spawn for all of them — and reset every other card's reading age in the process. `GET /api/usage/providers` now takes `?family=<id>`, `getProviderQuotas({ family })` resolves just that card (the derived image-gen card included), and each card carries its own refresh control that swaps in only its own result. A family that no longer resolves — its provider was disabled since the page loaded — comes back as an empty list and the card is dropped rather than left with a reading it can never refresh again. The section button is now "Refresh all".+## Upgrade notes++- **Migration 223 re-keys the quota-burn dispatch ledger.** The per-window dispatch counter — the cap that bounds how much subscription an unattended burn can spend — changed its key from the exact reset epoch to the hour it rounds into, so a provider reporting its reset a few seconds apart between reads lands in one bucket instead of two. Same file, different keys, which would have left an already-exhausted window reading zero on the first boot after upgrade and free to spend a whole extra cap inside itself. The migration carries the counts across (summing two old keys that fold into one bucket, since both were really spent) rather than dropping the ledger, which would read as zero for the same reason.+- **Migration 221 fails closed on the old arming switch.** An absent, entry-less, or unparseable `task-schedule.json` now reads as *not* armed — matching the shipped `enabled: false` default rather than assuming consent — and the schedule prune is the last write it performs, so a migration that dies partway through can't have its re-run mistake the entry it already deleted for permission to start burning.+## Full Changelog**Full Diff**: https://github.com/atomantic/PortOS/compare/v2.37.0...v2.38.0diff --git a/client/src/components/city/CityEmbers.jsx b/client/src/components/city/CityEmbers.jsxindex d99a2a2426..a2690a5666 100644--- a/client/src/components/city/CityEmbers.jsx+++ b/client/src/components/city/CityEmbers.jsx@@ -1,6 +1,7 @@import { useRef, useMemo } from 'react';import { useFrame } from '@react-three/fiber';import * as THREE from 'three';+import { seededRand } from './cityConstants';// Rising ember/spark particles that float upward from the city streets@@ -74,17 +75,25 @@ export default function CityEmbers({ settings }) {[0.4, 0.3, 1.0], // blue];+ // Seeded, like CityDataRain: `density` is clamped for the first 1.2s of+ // every mount and every visibility resume, so this memo re-runs on a+ // boundary the user is looking at. Bare Math.random() re-draws every+ // position and color there — the whole ember field teleports rather than+ // just changing count. A fixed seed keeps the first `n` embers identical+ // across that transition.+ const rand = seededRand(41);+for (let i = 0; i < n; i++) {// Spread across the city area- pos[i * 3] = (Math.random() - 0.5) * 50;+ pos[i * 3] = (rand() - 0.5) * 50;pos[i * 3 + 1] = 0; // Animated in shader- pos[i * 3 + 2] = (Math.random() - 0.5) * 50;+ pos[i * 3 + 2] = (rand() - 0.5) * 50;- sz[i] = 0.8 + Math.random() * 1.5;- spd[i] = 0.03 + Math.random() * 0.06;- ph[i] = Math.random();+ sz[i] = 0.8 + rand() * 1.5;+ spd[i] = 0.03 + rand() * 0.06;+ ph[i] = rand();- const c = palette[Math.floor(Math.random() * palette.length)];+ const c = palette[Math.floor(rand() * palette.length)];col[i * 3] = c[0];col[i * 3 + 1] = c[1];col[i * 3 + 2] = c[2];diff --git a/client/src/components/city/CityLights.jsx b/client/src/components/city/CityLights.jsxindex b98a4daf4b..97beaf97b4 100644--- a/client/src/components/city/CityLights.jsx+++ b/client/src/components/city/CityLights.jsx@@ -80,7 +80,7 @@ function ReactivePointLight({ position, baseIntensity, color, distance, brightne);}-export default function CityLights({ settings }) {+export default function CityLights({ settings, lightingTier }) {const { ground } = useCityPalette();const brightnessRef = useRef(settings?.ambientBrightness ?? 1.2);brightnessRef.current = settings?.ambientBrightness ?? 1.2;@@ -92,7 +92,14 @@ export default function CityLights({ settings }) {// Medium tier and up — the same gate the rest of the optional set dressing uses, so the// low tier sheds light count along with the props those lights were there to accent.- const showAccentLights = cityShowDetail(settings);+ //+ // Gated on the SETTLED tier, not the render tier the rest of the set dressing+ // reads. CityScene pins `effectiveTier: 'low'` for the first 1.2s of every mount+ // and visibility resume, and light count is part of three.js's program cache key+ // — so reading the clamped tier here would recompile every MeshStandardMaterial+ // in the scene at the warm-up boundary, a stall at exactly the moment the warm-up+ // exists to avoid one. Falls back to `settings` when the prop is absent.+ const showAccentLights = cityShowDetail(lightingTier ? { effectiveTier: lightingTier } : settings);// Neon scale: dim neon point lights during daytime (30% at noon, 100% at night)const neonScaleRef = useRef(1);diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsxindex 785166bdcf..7665faa344 100644--- a/client/src/components/city/CityScene.jsx+++ b/client/src/components/city/CityScene.jsx@@ -255,7 +255,11 @@ export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCam</ErrorBoundary>)}<CitySky settings={renderSettings} />- <CityLights settings={renderSettings} />+ {/* `lightingTier` is the SETTLED tier, deliberately not the warm-up-clamped+ one: the accent-light gate changes the scene's light COUNT, which is part+ of three.js's shader program cache key, so letting the clamp toggle it+ would recompile every lit material 1.2s into each load. */}+ <CityLights settings={renderSettings} lightingTier={settings?.effectiveTier} /><CityLandscape settings={renderSettings} /><CityWater settings={renderSettings} /><CityEnergyOverlay chronotype={chronotype} settings={renderSettings} />diff --git a/client/src/components/games/GameBindings.jsx b/client/src/components/games/GameBindings.jsxindex 0cd3f5e6f7..3ec451db8b 100644--- a/client/src/components/games/GameBindings.jsx+++ b/client/src/components/games/GameBindings.jsx@@ -156,9 +156,13 @@ function MusicBindingRow({onDismissOverwrite,}) {const [destinationPath, setDestinationPath] = useState(binding.destinationPath || '');+ // Key on the persisted VALUE, not the binding object: every mutation on this+ // page mints a fresh `game` (and so a fresh `binding`), so depending on the+ // object reset this input on unrelated saves — silently discarding a+ // destination the user was mid-way through typing.useEffect(() => {setDestinationPath(binding.destinationPath || '');- }, [binding]);+ }, [binding.id, binding.destinationPath]);const dirty = destinationPath.trim() !== (binding.destinationPath || '');const publicationCurrent = health?.publicationStatus === 'current';const { Icon, className } = healthTone(health);@@ -580,7 +584,8 @@ export default function GameBindings({health={musicIntegrity.get(binding.id)}issue={musicIssues.get(binding.trackId)}busy={busy}- overwriteRequested={musicOverwriteFor === binding.id}+ overwriteRequested={musicOverwriteFor?.bindingId === binding.id+ && musicOverwriteFor?.destinationPath === (binding.destinationPath || '')}onUpdate={onUpdateMusic}onPublish={onPublishMusic}onUnbind={onUnbindMusic}diff --git a/client/src/components/games/GameBindings.test.jsx b/client/src/components/games/GameBindings.test.jsxindex 5df82e1055..fd9a0a8e06 100644--- a/client/src/components/games/GameBindings.test.jsx+++ b/client/src/components/games/GameBindings.test.jsx@@ -155,7 +155,7 @@ describe('GameBindings', () => {});it('escalates an occupied music destination to explicit overwrite consent', () => {- renderBindings({ musicOverwriteFor: 'binding-1' });+ renderBindings({ musicOverwriteFor: { bindingId: 'binding-1', destinationPath: 'game/assets/music/example-theme.ogg' } });const section = musicSection();expect(within(section).getByText(@@ -168,6 +168,19 @@ describe('GameBindings', () => {expect(onDismissMusicOverwrite).toHaveBeenCalled();});+ it('drops overwrite consent when the destination it was granted for changed', () => {+ // The consent is for a SPECIFIC path. The server applies+ // `acknowledgeOverwrite` to whatever the binding points at when the request+ // lands, so a consent keyed on the binding alone would let a "yes" for the+ // occupied path silently authorize destroying a different, never-checked+ // file after the destination is edited.+ renderBindings({ musicOverwriteFor: { bindingId: 'binding-1', destinationPath: 'game/assets/music/some-other.ogg' } });+ const section = musicSection();++ expect(within(section).queryByRole('button', { name: 'Overwrite' })).not.toBeInTheDocument();+ expect(within(section).queryByText(/contains bytes PortOS did not publish/)).not.toBeInTheDocument();+ });+it('keeps publish disabled for a binding with no destination yet', () => {renderBindings({game: {diff --git a/client/src/components/musicVideo/ProjectToolbar.jsx b/client/src/components/musicVideo/ProjectToolbar.jsxindex 5143d751ed..ebea2f81ce 100644--- a/client/src/components/musicVideo/ProjectToolbar.jsx+++ b/client/src/components/musicVideo/ProjectToolbar.jsx@@ -88,8 +88,10 @@ export default function ProjectToolbar({<VideoRenderSettings videoSettings={videoSettings} generating={generatingVideos} /><buttononClick={sceneMedia.generateMissingFrames}- disabled={sceneCount === 0 || missingFrameCount === 0 || generatingFrames}- title={missingFrameCount > 0 ? `Generate ${missingFrameCount} missing reference frame${missingFrameCount === 1 ? '' : 's'}` : 'Every scene has a reference frame'}+ disabled={videoSettings.framePinSaving || sceneCount === 0 || missingFrameCount === 0 || generatingFrames}+ title={videoSettings.framePinSaving+ ? 'Saving the frame renderer…'+ : (missingFrameCount > 0 ? `Generate ${missingFrameCount} missing reference frame${missingFrameCount === 1 ? '' : 's'}` : 'Every scene has a reference frame')}className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"><ImageIcon size={15} /> Frames {referenceFrameCount}/{sceneCount}diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsxindex 2e9ced24e2..afb3ecc8d3 100644--- a/client/src/components/pipeline/stages/TextStagePanel.jsx+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx@@ -91,9 +91,14 @@ export default function TextStagePanel({useEffect(() => { draftOutputRef.current = draftOutput; }, [draftOutput]);// Live generation progress (#3393). The URL is set for the duration of one- // generate call; the server opens the channel when we attach, so subscribing- // just before the POST can't race it. Frames survive the teardown so the- // attempt scorecard stays on screen after the run finishes.+ // generate call. Note this attaches CONCURRENTLY with the POST, not strictly+ // before it: setting the URL is a state update, so the EventSource is not+ // constructed until React commits, while the POST leaves synchronously on the+ // next line. `emitStageProgress` is a no-op with no subscriber, so the+ // opening `context` frame can be dropped — the channel is advisory, and the+ // panel falls back to the spinner. Don't build anything on top of this that+ // needs the first frame. Frames survive the teardown so the attempt scorecard+ // stays on screen after the run finishes.const [progressUrl, setProgressUrl] = useState(null);// Which issue+stage the retained frames describe — the panel is reused across// issues, and a stale scorecard from a different record must not linger.diff --git a/client/src/hooks/useMusicVideoModelSettings.js b/client/src/hooks/useMusicVideoModelSettings.jsindex 043715374b..638819c057 100644--- a/client/src/hooks/useMusicVideoModelSettings.js+++ b/client/src/hooks/useMusicVideoModelSettings.js@@ -26,6 +26,7 @@ export default function useMusicVideoModelSettings({ project, onProjectPatch } =const [loras, setLoras] = useState([]);const [defaultModel, setDefaultModel] = useState('');const [saving, setSaving] = useState(false);+ const [framePinSaving, setFramePinSaving] = useState(false);useEffect(() => {getVideoGenStatus({ silent: true })@@ -98,11 +99,18 @@ export default function useMusicVideoModelSettings({ project, onProjectPatch } =// the image-side sibling of the video renderer pin above. Scene// reference-frame renders send no explicit mode, so the server resolves this// record pin directly (imageGen/prepareParams) — no client seeding needed.+ // `framePinSaving` is the image-side counterpart of `saving`, and carries the+ // same obligation: the optimistic patch repaints the picker immediately, but+ // the server resolves the RECORD pin at kickoff — so a frame render started+ // before the PATCH lands renders on the previous model while the board claims+ // the new one. It also serializes two quick pin changes, which would+ // otherwise race and could settle the record on the older of the two.const changeFramePin = ({ imageMode, imageModelId }) => {- if (!project) return;+ if (!project || framePinSaving) return;const projectId = project.id;const previous = { imageMode: project.imageMode ?? null, imageModelId: project.imageModelId ?? null };onProjectPatch?.(projectId, { imageMode, imageModelId });+ setFramePinSaving(true);updateMusicVideoProject(projectId, { imageMode, imageModelId }, { silent: true }).then((updated) => onProjectPatch?.(projectId, {imageMode: updated.imageMode ?? null,@@ -112,7 +120,8 @@ export default function useMusicVideoModelSettings({ project, onProjectPatch } =.catch((err) => {onProjectPatch?.(projectId, previous);toast.error(err?.message || 'Failed to save frame renderer');- });+ })+ .finally(() => setFramePinSaving(false));};return {@@ -120,6 +129,7 @@ export default function useMusicVideoModelSettings({ project, onProjectPatch } =modelsLoading,defaultModel,saving,+ framePinSaving,settings,effectiveModelId,activeModel,diff --git a/client/src/pages/Game.jsx b/client/src/pages/Game.jsxindex 36484bdf93..03f88f2186 100644--- a/client/src/pages/Game.jsx+++ b/client/src/pages/Game.jsx@@ -237,7 +237,14 @@ export default function Game() {setBusy('');if (!result?.game) {if (occupied) {- setMusicOverwrite(bindingId);+ // Key the consent to the destination it was granted FOR, not just the+ // binding. The path is editable inline, and the server applies+ // `acknowledgeOverwrite` to whatever the binding points at when the+ // request lands — so a bare id would let consent for A authorize an+ // unguarded overwrite of B. Same invariant the sprite publish lane+ // states in PublishWorkflow.jsx.+ const target = (game.musicBindings || []).find((entry) => entry.id === bindingId);+ setMusicOverwrite({ bindingId, destinationPath: target?.destinationPath || '' });return false;}toast.error('Music publish failed');diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsxindex 7ef30e32b2..a36416712e 100644--- a/client/src/pages/QuotaBurn.jsx+++ b/client/src/pages/QuotaBurn.jsx@@ -71,6 +71,7 @@ export default function QuotaBurn() {// re-arm the debounce it lives inside.const retriedRef = useRef(false);const persistRef = useRef(null);+ const savingRef = useRef(false);const load = useCallback(async (refresh = false) => {const seq = editSeqRef.current;@@ -79,7 +80,14 @@ export default function QuotaBurn() {// `status` is derived server-side and never edited here, so it is always// safe to adopt; `config` is the form's own state and must not be rewound.setStatus(data.status);- if (editSeqRef.current === seq) setConfig(data.config);+ // The counter alone only catches an edit that landed WHILE this GET was in+ // flight. An edit made just BEFORE it was issued leaves the counter+ // unmoved, so the response — which predates the still-debounced PUT —+ // would roll the textarea back to the last saved text, and the next+ // keystroke would rebuild the patch from that rewound value and persist+ // it. Anything unsaved or in flight means the server's copy is stale by+ // definition; don't adopt it.+ if (editSeqRef.current === seq && !pendingRef.current && !savingRef.current) setConfig(data.config);}, []);useEffect(() => {@@ -107,8 +115,13 @@ export default function QuotaBurn() {pendingRef.current = null;if (!patch) return;const seq = editSeqRef.current;+ savingRef.current = true;const result = await api.saveQuotaBurn(patch, { silent: true }).catch((err) => { toast.error(`Could not save: ${err.message}`); return null; });+ // Cleared before the `load()` below so that read can still adopt the+ // server's normalization — the flag exists to fence concurrent POLL reads,+ // not this function's own follow-up read.+ savingRef.current = false;if (!result) {// Put the patch BACK rather than dropping it. One rejected field (a 400diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex a76f77354e..9ceb9be75e 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -1160,7 +1160,12 @@ export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {if (!webSpeechShouldListen) return;webSpeechRestartFailures += 1;if (webSpeechRestartFailures >= WEB_SPEECH_MAX_RESTART_FAILURES) {- webSpeechShouldListen = false;+ // Full teardown, not a bare flag flip: every caller-side cleanup is gated+ // on isWebSpeechCapturing(), so clearing the flag without releasing the+ // audio-session claim strands it — pinning the document to+ // 'play-and-record' for the rest of the page session, which outranks the+ // 'playback' claim a SongBook play-along needs to beat the silent switch.+ stopWebSpeechCapture();callbacks.onError?.('restart-loop');return;}@@ -1176,7 +1181,9 @@ export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {recognition.onerror = (event) => {if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {- webSpeechShouldListen = false;+ // Same reason as onend's restart-cap branch: release the claim here or a+ // denied mic leaves the session pinned record-capable forever.+ stopWebSpeechCapture();callbacks.onError?.(event.error);}// "no-speech" and "aborted" are expected, ignore themdiff --git a/package-lock.json b/package-lock.jsonindex 904edf73d0..32cba674b4 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "portos",- "version": "2.37.0",+ "version": "2.38.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos",- "version": "2.37.0",+ "version": "2.38.0","license": "MIT","devDependencies": {"pm2": "7.0.3"diff --git a/package.json b/package.jsonindex 4708419beb..f75d0f4a00 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portos",- "version": "2.37.0",+ "version": "2.38.0","private": true,"description": "Local dev machine App OS portal","author": "Adam Eivy (@antic|@atomantic)",diff --git a/scripts/migrations/223-quota-burn-ledger-hour-keys.js b/scripts/migrations/223-quota-burn-ledger-hour-keys.jsnew file mode 100644index 0000000000..826b13e556--- /dev/null+++ b/scripts/migrations/223-quota-burn-ledger-hour-keys.js@@ -0,0 +1,104 @@+/**+ * Migration 223 — re-key the quota-burn dispatch ledger to hour-rounded windows.+ *+ * Background:+ * `data/cos/quota-burn-dispatches.json` counts how many burns a given reset+ * window has already spent, and `evaluateFamily` refuses to dispatch once a+ * window's count reaches `maxDispatchesPerWindow`. That cap is the only thing+ * bounding how much of a user's paid subscription an unattended burn spends.+ *+ * The key format changed this release. It used to be the EXACT reset epoch:+ * `${familyId}:${normalizeResetAt(limit).epochMs}`+ * and is now that epoch rounded to the hour (`windowKey` in+ * `server/services/quotaBurn.js`), so a provider that reports its reset a few+ * seconds differently between two reads lands in one bucket instead of two.+ *+ * Same file, same path, different keys — so without this migration an+ * upgraded install reads 0 for a window it has already exhausted and burns up+ * to a full extra cap inside it. Deleting the ledger does NOT fix that: an+ * absent count reads 0 too. The counts have to be CARRIED, not dropped.+ *+ * What it writes:+ * `data/cos/quota-burn-dispatches.json`, with every `family:epoch` key+ * rewritten to `family:hourRoundedEpoch`. Two old keys that round into the+ * same bucket have their counts SUMMED — the window really did spend both, so+ * taking the max (or the last writer) would hand back dispatches the user+ * already paid for.+ *+ * The release-era `__agentDispatches` sentinel (an object, not a count) is+ * dropped: nothing in the current code reads it, and leaving it behind means+ * `Number(ledger[key] || 0)` would see an object if it were ever addressed.+ *+ * Idempotent: an already-hour-rounded key rounds to itself, so a second run is+ * a no-op and the file is left untouched when nothing changes.+ */++import { readFile, writeFile, rename } from 'fs/promises';+import { join } from 'path';++const HOUR_MS = 60 * 60 * 1000;+// The release-era per-agent dedupe map. An object under a non-window key.+const LEGACY_AGENT_KEY = '__agentDispatches';++const readJson = async (abs) => {+ const raw = await readFile(abs, 'utf-8').catch((err) => { if (err.code === 'ENOENT') return null; throw err; });+ if (raw == null) return null;+ try { return JSON.parse(raw); } catch { return null; }+};++const writeJsonAtomic = async (abs, value) => {+ const tmp = `${abs}.tmp-223`;+ await writeFile(tmp, JSON.stringify(value, null, 2) + '\n');+ await rename(tmp, abs);+};++/**+ * Fold an old ledger into hour-rounded keys. Pure — exported for the test.+ *+ * @param {object} ledger raw parsed ledger+ * @returns {{ ledger: object, changed: boolean }}+ */+export function rekeyLedger(ledger) {+ const next = {};+ let changed = false;+ for (const [key, value] of Object.entries(ledger)) {+ if (key === LEGACY_AGENT_KEY) { changed = true; continue; }+ const parts = String(key).split(':');+ const epoch = Number(parts.pop());+ const family = parts.join(':');+ const count = Number(value);+ // An unparseable key or a non-numeric count is not something we can safely+ // re-bucket, and dropping it would forgive spend. Carry it verbatim.+ if (!family || !Number.isFinite(epoch) || !Number.isFinite(count)) {+ next[key] = value;+ continue;+ }+ const rounded = `${family}:${Math.round(epoch / HOUR_MS) * HOUR_MS}`;+ if (rounded !== key) changed = true;+ // SUM, don't overwrite: both old buckets were really spent.+ next[rounded] = (next[rounded] || 0) + count;+ }+ return { ledger: next, changed };+}++export default {+ async up({ rootDir }) {+ const ledgerFile = join(rootDir, 'data', 'cos', 'quota-burn-dispatches.json');+ const ledger = await readJson(ledgerFile);+ if (!ledger || typeof ledger !== 'object' || Array.isArray(ledger)) {+ console.log('🔥 migration 223: no quota-burn dispatch ledger — nothing to re-key');+ return { ok: true, reason: 'no-ledger' };+ }++ const { ledger: next, changed } = rekeyLedger(ledger);+ if (!changed) {+ console.log('🔥 migration 223: dispatch ledger already uses hour-rounded window keys');+ return { ok: true, reason: 'already-hourly' };+ }++ await writeJsonAtomic(ledgerFile, next);+ const count = Object.keys(next).length;+ console.log(`🔥 migration 223: re-keyed the quota-burn dispatch ledger to ${count} hour-rounded window(s)`);+ return { ok: true, windows: count };+ },+};diff --git a/scripts/migrations/223-quota-burn-ledger-hour-keys.test.js b/scripts/migrations/223-quota-burn-ledger-hour-keys.test.jsnew file mode 100644index 0000000000..36bddfb811--- /dev/null+++ b/scripts/migrations/223-quota-burn-ledger-hour-keys.test.js@@ -0,0 +1,94 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import migration, { rekeyLedger } from './223-quota-burn-ledger-hour-keys.js';++const HOUR_MS = 60 * 60 * 1000;++describe('rekeyLedger', () => {+ it('rounds an exact-epoch key to its hour bucket, carrying the count', () => {+ // 13:59 — the shape that motivated the change. The old key is the exact+ // reset epoch; the new one is the hour it rounds to.+ const exact = Date.UTC(2026, 7, 4, 13, 59);+ const { ledger, changed } = rekeyLedger({ [`claude:${exact}`]: 5 });+ expect(changed).toBe(true);+ expect(ledger).toEqual({ [`claude:${Math.round(exact / HOUR_MS) * HOUR_MS}`]: 5 });+ });++ it('SUMS two old keys that fall into the same hour bucket', () => {+ // The whole point of the new format: one window read twice, seconds apart,+ // produced two keys. Both dispatches really happened, so the merged bucket+ // must show 3 — taking the max would hand back a burn the user paid for.+ const base = Date.UTC(2026, 7, 4, 14, 0);+ const { ledger } = rekeyLedger({+ [`codex:${base + 1000}`]: 2,+ [`codex:${base - 2000}`]: 1,+ });+ expect(ledger).toEqual({ [`codex:${base}`]: 3 });+ });++ it('drops the release-era __agentDispatches sentinel', () => {+ const epoch = Math.round(Date.UTC(2026, 7, 4, 9, 0) / HOUR_MS) * HOUR_MS;+ const { ledger, changed } = rekeyLedger({+ [`grok:${epoch}`]: 1,+ __agentDispatches: { 'agent-1': `grok:${epoch}` },+ });+ expect(changed).toBe(true);+ expect(ledger).toEqual({ [`grok:${epoch}`]: 1 });+ });++ it('carries an unparseable key verbatim rather than forgiving its spend', () => {+ const { ledger } = rekeyLedger({ 'weird-key-no-epoch': 4 });+ expect(ledger).toEqual({ 'weird-key-no-epoch': 4 });+ });++ it('reports no change when every key is already hour-rounded', () => {+ const epoch = Math.round(Date.UTC(2026, 7, 4, 16, 0) / HOUR_MS) * HOUR_MS;+ const { ledger, changed } = rekeyLedger({ [`agy:${epoch}`]: 2 });+ expect(changed).toBe(false);+ expect(ledger).toEqual({ [`agy:${epoch}`]: 2 });+ });+});++describe('migration 223 up()', () => {+ let rootDir;+ const ledgerPath = () => join(rootDir, 'data', 'cos', 'quota-burn-dispatches.json');+ beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-223-'));+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ });+ afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });++ it('no-ops when the ledger has never been written', async () => {+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, reason: 'no-ledger' });+ });++ it('no-ops on an unparseable ledger rather than throwing the boot migration run', async () => {+ await writeFile(ledgerPath(), 'not json');+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, reason: 'no-ledger' });+ });++ it('carries an exhausted window across the key change so it cannot be re-spent', async () => {+ // The upgrade bug this migration exists to close: an install at 5/5 for a+ // 13:59 window would, without it, read 0 under the new key and burn a whole+ // extra cap inside the same window.+ const exact = Date.UTC(2026, 7, 4, 13, 59);+ await writeFile(ledgerPath(), JSON.stringify({ [`claude:${exact}`]: 5 }));++ await migration.up({ rootDir });++ const after = JSON.parse(await readFile(ledgerPath(), 'utf-8'));+ expect(after[`claude:${Math.round(exact / HOUR_MS) * HOUR_MS}`]).toBe(5);+ });++ it('is idempotent — a second run leaves the file byte-identical', async () => {+ const exact = Date.UTC(2026, 7, 4, 13, 59);+ await writeFile(ledgerPath(), JSON.stringify({ [`claude:${exact}`]: 5 }));++ await migration.up({ rootDir });+ const first = await readFile(ledgerPath(), 'utf-8');+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ reason: 'already-hourly' });+ expect(await readFile(ledgerPath(), 'utf-8')).toBe(first);+ });+});