@engramx/openclaw 0.1.0-rc.2

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.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 EngramX contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,277 @@
1
+ # EngramX + OpenClaw Integration
2
+
3
+ Hybrid memory plugin for [OpenClaw](https://github.com/openclaw/openclaw): local SQLite for fast search, [EngramX](https://engramx.ai) canister as the persistent source of truth, and periodic database backup to the canister for disaster recovery. Auto-detects active databases (SQLite, QMD, LanceDB) from `openclaw.json`.
4
+
5
+ ## Architecture
6
+
7
+ The canister exposes two storage systems: **Files** (memory markdown + session JSONL) and **Blobs** (SQLite backup chunks). Sessions are stored as JSONL files under `sessions/{agentId}/{key}.jsonl` — no separate session API.
8
+
9
+ ```
10
+ ┌──────────────────────────────────────────────────────────────────────┐
11
+ │ OpenClaw Gateway │
12
+ │ │
13
+ │ memory_search / memory_get ─────► Local SQLite (sqlite-vec + FTS5) │
14
+ │ (sub-100ms hybrid search) ▲ │
15
+ │ │ file watch + re-index │
16
+ │ engram_append_memory ──► EngramX ──────┤ │
17
+ │ (source of truth) canister │ sync to local disk │
18
+ │ │ ▼ │
19
+ │ │ memory/*.md (local files) │
20
+ │ │ sessions/{agentId}/*.jsonl │
21
+ │ │ │
22
+ │ periodic backup ────────────┤ │
23
+ │ (every 6h) │ detected DBs ───────► EngramX │
24
+ │ │ (SQLite/QMD/LanceDB, 1.9 MiB chunks)│
25
+ │ │ │
26
+ │ engram_wallet_balance ──────┘ Direct canister access (wallet) │
27
+ └──────────────────────────────────────────────────────────────────────┘
28
+ ```
29
+
30
+ ### Why hybrid?
31
+
32
+ | Concern | Local SQLite | EngramX Canister |
33
+ |---|---|---|
34
+ | **Search latency** | 50-200ms (vector + FTS5) | Not available (search removed) |
35
+ | **Write latency** | <1ms | 2-5s (ICP consensus) |
36
+ | **Persistence** | Lost if machine dies | Survives anything (on-chain) |
37
+ | **Vector search** | sqlite-vec cosine distance | Not available |
38
+ | **Disaster recovery** | None | Backup API (500 MiB max) |
39
+
40
+ The SQLite database is a **derived cache** — it's rebuilt from markdown files + an embedding provider. EngramX stores the source markdown. If you lose your machine, pull the files from EngramX and the SQLite index rebuilds automatically.
41
+
42
+ ## What it provides
43
+
44
+ ### Search tools (local SQLite — fast)
45
+
46
+ | Tool | Description |
47
+ |---|---|
48
+ | `memory_search` | Hybrid vector + FTS5 search across memory (sub-100ms) |
49
+ | `memory_get` | Read a local memory file by path |
50
+
51
+ These are identical to OpenClaw's built-in `memory-core` tools. Search never hits the canister.
52
+
53
+ ### Engram tools (canister — persistent)
54
+
55
+ | Tool | Description |
56
+ |---|---|
57
+ | `engram_append_memory` | Append to a memory file (writes to canister + local disk). Owner-protected paths are read-only for operators. |
58
+ | `engram_read_memory` | Read a file directly from the canister |
59
+ | `engram_list_memory` | List all files in the canister (includes session JSONL files) |
60
+ | `engram_wallet_balance` | Check engram wallet balance |
61
+
62
+ > No `engram_transfer` / write / delete / rollback tools — operators are append-only
63
+ > and have no owner-level fund control by design.
64
+
65
+ Sessions are stored as regular files (`sessions/{agentId}/{key}.jsonl`) and are visible via `engram_list_memory`. There is no separate session tool.
66
+
67
+ ### Background services
68
+
69
+ - **Memory sync** — pulls markdown files from canister to local disk on startup and periodically (default: every 60 min). Local writes are pushed back to the canister.
70
+ - **Database backup** — auto-detects active databases from `openclaw.json` and uploads snapshots periodically (default: every 6 hours). Uses `sqlite3 .backup` for consistent SQLite snapshots, `tar.gz` for directory-based backends (QMD, LanceDB). SHA-256 deduplication skips unchanged databases.
71
+ - **Session sync** — serializes conversation transcripts to JSONL and appends them to `sessions/{agentId}/{key}.jsonl` in the canister after each conversation. Always enabled.
72
+
73
+ ### CLI commands
74
+
75
+ ```
76
+ openclaw memory search <query> # Search local SQLite (fast)
77
+ openclaw engram status # Canister status
78
+ openclaw engram sync # Pull/push memory files now
79
+ openclaw engram backup # Backup all detected databases now
80
+ openclaw engram restore # List available backups (grouped by type)
81
+ openclaw engram files # List canister memory files (includes sessions)
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Option 1: Hosted (engramx.ai)
87
+
88
+ Use this when your engram is running on the IC mainnet via [engramx.ai](https://engramx.ai).
89
+
90
+ ### 1. Create an engram
91
+
92
+ Sign up at [engramx.ai](https://engramx.ai) and create an engram. Note your **canister ID**.
93
+
94
+ ### 2. Create an operator invite
95
+
96
+ In the engramx.ai dashboard, go to Access > Operators and click "Create Invite".
97
+
98
+ ### 3. Pair and install
99
+
100
+ ```bash
101
+ # First host — push local memory to engram
102
+ npx @engramx/client pair <INVITE_CODE> --engram <CANISTER_ID> --openclaw
103
+
104
+ # Replacement host — restore from engram
105
+ npx @engramx/client pair <INVITE_CODE> --engram <CANISTER_ID> --openclaw --recover
106
+ ```
107
+
108
+ This generates a session key, registers the operator, installs the plugin, configures `openclaw.json`, and either migrates local files or restores database backups. A local checkpoint is saved first — run `engramx rollback` to undo.
109
+
110
+ ### 4. Verify
111
+
112
+ ```bash
113
+ openclaw engram status
114
+ ```
115
+
116
+ ### Manual configuration
117
+
118
+ If you need to customize the plugin config, edit `~/.openclaw/openclaw.json`:
119
+
120
+ ```json5
121
+ {
122
+ "plugins": {
123
+ "slots": {
124
+ "memory": "memory-engramx"
125
+ },
126
+ "entries": {
127
+ "memory-engramx": {
128
+ "canisterId": "xxxxx-xxxxx-xxxxx-xxxxx-xxx",
129
+ // Memory file sync: canister <-> local disk
130
+ "sync": {
131
+ "onStartup": true, // pull files when OpenClaw starts
132
+ "intervalMinutes": 60, // sync every hour
133
+ "pushOnWrite": true // write to both canister and local
134
+ },
135
+ // Database backup: auto-detects SQLite/QMD/LanceDB
136
+ "backup": {
137
+ "enabled": true,
138
+ "intervalMinutes": 360 // backup every 6 hours
139
+ }
140
+ }
141
+ }
142
+ }
143
+ }
144
+ ```
145
+
146
+ ---
147
+
148
+ ## Option 2: Local Development
149
+
150
+ Use this to develop and test against a local ICP replica before `@engramx/client` is on npm.
151
+
152
+ ### Prerequisites
153
+
154
+ - [Node.js](https://nodejs.org/) >= 22.12
155
+ - [pnpm](https://pnpm.io/) 10.x
156
+ - [ICP CLI](https://github.com/nicoll-douglas/icp-cli) (`icp`)
157
+ - The [engramx](https://github.com/vhew/engramx) repo cloned locally
158
+ - The [openclaw](https://github.com/openclaw/openclaw) (OpenClaw) repo cloned locally
159
+
160
+ ### 1. Start EngramX locally
161
+
162
+ ```bash
163
+ cd /path/to/engramx
164
+ pnpm local:start
165
+ pnpm local:create-engram # note the ENGRAM_ID
166
+ ```
167
+
168
+ ### 2. Configure protected paths (optional)
169
+
170
+ Designate which file paths are owner-protected (read-only for operators):
171
+
172
+ ```bash
173
+ icp canister call <ENGRAM_ID> setProtectedPaths '(vec { "SOUL.md"; "USER.md"; "AGENTS.md" })' -e local
174
+ ```
175
+
176
+ ### 3. Build and link `@engramx/client`
177
+
178
+ ```bash
179
+ cd /path/to/engramx/packages/client
180
+ pnpm install && pnpm build
181
+ pnpm link --global
182
+ ```
183
+
184
+ ### 4. Set up the plugin in OpenClaw
185
+
186
+ ```bash
187
+ cp -r /path/to/engramx/integrations/openclaw /path/to/openclaw/extensions/memory-engramx
188
+ cd /path/to/openclaw/extensions/memory-engramx
189
+ pnpm install
190
+ pnpm link --global @engramx/client
191
+ ```
192
+
193
+ ### 5. Create an operator and pair
194
+
195
+ ```bash
196
+ # Create an invite (as the engram owner)
197
+ icp canister call <ENGRAM_ID> createOperatorInvite \
198
+ '("openclaw-dev", record { canRead = true; canWrite = true; canTransfer = false; dailySpendingLimitE8s = opt 0 })' \
199
+ -e local
200
+
201
+ # Pair and configure OpenClaw in one step
202
+ npx @engramx/client pair <INVITE_CODE> --engram <ENGRAM_ID> --openclaw --host http://localhost:4943
203
+ ```
204
+
205
+ The `--openclaw` flag installs the plugin config in `~/.openclaw/openclaw.json` automatically.
206
+
207
+ ### 6. Run OpenClaw
208
+
209
+ ```bash
210
+ cd /path/to/openclaw
211
+ pnpm gateway:watch
212
+ ```
213
+
214
+ ### 7. Verify
215
+
216
+ ```bash
217
+ openclaw engram status
218
+ openclaw engram sync
219
+ openclaw engram backup # triggers backup of all detected databases
220
+ ```
221
+
222
+ ### Resetting local state
223
+
224
+ ```bash
225
+ cd /path/to/engramx
226
+ pnpm local:reset --nuke && pnpm local:start
227
+ # Repeat steps 1 and 5 to recreate engram + operator
228
+ ```
229
+
230
+ ---
231
+
232
+ ## Configuration Reference
233
+
234
+ | Key | Type | Default | Description |
235
+ |---|---|---|---|
236
+ | `canisterId` | string | *required* | Engram canister ID (also reads `ENGRAM_CANISTER_ID` env) |
237
+ | `sessionKeyPath` | string | `~/.engramx/session.key` | Path to Ed25519 operator session key |
238
+ | `host` | string | `https://ic0.app` | ICP replica host |
239
+ | `memoryDir` | string | `memory` | Local directory for memory markdown files |
240
+ | `sync.onStartup` | boolean | `true` | Pull memory files from canister on startup |
241
+ | `sync.intervalMinutes` | number | `60` | Periodic sync interval (0 = disabled) |
242
+ | `sync.pushOnWrite` | boolean | `true` | Write to both canister and local disk |
243
+ | `backup.enabled` | boolean | `true` | Enable periodic database backup (auto-detects SQLite/QMD/LanceDB) |
244
+ | `backup.intervalMinutes` | number | `360` | Backup interval in minutes (minimum 30) |
245
+ | `backup.dbLabel` | string | auto | Label for backup snapshots |
246
+
247
+ ## Environment Variables
248
+
249
+ | Variable | Description |
250
+ |---|---|
251
+ | `ENGRAM_CANISTER_ID` | Fallback canister ID if not set in config |
252
+ | `ENGRAM_SESSION_KEY_PATH` | Override session key path |
253
+ | `OPENCLAW_STATE_DIR` | Override `.openclaw` directory location |
254
+
255
+ ## Disaster Recovery
256
+
257
+ If you lose your machine:
258
+
259
+ ```bash
260
+ # On a clean machine — create a new operator invite from the dashboard, then:
261
+ npx @engramx/client pair <INVITE_CODE> --engram <CANISTER_ID> --openclaw --recover
262
+ ```
263
+
264
+ This registers a new operator, installs the plugin, restores the latest database backups (SQLite, QMD, LanceDB — whichever were detected), and saves a checkpoint. Memory files sync automatically on next OpenClaw startup.
265
+
266
+ A local checkpoint is saved before any changes. Run `engramx rollback` to undo.
267
+
268
+ The only thing that needs regeneration is the embedding vectors, which are computed locally by the embedding provider (OpenAI, Gemini, etc.). The embedding cache in the database backup avoids re-computing embeddings for unchanged content.
269
+
270
+ ### Manual recovery
271
+
272
+ If you prefer fine-grained control:
273
+
274
+ 1. Set up OpenClaw + this plugin on a new machine
275
+ 2. Run `openclaw engram sync` — pulls all memory files from the canister
276
+ 3. Run `openclaw engram restore` — lists available backups grouped by database type
277
+ 4. Download and restore via the client SDK's backup API
@@ -0,0 +1,25 @@
1
+ export type EngramXPluginConfig = {
2
+ canisterId: string;
3
+ sessionKeyPath?: string;
4
+ host?: string;
5
+ memoryDir?: string;
6
+ sync: {
7
+ onStartup: boolean;
8
+ intervalMinutes: number;
9
+ pushOnWrite: boolean;
10
+ };
11
+ backup: {
12
+ enabled: boolean;
13
+ intervalMinutes: number;
14
+ dbLabel?: string;
15
+ };
16
+ git: {
17
+ enabled: boolean;
18
+ pushOnSync: boolean;
19
+ pushOnStop: boolean;
20
+ };
21
+ };
22
+ export declare function sha256File(filePath: string): string;
23
+ export declare const engramxConfigSchema: {
24
+ parse(value: unknown): EngramXPluginConfig;
25
+ };
package/dist/config.js ADDED
@@ -0,0 +1,100 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ const ALLOWED_KEYS = ['canisterId', 'sessionKeyPath', 'host', 'memoryDir', 'sync', 'backup', 'git'];
4
+ const SYNC_KEYS = ['onStartup', 'intervalMinutes', 'pushOnWrite'];
5
+ const BACKUP_KEYS = ['enabled', 'intervalMinutes', 'dbLabel'];
6
+ const GIT_KEYS = ['enabled', 'pushOnSync', 'pushOnStop'];
7
+ const ALLOWED_ENV_VARS = new Set([
8
+ 'HOME',
9
+ 'USER',
10
+ 'ENGRAM_CANISTER_ID',
11
+ 'ENGRAM_SESSION_KEY_PATH',
12
+ 'ENGRAMX_SESSION_KEY_PATH',
13
+ 'VAULT_CANISTER_ID',
14
+ 'VAULT_SESSION_KEY_PATH',
15
+ 'ENGRAM_HOST',
16
+ 'ENGRAM_OFFLINE_QUEUE_PATH',
17
+ 'VAULT_OFFLINE_QUEUE_PATH',
18
+ 'XDG_CONFIG_HOME',
19
+ 'XDG_DATA_HOME',
20
+ ]);
21
+ function resolveEnvVars(value) {
22
+ return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
23
+ if (!ALLOWED_ENV_VARS.has(envVar)) {
24
+ throw new Error(`Environment variable ${envVar} is not in the allowlist`);
25
+ }
26
+ const envValue = process.env[envVar];
27
+ if (!envValue) {
28
+ throw new Error(`Environment variable ${envVar} is not set`);
29
+ }
30
+ return envValue;
31
+ });
32
+ }
33
+ function assertAllowedKeys(value, allowed, label) {
34
+ const unknown = Object.keys(value).filter((k) => !allowed.includes(k));
35
+ if (unknown.length > 0) {
36
+ throw new Error(`memory-engramx ${label}: unknown keys: ${unknown.join(', ')}`);
37
+ }
38
+ }
39
+ export function sha256File(filePath) {
40
+ const content = readFileSync(filePath);
41
+ return createHash('sha256').update(content).digest('hex');
42
+ }
43
+ export const engramxConfigSchema = {
44
+ parse(value) {
45
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
46
+ throw new Error('memory-engramx: config object required');
47
+ }
48
+ const cfg = value;
49
+ assertAllowedKeys(cfg, ALLOWED_KEYS, 'config');
50
+ const canisterId = typeof cfg.canisterId === 'string'
51
+ ? resolveEnvVars(cfg.canisterId)
52
+ : process.env['ENGRAM_CANISTER_ID'];
53
+ if (!canisterId) {
54
+ throw new Error('memory-engramx: canisterId is required (config or ENGRAM_CANISTER_ID env)');
55
+ }
56
+ // Parse sync options
57
+ let sync = { onStartup: true, intervalMinutes: 60, pushOnWrite: true };
58
+ if (cfg.sync && typeof cfg.sync === 'object' && !Array.isArray(cfg.sync)) {
59
+ const s = cfg.sync;
60
+ assertAllowedKeys(s, SYNC_KEYS, 'sync');
61
+ sync = {
62
+ onStartup: s.onStartup !== false,
63
+ intervalMinutes: typeof s.intervalMinutes === 'number' ? Math.max(0, s.intervalMinutes) : 60,
64
+ pushOnWrite: s.pushOnWrite !== false,
65
+ };
66
+ }
67
+ // Parse backup options
68
+ let backup = { enabled: true, intervalMinutes: 360, dbLabel: undefined };
69
+ if (cfg.backup && typeof cfg.backup === 'object' && !Array.isArray(cfg.backup)) {
70
+ const b = cfg.backup;
71
+ assertAllowedKeys(b, BACKUP_KEYS, 'backup');
72
+ backup = {
73
+ enabled: b.enabled !== false,
74
+ intervalMinutes: typeof b.intervalMinutes === 'number' ? Math.max(30, b.intervalMinutes) : 360,
75
+ dbLabel: typeof b.dbLabel === 'string' ? b.dbLabel : undefined,
76
+ };
77
+ }
78
+ // Parse git options
79
+ let git = { enabled: false, pushOnSync: false, pushOnStop: true };
80
+ if (cfg.git && typeof cfg.git === 'object' && !Array.isArray(cfg.git)) {
81
+ const g = cfg.git;
82
+ assertAllowedKeys(g, GIT_KEYS, 'git');
83
+ git = {
84
+ enabled: g.enabled === true,
85
+ pushOnSync: g.pushOnSync === true,
86
+ pushOnStop: g.pushOnStop !== false,
87
+ };
88
+ }
89
+ return {
90
+ canisterId,
91
+ sessionKeyPath: typeof cfg.sessionKeyPath === 'string' ? cfg.sessionKeyPath : undefined,
92
+ host: typeof cfg.host === 'string' ? cfg.host : undefined,
93
+ memoryDir: typeof cfg.memoryDir === 'string' ? cfg.memoryDir : undefined,
94
+ sync,
95
+ backup,
96
+ git,
97
+ };
98
+ },
99
+ };
100
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAwBvC,MAAM,YAAY,GAAG,CAAC,YAAY,EAAE,gBAAgB,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;AAEpG,MAAM,SAAS,GAAG,CAAC,WAAW,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;AAClE,MAAM,WAAW,GAAG,CAAC,SAAS,EAAE,iBAAiB,EAAE,SAAS,CAAC,CAAC;AAC9D,MAAM,QAAQ,GAAG,CAAC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C;YACtE,MAAM,CAAC,GAAG,GAAG,CAAC,GAA8B,CAAC;YAC7C,iBAAiB,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;YACtC,GAAG,GAAG;gBACJ,OAAO,EAAE,CAAC,CAAC,OAAO,KAAK,IAAI;gBAC3B,UAAU,EAAE,CAAC,CAAC,UAAU,KAAK,IAAI;gBACjC,UAAU,EAAE,CAAC,CAAC,UAAU,KAAK,KAAK;aACnC,CAAC;QACJ,CAAC;QAED,OAAO;YACL,UAAU;YACV,cAAc,EAAE,OAAO,GAAG,CAAC,cAAc,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS;YACvF,IAAI,EAAE,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;YACzD,SAAS,EAAE,OAAO,GAAG,CAAC,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS;YACxE,IAAI;YACJ,MAAM;YACN,GAAG;SACJ,CAAC;IACJ,CAAC;CACF,CAAC"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * OpenClaw Memory Plugin: EngramX (Hybrid Architecture)
3
+ *
4
+ * This plugin uses a hybrid approach:
5
+ *
6
+ * EngramX canister = source of truth for markdown memory files
7
+ * Local SQLite = performance cache for search (vector + FTS5)
8
+ * EngramX backup API = disaster recovery for the SQLite database
9
+ *
10
+ * How it works:
11
+ * 1. Local SQLite search (memory_search / memory_get) — delegated to
12
+ * OpenClaw's built-in memory-core runtime, which uses sqlite-vec
13
+ * and FTS5 for sub-100ms hybrid search. Never queries the canister.
14
+ *
15
+ * 2. Memory file sync — pulls markdown files from the engram canister
16
+ * to the local memory/ directory on startup and periodically. Local
17
+ * file changes are pushed back to the canister. The existing SQLite
18
+ * indexer watches these files and re-chunks/embeds automatically.
19
+ *
20
+ * 3. Database backup — auto-detects active databases (SQLite, QMD,
21
+ * LanceDB) from openclaw.json and periodically uploads snapshots
22
+ * to the engram canister's backup API for disaster recovery.
23
+ *
24
+ * 4. Session sync — serializes conversation transcripts to JSONL files
25
+ * stored in the canister under sessions/{agentId}/{key}.jsonl.
26
+ *
27
+ * 5. Supplementary engram_* tools — direct canister access for wallet,
28
+ * audit log, and cross-machine memory retrieval.
29
+ */
30
+ import type { OpenClawPluginApi } from 'openclaw/plugin-sdk';
31
+ declare const memoryEngramXPlugin: {
32
+ id: string;
33
+ name: string;
34
+ description: string;
35
+ kind: "memory";
36
+ configSchema: {
37
+ parse(value: unknown): import("./config.js").EngramXPluginConfig;
38
+ };
39
+ register(api: OpenClawPluginApi): void;
40
+ };
41
+ export default memoryEngramXPlugin;