memorio 4.9.31 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/AGENTS.md +3 -3
  2. package/README.md +327 -330
  3. package/SECURITY.md +17 -1
  4. package/SUMMARY.md +59 -45
  5. package/adr/001-state-proxy-model.md +96 -0
  6. package/adr/002-observer-semantics.md +180 -0
  7. package/adr/003-deep-mutation-semantics.md +129 -0
  8. package/adr/004-array-mutation-semantics.md +128 -0
  9. package/adr/005-scheduler-contract.md +149 -0
  10. package/adr/006-context-isolation.md +92 -0
  11. package/adr/007-mutation-records.md +118 -0
  12. package/adr/008-transactions.md +106 -0
  13. package/adr/009-history-model.md +110 -0
  14. package/adr/README.md +46 -0
  15. package/adr/template.md +49 -0
  16. package/examples/basic.ts +115 -115
  17. package/examples/browser-vanilla.html +358 -358
  18. package/examples/cache.ts +72 -72
  19. package/examples/cross-platform-guards.ts +57 -57
  20. package/examples/history.ts +104 -0
  21. package/examples/idb.ts +109 -109
  22. package/examples/multi-tenant-context.ts +44 -44
  23. package/examples/node-server.ts +308 -308
  24. package/examples/observer.ts +60 -60
  25. package/examples/platform.ts +115 -115
  26. package/examples/react-app.tsx +362 -362
  27. package/examples/react-observer.tsx +63 -63
  28. package/examples/semantic-memory.ts +60 -60
  29. package/examples/session-advanced.ts +91 -91
  30. package/examples/sqlite-batched-writes.ts +57 -57
  31. package/examples/state-advanced.ts +89 -89
  32. package/examples/store-advanced.ts +117 -117
  33. package/examples/sync.ts +90 -0
  34. package/examples/typed-and-schema.ts +102 -100
  35. package/examples/useObserver.tsx +140 -141
  36. package/global.cjs +4594 -0
  37. package/global.d.ts +8 -0
  38. package/global.js +4532 -0
  39. package/index.cjs +706 -649
  40. package/index.d.ts +1 -0
  41. package/index.js +686 -648
  42. package/llms.txt +72 -4
  43. package/markdown/AUDIT-REPORT.md +135 -0
  44. package/markdown/CACHE.md +100 -0
  45. package/markdown/CHANGELOG.md +243 -0
  46. package/markdown/DEVTOOLS.md +129 -0
  47. package/markdown/DISPATCH.md +177 -0
  48. package/markdown/HISTORY.md +199 -0
  49. package/markdown/IDB.md +178 -0
  50. package/markdown/IMPORT.md +153 -0
  51. package/markdown/INSPECT.md +123 -0
  52. package/markdown/LOGGER.md +154 -0
  53. package/markdown/MEMORY-ATTACHMENT.md +96 -0
  54. package/markdown/MEMORY.md +162 -0
  55. package/markdown/OBSERVER.md +209 -0
  56. package/markdown/PLATFORM.md +271 -0
  57. package/markdown/PROJECT.md +311 -0
  58. package/markdown/SCHEMA.md +176 -0
  59. package/markdown/SECURITY.md +330 -0
  60. package/markdown/SESSION.md +165 -0
  61. package/markdown/SQLITE.md +190 -0
  62. package/markdown/STATE.md +160 -0
  63. package/markdown/STORE.md +171 -0
  64. package/markdown/SYNC.md +319 -0
  65. package/markdown/TYPED.md +165 -0
  66. package/markdown/USEOBSERVER.md +257 -0
  67. package/modules/redux.cjs +561 -374
  68. package/modules/redux.cjs.map +1 -1
  69. package/modules/redux.js +561 -374
  70. package/modules/redux.js.map +1 -1
  71. package/package.json +13 -3
  72. package/types/env.d.ts +19 -9
  73. package/types/exports.d.ts +20 -0
  74. package/types/history.d.ts +13 -1
  75. package/types/memorio.d.ts +17 -5
  76. package/types/mutation.d.ts +75 -0
package/README.md CHANGED
@@ -1,533 +1,530 @@
1
1
  # 🧠 memorio
2
2
 
3
- **Local-first memory for JavaScript.**
4
- One import. Global state, local persistence, SQLite, semantic memory, optional sync.
3
+ **Application state intelligence runtime.**
5
4
 
