Files
OpenMAIC/e2e/fixtures
f378c25a53 feat(storage): route settings/user-profile persist through KVStore (no legacy migration) (#1001)
* feat(storage): route zustand persist through KVStore

The settings and user-profile stores persisted through zustand's default
`localStorage` storage, while the rest of the app's small keyed values had
already moved to `@openmaic/storage`'s `KVStore` — two unrelated mechanisms
over the same browser API, which is the split-brain the storage RFC set out
to remove. `kvPersistStorage` shipped with the package but had no importer.

Add `lib/store/kv-persist.ts`, the app seam that adapts a `KVStore` into a
zustand `PersistStorage`, and wire both stores to it under an explicit
`account` scope. Store logic is unchanged: `version` / `migrate` / `merge`
still belong to the stores, only the bytes' destination moves.

Existing installs are adopted rather than orphaned. On first read the seam
moves the raw `localStorage` entry into the KV scope — write first, then
drop the raw key, so an interrupted migration leaves the value readable
from one side or the other but never from neither. Once KV holds the entry
it is authoritative, so a stale raw entry reappearing cannot roll back
newer state, and re-running can neither duplicate nor resurrect anything.
An entry that is not a readable persist envelope is left exactly where it
is.

Hydration is now asynchronous, because a `KVStore` may be remote. The
browser backend resolves within a few microtasks of the store module being
evaluated, so nothing user-visible changes, but tests that assert on
persisted state now await `persist.rehydrate()` instead of relying on a
synchronous read.

The four pre-persist keys (`llmModel` / `providersConfig` / `ttsModel` /
`selectedAgentIds`) are deliberately untouched: they are read-only inputs
to a migration that never owned them, and `providersConfig` is still read
independently by `lib/ai/providers.ts`.

Part of #857.

* fix(storage): close the async-storage failure modes in the KV persist seam

Cross-review found that routing `persist` through an asynchronous store
opens failure modes a synchronous `localStorage` never had. Each one below
is now covered by a test that fails without its fix.

Data loss on a failed or empty hydration. A KV read that threw was
indistinguishable from an empty scope, so the store stayed on defaults
while an always-on initializer's `set()` persisted those defaults; the
next load then read them as a completed migration and deleted the raw
original, leaving nothing. Reads now separate "nothing there" from "the
backend could not answer": a failed read serves the raw entry read-only,
adopts nothing and deletes nothing, and leaves the key unwritable for the
session so no un-hydrated state can be persisted over an original. Raw
entries are additionally only dropped against a recorded completion
marker, so a KV entry of unknown provenance can never authorize deleting
the only copy of the user's data.

Lost adoption across tabs. A reader whose KV read answered before another
tab's adoption write, and whose localStorage read landed after that tab's
delete, saw nothing in either place and hydrated defaults. Against a
remote backend that interleaving is ordinary rather than rare, so an
apparent "nothing anywhere" is now re-checked before it is believed.

Out-of-order writes. Two rapid `setItem`s could complete in either order
and let the older value win. Reads and writes are serialized per key.

Pre-persist migration resurrecting on every load. `migrateFromOldStorage`
was guarded by the existence of the raw `settings-storage` key — the very
key the migration removes — so once the blob moved into the KVStore it ran
on every load and republished whatever the pre-persist keys still held,
including API keys the user had since deleted, into first-frame state. It
is now the persist layer's last-resort source instead of a synchronous
read in the store initializer: its result is adopted like any other
migration, so the adopted entry is the marker that stops it. Initial state
is plain defaults, and nothing stored reaches observable state before the
storage layer has vouched for it. The source keys are still only read,
never deleted, since `lib/ai/providers.ts` remains a reader.

Also: KV reads and writes are guarded so a corrupt entry surfaces instead
of throwing through zustand's silent catch; clearing the cache now clears
the migrated stores through their own storage, which a server-backed
scope would need and a blanket `localStorage.clear()` would only appear to
do; `removeItem` drops the KV copy before the raw one; and the e2e suite
gains post-migration steady-state coverage, which every existing spec
missed by seeding the pre-cutover key.

Part of #857.

* fix(storage): scope migration bookkeeping to the device, gate writes on call

Second review round. The findings shared one root cause: two of the three
sentinels recorded a fact about *this machine's* files but were stored
beside the data, in the store's own scope. Under a syncing `account`
backend that is a category error with teeth — one device's history would
travel to another and authorize deleting files it says nothing about.

Sentinels are now always `device`-scoped and carry a reserved `__` prefix,
whatever scope the store uses. The worst combination this closes: device A
migrates, its marker syncs, device B — which has never run this build —
loads and deletes the raw entry that is still the only copy of its own
settings. A test drives exactly that sequence against two devices sharing
one account scope and nothing else.

The pre-persist fallback gains a device sentinel of its own. Its source
keys are device-local and deliberately left in place, so "KV and raw are
both empty" was not a safe trigger: clearing the account entry, from the
cache button or a server-side wipe, let any device re-read those keys and
republish credentials the user had rotated. It is now consulted at most
once per device, and `removeItem` deliberately does not clear that
sentinel — clearing the entry is precisely the case it exists for. The
fallback also no longer writes the adoption marker: that marker is a
licence to delete a raw persist entry, and the fallback has adopted no
such thing. Were it written, a raw entry later restored by an older bundle
would be deleted unread.

The write gate is now read when `setItem` is called rather than when its
queued turn arrives. Evaluated inside the queue, a write issued during
hydration waited behind `getItem`, found the gate opened by the very read
it raced, and persisted its pre-hydration snapshot on top of the stored
value.

Refused writes are no longer a dead end: the first one asks the store to
rehydrate, since the backend may have recovered, and if that does not work
the user is told through a durable notice rather than losing every change
on reload. Each refusal is logged, not just the first — a once-per-session
warning hides how long a session has been silently unsaved.

`removeItem` now propagates backend failures, so clearing the cache cannot
report success for a clear that did not happen, and that flow reloads
immediately instead of leaving a window in which a background `set()`
re-persists the credentials just deleted.

Also: the recovery hook is bound after each store is constructed, because
naming the store inside its own definition made its type circular and
silently widened every selector to `any`; the `serial` comment no longer
claims an unreachable rejection handler; and the pre-persist version stamp
documents that it skips `migrate`'s unversioned normalization too, which
`merge` redoes anyway.

Part of #857.

* refactor(storage): make the KV persist seam a per-key state machine

Three review rounds kept turning up the same defect class in new places:
a backend failure read as "there is nothing there", and the result of an
operation that nobody looked at. Patching instances of it was not working,
because both are possible whenever a call site is free to decide for itself
what a failed operation meant. This makes that decision unavailable to
call sites.

Every backend call now returns an `Outcome` whose payload is a private
field and whose only reader demands a `KeyState`. Feeding the machine is
not a convention to remember; it is the only way to get the value out.
What comes back is the value or `UNAVAILABLE` — deliberately not `null`,
so "the backend could not answer" is not spellable as "nothing is there".
The machine then decides, in one place, what failure means: any read
failure is unavailability, any write failure closes the key, and either
raises the health signal and asks for recovery.

The scattered closure flags (a settled set, a warned set, a recovery
latch) become one explicit phase per key — unhydrated, settled,
unavailable, clearing — with the transition table written out in the
docstring and a test per row.

What that consumes:

- A write failing after the key settled used to be ignored; its outcome
  now closes the key, signals, and the value is remembered for replay.
- `removeItem` enters `clearing` synchronously at call time, so a `set()`
  racing a clear cannot be admitted, queue behind the delete, and write
  the just-deleted value back. Nothing is replayed across a clear.
- The pre-persist sentinel is recorded by *every* settling path, not only
  the one that consults the old keys. A device that had only ever loaded
  an already-populated account entry recorded nothing, and so stayed
  eligible to republish its own stale credentials the moment that entry
  was cleared — which the docstring already claimed it would not.
- Two places treated a failed read as an answer: the sentinel read that
  decides whether the fallback runs, and the confirming re-read before
  adopting. Both now stop.
- An adoption whose marker did not land no longer settles, and never
  deletes the raw entry: no proof, no licence.
- Refused and failed writes are remembered and replayed once storage
  recovers, but only when the store was holding real data at the time —
  replaying a snapshot taken over defaults would overwrite the stored
  value, which is the failure this seam exists to prevent. When a
  snapshot cannot be replayed the user is told, because rehydration is
  about to discard those edits.
- Health notices publish on a later task, so a recovery that lands
  moments later cancels a warning nobody should have seen, and a
  subscriber mounting after the failure is caught up once its toast host
  exists. `StorageHealthNotice` now sits after the `Toaster` for the same
  reason.

Also: adoption re-reads before committing so a concurrent write is not
rolled back; a shadowed raw entry is only deleted if it parses, matching
the promise never to delete bytes we could not read; the unavailable copy
points at the control that resolves it rather than suggesting a reload
that cannot; and the version pin, the pre-persist retention rationale, and
the cache-clear comment say what is actually true.

Part of #857.

* fix(storage): separate the contexts settle() was conflating

Convergence round on the state machine. The findings share a root: settle()
treated every read that concluded as licence to open the key, without
asking what else was true at the time.

- A read finishing while a clear is outstanding no longer settles. Under a
  remote backend a recovery rehydrate in flight during a clear is ordinary,
  and opening the gate there admits a write that queues behind the pending
  delete and restores the credentials just removed. Only finishClear opens
  a cleared key.
- The raw entry served read-only after a failed read no longer counts as
  the authoritative value. A shadowed raw entry is by construction the
  older copy — long-term coexistence with a newer KV value is a designed
  state — so an edit taken against it must never be replayed, or one
  transient read failure on one device rolls the whole account back.
- A write that lands supersedes an earlier failed one. Both were admitted
  before the key closed, so the queue ordered them; replaying the older
  snapshot on recovery would undo the newer value.
- Unreachable browser storage is a failure, not an empty store. Privacy
  modes make localStorage throw; treating that as "nothing stored" hydrated
  defaults, refused every write and said nothing until the user reloaded
  and found the work gone. SSR stays a silent no-op.
- The recovery latch re-arms when storage answers, so the three recovery
  transitions are not empty promises from the second failure onward.
- A refusal carries the phase it happened in. Cold-start timing — an
  always-on initializer writing before the first read resolves, on a
  backend that never failed — is a log line, not a sticky red toast; only
  a refusal under `unavailable` reports lost changes.

The health channel stops delivering stale catch-ups: its timers are
cancellable and re-read the current state when they fire, so a recovery
cannot be overtaken by a warning with nothing left to dismiss it. And
`changes-lost` is now a fait accompli rather than a condition — a later
recovery has nothing to retract and leaves it standing.

Also: a throwing `localStorage` is unavailability rather than absence
wherever the raw entry is read; clearing records the pre-persist sentinel
like every other settling path, making that docstring true; the raw entry
is dropped before the marker so a failed marker clear leaves something
inert; and the pre-persist fallback and its four source reads can no
longer throw into zustand's silent catch.

Part of #857.

* fix(storage): hold a replay until it lands, and prove a raw copy before deleting it

Three failure-path corners.

A replay was retired the moment its write was attempted. Readable but not
writable is a real state — a quota-exhausted backend answers reads
perfectly — so a recovering read could succeed, the replay write fail, and
the snapshot be gone with nothing owed: the next rehydrate served the older
stored value over the user's edit and said nothing. The snapshot is now
held until the write is durable; a failed replay goes back to being a
refused write, so the next recovery tries again and a permanent failure is
eventually reported.

The adoption marker was treated as proof that a raw entry is the
migration's leftover. It proves only that a migration happened on this
device once. A rolled-back deployment, or a tab still running the old
bundle, writes the raw key again with settings the migration never saw, and
the next load on the new bundle deleted them unread. A raw entry is now
dropped only when its content equals the value shadowing it — anything else
is data, and keeping a copy beats deleting an original here as everywhere
else in this file.

`changes-lost` was being cancelled by a later recovery. The two statuses
answer different questions: "storage is down" describes the world now and
stops being true when storage works, while "your edits were lost" describes
something that already happened and no amount of recovery undoes. They are
now tracked on independent lines per key and rendered as two toasts with
distinct ids, so retracting the fault cannot take the acknowledgement with
it; the loss notice goes away only when the user closes it.

Part of #857.

* fix(storage): bound recovery, keep a live store from walking backwards

Three interactions the state machine did not have an answer for.

Recovery had no budget. A backend that reads but cannot write — a
quota-exhausted one does exactly that — turned it into a treadmill: the
recovering read succeeds, the key settles, the replay write fails, and that
failure asks for recovery again, forever. Attempts now follow a backoff
schedule whose length is the cap, and the budget is re-armed only on real
progress: a settle that left nothing owed. A settle reached *by* a recovery
with a replay still queued is not progress, and counting it as such is
precisely what made every lap look like a fresh start. When the budget runs
out the key is left read-only and the loss is reported, rather than
retrying where nobody can see it failing.

A failed read could walk a live store backwards. Once a session has loaded
the authoritative value, a transient read failure was still falling back to
the shadowed raw copy — which is legitimately older, and legitimately
long-lived now that a differing raw entry is kept rather than deleted — and
handing it to zustand overwrote a live store with stale data. Worse, the
store had already latched "holding real data", so edits made on top of that
stale value counted as replayable. A failed read after an authoritative one
now returns nothing, which is exactly "keep what you have", and the raw
fallback stays where it belongs: the case where nothing authoritative has
been seen at all.

Dismissing a lost-changes toast only closed the UI. The key stayed in the
lost set, so the same store losing changes a second time was swallowed as a
duplicate and any later subscriber resurrected a notice the user had
already dealt with. The close button now clears the latch, so a second loss
is reported and an acknowledged one stays gone.

Part of #857.

* fix(storage): close the last two provisional and clear-ordering gaps

An abandoned migration was handing back an authoritative value. When the
confirming re-read fails, or the adoption write does, `adopt` returns the
raw envelope unadopted — the same footing as the raw copy served after any
other failed read — but it was returned bare, so the store latched "holding
real data" and an edit taken on top of it counted as replayable. Another
device publishing to the account scope in that window would have been
rolled back. `adopt` now reports provisionality like every other read path,
and the shape is a named `LoadedValue` so the next path cannot forget.

Clearing swallowed a failed raw-entry deletion. The account entry was
already gone by then and the marker was cleared afterwards, so the
operation reported success while leaving an empty scope beside a live raw
entry — precisely the shape the next hydration re-adopts, handing back the
settings the user had just deleted. The raw entry now goes first and its
failure propagates, which also fixes the ordering: failing before anything
is removed leaves the KV value authoritative and the clear simply
unperformed, which the caller can retry. Adoption keeps the tolerant
variant, where a leftover raw entry is a duplicate rather than a loss.

Part of #857.

* fix(storage): make the shadowed-raw delete atomic against a concurrent tab

cosarah reproduced a data loss: both raw-entry deletes verified the value,
then awaited (reading or writing the adoption marker), then removed the key
by name. A tab running an old bundle — which takes no Web Lock, so a lock
could not have helped — overwrites the raw key with newer settings during
that await, and the unconditional `removeItem` then deletes the newer value.

The raw side is synchronous `localStorage`, so the fix needs no lock. Both
deletes now finish every await first, then run a single synchronous
compare-and-delete: re-read the raw bytes, and remove only if they still
equal the exact string that was verified. A competing tab is a separate
context whose writes surface here only at event-loop boundaries, so its
write lands wholly before the re-read (seen — bytes differ — kept) or after
the remove, never in between. A changed value is newer data, not a
migration leftover, and is kept.

Both sites cosarah named are covered: the shadowed-cleanup path
(`dropShadowedLegacy`) and the adoption cleanup in `adopt`. `readLegacyEntry`
now carries the exact bytes alongside the parse so the re-check is
byte-exact rather than comparing a re-serialized value. The clear path's
delete is unchanged: it is a deliberate full delete, not a conditional
leftover cleanup.

Part of #857.

* fix(storage): stop deleting the raw entry — adopt by copy (Plan B)

Maintainer decision after cross-vendor + red-team review: `localStorage`
has no cross-process atomic compare-and-delete (the storage mutex was
dropped from the spec), so a tab on an old bundle can insert a write
between our re-read and our removeItem in a genuinely parallel process. The
synchronous compare-and-delete narrowed that window but could not close it
— as its own comment admitted. Since the raw-cleanup cannot be done safely
on localStorage while an old bundle may be live, this stops doing it.

Adoption is now a copy: the value is written to KV and the raw entry is
left in place. The delete race is therefore impossible — there is no
delete. KV stays authoritative (once it holds the value, reads take the KV
path and never consume the raw one), so the shadow duplicate is inert,
left for a wholesale raw-cleanup at migration exit.

Removed with the two deletes:
- `dropShadowedLegacy` (its only job was the gated delete) and its three
  call sites.
- `deleteLegacyIfUnchanged` and the `{raw,value}` shape of the legacy read
  (`readLegacyEntry` → back to `readLegacy` returning the value).
- The adoption marker (`__persist-adopted:`), whose only reader was that
  delete gate. It did not prevent re-adoption — the presence of the KV
  value does — so removing it breaks no invariant. `dropRaw` / `expectedRaw`
  on `adopt` and the marker-clear step in the clear path go with it.

The clear path (user deletes all data) still deletes the raw entry
strictly — that is a deliberate full delete, not a migration cleanup.

Tests: the delete/marker cases become "the raw shadow always survives, KV
is authoritative"; a two-device and an old-bundle-concurrent-write case
guard it, and re-adding a delete on either adoption path turns them red.

Part of #857.

* fix(storage): add a monotonic migrated marker to stop shadow resurrection

Cross-vendor + red-team review independently caught a P1 the previous
"adopt-as-copy" revision introduced. Because the raw entry is now kept and
writes only ever reach KV, the raw copy becomes a frozen pre-cutover value.
If the account KV is later emptied by something other than a local clear —
a server-side wipe, an account switch, KV eviction — the next load saw
`stored === null` beside a live raw entry and re-adopted that stale copy,
refilling the wiped account with ancient settings/credentials and syncing
them to every device. Deterministic, not a race; it would fire once a
server-backed account backend exists.

Root cause: "keep the raw entry" inherently requires a record that it has
already been migrated, so an empty-KV load can tell "first migration" from
"external wipe". Removing the old delete-authorization marker in the copy
revision dropped that record — Plan B was only half done.

Adds a monotonic, device-scoped `__migrated:<name>` marker:
- Read on every load. `stored === null` + raw present + marker set ⇒ respect
  the wipe, do not adopt (fall through to the confirm re-read, so a
  concurrent repopulation is still served). Only a genuine first migration
  (no marker, raw present) adopts.
- Written best-effort after a successful KV write. A failed write degrades
  to the KV value's own presence check, so resurrection needs both a failed
  marker write and a later external wipe.
- Read failure fails closed (do not adopt), never "assume not migrated".
- Monotonic: only ever set true, cleared only by a deliberate full clear —
  no compare-and-delete race, which is why it is safe where deleting the raw
  entry was not. Live state with a real reader, not the delete-authorization
  marker removed earlier.

The clear path clears the marker too (back to a genuine first-load state);
best-effort, since with the raw entry already gone a leftover marker is
inert.

Tests: resurrection guard (external wipe does not re-adopt; concurrent
post-wipe write is served; first migration records the marker; marker read
fails closed) + the clear-path marker clearing. Mutation-checked: removing
the gate resurrects the shadow, dropping the record leaves it unguarded.
P3: the inert `__persist-adopted:` test rot is retargeted to the real
`__migrated:` path.

Part of #857.

* refactor(storage): remove automatic legacy migration — pure KV wiring

Maintainer decision (terminal): after repeated review rounds kept finding
new P1s in the legacy-adoption path — its state space is too large to keep
correct — the PR is narrowed from "migrate + wire" to "wire only". Settings
and user-profile persist through the KVStore; pre-cutover data is not
migrated; an upgrading user reconfigures once (the data is reconstructable
and the cost is one-time).

Removed the entire legacy-adoption subsystem from the adapter:
- `adopt()`, `readLegacy()`, the `legacyStorage` dep, and the raw-fallback
  read on a failed KV read.
- The `__migrated:` marker and its resurrection guard, the confirm-re-read,
  and the `provisional`/`LoadedValue` machinery.
- The `prePersistFallback` dep, `recordPrePersistHandled`, the
  `__pre-persist-consulted:` sentinel, and `readSentinel`/`writeSentinel`.
- In settings.ts, `readPrePersistSettings` (the llmModel/providersConfig
  reader wired as that fallback) — reading legacy keys is migration, which
  this PR no longer does. `lib/ai/providers.ts` still reads `providersConfig`
  independently, so those source keys are left in place.

The adapter now reads and writes the KV scope and touches no legacy key: an
empty scope hydrates the store to defaults (ordinary zustand). `load()` is a
single KV read; a failed read stays unsettled so defaults are never
persisted over an unread value; the clear path removes only the KV entry.

Kept, because they are async-storage *steady state* a remote KV backend
needs, not migration scaffolding: the KeyState machine (hydration gate,
write gate, recovery, replay), the Outcome discipline, per-key
serialization, and the persist-health channel.

Added `purgeLegacyPersistKey`: a best-effort, fire-and-forget removal of the
old raw persist blob, called once by each store. Never read, so a leftover
is pure garbage — and the old settings blob held plaintext provider API
keys, so clearing it is a small security win.

Net: the adapter drops ~460 lines. Tests are rewritten to steady-state KV
coverage plus an explicit "old raw key is ignored, not migrated" proof at
the store level; the e2e seed fixtures move from the raw key to the KV scope
key.

Part of #857.

* docs(storage): align README and comments with the no-migration behavior

Follow-up requested on the approved PR: the migration/adoption logic was
removed, but a few comments and one README roadmap line still referred to
those deleted concepts. Documentation only — no behaviour change.

- README roadmap: the settings/user-profile line said "adopting their
  pre-cutover raw keys"; it now states there is no automatic migration
  (legacy keys ignored and best-effort purged, users reconfigure once).
- kv-persist.ts: the per-key serial chain comment no longer claims to keep
  "adoption" from interleaving; it serializes a key's read/write/clear.
- settings.ts: `SETTINGS_PERSIST_VERSION` no longer documents a
  "pre-persist fallback" that no longer exists.
- Test/fixture headers that described seeding "the pre-cutover raw key" for
  "one-time adoption" now describe seeding the KV `account` scope, with no
  legacy-key migration.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(storage): bump version to 0.1.1 for README doc alignment

The README is a publishable input, and the no-migration doc alignment
changed it, so the package version must increase. Patch bump: documentation
only, no code or API change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com>
Co-authored-by: wyuc <zdq1204@gmail.com>
2026-07-30 15:12:51 +08:00
..