6
- [![npm version](https://img.shields.io/npm/v/memorio.svg)](https://www.npmjs.com/package/memorio)
7
- [![npm downloads](https://img.shields.io/npm/dm/memorio.svg)](https://www.npmjs.com/package/memorio)
8
- [![Socket Badge](https://socket.dev/api/badge/npm/package/memorio)](https://socket.dev/npm/package/memorio)
9
- [![Known Vulnerabilities](https://snyk.io/test/npm/memorio/badge.svg)](https://snyk.io/test/npm/memorio)
10
- [![zero deps](https://img.shields.io/badge/dependencies-0-brightgreen)](#security)
11
- [![license](https://img.shields.io/npm/l/memorio.svg)](#license)
5
+ Use it like an object.
12
6
 
13
7
  ```ts
14
- import 'memorio'
8
+ import 'memorio/global'
15
9
 
16
10
  state.user = { name: 'Sara', role: 'admin' }
17
11
  state.counter++
12
+
13
+ console.log(state.user.name)
14
+ console.log(state.counter)
18
15
  ```
19
16
 
20
17
  No provider tree. No reducers. No actions. No boilerplate.
21
18
  Just data, available where your application needs it.
22
19
 
23
- **And if you don't want a global API, don't use one:**
20
+ ---
24
21
 
25
- ```ts
26
- import { state, store, session, cache, idb, sqlite, memorio } from 'memorio'
27
- ```
22
+ ## Why memorio?
28
23
 
29
- The global API is a **choice**, not an architectural requirement.
24
+ Most applications eventually need more than one kind of data: reactive state, persistent values, session data, caches, structured browser storage, local SQL, application memory, history, and optional sync.
30
25
 
31
- ---
26
+ Usually that means a different library - and a different mental model - for each.
32
27
 
33
- ## Table of contents
34
-
35
- - [Why memorio](#why-memorio)
36
- - [Global is optional](#global-is-optional)
37
- - [Which layer should I use](#which-layer-should-i-use)
38
- - [Install](#install)
39
- - [Quick start](#quick-start)
40
- - [Observing changes](#observing-changes)
41
- - [The layers](#the-layers) — store · session · cache · idb · sqlite · memory
42
- - [Redux and other state managers](#redux-and-other-state-managers)
43
- - [memorio vs Redux, at a glance](#memorio-vs-redux-at-a-glance)
44
- - [React integration](#react-integration)
45
- - [Typed state & schema validation](#typed-state--schema-validation)
46
- - [Local-first sync](#local-first-sync)
47
- - [Cross-platform support](#cross-platform-support)
48
- - [Security](#security)
49
- - [Honest limitations](#honest-limitations)
50
- - [When to use something else](#when-to-use-something-else)
51
- - [Design philosophy](#design-philosophy)
52
- - [A mental model](#a-mental-model)
53
- - [License](#license)
28
+ **Memorio gives them one consistent runtime, without making the simple case complicated.**
54
29
 
55
- ---
30
+ ```ts
31
+ state.value = 42
32
+ ```
56
33
 
57
- ## Why memorio
34
+ Add persistence, memory, history, or sync only when your application actually needs them. The common case stays tiny; the runtime grows with you.
58
35
 
59
- Modern JavaScript applications often split their data across systems that don't talk to each other: a state manager, `localStorage`, `sessionStorage`, IndexedDB, a cache, SQLite, a server database, maybe an AI memory layer, maybe a sync layer on top. Each with its own API, its own lifecycle, its own mental model.
36
+ ---
60
37
 
61
- memorio brings these concerns into **one runtime and one consistent model**, while keeping each layer independent.
38
+ ## Install
62
39
 
63
- | Layer | Purpose | Persistence | Reactive |
64
- |---|---|---:|---:|
65
- | `state` | application state | No | Yes |
66
- | `cache` | transient runtime data | No | No |
67
- | `session` | tab/session data | Yes | No |
68
- | `store` | persistent key/value data | Yes | No |
69
- | `idb` | durable structured browser data | Yes | No |
70
- | `sqlite` *(beta)* | relational local SQL | Optional | No |
71
- | `memory` | structured application memory | Yes | Optional |
72
- | `journal` *(beta)* | local-first operation history | Yes | No |
40
+ ```bash
41
+ npm install memorio
42
+ ```
43
+
44
+ Zero production dependencies in core. Optional integrations (`react`, `sql.js`, etc.) are installed only when you use them.
73
45
 
74
- Start with `state`. Add persistence or memory only when your application actually needs it.
46
+ ---
75
47
 
76
- ## Global is optional
48
+ ## Global or explicit
77
49
 
78
50
  ```ts
79
- import 'memorio'
51
+ // Opt-in global access
52
+ import 'memorio/global'
80
53
  state.user = { name: 'Sara' }
54
+
55
+ // Or explicit imports
56
+ import { state, store, memory } from 'memorio'
81
57
  ```
82
58
 
83
- is useful when an application benefits from a shared runtime and a simple API. But memorio does **not** require applications to expose or use global state — explicit imports work against the exact same runtime:
59
+ Memorio never puts APIs on `globalThis` automatically and never infers dev mode from `NODE_ENV` or your bundler - global access is always something you choose.
84
60
 
85
- ```ts
86
- import { state } from 'memorio'
87
- state.user = { name: 'Sara' }
88
- ```
61
+ ---
62
+
63
+ ## The layers
89
64
 
90
- This makes memorio suitable for small apps, modular apps, libraries, component systems, tests, or applications that already use another state manager and prefer explicit dependencies.
65
+ | Layer | Purpose | Persistence | Reactive |
66
+ | --------- | --------------------------------- | :---------: | :------: |
67
+ | `state` | application state | No | Yes |
68
+ | `cache` | transient runtime data | No | No |
69
+ | `session` | tab/session data | Yes | No |
70
+ | `store` | persistent key/value data | Yes | No |
71
+ | `idb` | durable structured browser data | Yes | No |
72
+ | `sqlite` | relational local SQL | Optional | No |
73
+ | `memory` | structured application memory | Yes | Optional |
74
+ | `journal` | local-first operation history | Yes | No |
91
75
 
92
- **Global when convenient. Explicit when appropriate.**
76
+ You don't have to use all of them - start with `state`.
93
77
 
94
- ## Which layer should I use
78
+ **Which one do I need?**
95
79
 
96
80
  ```text
97
81
  Does the UI need to react automatically to changes?
98
- │
99
- ├─ Yes → state
100
- │
101
- └─ No
102
- │
103
- ├─ Only while the runtime exists? → cache
104
- ├─ Only for this browser tab/session? → session
105
- ├─ Small persistent key/value data? → store
106
- ├─ Larger or structured browser data? → idb
107
- ├─ Relations, joins, or SQL? → sqlite
108
- └─ Knowledge the application should
109
- remember (confidence, source, expiry)? → memory
82
+ yes → state
83
+ no → cache (runtime only) · session (this tab) · store (small persistent kv)
84
+ idb (structured browser data) · sqlite (relations/SQL) · memory (what the app should remember)
110
85
  ```
111
86
 
112
- ## Install
113
-
114
- ```bash
115
- npm install memorio
116
- ```
87
+ ---
117
88
 
118
- Optional peers, only loaded when used:
89
+ ## Before / after
119
90
 
120
- ```bash
121
- npm install react react-dom # React integration
122
- npm install sql.js # sqlite engine
91
+ ```ts
92
+ // Without memorio
93
+ const [user, setUser] = useState(null)
94
+ useEffect(() => {
95
+ const saved = localStorage.getItem('user')
96
+ if (saved) setUser(JSON.parse(saved))
97
+ }, [])
98
+ useEffect(() => {
99
+ localStorage.setItem('user', JSON.stringify(user))
100
+ }, [user])
101
+
102
+ // With memorio
103
+ import { state, persist } from 'memorio'
104
+ state.user = { name: 'Sara' }
105
+ const off = persist('state.user') // restores + keeps in sync
123
106
  ```
124
107
 
125
- **Zero production dependencies** in the core package. See [Security](#security).
108
+ ---
126
109
 
127
- ## Quick start
110
+ ## Persistent state
128
111
 
129
112
  ```ts
130
- import 'memorio'
113
+ import { state, persist } from 'memorio'
131
114
 
132
- state.user = { name: 'Sara', role: 'admin' }
133
- state.counter++
115
+ state.user = { name: 'Sara' }
116
+ const off = persist('state.user')
134
117
 
135
- console.log(state.user.name)
136
- console.log(state.counter)
118
+ // later
119
+ off()
137
120
  ```
138
121
 
139
- Reactive, Proxy-based state. No provider tree to configure, no reducer to maintain.
122
+ Nested paths work when the intermediate objects already exist: `persist('state.user.preferences.theme')`.
123
+ Without `localStorage` (e.g. Node), `store` falls back to memory.
140
124
 
141
- Lock a slice you don't want mutated by accident:
125
+ ---
126
+
127
+ ## Observing changes
142
128
 
143
129
  ```ts
144
- state.config = { maxUsers: 100 }
145
- state.config.lock()
130
+ import { observer } from 'memorio'
146
131
 
147
- state.config.maxUsers = 200 // throws
132
+ const off = observer('state.user', (next, previous) => {
133
+ console.log('user changed:', next, previous)
134
+ })
148
135
 
149
- state.config.unlock()
150
- state.config.maxUsers = 200 // ok
136
+ off() // unsubscribe
151
137
  ```
152
138
 
153
- Prefer explicit imports over the global? Same runtime either way:
139
+ Prefer the returned `off()` for targeted teardown (it unsubscribes only *this* callback).
140
+ The alternatives remove listeners by path name:
154
141
 
155
142
  ```ts
156
- import { state, store, session, cache, idb, sqlite, memorio } from 'memorio'
143
+ observer.remove('state.user') // removes ALL callbacks for this path
144
+ observer.removeAll() // removes every observer at once
157
145
  ```
158
146
 
159
- ## Observing changes
147
+ ---
148
+
149
+ ## Application memory
160
150
 
161
- Reactivity is part of the runtime — it is not tied to React.
151
+ State stores what the application **has**. Memory stores what it **remembers**.
162
152
 
163
153
  ```ts
164
- observer('state.user', (next, previous) => {
165
- console.log('user changed:', next, previous)
154
+ import { memorio } from 'memorio'
155
+
156
+ await memorio.memory.remember('user.language', 'Italian', {
157
+ type: 'preference',
158
+ confidence: 0.92,
159
+ scope: 'local',
160
+ tags: ['user', 'ui'],
161
+ source: 'conversation'
166
162
  })
167
163
 
168
- // nested paths work too
169
- observer('state.user.name', callback)
164
+ const language = await memorio.memory.recall('user.language')
170
165
  ```
171
166
 
172
- Lower-level event access is also available:
167
+ Updating an entry doesn't overwrite it - the previous entry becomes `superseded`, the new one `active`:
173
168
 
174
169
  ```ts
175
- const off = memorio.dispatch.listen('state.user', event => console.debug(event.detail))
176
- memorio.dispatch.set('state.user', { detail: { name: 'Sara' } })
177
-
178
- off() // remove only this subscription
170
+ await memorio.memory.update('user.language', 'English', { confidence: 0.95 })
179
171
  ```
180
172
 
181
- Each subscription owns its own unsubscribe function. Prefer the returned `off()` over `memorio.dispatch.remove('state.user')`, which removes **all** listeners registered under that name.
182
-
183
- React apps get a dedicated hook, `useObserver` — see [React integration](#react-integration).
184
-
185
- ## The layers
186
-
187
- ### `store` — persistent key/value data
173
+ Retrieve relevant memory instead of loading everything:
188
174
 
189
175
  ```ts
190
- store.set('preferences', { theme: 'dark' })
191
- const preferences = store.get('preferences')
176
+ const context = await memorio.memory.context({
177
+ tags: 'user',
178
+ types: ['preference', 'decision'],
179
+ minConfidence: 0.7,
180
+ maxEntries: 10
181
+ })
192
182
  ```
193
183
 
194
- Backed by `localStorage` in the browser. Falls back to memory in environments without persistent storage — check `store.isPersistent` when portability matters.
195
-
196
- ### `session` — data for the current session
184
+ > **Note:** "structured memory" here means metadata-based ranking (tags, type, confidence, recency) - not embedding similarity search. Pair `memorio.memory` with a dedicated vector store if you need that.
197
185
 
198
- ```ts
199
- session.set('wizard-step', 3)
200
- const step = session.get('wizard-step')
186
+ ```text
187
+ sqlite → what data do I have?
188
+ memory → what does my application remember?
201
189
  ```
202
190
 
203
- Backed by `sessionStorage`. Good for multi-step workflows, temporary preferences, tab-scoped data.
191
+ ---
204
192
 
205
- ### `cache` — volatile runtime data
193
+ ## The other layers, briefly
206
194
 
195
+ **`store`** - persistent key/value, backed by `localStorage` in browsers, memory elsewhere.
207
196
  ```ts
208
- cache.set('expensive-result', computeExpensiveResult())
197
+ store.set('preferences', { theme: 'dark' })
198
+ const preferences = store.get('preferences')
209
199
  ```
210
200
 
211
- Disappears when the runtime disappears. No persistence guarantee, ever.
201
+ **`session`** - scoped to the current browser session (`sessionStorage`). Good for wizard steps and tab-local state.
212
202
 
213
- ### `idb` — durable structured browser data
203
+ **`cache`** - volatile, in-memory, disappears when the runtime disappears.
214
204
 
205
+ **`idb`** - durable structured browser data:
215
206
  ```ts
216
207
  await idb.db.create('app')
217
208
  await idb.table.create('app', 'users')
218
209
  await idb.data.set('app', 'users', { id: 1, name: 'Sara' })
210
+ ```
219
211
 
220
- const user = await idb.data.get('app', 'users', 1)
212
+ **`sqlite`** - relational local SQL, in-memory by default via `sql.js`:
213
+ ```ts
214
+ await sqlite.ready
215
+ await sqlite.db.create('app', { persistence: true })
216
+ await sqlite.query.run('app', `CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, role TEXT)`)
217
+ await sqlite.query.select('app', `SELECT * FROM users WHERE role = ?`, ['admin'])
221
218
  ```
219
+ > ⚠️ Persistence serializes the **entire database** on flush - fine for small/medium datasets, but large ones need deliberate batching.
220
+
221
+ Check what's actually available at runtime before depending on a backend: `memorio.getCapabilities()`.
222
222
 
223
- Check runtime support before depending on it: `memorio.getCapabilities()`.
223
+ ---
224
224
 
225
- ### `sqlite` — local SQL
225
+ ## State Intelligence
226
+
227
+ With history tracking enabled, mutations are recorded with a unique ID, HLC timestamp, source, and causal context - the foundation for undo/redo, diff, trace, and (planned) replay.
226
228
 
227
229
  ```ts
228
- await sqlite.ready
229
- await sqlite.db.create('app')
230
+ import { memorio } from 'memorio'
231
+
232
+ memorio.enableHistory(true)
233
+
234
+ state.user = { name: 'John' }
235
+ state.user.name = 'Maria'
236
+ state.user.name = 'Pedro'
230
237
 
231
- await sqlite.query.run('app', `
232
- CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, role TEXT)
233
- `)
234
- await sqlite.query.run('app', `INSERT INTO users (name, role) VALUES (?, ?)`, ['Sara', 'admin'])
238
+ const history = memorio.trace()
239
+ memorio.undo()
240
+ memorio.redo()
235
241
 
236
- const admins = await sqlite.query.select('app', `SELECT * FROM users WHERE role = ?`, ['admin'])
242
+ memorio.canUndo()
243
+ memorio.canRedo()
237
244
  ```
238
245
 
239
- Runs **in memory by default**, using `sql.js`. Persistence is explicit:
246
+ **Explicit mutations & transactions:**
240
247
 
241
248
  ```ts
242
- await sqlite.db.create('app', { persistence: true })
249
+ const mutation = memorio.mutate('state.user.role', 'admin', { source: 'permissions.enableAdmin' })
250
+ // mutation.id · mutation.hlc · mutation.source
251
+
252
+ const tx = memorio.transaction('user.migration', 'Migrate to v2 schema')
253
+ state.user.role = 'admin'
254
+ state.user.permissions = ['read', 'write']
255
+ memorio.commitTransaction()
256
+
257
+ // or abort and roll back
258
+ memorio.transaction('failed-op')
259
+ state.user.name = 'Maria'
260
+ memorio.abortTransaction()
243
261
  ```
244
262
 
245
- > ⚠️ **Persistence is not incremental.** It serializes the **entire** database on flush — fine for small/medium local datasets, but large databases should not be persisted after every mutation. Batch writes and flush deliberately. memorio's SQLite layer is an embedded local SQL runtime, not a replacement for a server database.
263
+ **Roadmap:**
246
264
 
247
- ### `memory` — application memory
265
+ | Phase | Capability | Status |
266
+ | ----- | ---------------------------- | --------------------------------------------------- |
267
+ | 1 | Mutation Engine | ✅ Active |
268
+ | 2 | Undo / Redo / Diff / Revert | ✅ Partial (basic trace + undo/redo shipped above) |
269
+ | 3 | History Engine (persisted, queryable history) | Planned |
270
+ | 4 | Replay / Time Machine | Planned |
271
+ | 5 | Causal Graph | Planned |
272
+ | 6 | Explain / Trace / Impact | Planned |
273
+ | 7 | What-if Simulation | Planned |
248
274
 
249
- The layer that makes memorio more than a state manager. `memory` represents information the application wants to **remember**, not just store — it can carry type, confidence, source, scope, tags, lifetime, status, and history.
275
+ ---
276
+
277
+ ## Typed state & validation
250
278
 
251
279
  ```ts
252
- await memorio.memory.remember('user.language', 'Italian', {
253
- type: 'preference',
254
- confidence: 0.92,
255
- scope: 'local',
256
- tags: ['user', 'ui'],
257
- source: 'conversation',
258
- })
280
+ import { memorio } from 'memorio'
259
281
 
260
- const language = await memorio.memory.recall('user.language')
261
- ```
282
+ interface AppState {
283
+ user: { name: string; age: number; email: string }
284
+ theme: 'light' | 'dark'
285
+ }
262
286
 
263
- Updates don't overwrite — they supersede, preserving history:
287
+ const app = memorio.typed<AppState>()
288
+ app.theme = 'dark' // ✅
289
+ app.theme = 'purple' // ❌ TypeScript error
264
290
 
265
- ```ts
266
- await memorio.memory.update('user.language', 'English', { confidence: 0.95 })
267
- // previous entry → status: 'superseded' | new entry → status: 'active'
291
+ app === state // same proxy, typed
268
292
  ```
269
293
 
270
- Retrieve what's relevant to the current operation, not everything:
294
+ Runtime schemas validate values crossing trust boundaries:
271
295
 
272
296
  ```ts
273
- const context = await memorio.memory.context({
274
- tags: 'user',
275
- types: ['preference', 'decision'],
276
- minConfidence: 0.7,
277
- maxEntries: 10,
297
+ memorio.registerSchema('user', {
298
+ type: 'object',
299
+ required: ['name', 'email'],
300
+ properties: {
301
+ name: { type: 'string', min: 1 },
302
+ email: { type: 'string', pattern: /^[^@]+@[^@]+$/ }
303
+ }
278
304
  })
279
- ```
280
305
 
281
- The context system considers tags, type, confidence, and recency.
306
+ memorio.registerSchema('tags', { type: 'array', items: { type: 'string' } })
282
307
 
283
- > ℹ️ **"Semantic" here means structured, not embedding-based.** `memory.context()` ranks by tags, type, confidence and recency — there is no hidden vector database and no claim that free text has been understood through embeddings. If you need true similarity search, pair a dedicated embedding/vector store with `memorio.memory` for the lifecycle on top (confidence, source, TTL, scope, history, supersession).
308
+ state.tags = ['a', 'b'] // accepted
309
+ state.tags = [1, 2, 3] // rejected
310
+ ```
284
311
 
285
- In short: `sqlite` answers "what data do I have?" — `memory` answers "what does my app remember, and how sure is it?" They're not competing for the same job.
312
+ ---
286
313
 
287
- ## Redux and other state managers
314
+ ## React integration
288
315
 
289
- memorio does not need to replace your existing state manager. Its Redux integration ships as a **separate, optional entry point**:
316
+ `useObserver` is a thin bridge over the observer engine. For the common React case,
317
+ wrap it in a tiny helper so components read state like any other value:
290
318
 
291
- ```ts
292
- import { createMemorioReduxBridge } from 'memorio/redux'
319
+ ```tsx
320
+ import { useReducer } from 'react'
321
+ import { useObserver, state } from 'memorio'
322
+
323
+ // Subscribe to one or more state paths and re-render on change.
324
+ function useMemorioValue(path: any) {
325
+ const [, update] = useReducer((n: number) => n + 1, 0)
326
+ useObserver(update, path)
327
+ return path
328
+ }
329
+
330
+ function Counter() {
331
+ const counter = useMemorioValue(state.counter)
332
+ return <div>{counter}</div>
333
+ }
293
334
  ```
294
335
 
295
- Redux is not a dependency of memorio — the adapter works against a small structural interface (`getState` / `subscribe` / `dispatch`), so it can work with Redux-style stores without coupling memorio's core to Redux.
336
+ `useObserver` can also auto-discover dependencies — pass a callback with no explicit
337
+ deps and it tracks every state path read inside it — but the explicit-deps form above
338
+ is cheaper and easier to reason about at scale.
296
339
 
297
- > **Ownership rule:** your state manager owns application state. memorio owns memory.
340
+ Memorio itself stays framework-independent - React is an integration, not a requirement.
298
341
 
299
- The bridge does not mirror the entire store — only explicitly mapped values are persisted:
342
+ ---
343
+
344
+ ## Redux and other state managers
345
+
346
+ > **Your state manager owns application state. Memorio owns memory.**
300
347
 
301
348
  ```ts
349
+ import { createMemorioReduxBridge } from 'memorio/redux'
350
+
302
351
  const memorioRedux = createMemorioReduxBridge<AppState>({
303
352
  mappings: {
304
353
  'user.preferences': {
305
354
  selector: state => state.user.preferences,
306
355
  type: 'preference',
307
356
  scope: 'local',
308
- tags: ['app', 'user'],
357
+ tags: ['app', 'user']
309
358
  },
310
- 'user.name': state => state.user.name,
359
+ 'user.name': state => state.user.name
311
360
  },
312
361
  whitelist: ['user/preferencesChanged', 'user/nameChanged'],
313
- debug: true,
362
+ debug: true
314
363
  })
315
364
 
316
365
  const store = createStore(reducer, applyMiddleware(memorioRedux.middleware))
317
- ```
318
366
 
319
- Hydration is explicit and one-shot:
320
-
321
- ```ts
322
367
  await memorioRedux.hydrate(store, {
323
- onHydration(values) {
324
- store.dispatch(restorePreferences(values))
325
- },
368
+ onHydration(values) { store.dispatch(restorePreferences(values)) }
326
369
  })
327
370
  ```
328
371
 
329
- Direction of ownership — there is intentionally no permanent two-way mirror:
330
-
331
372
  ```text
332
- Redux ─────────────→ memorio memorio ────────────→ Redux
333
- application state durable memory bootstrap hydration
373
+ Redux ─────────────→ memorio memorio ───────────→ Redux
374
+ application state durable memory bootstrap hydration (one-shot)
334
375
  ```
335
376
 
336
- - only mapped selectors are persisted — the entire Redux tree is never mirrored
337
- - hydration is one-shot; restore dispatches do not create synchronization loops
338
- - persistence happens outside the reducer path; bursts of actions are coalesced
339
- - memorio failures do not break Redux dispatch — errors can be reported through `onError`
340
- - the adapter does not expose the memorio database through `globalThis` or DevTools
377
+ The bridge persists only mapped selectors, never mirrors the full tree, coalesces bursts, and never breaks Redux dispatch if Memorio fails.
341
378
 
342
- ### memorio vs Redux, at a glance
343
-
344
- Not a replacement — a different scope. Useful mainly for deciding which one (or both) fits a given piece of state.
345
-
346
- | | Redux | memorio |
379
+ | | Redux | Memorio |
347
380
  |---|---|---|
348
- | Core model | single store, plain object | multiple independent layers (`state`, `store`, `session`, `cache`, `idb`, `sqlite`, `memory`) |
349
- | State changes | via dispatched actions + reducers | direct mutation on a reactive proxy |
350
- | Persistence | not built in (needs `redux-persist` or similar) | built into `store`/`session`/`idb`/`sqlite` |
351
- | Structured "memory" (confidence, TTL, source, supersession) | not a concept in Redux | native, via the `memory` layer |
352
- | Offline sync / conflict resolution | not built in | built into `memory.configure()` (operations + journal + HLC ordering) |
353
- | Time-travel debugging, strict middleware pipelines | yes, mature ecosystem | not a goal — see [When to use something else](#when-to-use-something-else) |
354
- | Dependencies | small core, large plugin ecosystem | zero production dependencies |
355
-
356
- Pick Redux when you need its action-pipeline discipline and tooling. Pick memorio when you want state, persistence, and structured memory under one runtime without wiring several libraries together. Nothing stops you from using both — that's exactly what the [Redux bridge](#redux-and-other-state-managers) is for.
357
-
358
- ## React integration
359
-
360
- React is an integration, not a requirement — `useObserver` connects to the same observer system described above.
361
-
362
- ```tsx
363
- function Counter() {
364
- const [, forceUpdate] = useReducer(x => x + 1, 0)
365
- useObserver(forceUpdate, [state.counter])
366
- return <div>{state.counter}</div>
367
- }
368
- ```
369
-
370
- The runtime itself remains independent of React.
371
-
372
- ## Typed state & schema validation
373
-
374
- TypeScript types give compile-time guarantees without creating another state container:
375
-
376
- ```ts
377
- interface AppState {
378
- user: { name: string; age: number; email: string }
379
- theme: 'light' | 'dark'
380
- }
381
-
382
- const app = memorio.typed<AppState>()
383
- app.theme = 'dark'
384
- app.theme = 'purple' // TypeScript error
385
- ```
386
-
387
- `app === state` — same proxy, no duplicated store.
388
-
389
- Runtime validation protects values crossing trust boundaries:
390
-
391
- ```ts
392
- memorio.registerSchema('user', {
393
- type: 'object',
394
- required: ['name', 'email'],
395
- properties: {
396
- name: { type: 'string', min: 1 },
397
- email: { type: 'string', pattern: /^[^@]+@[^@]+$/ },
398
- },
399
- })
400
-
401
- state.user = { name: 'Sara' } // rejected: missing required "email"
402
- ```
381
+ | Core model | single store | independent runtime layers |
382
+ | State changes | actions + reducers | direct reactive mutation |
383
+ | Persistence | external integration | built in |
384
+ | Structured memory | - | native |
385
+ | Offline memory sync | - | supported |
386
+ | Time-travel debugging | mature | State Intelligence (in progress) |
387
+ | Production dependencies | ecosystem-dependent | zero in core |
403
388
 
404
- Arrays validate each element via `items`:
389
+ Use Redux when you need its action-pipeline discipline and ecosystem. Use Memorio when you want state, persistence, and structured memory under one runtime. You can use both.
405
390
 
406
- ```ts
407
- memorio.registerSchema('tags', { type: 'array', items: { type: 'string' } })
408
-
409
- state.tags = ['a', 'b'] // accepted
410
- state.tags = [1, 2, 3] // rejected
411
- ```
391
+ ---
412
392
 
413
393
  ## Local-first sync
414
394
 
415
- The local application owns its data — the cloud is optional transport. memorio synchronizes **operations** (`remember`, `update`, `forget`, `expire`, `confirm`, `supersede`), not database dumps. A local journal records operations so temporary network failures don't stop the application from working.
395
+ Memorio synchronizes **operations** (`remember`, `update`, `forget`, `expire`, `confirm`, `supersede`), not database dumps. A local journal keeps the app working through network failures; the cloud is optional transport, not a prerequisite.
416
396
 
417
397
  ```ts
418
398
  memorio.memory.configure({
419
399
  namespace: 'user:123:device:abc',
420
400
  provider: {
421
401
  push: ops => fetch('/api/sync', { method: 'POST', body: JSON.stringify(ops) }),
422
- pull: since => fetch(`/api/sync?since=${since}`).then(r => r.json()),
402
+ pull: since => fetch(`/api/sync?since=${since}`).then(r => r.json())
423
403
  },
424
- auto: true,
404
+ auto: true
425
405
  })
426
406
  ```
427
407
 
428
- ```text
429
- local application → memorio memory → local journal → offline / cloud
430
- ```
431
-
432
- The network is an extension of the local application, not its prerequisite.
433
-
434
- Remote operations are ordered causally using HLC timestamps. For concurrent writes to the same key, memorio provides a deterministic default — a custom resolver can override it:
408
+ Concurrent operations use HLC ordering by default; override with a custom resolver:
435
409
 
436
410
  ```ts
437
411
  memorio.memory.configure({
438
412
  resolveConflict(local, remote) {
439
413
  if (remote.source === 'user-correction') return remote
440
414
  return local.confidence >= remote.confidence ? local : remote
441
- },
415
+ }
442
416
  })
443
417
  ```
444
418
 
445
- Without a resolver, the default policy applies the remote entry on a tie. The resolver operates client-side — the sync provider is still responsible for any final server-side conflict policy.
419
+ The sync provider is still responsible for the final server-side conflict policy.
420
+
421
+ ---
446
422
 
447
423
  ## Cross-platform support
448
424
 
449
- | API | Browser | Node.js | Deno | Edge / Workers |
450
- |---|:---:|:---:|:---:|:---:|
451
- | `state` / `observer` / `cache` | ✅ | ✅ | ✅ | ✅ |
452
- | `store` / `session` | persistent | memory fallback | memory fallback | capability-dependent |
453
- | `idb` | ✅ | ❌ | ❌ | capability-dependent |
454
- | `sqlite` | ✅ | ❌ | ❌ | capability-dependent |
455
- | `devtools` | dev-only | ❌ | ❌ | capability-dependent |
425
+ | API | Browser | Node.js | Deno | Edge / Workers |
426
+ | -------------------------------- | :--------: | :---------------: | :----------------: | :---------------------: |
427
+ | `state` / `observer` / `cache` | ✅ | ✅ | ✅ | ✅ |
428
+ | `store` / `session` | persistent | memory fallback | memory fallback | capability-dependent |
429
+ | `idb` | ✅ | ❌ | ❌ | capability-dependent |
430
+ | `sqlite` | ✅ | ❌ | ❌ | capability-dependent |
431
+ | `memory` / `journal` | ✅ | ✅ | ✅ | ✅ |
432
+ | `devtools` | dev-only | ❌ | ❌ | capability-dependent |
456
433
 
457
434
  ```ts
458
435
  memorio.getCapabilities()
459
- memorio.isBrowser() / memorio.isNode() / memorio.isDeno() / memorio.isEdge()
436
+ memorio.isBrowser() // .isNode() · .isDeno() · .isEdge()
460
437
  ```
461
438
 
462
- Do not assume every persistence backend exists in every runtime.
439
+ Don't assume every persistence backend exists in every runtime - check first.
440
+
441
+ > **SQLite on Node.js / Deno:** Memorio's `sqlite` is backed by `sql.js` (SQLite compiled to WebAssembly), which requires browser APIs (`window`, `document`, `WebAssembly`). It is not available in Node.js or Deno. For server-side SQL, pair Memorio with a native SQLite package directly; use `store` or `idb` for in-process persistence from Memorio.
442
+
443
+ ---
463
444
 
464
445
  ## Security
465
446
 
466
- - Zero production dependencies — [checked by Socket.dev](https://socket.dev/npm/package/memorio) and [scanned by Snyk](https://snyk.io/test/npm/memorio)
467
- - No `eval`, no dynamic code execution, no bundled telemetry
468
- - Sanitized keys, validated inputs, caught module-boundary errors
469
- - Bounded journal entries, UUID-based session identifiers
447
+ Core has zero production dependencies. No `eval`, no dynamic code execution, no bundled telemetry, sanitized keys, validated inputs, bounded journal entries, UUID-based session identifiers. Independently checkable via Socket.dev / Snyk.
470
448
 
471
- > ⚠️ **memorio does not encrypt data by default.** This applies to `state`, `store`, `session`, `idb`, `memory`, and `sqlite`. Treat browser storage as client-controlled data — if your application handles auth secrets, credentials, or regulated data, bring your own encryption, backend authorization, and server-side security controls.
449
+ > ⚠️ **Memorio does not encrypt data by default** - this applies to every layer (`state`, `store`, `session`, `idb`, `memory`, `sqlite`). Treat browser storage as client-controlled. Use proper encryption and backend authorization for credentials or regulated data.
472
450
 
473
- **Contexts are not security boundaries.** `memorio.createContext('tenant-123')` is useful for organizing and isolating application concerns — it is **not** an authorization mechanism. Code running inside the same JS runtime can potentially access other memorio contexts. Real tenant isolation belongs at the backend/authentication layer.
451
+ **Contexts are not authorization:**
474
452
 
475
- memorio's DevTools are intended for development only, disabled via runtime detection (`process.env.NODE_ENV`) — not build-time removal. Make sure your bundler actually defines this correctly in production; don't treat DevTools absence as a security boundary.
453
+ ```ts
454
+ memorio.createContext('tenant-123')
455
+ ```
476
456
 
477
- ## Honest limitations
457
+ Contexts organize and isolate application concerns - they're not a security boundary. Code in the same JS runtime can potentially reach other contexts. Real tenant isolation belongs at the auth/backend layer.
478
458
 
479
- memorio deliberately documents its edges.
459
+ DevTools expose data for development only, and only when you opt into `memorio/global`.
480
460
 
481
- - **Semantic memory is structured, not vector-based.** `memory.context()` uses structured ranking, not embedding similarity search.
482
- - **SQLite persistence is not incremental** — the current strategy serializes the complete database on flush; large datasets need deliberate batching.
483
- - **Contexts and namespaces are not authorization** — they organize application data, they don't replace authentication or backend authorization.
484
- - **Data is not encrypted automatically** — memorio doesn't pretend local persistence is secure storage.
485
- - **DevTools are runtime-controlled, not build-removed** — production builds should still configure `NODE_ENV` correctly.
461
+ ---
486
462
 
487
463
  ## When to use something else
488
464
 
489
- memorio is intentionally not everything.
465
+ - **A strict Redux-style architecture** - when you need action pipelines, extensive middleware, event-sourcing, or mature time-travel tooling. Memorio can integrate rather than replace.
466
+ - **A server database** - for authoritative persistence, multi-user authorization, or server-side transactions.
467
+ - **A dedicated vector database** - for true embedding similarity search. Memorio can still manage the lifecycle/metadata of what you retrieve from it.
468
+
469
+ Memorio occupies a distinct space: **application state + history + causality + replay + impact analysis + simulation**. If you need to know *why* state changed, *who* changed it, or *what would happen* if it changed, Memorio is the tool - not just a state container.
490
470
 
491
- - **Need strict Redux-style architecture** (action pipelines, reducer-based transitions, extensive middleware, time-travel debugging, event-sourcing)? memorio can integrate with such systems rather than replace them.
492
- - **Need a server database** (authoritative persistence, multi-user authorization, server-side transactions, backend-controlled access)? Use one — memorio doesn't provide it.
493
- - **Need true embedding similarity / vector search**? Pair a dedicated vector database with `memorio.memory`, which can still manage the lifecycle and metadata of the retrieved knowledge.
471
+ ---
494
472
 
495
473
  ## Design philosophy
496
474
 
497
- 1. **Local first** — the application stays useful when the network disappears.
498
- 2. **Persistence is optional** — start in memory, persist only when it provides value.
499
- 3. **The cloud is optional** — remote sync extends the local application; it does not define it.
500
- 4. **Use the right primitive** — don't put relational data in a key/value store, or semantic memory in ordinary state.
501
- 5. **Memory has meaning** — confidence, source, type, scope, TTL, tags, history, status. That's different from simply storing a value.
502
- 6. **Global access is a convenience, not a requirement** — both `import 'memorio'` and `import { state } from 'memorio'` are valid; memorio does not impose one architecture.
503
- 7. **Tell the truth about boundaries** — local data is not automatically secure, persistence is not authorization, structured memory is not automatically AI semantic search.
504
- 8. **Keep the common case tiny:**
505
- ```ts
506
- import 'memorio'
507
- state.value = 42
508
- ```
509
- Everything else is there when you need it.
510
-
511
- ## A mental model
475
+ 1. **Local first** - the app stays useful when the network disappears.
476
+ 2. **Persistence is optional** - start in memory, persist only when it adds value.
477
+ 3. **The cloud is optional** - sync extends the local app; it doesn't define it.
478
+ 4. **Use the right primitive** - relational data belongs in SQL, not a kv store; memory isn't the same as ordinary state.
479
+ 5. **Memory has meaning** - confidence, source, type, scope, TTL, tags, history, status: more than "just a value."
480
+ 6. **Global access is explicit** - opt in with `import 'memorio/global'`, or keep it explicit with named imports.
481
+ 7. **Tell the truth about boundaries** - not encrypted, not authorization, not embedding search unless paired with one.
482
+ 8. **Keep the common case tiny** - `state.value = 42` is a complete, valid program.
512
483
 
513
- ```text
514
- memorio
515
- │
516
- ┌──────────────┼──────────────┐
517
- │ │ │
518
- runtime persistence memory
519
- │ │ │
520
- ┌─────┼─────┐ ┌────┼────┐ structured
521
- │ │ │ │ │ │ knowledge
522
- state cache session store idb sqlite
523
- │
524
- observer
525
- │
526
- ▼
527
- application → journal → optional sync → cloud
484
+ ---
485
+
486
+ ## Quick recipes
487
+
488
+ ```ts
489
+ // Global state
490
+ import 'memorio/global'
491
+ state.user = { name: 'Sara', role: 'admin' }
492
+
493
+ // Explicit state
494
+ import { state } from 'memorio'
495
+ state.counter++
496
+
497
+ // Persistent kv
498
+ import { store } from 'memorio'
499
+ store.set('preferences', { theme: 'dark' })
500
+
501
+ // Persistent reactive state
502
+ import { state, persist } from 'memorio'
503
+ state.user = { name: 'Sara' }
504
+ const off = persist('state.user')
505
+
506
+ // Application memory
507
+ import { memorio } from 'memorio'
508
+ await memorio.memory.remember('user.language', 'Italian', {
509
+ type: 'preference', confidence: 0.92, source: 'conversation'
510
+ })
511
+
512
+ // Observe a value
513
+ import { observer } from 'memorio'
514
+ const off = observer('state.user', (next, previous) => console.log(next, previous))
515
+
516
+ // Track mutations, undo, and trace history
517
+ import { memorio } from 'memorio'
518
+ memorio.enableHistory(true)
519
+ memorio.mutate('state.user.role', 'admin', { source: 'permissions.save' })
520
+ const tx = memorio.transaction('migration', 'v2 schema migration')
521
+ state.user.v2 = true
522
+ memorio.commitTransaction()
523
+ memorio.undo()
524
+ console.debug(memorio.trace())
528
525
  ```
529
526
 
530
- The important part is not that memorio has many layers — it's that **you do not have to use them all**.
527
+ ---
531
528
 
532
529
  ## License
533
530