Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: second brain memory system with SQLite, FTS5 search, and friendlier Telegram error handling
M Shehzenc46a25bf3843
diff --git a/.gitignore b/.gitignoreindex 7df34dba..c69ad349 100644--- a/.gitignore+++ b/.gitignore@@ -5,5 +5,4 @@ dist/.DS_Store*.tsbuildinfoconfig/-memory/soul/\ No newline at end of filediff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 42265eaf..df8f8006 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -17,6 +17,7 @@ Mercury is a soul-driven, token-efficient AI agent that runs 24/7. It is an **or| Short-term memory | Working memory | `src/memory/store.ts` || Episodic memory | Recent experiences | `src/memory/store.ts` || Long-term memory | Life lessons | `src/memory/store.ts` |+| Second brain | Structured long-term user model | `src/memory/user-memory.ts` + `src/memory/second-brain-db.ts` || Providers | Senses | `src/providers/` || Capabilities | Hands & tools | `src/capabilities/` || Permissions | Boundaries | `src/capabilities/permissions.ts` |@@ -52,7 +53,9 @@ src/│ ├── list-tasks.ts│ └── cancel-task.ts├── memory/ # Persistence layer-│ └── store.ts # Short/long/episodic memory+│ ├── store.ts # Short/long/episodic memory+│ ├── second-brain-db.ts # SQLite storage engine (FTS5)+│ └── user-memory.ts # Second brain: autonomous structured memory├── providers/ # LLM APIs│ ├── base.ts # Abstract provider + getModelInstance()│ ├── openai-compat.ts@@ -153,8 +156,57 @@ All runtime data lives in `~/.mercury/` (not the project directory):- System prompt (soul + guardrails + persona): ~500 tokens per request- Short-term context: last 10 messages- Long-term facts: keyword-matched, ~3 facts injected+- Second brain: relevant user memories injected via `retrieveRelevant()` (~900 chars)- Daily default: 50,000 tokens+## Second Brain++Mercury's second brain is an autonomous, persistent user model that learns from conversations over time. It is not a raw chat log and it is not a document dump. It stores compact, structured memories it believes may help in future conversations.++### How It Learns (Background, Invisible)++For each non-trivial conversation:+1. Mercury responds to the user normally.+2. After the response is sent, a background `extractMemory()` call extracts 0-3 typed memory candidates (preference, goal, project, etc.) using a separate LLM call (~800 tokens).+3. Each candidate goes through `UserMemoryStore.remember()` which:+ - Merges with existing memory if >= 74% overlap (strengthens evidence)+ - Auto-resolves conflicts (higher confidence wins, equal confidence → newer wins)+ - Auto-tiers: identity/preference → durable, goal/project → active+ - Promotes active → durable after 3+ reinforcing observations+ - Stores weak memories with low confidence — they decay naturally+4. On each heartbeat, Mercury consolidates (re-synthesizes profile/active summaries, generates reflections) and prunes (dismisses stale memories, promotes reinforced ones).++The user never sees or waits for this process. No tool calls are involved in the agentic loop.++### What It Does Not Store++- Greetings, small talk, filler+- Low-signal one-off details (below 0.55 confidence minimum)+- Speculative assistant guesses++### `/memory` Command++```+/memory → Opens arrow-key menu (CLI) or sends overview (Telegram)++Menu:+ Overview — total memories, breakdown by type, learning status+ Recent — last 10 memories (type + summary + confidence)+ Search — full-text search across all memories+ Pause Learning — toggle: stop/resume storing new memories+ Clear All — confirm, then wipes all memories+ Back+```++### User Controls++The second brain is autonomous in learning and management. The user's only controls are:+- **Pause/resume** learning (for sensitive conversations)+- **Clear all** memories (start fresh)+- **Observe** via overview, recent, and search++No review queue. No manual pinning. No manual conflict resolution. No manual editing.+## Channels### CLIdiff --git a/DECISIONS.md b/DECISIONS.mdindex 7f56c89b..5f10557f 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -63,4 +63,21 @@- PM2 as user install — requires non-technical users to learn a separate tool- `forever` — officially deprecated by its own maintainers- Native detached only — no crash recovery, no boot startup-- **Consequence**: Zero external dependencies for core daemonization. Boot services are user-level (no sudo on Mac/Linux). Windows gets background mode + documented PM2 path. Foreground mode unchanged — daemon mode is opt-in. In daemon mode, CLI becomes log-only; Telegram (or other remote channels) is the interactive interface.\ No newline at end of file+- **Consequence**: Zero external dependencies for core daemonization. Boot services are user-level (no sudo on Mac/Linux). Windows gets background mode + documented PM2 path. Foreground mode unchanged — daemon mode is opt-in. In daemon mode, CLI becomes log-only; Telegram (or other remote channels) is the interactive interface.++## ADR-010: Second Brain — SQLite-backed autonomous structured memory++- **Context**: Mercury needs a persistent user model that learns from conversations over time. The previous LongTermMemory (flat JSONL) is too simple — keyword-only search, no structure, no merge, no conflict handling, no tiering. A second brain was partially implemented (second-brain-db.ts for SQLite, user-memory.ts for JSON) but both were disconnected dead code.+- **Decision**: Build a unified second brain using SQLite (better-sqlite3) as the storage backend with the UserMemoryStore business logic layer. Key principles:+ - **Autonomous**: No review queue, no user approval. Memories are stored, merged, and de-conflicted automatically via confidence scores. Weak memories survive with low scores and decay naturally.+ - **Automatic conflict resolution**: When a polarity conflict is detected (e.g., "prefers X" vs "does not prefer X"), the higher-confidence memory wins silently. Equal confidence → newer wins.+ - **Automatic tiering**: Memory types like goals and projects start as `active` (time-bound); identity and preferences start as `durable`. Memories reinforced 3+ times are promoted from active to durable.+ - **Staleness pruning**: Active inferred memories not seen in 21 days are dismissed. Durable inferred memories with no reinforcement in 120 days have their confidence decayed; below 0.3 they are dismissed.+ - **Invisible to the user**: Memory extraction runs as a fire-and-forget background process after the response is sent. No tool calls in the agentic loop, no status messages. The user never waits.+ - **10 memory types**: identity, preference, goal, project, habit, decision, constraint, relationship, episode, reflection.+ - **FTS5 full-text search** for the `/memory search` command.+- **Alternatives considered**:+ - JSON-only (UserMemoryStore as-is) — good logic but no search, scales poorly+ - SQLite-only (SecondBrainDB as-is) — good storage but no merge/conflict/reflection logic+ - Vector embeddings — overkill for current scale, adds heavy dependency+- **Consequence**: SQLite with WAL mode gives fast reads for prompt injection (microseconds). FTS5 enables fast search. The business logic (merge, conflict, reflection, tiering, staleness) is inherited from UserMemoryStore. One native dependency (better-sqlite3). The user's only controls are: observe (overview, recent, search), pause/resume learning, and clear all.\ No newline at end of filediff --git a/package-lock.json b/package-lock.jsonindex e18d9414..59b4c81a 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,18 +1,19 @@{"name": "@cosmicstack/mercury-agent",- "version": "0.4.0",+ "version": "0.4.1","lockfileVersion": 2,"requires": true,"packages": {"": {"name": "@cosmicstack/mercury-agent",- "version": "0.4.0",+ "version": "0.4.1","license": "MIT","dependencies": {"@ai-sdk/anthropic": "^1.2.0","@ai-sdk/openai": "^1.3.0","@grammyjs/auto-retry": "^2.0.2","ai": "^4.3.0",+ "better-sqlite3": "^12.9.0","chalk": "^5.4.0","commander": "^12.1.0","dotenv": "^16.4.7",@@ -29,6 +30,7 @@"mercury": "dist/index.js"},"devDependencies": {+ "@types/better-sqlite3": "^7.6.13","@types/node": "^22.13.0","@types/node-cron": "^3.0.11","@types/react": "^18.3.0",@@ -944,6 +946,16 @@"win32"]},+ "node_modules/@types/better-sqlite3": {+ "version": "7.6.13",+ "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",+ "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/chai": {"version": "5.2.3","resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",@@ -1200,6 +1212,64 @@}]},+ "node_modules/better-sqlite3": {+ "version": "12.9.0",+ "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.9.0.tgz",+ "integrity": "sha512-wqUv4Gm3toFpHDQmaKD4QhZm3g1DjUBI0yzS4UBl6lElUmXFYdTQmmEDpAFa5o8FiFiymURypEnfVHzILKaxqQ==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "bindings": "^1.5.0",+ "prebuild-install": "^7.1.1"+ },+ "engines": {+ "node": "20.x || 22.x || 23.x || 24.x || 25.x"+ }+ },+ "node_modules/bindings": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",+ "license": "MIT",+ "dependencies": {+ "file-uri-to-path": "1.0.0"+ }+ },+ "node_modules/bl": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",+ "license": "MIT",+ "dependencies": {+ "buffer": "^5.5.0",+ "inherits": "^2.0.4",+ "readable-stream": "^3.4.0"+ }+ },+ "node_modules/buffer": {+ "version": "5.7.1",+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.3.1",+ "ieee754": "^1.1.13"+ }+ },"node_modules/bundle-require": {"version": "5.1.0","resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz",@@ -1275,6 +1345,12 @@"url": "https://paulmillr.com/funding/"}},+ "node_modules/chownr": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",+ "license": "ISC"+ },"node_modules/commander": {"version": "12.1.0","resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",@@ -1320,6 +1396,21 @@}}},+ "node_modules/decompress-response": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^3.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/deep-eql": {"version": "5.0.2","resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",@@ -1329,6 +1420,15 @@"node": ">=6"}},+ "node_modules/deep-extend": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",+ "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",+ "license": "MIT",+ "engines": {+ "node": ">=4.0.0"+ }+ },"node_modules/dequal": {"version": "2.0.3","resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",@@ -1337,6 +1437,15 @@"node": ">=6"}},+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/diff-match-patch": {"version": "1.0.5","resolved": "https://registry.npmjs.org/diff-match-patch/-/diff-match-patch-1.0.5.tgz",@@ -1353,6 +1462,15 @@"url": "https://dotenvx.com"}},+ "node_modules/end-of-stream": {+ "version": "1.4.5",+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",+ "license": "MIT",+ "dependencies": {+ "once": "^1.4.0"+ }+ },"node_modules/es-module-lexer": {"version": "1.7.0","resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",@@ -1417,6 +1535,15 @@"node": ">=6"}},+ "node_modules/expand-template": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",+ "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",+ "license": "(MIT OR WTFPL)",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/expect-type": {"version": "1.3.0","resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",@@ -1443,6 +1570,12 @@}}},+ "node_modules/file-uri-to-path": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",+ "license": "MIT"+ },"node_modules/fix-dts-default-cjs-exports": {"version": "1.0.1","resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz",@@ -1454,6 +1587,12 @@"rollup": "^4.34.8"}},+ "node_modules/fs-constants": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",+ "license": "MIT"+ },"node_modules/fsevents": {"version": "2.3.3","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",@@ -1468,6 +1607,12 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/github-from-package": {+ "version": "0.0.0",+ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",+ "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",+ "license": "MIT"+ },"node_modules/grammy": {"version": "1.42.0","resolved": "https://registry.npmjs.org/grammy/-/grammy-1.42.0.tgz",@@ -1482,6 +1627,38 @@"node": "^12.20.0 || >=14.13.1"}},+ "node_modules/ieee754": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ini": {+ "version": "1.3.8",+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",+ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",+ "license": "ISC"+ },"node_modules/joycon": {"version": "3.1.1","resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",@@ -1591,6 +1768,33 @@"node": ">= 18"}},+ "node_modules/mimic-response": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/mkdirp-classic": {+ "version": "0.5.3",+ "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",+ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",+ "license": "MIT"+ },"node_modules/mlly": {"version": "1.8.2","resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz",@@ -1636,6 +1840,24 @@"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"}},+ "node_modules/napi-build-utils": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",+ "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",+ "license": "MIT"+ },+ "node_modules/node-abi": {+ "version": "3.89.0",+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz",+ "integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==",+ "license": "MIT",+ "dependencies": {+ "semver": "^7.3.5"+ },+ "engines": {+ "node": ">=10"+ }+ },"node_modules/node-cron": {"version": "3.0.3","resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz",@@ -1679,6 +1901,7 @@"version": "1.2.0","resolved": "https://registry.npmjs.org/ollama-ai-provider/-/ollama-ai-provider-1.2.0.tgz","integrity": "sha512-jTNFruwe3O/ruJeppI/quoOUxG7NA6blG3ZyQj3lei4+NnJo7bi3eIRWqlVpRlu/mbzbFXeJSBuYQWF6pzGKww==",+ "license": "Apache-2.0","dependencies": {"@ai-sdk/provider": "^1.0.0","@ai-sdk/provider-utils": "^2.0.0",@@ -1704,6 +1927,15 @@"node": ">=14.0.0"}},+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },"node_modules/partial-json": {"version": "0.1.7","resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",@@ -1867,6 +2099,33 @@}}},+ "node_modules/prebuild-install": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",+ "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",+ "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",+ "license": "MIT",+ "dependencies": {+ "detect-libc": "^2.0.0",+ "expand-template": "^2.0.3",+ "github-from-package": "0.0.0",+ "minimist": "^1.2.3",+ "mkdirp-classic": "^0.5.3",+ "napi-build-utils": "^2.0.0",+ "node-abi": "^3.3.0",+ "pump": "^3.0.0",+ "rc": "^1.2.7",+ "simple-get": "^4.0.0",+ "tar-fs": "^2.0.0",+ "tunnel-agent": "^0.6.0"+ },+ "bin": {+ "prebuild-install": "bin.js"+ },+ "engines": {+ "node": ">=10"+ }+ },"node_modules/process-warning": {"version": "5.0.0","resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",@@ -1882,11 +2141,36 @@}]},+ "node_modules/pump": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",+ "license": "MIT",+ "dependencies": {+ "end-of-stream": "^1.1.0",+ "once": "^1.3.1"+ }+ },"node_modules/quick-format-unescaped": {"version": "4.0.4","resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz","integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="},+ "node_modules/rc": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",+ "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",+ "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",+ "dependencies": {+ "deep-extend": "^0.6.0",+ "ini": "~1.3.0",+ "minimist": "^1.2.0",+ "strip-json-comments": "~2.0.1"+ },+ "bin": {+ "rc": "cli.js"+ }+ },"node_modules/react": {"version": "18.3.1","resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",@@ -1899,6 +2183,20 @@"node": ">=0.10.0"}},+ "node_modules/readable-stream": {+ "version": "3.6.2",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",+ "license": "MIT",+ "dependencies": {+ "inherits": "^2.0.3",+ "string_decoder": "^1.1.1",+ "util-deprecate": "^1.0.1"+ },+ "engines": {+ "node": ">= 6"+ }+ },"node_modules/readdirp": {"version": "4.1.2","resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",@@ -1973,6 +2271,26 @@"fsevents": "~2.3.2"}},+ "node_modules/safe-buffer": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },"node_modules/safe-stable-stringify": {"version": "2.5.0","resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",@@ -1986,12 +2304,69 @@"resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz","integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw=="},+ "node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },"node_modules/siginfo": {"version": "2.0.0","resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz","integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==","dev": true},+ "node_modules/simple-concat": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",+ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/simple-get": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",+ "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decompress-response": "^6.0.0",+ "once": "^1.3.1",+ "simple-concat": "^1.0.0"+ }+ },"node_modules/sonic-boom": {"version": "4.2.1","resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",@@ -2038,6 +2413,24 @@"integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==","dev": true},+ "node_modules/string_decoder": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.2.0"+ }+ },+ "node_modules/strip-json-comments": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",+ "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/strip-literal": {"version": "3.1.0","resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",@@ -2099,6 +2492,34 @@"react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/tar-fs": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",+ "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",+ "license": "MIT",+ "dependencies": {+ "chownr": "^1.1.1",+ "mkdirp-classic": "^0.5.2",+ "pump": "^3.0.0",+ "tar-stream": "^2.1.4"+ }+ },+ "node_modules/tar-stream": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",+ "license": "MIT",+ "dependencies": {+ "bl": "^4.0.3",+ "end-of-stream": "^1.4.1",+ "fs-constants": "^1.0.0",+ "inherits": "^2.0.3",+ "readable-stream": "^3.1.1"+ },+ "engines": {+ "node": ">=6"+ }+ },"node_modules/thenify": {"version": "3.3.1","resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",@@ -2266,6 +2687,18 @@}}},+ "node_modules/tunnel-agent": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",+ "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",+ "license": "Apache-2.0",+ "dependencies": {+ "safe-buffer": "^5.0.1"+ },+ "engines": {+ "node": "*"+ }+ },"node_modules/typescript": {"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",@@ -2299,6 +2732,12 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },"node_modules/uuid": {"version": "8.3.2","resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",@@ -2962,6 +3401,12 @@"node": ">=8"}},+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },"node_modules/yaml": {"version": "2.8.3","resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz",@@ -3463,6 +3908,15 @@"dev": true,"optional": true},+ "@types/better-sqlite3": {+ "version": "7.6.13",+ "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",+ "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==",+ "dev": true,+ "requires": {+ "@types/node": "*"+ }+ },"@types/chai": {"version": "5.2.3","resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",@@ -3645,6 +4099,42 @@"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz","integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="},+ "better-sqlite3": {+ "version": "12.9.0",+ "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.9.0.tgz",+ "integrity": "sha512-wqUv4Gm3toFpHDQmaKD4QhZm3g1DjUBI0yzS4UBl6lElUmXFYdTQmmEDpAFa5o8FiFiymURypEnfVHzILKaxqQ==",+ "requires": {+ "bindings": "^1.5.0",+ "prebuild-install": "^7.1.1"+ }+ },+ "bindings": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",+ "requires": {+ "file-uri-to-path": "1.0.0"+ }+ },+ "bl": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",+ "requires": {+ "buffer": "^5.5.0",+ "inherits": "^2.0.4",+ "readable-stream": "^3.4.0"+ }+ },+ "buffer": {+ "version": "5.7.1",+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",+ "requires": {+ "base64-js": "^1.3.1",+ "ieee754": "^1.1.13"+ }+ },"bundle-require": {"version": "5.1.0","resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz",@@ -3693,6 +4183,11 @@"readdirp": "^4.0.1"}},+ "chownr": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="+ },"commander": {"version": "12.1.0","resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",@@ -3724,17 +4219,35 @@"ms": "^2.1.3"}},+ "decompress-response": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",+ "requires": {+ "mimic-response": "^3.1.0"+ }+ },"deep-eql": {"version": "5.0.2","resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz","integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==","dev": true},+ "deep-extend": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",+ "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="+ },"dequal": {"version": "2.0.3","resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz","integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="},+ "detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="+ },"diff-match-patch": {"version": "1.0.5","resolved": "https://registry.npmjs.org/diff-match-patch/-/diff-match-patch-1.0.5.tgz",@@ -3745,6 +4258,14 @@"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz","integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="},+ "end-of-stream": {+ "version": "1.4.5",+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",+ "requires": {+ "once": "^1.4.0"+ }+ },"es-module-lexer": {"version": "1.7.0","resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",@@ -3799,6 +4320,11 @@"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz","integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="},+ "expand-template": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",+ "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="+ },"expect-type": {"version": "1.3.0","resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",@@ -3812,6 +4338,11 @@"dev": true,"requires": {}},+ "file-uri-to-path": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="+ },"fix-dts-default-cjs-exports": {"version": "1.0.1","resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz",@@ -3823,6 +4354,11 @@"rollup": "^4.34.8"}},+ "fs-constants": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="+ },"fsevents": {"version": "2.3.3","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",@@ -3830,6 +4366,11 @@"dev": true,"optional": true},+ "github-from-package": {+ "version": "0.0.0",+ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",+ "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="+ },"grammy": {"version": "1.42.0","resolved": "https://registry.npmjs.org/grammy/-/grammy-1.42.0.tgz",@@ -3841,6 +4382,21 @@"node-fetch": "^2.7.0"}},+ "ieee754": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="+ },+ "inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="+ },+ "ini": {+ "version": "1.3.8",+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",+ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="+ },"joycon": {"version": "3.1.1","resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",@@ -3923,6 +4479,21 @@"resolved": "https://registry.npmjs.org/marked/-/marked-14.1.4.tgz","integrity": "sha512-vkVZ8ONmUdPnjCKc5uTRvmkRbx4EAi2OkTOXmfTDhZz3OFqMNBM1oTTWwTr4HY4uAEojhzPf+Fy8F1DWa3Sndg=="},+ "mimic-response": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="+ },+ "minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="+ },+ "mkdirp-classic": {+ "version": "0.5.3",+ "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",+ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="+ },"mlly": {"version": "1.8.2","resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz",@@ -3956,6 +4527,19 @@"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz","integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="},+ "napi-build-utils": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",+ "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="+ },+ "node-abi": {+ "version": "3.89.0",+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz",+ "integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==",+ "requires": {+ "semver": "^7.3.5"+ }+ },"node-cron": {"version": "3.0.3","resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz",@@ -3993,6 +4577,14 @@"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz","integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="},+ "once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "requires": {+ "wrappy": "1"+ }+ },"partial-json": {"version": "0.1.7","resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",@@ -4090,16 +4682,55 @@"lilconfig": "^3.1.1"}},+ "prebuild-install": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",+ "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",+ "requires": {+ "detect-libc": "^2.0.0",+ "expand-template": "^2.0.3",+ "github-from-package": "0.0.0",+ "minimist": "^1.2.3",+ "mkdirp-classic": "^0.5.3",+ "napi-build-utils": "^2.0.0",+ "node-abi": "^3.3.0",+ "pump": "^3.0.0",+ "rc": "^1.2.7",+ "simple-get": "^4.0.0",+ "tar-fs": "^2.0.0",+ "tunnel-agent": "^0.6.0"+ }+ },"process-warning": {"version": "5.0.0","resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz","integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA=="},+ "pump": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",+ "requires": {+ "end-of-stream": "^1.1.0",+ "once": "^1.3.1"+ }+ },"quick-format-unescaped": {"version": "4.0.4","resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz","integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="},+ "rc": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",+ "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",+ "requires": {+ "deep-extend": "^0.6.0",+ "ini": "~1.3.0",+ "minimist": "^1.2.0",+ "strip-json-comments": "~2.0.1"+ }+ },"react": {"version": "18.3.1","resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",@@ -4109,6 +4740,16 @@"loose-envify": "^1.1.0"}},+ "readable-stream": {+ "version": "3.6.2",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",+ "requires": {+ "inherits": "^2.0.3",+ "string_decoder": "^1.1.1",+ "util-deprecate": "^1.0.1"+ }+ },"readdirp": {"version": "4.1.2","resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",@@ -4161,6 +4802,11 @@"fsevents": "~2.3.2"}},+ "safe-buffer": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="+ },"safe-stable-stringify": {"version": "2.5.0","resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",@@ -4171,12 +4817,32 @@"resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz","integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw=="},+ "semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="+ },"siginfo": {"version": "2.0.0","resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz","integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==","dev": true},+ "simple-concat": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",+ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="+ },+ "simple-get": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",+ "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",+ "requires": {+ "decompress-response": "^6.0.0",+ "once": "^1.3.1",+ "simple-concat": "^1.0.0"+ }+ },"sonic-boom": {"version": "4.2.1","resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",@@ -4214,6 +4880,19 @@"integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==","dev": true},+ "string_decoder": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",+ "requires": {+ "safe-buffer": "~5.2.0"+ }+ },+ "strip-json-comments": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",+ "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="+ },"strip-literal": {"version": "3.1.0","resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",@@ -4263,6 +4942,29 @@"use-sync-external-store": "^1.6.0"}},+ "tar-fs": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",+ "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",+ "requires": {+ "chownr": "^1.1.1",+ "mkdirp-classic": "^0.5.2",+ "pump": "^3.0.0",+ "tar-stream": "^2.1.4"+ }+ },+ "tar-stream": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",+ "requires": {+ "bl": "^4.0.3",+ "end-of-stream": "^1.4.1",+ "fs-constants": "^1.0.0",+ "inherits": "^2.0.3",+ "readable-stream": "^3.1.1"+ }+ },"thenify": {"version": "3.3.1","resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",@@ -4376,6 +5078,14 @@"tree-kill": "^1.2.2"}},+ "tunnel-agent": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",+ "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",+ "requires": {+ "safe-buffer": "^5.0.1"+ }+ },"typescript": {"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",@@ -4400,6 +5110,11 @@"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==","requires": {}},+ "util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="+ },"uuid": {"version": "8.3.2","resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",@@ -4706,6 +5421,11 @@"stackback": "0.0.2"}},+ "wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="+ },"yaml": {"version": "2.8.3","resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz",diff --git a/package.json b/package.jsonindex a803901b..b51def37 100644--- a/package.json+++ b/package.json@@ -58,6 +58,7 @@"@ai-sdk/openai": "^1.3.0","@grammyjs/auto-retry": "^2.0.2","ai": "^4.3.0",+ "better-sqlite3": "^12.9.0","chalk": "^5.4.0","commander": "^12.1.0","dotenv": "^16.4.7",@@ -71,6 +72,7 @@"zod": "^3.25.76"},"devDependencies": {+ "@types/better-sqlite3": "^7.6.13","@types/node": "^22.13.0","@types/node-cron": "^3.0.11","@types/react": "^18.3.0",diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.tsindex d44e0536..7d98f604 100644--- a/src/capabilities/registry.ts+++ b/src/capabilities/registry.ts@@ -43,6 +43,11 @@ export interface ChatCommandContext {config: () => import('../utils/config.js').MercuryConfig;tokenBudget: () => import('../utils/tokens.js').TokenBudget;manual: () => string;+ memorySummary: () => import('../memory/user-memory.js').UserMemorySummary;+ memoryRecent: (limit?: number) => import('../memory/user-memory.js').UserMemoryRecord[];+ memorySearch: (query: string, limit?: number) => import('../memory/user-memory.js').UserMemoryRecord[];+ memorySetLearningPaused: (paused: boolean) => void;+ memoryClear: () => number;}export class CapabilityRegistry {diff --git a/src/channels/telegram.ts b/src/channels/telegram.tsindex 0ed195c1..2a09b6dd 100644--- a/src/channels/telegram.ts+++ b/src/channels/telegram.ts@@ -24,6 +24,7 @@ import { mdToTelegram } from '../utils/markdown.js';const MAX_MESSAGE_LENGTH = 4096;const ACCESS_ACTION_PREFIX = 'tg_access';+const MEMORY_ACTION_PREFIX = 'tg_memory';type ApprovalResolver = (response: 'yes' | 'always' | 'no') => void;@@ -84,6 +85,15 @@ export class TelegramChannel extends BaseChannel {return;}+ if (command === '/memory') {+ if (!this.chatCommandContext) {+ await this.sendDirectMessage(chatId, 'Memory not available.');+ return;+ }+ await this.sendMemoryKeyboard(chatId);+ return;+ }+this.lastActiveChatId = chatId;logger.info({ chatId, text: ctx.message.text?.slice(0, 50) }, 'Telegram message received');@@ -121,6 +131,11 @@ export class TelegramChannel extends BaseChannel {return;}+ if (data.startsWith(`${MEMORY_ACTION_PREFIX}:`)) {+ await this.handleMemoryCallback(ctx, data);+ return;+ }+const resolver = this.pendingApprovals.get(data);if (!resolver) {await ctx.answerCallbackQuery({ text: 'Expired' });@@ -156,7 +171,18 @@ export class TelegramChannel extends BaseChannel {}).catch((err: any) => {if (!settled) {settled = true;- reject(err);+ const message = err?.description || err?.message || String(err);+ if (err?.error_code === 401) {+ reject(new Error(`Telegram bot token is invalid. Get a fresh token from @BotFather via /token.\n Details: ${message}`));+ } else if (err?.error_code === 404) {+ reject(new Error(`Telegram bot not found — the token may be wrong or the bot was deleted. Verify with @BotFather.\n Details: ${message}`));+ } else if (err?.error_code === 429) {+ reject(new Error(`Telegram is rate-limiting this bot. Wait a minute and try again.\n Details: ${message}`));+ } else if (err?.error_code === 403) {+ reject(new Error(`Telegram bot lacks permission for this action. Check bot scopes with @BotFather.\n Details: ${message}`));+ } else {+ reject(new Error(`Telegram bot failed to start: ${message}`));+ }return;}logger.error({ err: err.message }, 'Telegram bot start loop failed after startup');@@ -179,6 +205,7 @@ export class TelegramChannel extends BaseChannel {{ command: 'budget_reset', description: 'Reset token usage to zero' },{ command: 'budget_set', description: 'Set new daily token budget' },{ command: 'stream', description: 'Toggle text streaming on/off' },+ { command: 'memory', description: 'View and manage second brain memory' },{ command: 'unpair', description: 'Reset all Telegram access for this Mercury instance' },];@@ -551,6 +578,144 @@ export class TelegramChannel extends BaseChannel {await ctx.answerCallbackQuery({ text: 'Unknown action' });}+ private async sendMemoryKeyboard(chatId: number): Promise<void> {+ if (!this.bot || !this.chatCommandContext) return;++ const summary = this.chatCommandContext.memorySummary();+ const lines = [+ `<b>Memory Overview</b>`,+ `Total memories: ${summary.total}`,+ `Learning: ${summary.learningPaused ? '⏸ PAUSED' : '✅ ACTIVE'}`,+ ];+ if (summary.profileSummary) {+ lines.push(`\n<i>Profile: ${this.escapeHtml(summary.profileSummary)}</i>`);+ }+ const typeEntries = Object.entries(summary.byType);+ if (typeEntries.length > 0) {+ lines.push('\n<b>By type:</b>');+ for (const [type, count] of typeEntries) {+ lines.push(` ${type}: ${count}`);+ }+ }++ const learningLabel = summary.learningPaused ? '▶ Resume' : '⏸ Pause';+ const keyboard = new InlineKeyboard()+ .text('📋 Overview', `${MEMORY_ACTION_PREFIX}:overview`)+ .text('🔍 Recent', `${MEMORY_ACTION_PREFIX}:recent`)+ .row()+ .text(learningLabel, `${MEMORY_ACTION_PREFIX}:toggle_learning`)+ .text('🗑 Clear All', `${MEMORY_ACTION_PREFIX}:clear_confirm`);++ await this.bot.api.sendMessage(chatId, lines.join('\n'), {+ parse_mode: 'HTML',+ reply_markup: keyboard,+ }).catch(async () => {+ await this.bot!.api.sendMessage(chatId, lines.join('\n'), { reply_markup: keyboard });+ });+ }++ private async handleMemoryCallback(ctx: any, data: string): Promise<void> {+ if (!this.bot || !this.chatCommandContext) {+ await ctx.answerCallbackQuery({ text: 'Not available' });+ return;+ }++ const action = data.slice(`${MEMORY_ACTION_PREFIX}:`.length);+ const chatId = ctx.callbackQuery.message?.chat?.id;+ if (!chatId) {+ await ctx.answerCallbackQuery({ text: 'Error' });+ return;+ }++ if (action === 'overview') {+ await ctx.answerCallbackQuery({ text: 'Overview' });+ const summary = this.chatCommandContext.memorySummary();+ const lines = [+ `<b>Memory Overview</b>`,+ `Total memories: ${summary.total}`,+ `Learning: ${summary.learningPaused ? '⏸ PAUSED' : '✅ ACTIVE'}`,+ ];+ if (summary.profileSummary) {+ lines.push(`\n<i>Profile: ${this.escapeHtml(summary.profileSummary)}</i>`);+ }+ if (summary.activeSummary) {+ lines.push(`<i>Active: ${this.escapeHtml(summary.activeSummary)}</i>`);+ }+ const typeEntries = Object.entries(summary.byType);+ if (typeEntries.length > 0) {+ lines.push('\n<b>By type:</b>');+ for (const [type, count] of typeEntries) {+ lines.push(` ${type}: ${count}`);+ }+ }+ await this.bot.api.sendMessage(chatId, lines.join('\n'), { parse_mode: 'HTML' }).catch(async () => {+ await this.bot!.api.sendMessage(chatId, lines.join('\n'));+ });+ return;+ }++ if (action === 'recent') {+ await ctx.answerCallbackQuery({ text: 'Recent memories' });+ const recent = this.chatCommandContext.memoryRecent(10);+ if (recent.length === 0) {+ await this.bot.api.sendMessage(chatId, 'No memories yet.').catch(() => {});+ return;+ }+ const lines = ['<b>Recent Memories:</b>\n'];+ for (const r of recent) {+ const scope = r.scope === 'active' ? '⏳' : '📌';+ lines.push(`${scope} [${r.type}] ${this.escapeHtml(r.summary)}`);+ lines.push(` Confidence: ${r.confidence.toFixed(2)} | Evidence: ${r.evidenceKind} | Seen: ${r.evidenceCount}x`);+ }+ await this.bot.api.sendMessage(chatId, lines.join('\n'), { parse_mode: 'HTML' }).catch(async () => {+ await this.bot!.api.sendMessage(chatId, lines.join('\n'));+ });+ return;+ }++ if (action === 'toggle_learning') {+ const currentSummary = this.chatCommandContext.memorySummary();+ const currentlyPaused = currentSummary.learningPaused;+ this.chatCommandContext.memorySetLearningPaused(!currentlyPaused);+ const label = currentlyPaused ? '▶ Learning resumed' : '⏸ Learning paused';+ await ctx.answerCallbackQuery({ text: label });+ await this.bot.api.sendMessage(chatId, currentlyPaused+ ? 'Learning resumed. Mercury will remember new things from conversations.'+ : 'Learning paused. Mercury will not store new memories until resumed.',+ ).catch(() => {});+ await this.sendMemoryKeyboard(chatId);+ return;+ }++ if (action === 'clear_confirm') {+ const keyboard = new InlineKeyboard()+ .text('🗑 Yes, clear everything', `${MEMORY_ACTION_PREFIX}:clear_yes`)+ .text('✖ Cancel', `${MEMORY_ACTION_PREFIX}:clear_no`);+ await ctx.answerCallbackQuery({});+ await this.bot.api.sendMessage(chatId, '⚠️ Are you sure you want to clear <b>all</b> memories? This cannot be undone.', {+ parse_mode: 'HTML',+ reply_markup: keyboard,+ }).catch(async () => {+ await this.bot!.api.sendMessage(chatId, '⚠️ Are you sure you want to clear all memories?', { reply_markup: keyboard });+ });+ return;+ }++ if (action === 'clear_yes') {+ const cleared = this.chatCommandContext.memoryClear();+ await ctx.answerCallbackQuery({ text: `Cleared ${cleared} memories` });+ await this.bot.api.sendMessage(chatId, `Cleared ${cleared} memories.`).catch(() => {});+ return;+ }++ if (action === 'clear_no') {+ await ctx.answerCallbackQuery({ text: 'Cancelled' });+ return;+ }++ await ctx.answerCallbackQuery({ text: 'Unknown action' });+ }+private resolveTargetChatIds(targetId?: string): number[] {if (!targetId || targetId === 'notification') {return getTelegramApprovedChatIds(this.config);diff --git a/src/core/agent.ts b/src/core/agent.tsindex 25219364..035461a1 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -3,6 +3,7 @@ import type { ChannelMessage, ChannelType } from '../types/channel.js';import type { ProviderRegistry } from '../providers/registry.js';import type { Identity } from '../soul/identity.js';import type { ShortTermMemory, LongTermMemory, EpisodicMemory } from '../memory/store.js';+import type { UserMemoryStore } from '../memory/user-memory.js';import type { ChannelRegistry } from '../channels/registry.js';import type { MercuryConfig } from '../utils/config.js';import type { TokenBudget } from '../utils/tokens.js';@@ -95,6 +96,7 @@ export class Agent {private shortTerm: ShortTermMemory,private longTerm: LongTermMemory,private episodic: EpisodicMemory,+ private userMemory: UserMemoryStore | null,private channels: ChannelRegistry,private tokenBudget: TokenBudget,capabilities: CapabilityRegistry,@@ -249,7 +251,6 @@ export class Agent {const systemPrompt = this.buildSystemPrompt();const recentMemory = this.shortTerm.getRecent(msg.channelId, 10);- const relevantFacts = this.longTerm.search(msg.content, 3);const messages: any[] = [];@@ -279,12 +280,25 @@ export class Agent {messages.push({ role: 'assistant', content: 'Understood. I will try a different approach.' });}- if (relevantFacts.length > 0) {- messages.push({- role: 'user',- content: 'Relevant facts from memory:\n' + relevantFacts.map(f => `- ${f.fact}`).join('\n'),- });- messages.push({ role: 'assistant', content: 'Noted. I\'ll use these facts.' });+ if (this.userMemory) {+ const memoryContext = this.userMemory.retrieveRelevant(msg.content, { maxRecords: 5, maxChars: 900 });+ if (memoryContext.context) {+ messages.push({+ role: 'user',+ content: memoryContext.context,+ });+ messages.push({ role: 'assistant', content: 'Noted. I\'ll keep this in mind.' });+ }+ } else {+ const relevantFacts = this.longTerm.search(msg.content, 3);+ if (relevantFacts.length > 0) {+ messages.push({+ role: 'user',+ content: 'Relevant facts from memory:\n' + relevantFacts.map(f => `- ${f.fact}`).join('\n'),+ });+ messages.push({ role: 'assistant', content: 'Noted. I\'ll use these facts.' });+ }+ }}if (recentMemory.length > 0) {@@ -451,8 +465,8 @@ export class Agent {});if (msg.channelType !== 'internal') {- this.extractFacts(msg.content, finalText).catch(err => {- logger.warn({ err }, 'Fact extraction failed');+ this.extractMemory(msg.content, finalText).catch(err => {+ logger.warn({ err }, 'Memory extraction failed');});}@@ -562,6 +576,22 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userlogger.info({ pruned }, 'Episodic memory pruned');}+ if (this.userMemory) {+ try {+ const consolidation = this.userMemory.consolidate();+ if (consolidation.profileUpdated || consolidation.reflectionCount > 0) {+ logger.info({ consolidation }, 'Second brain consolidated');+ }++ const pruning = this.userMemory.prune();+ if (pruning.activePruned > 0 || pruning.durablePruned > 0 || pruning.promoted > 0) {+ logger.info({ pruning }, 'Second brain pruned');+ }+ } catch (err) {+ logger.warn({ err }, 'Second brain heartbeat error');+ }+ }+const notifications: string[] = [];const usagePct = this.tokenBudget.getUsagePercentage();@@ -594,46 +624,26 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub user}}- private async extractFacts(userMessage: string, agentResponse: string): Promise<void> {+ private async extractMemory(userMessage: string, agentResponse: string): Promise<void> {+ if (!this.userMemory) return;+ if (this.userMemory.isLearningPaused()) return;+const trivial = /^(hi|hello|hey|thanks|thank you|ok|okay|yes|no|bye|goodbye|good morning|good evening)\b/i;if (trivial.test(userMessage.trim())) return;- if (!this.tokenBudget.canAfford(500)) return;+ if (!this.tokenBudget.canAfford(800)) return;try {const provider = this.providers.getDefault();const result = await generateText({model: provider.getModelInstance(),- system: 'You are a fact extractor. Read the conversation below and extract 1-3 important facts worth remembering long-term. Output each fact on a separate line, prefixed with "- ". Only extract facts that are specific, factual, and not obvious. If nothing is worth remembering, output nothing.',+ system: `You extract structured memory from conversations. Read the conversation and output a JSON array of memory candidates. Each candidate has: type (one of: identity, preference, goal, project, habit, decision, constraint, relationship, episode), summary (concise fact, 12-220 chars), detail (optional longer explanation), evidenceKind (direct for explicitly stated facts, inferred for patterns you notice), confidence (0.0-1.0), importance (0.0-1.0), durability (0.0-1.0). Extract 0-3 candidates. Only extract specific, durable, user-specific information. Do NOT extract trivial observations, greetings, or assistant behavior. Output pure JSON array, no markdown.`,messages: [{ role: 'user', content: `User: ${userMessage}\nAssistant: ${agentResponse}` },],- maxTokens: 200,+ maxTokens: 400,});- const text = result.text.trim();- if (!text) return;-- const facts = text- .split('\n')- .map(l => l.replace(/^-\s*/, '').trim())- .filter(f => f.length > 10 && f.length < 200);-- const existing = this.longTerm.getAll();- for (const fact of facts.slice(0, 3)) {- const isDupe = existing.some(e =>- e.fact.toLowerCase().includes(fact.toLowerCase().slice(0, 30))- );- if (!isDupe) {- this.longTerm.add({- topic: 'extracted',- fact,- source: 'conversation',- });- logger.info({ fact: fact.slice(0, 60) }, 'Fact extracted to long-term memory');- }- }-this.tokenBudget.recordUsage({provider: provider.name,model: provider.getModel(),@@ -642,8 +652,60 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub usertotalTokens: (result.usage?.promptTokens ?? 0) + (result.usage?.completionTokens ?? 0),channelType: 'internal',});++ const text = result.text.trim();+ if (!text) return;++ let candidates: Array<{+ type: string;+ summary: string;+ detail?: string;+ evidenceKind?: string;+ confidence: number;+ importance: number;+ durability: number;+ }>;++ try {+ const jsonStr = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');+ candidates = JSON.parse(jsonStr);+ } catch {+ const facts = text+ .split('\n')+ .map(l => l.replace(/^-\s*/, '').trim())+ .filter(f => f.length > 10 && f.length < 200);+ candidates = facts.slice(0, 3).map(f => ({+ type: 'preference',+ summary: f,+ confidence: 0.75,+ importance: 0.7,+ durability: 0.7,+ evidenceKind: 'inferred',+ }));+ }++ const validTypes = ['identity', 'preference', 'goal', 'project', 'habit', 'decision', 'constraint', 'relationship', 'episode'];+ const typed = candidates+ .filter(c => c.summary && c.summary.length >= 12 && c.summary.length <= 220)+ .filter(c => validTypes.includes(c.type))+ .map(c => ({+ type: c.type as any,+ summary: c.summary,+ detail: c.detail,+ evidenceKind: (c.evidenceKind === 'direct' ? 'direct' : 'inferred') as 'direct' | 'inferred',+ confidence: Math.min(1, Math.max(0, c.confidence ?? 0.7)),+ importance: Math.min(1, Math.max(0, c.importance ?? 0.7)),+ durability: Math.min(1, Math.max(0, c.durability ?? 0.7)),+ }));++ if (typed.length > 0) {+ const remembered = this.userMemory.remember(typed, 'conversation');+ if (remembered.length > 0) {+ logger.info({ count: remembered.length, types: remembered.map(r => r.type) }, 'Second brain memories stored');+ }+ }} catch (err) {- logger.warn({ err }, 'Fact extraction error');+ logger.warn({ err }, 'Memory extraction error');}}@@ -720,6 +782,21 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userreturn true;}+ if (cmd === '/memory') {+ if (!this.userMemory) {+ await channel.send('Second brain is not enabled.', channelId);+ return true;+ }++ if (channelType === 'cli' && channel instanceof CLIChannel) {+ await this.openCliMemoryMenu(channel, channelId);+ return true;+ }++ await this.sendMemoryOverview(channel, channelId);+ return true;+ }+if (cmd.startsWith('/telegram')) {if (channelType !== 'cli') {await channel.send('`/telegram` is only available from the Mercury CLI chat.', channelId);@@ -988,6 +1065,7 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userconst streamLabel = this.telegramStreaming ? 'Disable Telegram Streaming' : 'Enable Telegram Streaming';const action = await select('Mercury Commands', [{ value: 'status', label: 'Status' },+ { value: 'memory', label: 'Memory' },{ value: 'telegram', label: 'Telegram' },{ value: 'tools', label: 'Tools' },{ value: 'skills', label: 'Skills' },@@ -1005,6 +1083,15 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub usercontinue;}+ if (action === 'memory') {+ if (this.userMemory) {+ await this.openCliMemoryMenu(channel, channelId, select);+ } else {+ await channel.send('Second brain is not enabled.', channelId);+ }+ continue;+ }+if (action === 'telegram') {await this.openCliTelegramMenu(channel, channelId, select);continue;@@ -1032,6 +1119,116 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub user});}+ private async sendMemoryOverview(channel: any, channelId: string): Promise<void> {+ if (!this.userMemory) return;+ const summary = this.userMemory.getSummary();+ const lines = [+ `**Memory Overview**`,+ `Total memories: ${summary.total}`,+ `Learning: ${summary.learningPaused ? 'PAUSED' : 'ACTIVE'}`,+ ];+ if (summary.profileSummary) {+ lines.push(`Profile: ${summary.profileSummary}`);+ }+ if (summary.activeSummary) {+ lines.push(`Active: ${summary.activeSummary}`);+ }+ const typeEntries = Object.entries(summary.byType);+ if (typeEntries.length > 0) {+ lines.push('');+ lines.push('By type:');+ for (const [type, count] of typeEntries) {+ lines.push(` ${type}: ${count}`);+ }+ }+ await channel.send(lines.join('\n'), channelId);+ }++ private async openCliMemoryMenu(channel: CLIChannel, channelId: string, select?: (title: string, options: ArrowSelectOption[]) => Promise<string>): Promise<void> {+ if (!this.userMemory) return;++ const runMenu = async (sel: (title: string, options: ArrowSelectOption[]) => Promise<string>) => {+ while (true) {+ const learningLabel = this.userMemory!.isLearningPaused() ? 'Resume Learning' : 'Pause Learning';+ const action = await sel('Memory', [+ { value: 'overview', label: 'Overview' },+ { value: 'recent', label: 'Recent Memories' },+ { value: 'search', label: 'Search' },+ { value: 'toggle', label: learningLabel },+ { value: 'clear', label: 'Clear All Memories' },+ { value: 'back', label: 'Back' },+ ]);++ if (action === 'back') return;++ if (action === 'overview') {+ await this.sendMemoryOverview(channel, channelId);+ continue;+ }++ if (action === 'recent') {+ const recent = this.userMemory!.getRecent(10);+ if (recent.length === 0) {+ await channel.send('No memories yet.', channelId);+ continue;+ }+ const lines = ['**Recent Memories:**', ''];+ for (const r of recent) {+ const scope = r.scope === 'active' ? '⏳' : '📌';+ const kind = r.evidenceKind === 'direct' ? 'direct' : r.evidenceKind === 'inferred' ? 'inferred' : r.evidenceKind;+ lines.push(`${scope} [${r.type}] ${r.summary}`);+ lines.push(` Confidence: ${r.confidence.toFixed(2)} | Evidence: ${kind} | Seen: ${r.evidenceCount}x`);+ }+ await channel.send(lines.join('\n'), channelId);+ continue;+ }++ if (action === 'search') {+ const query = await channel.prompt('Search memories: ');+ if (!query) continue;+ const results = this.userMemory!.search(query, 10);+ if (results.length === 0) {+ await channel.send(`No memories found matching "${query}".`, channelId);+ continue;+ }+ const lines = [`**Search results for "${query}":**`, ''];+ for (const r of results) {+ const scope = r.scope === 'active' ? '⏳' : '📌';+ lines.push(`${scope} [${r.type}] ${r.summary}`);+ lines.push(` Confidence: ${r.confidence.toFixed(2)} | Evidence: ${r.evidenceKind} | Seen: ${r.evidenceCount}x`);+ }+ await channel.send(lines.join('\n'), channelId);+ continue;+ }++ if (action === 'toggle') {+ const currentlyPaused = this.userMemory!.isLearningPaused();+ this.userMemory!.setLearningPaused(!currentlyPaused);+ await channel.send(currentlyPaused ? 'Learning resumed. Mercury will remember new things from conversations.' : 'Learning paused. Mercury will not store new memories until resumed.', channelId);+ continue;+ }++ if (action === 'clear') {+ const confirm = await sel('Clear all memories?', [+ { value: 'cancel', label: 'Cancel' },+ { value: 'confirm', label: 'Clear everything' },+ ]);+ if (confirm === 'confirm') {+ const cleared = this.userMemory!.clear();+ await channel.send(`Cleared ${cleared} memories.`, channelId);+ }+ continue;+ }+ }+ };++ if (select) {+ await runMenu(select);+ } else {+ await channel.withMenu(runMenu);+ }+ }+private async openCliTelegramMenu(channel: CLIChannel,channelId: string,diff --git a/src/index.ts b/src/index.tsindex 154e5639..d9d1d4ab 100644--- a/src/index.ts+++ b/src/index.ts@@ -29,6 +29,7 @@ import type { ProviderName } from './utils/config.js';import { logger } from './utils/logger.js';import { Identity } from './soul/identity.js';import { ShortTermMemory, LongTermMemory, EpisodicMemory } from './memory/store.js';+import { UserMemoryStore } from './memory/user-memory.js';import { ProviderRegistry } from './providers/registry.js';import { Agent } from './core/agent.js';import { Scheduler } from './core/scheduler.js';@@ -489,7 +490,14 @@ async function completeInitialTelegramPairing(config: MercuryConfig): Promise<voconst telegram = new TelegramChannel(config);try {await telegram.start();+ } catch (err: any) {+ console.log(chalk.red(`\n ✗ ${err.message || err}`));+ console.log('');+ await telegram.stop();+ return;+ }+ try {while (true) {const pairingCode = await ask(chalk.white(' Telegram Pairing Code: '));if (!pairingCode) {@@ -863,6 +871,21 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {const longTerm = new LongTermMemory(config);const episodic = new EpisodicMemory(config);+ let userMemory: UserMemoryStore | null = null;+ if (config.memory.secondBrain?.enabled !== false) {+ try {+ userMemory = new UserMemoryStore(config);+ if (!isDaemon) {+ console.log(chalk.dim(` Second brain: enabled (${userMemory.getSummary().total} existing memories)`));+ } else {+ logger.info({ total: userMemory.getSummary().total }, 'Second brain loaded');+ }+ } catch (err) {+ logger.warn({ err }, 'Second brain initialization failed, continuing without it');+ userMemory = null;+ }+ }+const channels = new ChannelRegistry(config);const capabilities = new CapabilityRegistry(skillLoader, scheduler, tokenBudget);@@ -872,6 +895,11 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {config: () => config,tokenBudget: () => tokenBudget,manual: () => getManual(),+ memorySummary: () => userMemory ? userMemory.getSummary() : { total: 0, byType: {}, learningPaused: false },+ memoryRecent: (limit?: number) => userMemory ? userMemory.getRecent(limit) : [],+ memorySearch: (query: string, limit?: number) => userMemory ? userMemory.search(query, limit) : [],+ memorySetLearningPaused: (paused: boolean) => { if (userMemory) userMemory.setLearningPaused(paused); },+ memoryClear: () => userMemory ? userMemory.clear() : 0,});capabilities.setSendFileHandler(async (filePath: string) => {@@ -914,7 +942,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {capabilities.registerAll();const agent = new Agent(- config, providers, identity, shortTerm, longTerm, episodic, channels, tokenBudget, capabilities, scheduler,+ config, providers, identity, shortTerm, longTerm, episodic, userMemory, channels, tokenBudget, capabilities, scheduler,);await agent.birth();@@ -923,6 +951,10 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {const cliChannel = channels.get('cli') as CLIChannel | undefined;const tgChannel = channels.get('telegram') as TelegramChannel | undefined;+ if (tgChannel) {+ tgChannel.setChatCommandContext(capabilities.getChatCommandContext()!);+ }+capabilities.permissions.onAsk(async (prompt: string) => {const channelType = capabilities.permissions.getCurrentChannelType();if (channelType === 'telegram' && tgChannel) {@@ -957,6 +989,12 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {} else {logger.info('Mercury is shutting down (daemon mode)');}+ if (userMemory) {+ try {+ userMemory.consolidate();+ userMemory.close();+ } catch {}+ }await agent.shutdown();process.exit(0);};diff --git a/src/memory/index.ts b/src/memory/index.tsindex cea6fc83..17a15cc7 100644--- a/src/memory/index.ts+++ b/src/memory/index.ts@@ -1,2 +1,6 @@export { ShortTermMemory, LongTermMemory, EpisodicMemory } from './store.js';-export type { MemoryEntry, LongTermFact, EpisodicEvent } from './store.js';\ No newline at end of file+export type { MemoryEntry, LongTermFact, EpisodicEvent } from './store.js';+export { UserMemoryStore } from './user-memory.js';+export type { UserMemoryType, UserMemoryRecord, UserMemoryCandidate, UserMemorySummary, RetrievedUserMemory } from './user-memory.js';+export { SecondBrainDB } from './second-brain-db.js';+export type { MemoryRow } from './second-brain-db.js';\ No newline at end of filediff --git a/src/memory/second-brain-db.ts b/src/memory/second-brain-db.tsnew file mode 100644index 00000000..15239a14--- /dev/null+++ b/src/memory/second-brain-db.ts@@ -0,0 +1,343 @@+import Database from 'better-sqlite3';+import { existsSync, mkdirSync } from 'node:fs';+import { dirname } from 'node:path';+import { logger } from '../utils/logger.js';++export interface MemoryRow {+ id: string;+ user_key: string;+ type: string;+ summary: string;+ detail: string | null;+ scope: string;+ evidence_kind: string;+ source: string;+ confidence: number;+ importance: number;+ durability: number;+ evidence_count: number;+ provenance: string | null;+ dismissed: number;+ superseded_by: string | null;+ created_at: number;+ updated_at: number;+ last_seen_at: number;+ last_used_at: number | null;+ last_used_query: string | null;+}++export class SecondBrainDB {+ private db: Database.Database;++ constructor(dbPath: string) {+ const dir = dirname(dbPath);+ if (!existsSync(dir)) {+ mkdirSync(dir, { recursive: true });+ }+ this.db = new Database(dbPath);+ this.db.pragma('journal_mode = WAL');+ this.db.pragma('synchronous = NORMAL');+ }++ init(): void {+ this.db.exec(`+ CREATE TABLE IF NOT EXISTS memories (+ id TEXT PRIMARY KEY,+ user_key TEXT NOT NULL,+ type TEXT NOT NULL,+ summary TEXT NOT NULL,+ detail TEXT,+ scope TEXT NOT NULL DEFAULT 'durable',+ evidence_kind TEXT NOT NULL DEFAULT 'inferred',+ source TEXT NOT NULL DEFAULT 'conversation',+ confidence REAL NOT NULL,+ importance REAL NOT NULL,+ durability REAL NOT NULL,+ evidence_count INTEGER NOT NULL DEFAULT 1,+ provenance TEXT,+ dismissed INTEGER NOT NULL DEFAULT 0,+ superseded_by TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ last_seen_at INTEGER NOT NULL,+ last_used_at INTEGER,+ last_used_query TEXT+ );++ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(+ summary, detail, content=memories, content_rowid=rowid+ );++ CREATE TABLE IF NOT EXISTS second_brain_meta (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+ );++ CREATE INDEX IF NOT EXISTS idx_memories_user_type ON memories(user_key, type);+ CREATE INDEX IF NOT EXISTS idx_memories_user_dismissed ON memories(user_key, dismissed);+ CREATE INDEX IF NOT EXISTS idx_memories_user_updated ON memories(user_key, updated_at);+ CREATE INDEX IF NOT EXISTS idx_memories_user_scope ON memories(user_key, scope);+ CREATE INDEX IF NOT EXISTS idx_memories_user_evidence_kind ON memories(user_key, evidence_kind);++ CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN+ INSERT INTO memories_fts(rowid, summary, detail) VALUES (new.rowid, new.summary, new.detail);+ END;++ CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN+ INSERT INTO memories_fts(memories_fts, rowid, summary, detail) VALUES('delete', old.rowid, old.summary, old.detail);+ END;++ CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN+ INSERT INTO memories_fts(memories_fts, rowid, summary, detail) VALUES('delete', old.rowid, old.summary, old.detail);+ INSERT INTO memories_fts(rowid, summary, detail) VALUES (new.rowid, new.summary, new.detail);+ END;+ `);++ this.db.pragma('foreign_keys = ON');+ logger.info('Second brain database initialized');+ }++ insert(row: Omit<MemoryRow, 'rowid'> & { rowid?: never }): void {+ const stmt = this.db.prepare(`+ INSERT INTO memories (+ id, user_key, type, summary, detail, scope, evidence_kind, source,+ confidence, importance, durability, evidence_count, provenance,+ dismissed, superseded_by, created_at, updated_at,+ last_seen_at, last_used_at, last_used_query+ ) VALUES (+ @id, @user_key, @type, @summary, @detail, @scope, @evidence_kind, @source,+ @confidence, @importance, @durability, @evidence_count, @provenance,+ @dismissed, @superseded_by, @created_at, @updated_at,+ @last_seen_at, @last_used_at, @last_used_query+ )+ `);+ stmt.run({+ id: row.id,+ user_key: row.user_key,+ type: row.type,+ summary: row.summary,+ detail: row.detail ?? null,+ scope: row.scope ?? 'durable',+ evidence_kind: row.evidence_kind ?? 'inferred',+ source: row.source ?? 'conversation',+ confidence: row.confidence,+ importance: row.importance,+ durability: row.durability,+ evidence_count: row.evidence_count ?? 1,+ provenance: row.provenance ?? null,+ dismissed: row.dismissed ?? 0,+ superseded_by: row.superseded_by ?? null,+ created_at: row.created_at,+ updated_at: row.updated_at,+ last_seen_at: row.last_seen_at,+ last_used_at: row.last_used_at ?? null,+ last_used_query: row.last_used_query ?? null,+ });+ }++ update(row: Partial<MemoryRow> & { id: string }): void {+ const fields: string[] = [];+ const values: Record<string, unknown> = { id: row.id };++ const allowedFields = [+ 'summary', 'detail', 'scope', 'evidence_kind', 'source',+ 'confidence', 'importance', 'durability', 'evidence_count',+ 'provenance', 'dismissed', 'superseded_by',+ 'updated_at', 'last_seen_at', 'last_used_at', 'last_used_query',+ ] as const;++ for (const field of allowedFields) {+ if (row[field] !== undefined) {+ fields.push(`${field} = @${field}`);+ values[field] = row[field];+ }+ }++ if (fields.length === 0) return;++ const stmt = this.db.prepare(`UPDATE memories SET ${fields.join(', ')} WHERE id = @id`);+ stmt.run(values);+ }++ getActive(userKey: string): MemoryRow[] {+ const stmt = this.db.prepare('SELECT * FROM memories WHERE user_key = ? AND dismissed = 0 ORDER BY updated_at DESC');+ return stmt.all(userKey) as MemoryRow[];+ }++ getById(id: string): MemoryRow | undefined {+ const stmt = this.db.prepare('SELECT * FROM memories WHERE id = ?');+ return stmt.get(id) as MemoryRow | undefined;+ }++ getByType(userKey: string, type: string): MemoryRow[] {+ const stmt = this.db.prepare('SELECT * FROM memories WHERE user_key = ? AND type = ? AND dismissed = 0 ORDER BY updated_at DESC');+ return stmt.all(userKey, type) as MemoryRow[];+ }++ findMergeCandidate(userKey: string, type: string, normalizedTerms: string[]): MemoryRow | undefined {+ const stmt = this.db.prepare(`+ SELECT * FROM memories WHERE user_key = ? AND type = ? AND dismissed = 0+ AND (summary LIKE ? OR ${normalizedTerms.map(() => 'summary LIKE ?').join(' OR ')})+ LIMIT 5+ `);+ const likeAny = normalizedTerms.map(t => `%${t}%`);+ const rows = stmt.all(userKey, type, `%${normalizedTerms.slice(0, 3).join('%')}%`, ...likeAny) as MemoryRow[];+ return rows.find(row => !this.rowHasNegationMismatch(row.summary, normalizedTerms));+ }++ findConflictCandidate(userKey: string, type: string, summaryTerms: string[]): MemoryRow | undefined {+ const stmt = this.db.prepare(`+ SELECT * FROM memories WHERE user_key = ? AND type = ? AND dismissed = 0+ AND (${summaryTerms.map(() => 'summary LIKE ?').join(' OR ')})+ LIMIT 5+ `);+ const likes = summaryTerms.map(t => `%${t}%`);+ const rows = stmt.all(userKey, type, ...likes) as MemoryRow[];+ return rows.find(row => this.rowHasNegationMismatch(row.summary, summaryTerms));+ }++ private rowHasNegationMismatch(existingSummary: string, incomingTerms: string[]): boolean {+ const lower = existingSummary.toLowerCase();+ const negationWords = ['not', 'never', 'no longer', 'avoid', 'against', 'disabled'];+ const hasNegation = negationWords.some(w => lower.includes(w));+ const incomingLower = incomingTerms.join(' ');+ const incomingHasNegation = negationWords.some(w => incomingLower.includes(w));+ return hasNegation !== incomingHasNegation;+ }++ searchRelevant(userKey: string, query: string, limit: number = 10): MemoryRow[] {+ const tokens = query.split(/\s+/).filter(t => t.length > 0).map(t => t.replace(/"/g, '""'));+ if (tokens.length === 0) {+ const stmt = this.db.prepare('SELECT * FROM memories WHERE user_key = ? AND dismissed = 0 ORDER BY updated_at DESC LIMIT ?');+ return stmt.all(userKey, limit) as MemoryRow[];+ }+ const ftsQuery = tokens.join(' OR ');+ const ftsStmt = this.db.prepare(`+ SELECT m.* FROM memories m+ JOIN memories_fts fts ON m.rowid = fts.rowid+ WHERE memories_fts MATCH ? AND m.user_key = ? AND m.dismissed = 0+ ORDER BY rank+ LIMIT ?+ `);+ try {+ return ftsStmt.all(ftsQuery, userKey, limit) as MemoryRow[];+ } catch {+ const likeClauses = tokens.map(() => '(summary LIKE ? OR detail LIKE ?)').join(' OR ');+ const stmt = this.db.prepare(`SELECT * FROM memories WHERE user_key = ? AND dismissed = 0 AND (${likeClauses}) ORDER BY updated_at DESC LIMIT ?`);+ const likes = tokens.flatMap(t => [`%${t}%`, `%${t}%`]);+ return stmt.all(userKey, ...likes, limit) as MemoryRow[];+ }+ }++ searchFTS(userKey: string, query: string, limit: number = 10): MemoryRow[] {+ return this.searchRelevant(userKey, query, limit);+ }++ softDelete(id: string): boolean {+ const stmt = this.db.prepare('UPDATE memories SET dismissed = 1, updated_at = ? WHERE id = ?');+ const result = stmt.run(Date.now(), id);+ return result.changes > 0;+ }++ clearByType(userKey: string, type?: string): number {+ if (type) {+ const stmt = this.db.prepare('UPDATE memories SET dismissed = 1, updated_at = ? WHERE user_key = ? AND type = ? AND dismissed = 0');+ const result = stmt.run(Date.now(), userKey, type);+ return result.changes;+ }+ const stmt = this.db.prepare('UPDATE memories SET dismissed = 1, updated_at = ? WHERE user_key = ? AND dismissed = 0');+ const result = stmt.run(Date.now(), userKey);+ return result.changes;+ }++ hardDeleteDismissed(userKey: string): number {+ const stmt = this.db.prepare('DELETE FROM memories WHERE user_key = ? AND dismissed = 1');+ const result = stmt.run(userKey);+ return result.changes;+ }++ promoteToDurable(userKey: string): number {+ const stmt = this.db.prepare(`+ UPDATE memories SET scope = 'durable', updated_at = ?+ WHERE user_key = ? AND scope = 'active' AND dismissed = 0+ AND evidence_count >= 3 AND evidence_kind IN ('direct', 'manual')+ `);+ const result = stmt.run(Date.now(), userKey);+ return result.changes;+ }++ pruneStale(userKey: string): { activePruned: number; durablePruned: number } {+ const now = Date.now();+ const twentyOneDays = 21 * 24 * 60 * 60 * 1000;+ const fortyTwoDays = 42 * 24 * 60 * 60 * 1000;+ const oneHundredTwentyDays = 120 * 24 * 60 * 60 * 1000;++ const activeInferred = this.db.prepare(`+ UPDATE memories SET dismissed = 1, updated_at = ?+ WHERE user_key = ? AND scope = 'active' AND evidence_kind = 'inferred' AND dismissed = 0+ AND last_seen_at < ? AND last_seen_at > 0+ `);+ const activeInferredResult = activeInferred.run(now, userKey, now - twentyOneDays);++ const activeDirect = this.db.prepare(`+ UPDATE memories SET dismissed = 1, updated_at = ?+ WHERE user_key = ? AND scope = 'active' AND evidence_kind = 'direct' AND dismissed = 0+ AND last_seen_at < ? AND last_seen_at > 0+ `);+ const activeDirectResult = activeDirect.run(now, userKey, now - fortyTwoDays);++ const activePruned = activeInferredResult.changes + activeDirectResult.changes;++ const durableInferred = this.db.prepare(`+ UPDATE memories SET confidence = MAX(0.15, confidence - 0.15), updated_at = ?+ WHERE user_key = ? AND scope = 'durable' AND evidence_kind = 'inferred' AND dismissed = 0+ AND last_seen_at < ? AND last_seen_at > 0+ `);+ durableInferred.run(now, userKey, now - oneHundredTwentyDays);++ const durablePruned = this.db.prepare(`+ UPDATE memories SET dismissed = 1, updated_at = ?+ WHERE user_key = ? AND scope = 'durable' AND dismissed = 0+ AND confidence < 0.3 AND last_seen_at < ? AND last_seen_at > 0+ `);+ const durablePrunedResult = durablePruned.run(now, userKey, now - oneHundredTwentyDays);++ return { activePruned, durablePruned: durablePrunedResult.changes };+ }++ setMeta(key: string, value: string): void {+ const stmt = this.db.prepare('INSERT OR REPLACE INTO second_brain_meta (key, value) VALUES (@key, @value)');+ stmt.run({ key, value });+ }++ getMeta(key: string): string | null {+ const stmt = this.db.prepare('SELECT value FROM second_brain_meta WHERE key = ?');+ const row = stmt.get(key) as { value: string } | undefined;+ return row?.value ?? null;+ }++ deleteMeta(key: string): void {+ const stmt = this.db.prepare('DELETE FROM second_brain_meta WHERE key = ?');+ stmt.run(key);+ }++ countByType(userKey: string): Record<string, number> {+ const stmt = this.db.prepare("SELECT type, COUNT(*) as count FROM memories WHERE user_key = ? AND dismissed = 0 GROUP BY type");+ const rows = stmt.all(userKey) as Array<{ type: string; count: number }>;+ const result: Record<string, number> = {};+ for (const row of rows) {+ result[row.type] = row.count;+ }+ return result;+ }++ totalActive(userKey: string): number {+ const stmt = this.db.prepare('SELECT COUNT(*) as count FROM memories WHERE user_key = ? AND dismissed = 0');+ const row = stmt.get(userKey) as { count: number };+ return row.count;+ }++ close(): void {+ this.db.close();+ }+}\ No newline at end of filediff --git a/src/memory/user-memory.test.ts b/src/memory/user-memory.test.tsnew file mode 100644index 00000000..8df53982--- /dev/null+++ b/src/memory/user-memory.test.ts@@ -0,0 +1,237 @@+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { getDefaultConfig } from '../utils/config.js';+import { UserMemoryStore } from './user-memory.js';++const tempDirs: string[] = [];++function createStore(): UserMemoryStore {+ const dir = mkdtempSync(join(tmpdir(), 'mercury-sb-'));+ tempDirs.push(dir);+ const config = getDefaultConfig();+ config.memory.dir = dir;+ config.memory.secondBrain = { enabled: true, maxRecords: 50, dbPath: join(dir, 'second-brain', 'second-brain.db') };+ const store = new UserMemoryStore(config);+ return store;+}++afterEach(() => {+ while (tempDirs.length > 0) {+ const dir = tempDirs.pop()!;+ try {+ rmSync(dir, { recursive: true, force: true });+ } catch {}+ }+});++describe('UserMemoryStore', () => {+ it('merges similar durable memories instead of duplicating them', () => {+ const store = createStore();++ store.remember([+ { type: 'preference', summary: 'User prefers concise answers.', confidence: 0.9, importance: 0.8, durability: 0.9 },+ ]);++ store.remember([+ { type: 'preference', summary: 'User prefers concise technical answers.', confidence: 0.94, importance: 0.81, durability: 0.92 },+ ]);++ const recent = store.getRecent();+ expect(recent).toHaveLength(1);+ expect(recent[0].evidenceCount).toBe(2);+ expect(recent[0].summary).toContain('concise');+ });++ it('retrieves only relevant records for a query', () => {+ const store = createStore();++ store.remember([+ { type: 'project', summary: 'User is building Mercury as a personal AI agent.', confidence: 0.95, importance: 0.9, durability: 0.95 },+ ]);+ store.remember([+ { type: 'preference', summary: 'User prefers concise answers.', confidence: 0.95, importance: 0.75, durability: 0.9 },+ ]);+ store.consolidate();++ const result = store.retrieveRelevant('Plan Mercury architecture', { maxRecords: 3, maxChars: 500 });++ expect(result.records).toHaveLength(1);+ expect(result.records[0].type).toBe('project');+ expect(result.context).toContain('Mercury');+ });++ it('auto-resolves conflicts by dismissing the lower-confidence memory', () => {+ const store = createStore();++ store.remember([+ { type: 'preference', summary: 'User prefers concise answers.', confidence: 0.96, importance: 0.84, durability: 0.92 },+ ]);++ store.remember([+ { type: 'preference', summary: 'User does not prefer concise answers.', confidence: 0.88, importance: 0.82, durability: 0.88 },+ ]);++ const recent = store.getRecent();+ const active = recent.filter(r => !r.dismissed);+ expect(active).toHaveLength(1);+ expect(active[0].summary).toContain('concise answers');+ expect(active[0].summary).not.toContain('does not');+ });++ it('auto-resolves conflicts when incoming has higher confidence', () => {+ const store = createStore();++ store.remember([+ { type: 'preference', summary: 'User prefers verbose answers.', confidence: 0.75, importance: 0.7, durability: 0.7 },+ ]);++ store.remember([+ { type: 'preference', summary: 'User does not prefer verbose answers.', confidence: 0.95, importance: 0.9, durability: 0.9 },+ ]);++ const recent = store.getRecent();+ const active = recent.filter(r => !r.dismissed);+ expect(active).toHaveLength(1);+ expect(active[0].summary).toContain('does not prefer verbose');+ });++ it('synthesizes a compact profile and reflection records from repeated signal', () => {+ const store = createStore();++ store.remember([+ { type: 'identity', summary: 'User is building Mercury.', confidence: 0.96, importance: 0.92, durability: 0.95 },+ ]);+ store.remember([+ { type: 'preference', summary: 'User prefers concise technical answers.', confidence: 0.96, importance: 0.84, durability: 0.92 },+ ]);+ store.remember([+ { type: 'preference', summary: 'User prefers practical implementation details.', confidence: 0.95, importance: 0.82, durability: 0.9 },+ ]);+ store.remember([+ { type: 'goal', summary: 'User wants Mercury to become a second brain.', confidence: 0.97, importance: 0.95, durability: 0.94 },+ ]);++ const result = store.consolidate();+ const summary = store.getSummary();+ const recent = store.getRecent(10);+ const reflections = recent.filter(r => r.type === 'reflection');++ expect(result.reflectionCount).toBeGreaterThan(0);+ expect(summary.profileSummary).toContain('Mercury');+ expect(summary.profileSummary).toContain('concise');+ expect(reflections.length).toBeGreaterThan(0);+ });++ it('separates active state from durable profile', () => {+ const store = createStore();++ store.remember([+ { type: 'project', summary: 'User is building Mercury memory architecture this week.', confidence: 0.96, importance: 0.91, durability: 0.82 },+ ]);+ store.remember([+ { type: 'goal', summary: 'User wants Mercury to become a second brain.', confidence: 0.97, importance: 0.95, durability: 0.93 },+ ]);+ store.remember([+ { type: 'preference', summary: 'User prefers concise answers.', confidence: 0.96, importance: 0.82, durability: 0.92 },+ ]);+ store.remember([+ { type: 'preference', summary: 'User does not prefer concise answers.', confidence: 0.95, importance: 0.82, durability: 0.9 },+ ]);+ store.consolidate();++ const summary = store.getSummary();+ const active = store.getActiveSummary();++ expect(active).toContain('Mercury memory architecture');+ expect(summary.profileSummary).toContain('second brain');+ });++ it('supports pause and resume of learning', () => {+ const store = createStore();++ expect(store.isLearningPaused()).toBe(false);++ store.setLearningPaused(true);+ expect(store.isLearningPaused()).toBe(true);++ store.remember([+ { type: 'goal', summary: 'User wants autonomous learning.', confidence: 0.95, importance: 0.92, durability: 0.88 },+ ]);+ expect(store.getSummary().total).toBe(0);++ store.setLearningPaused(false);+ store.remember([+ { type: 'goal', summary: 'User wants autonomous learning.', confidence: 0.95, importance: 0.92, durability: 0.88 },+ ]);+ expect(store.getSummary().total).toBe(1);+ });++ it('clears all memories', () => {+ const store = createStore();++ store.remember([+ { type: 'identity', summary: 'User is a software developer.', confidence: 0.95, importance: 0.9, durability: 0.9 },+ ]);+ store.remember([+ { type: 'preference', summary: 'User prefers dark mode.', confidence: 0.9, importance: 0.75, durability: 0.85 },+ ]);++ expect(store.getSummary().total).toBe(2);++ const cleared = store.clear();+ expect(cleared).toBe(2);+ expect(store.getSummary().total).toBe(0);+ });++ it('full-text search finds relevant memories', () => {+ const store = createStore();++ store.remember([+ { type: 'project', summary: 'User is building a personal knowledge management system.', confidence: 0.95, importance: 0.9, durability: 0.9 },+ ]);+ store.remember([+ { type: 'preference', summary: 'User prefers tea over coffee.', confidence: 0.8, importance: 0.5, durability: 0.7 },+ ]);++ const results = store.search('knowledge management');+ expect(results.length).toBeGreaterThanOrEqual(1);+ expect(results[0].summary).toContain('knowledge management');+ });++ it('deprioritizes stale inferred memories in retrieval', () => {+ const store = createStore();++ const [inferred] = store.remember([+ { type: 'goal', summary: 'User may be exploring memory tooling.', confidence: 0.88, importance: 0.84, durability: 0.82, evidenceKind: 'inferred' },+ ]);+ const [direct] = store.remember([+ { type: 'goal', summary: 'User explicitly wants Mercury to become a second brain.', confidence: 0.9, importance: 0.9, durability: 0.9, evidenceKind: 'direct' },+ ]);++ store.consolidate();+ const summary = store.getSummary();+ expect(summary.profileSummary).toContain('second brain');+ });++ it('stores weak memories that pass minimum threshold', () => {+ const store = createStore();++ store.remember([+ { type: 'habit', summary: 'User seems to work on projects late evenings.', confidence: 0.58, importance: 0.6, durability: 0.6, evidenceKind: 'inferred' },+ ]);++ expect(store.getSummary().total).toBe(1);+ });++ it('rejects memories below minimum confidence', () => {+ const store = createStore();++ store.remember([+ { type: 'habit', summary: 'Too uncertain to store.', confidence: 0.3, importance: 0.4, durability: 0.4 },+ ]);++ expect(store.getSummary().total).toBe(0);+ });+});\ No newline at end of filediff --git a/src/memory/user-memory.ts b/src/memory/user-memory.tsnew file mode 100644index 00000000..7899a91c--- /dev/null+++ b/src/memory/user-memory.ts@@ -0,0 +1,698 @@+import type { MercuryConfig } from '../utils/config.js';+import { SecondBrainDB, type MemoryRow } from './second-brain-db.js';+import { join } from 'node:path';+import { logger } from '../utils/logger.js';++export type UserMemoryType =+ | 'identity'+ | 'preference'+ | 'goal'+ | 'project'+ | 'habit'+ | 'decision'+ | 'constraint'+ | 'relationship'+ | 'episode'+ | 'reflection';++export interface UserMemoryRecord {+ id: string;+ type: UserMemoryType;+ summary: string;+ detail?: string | null;+ scope: 'durable' | 'active';+ evidenceKind: 'direct' | 'inferred' | 'manual' | 'system';+ source: 'conversation' | 'system';+ confidence: number;+ importance: number;+ durability: number;+ evidenceCount: number;+ provenance?: string | null;+ dismissed: boolean;+ supersededBy?: string | null;+ createdAt: number;+ updatedAt: number;+ lastSeenAt: number;+ lastUsedAt?: number | null;+ lastUsedQuery?: string | null;+}++export interface UserMemoryCandidate {+ type: UserMemoryType;+ summary: string;+ detail?: string;+ evidenceKind?: 'direct' | 'inferred';+ confidence: number;+ importance: number;+ durability: number;+}++export interface UserMemorySummary {+ total: number;+ byType: Partial<Record<UserMemoryType, number>>;+ learningPaused: boolean;+ profileSummary?: string;+ activeSummary?: string;+}++export interface RetrievedUserMemory {+ records: UserMemoryRecord[];+ context: string;+}++const MIN_CONFIDENCE = 0.55;++export class UserMemoryStore {+ private db: SecondBrainDB;+ private maxRecords: number;+ private userKey: string;+ private consolidateThrottleMs: number;+ private lastConsolidateAt: number = 0;++ constructor(config: MercuryConfig, userKey: string = 'user:owner') {+ this.userKey = userKey;+ this.maxRecords = config.memory.secondBrain?.maxRecords ?? 50;+ this.consolidateThrottleMs = 5 * 60 * 1000; // 5 minutes+ const dbPath = config.memory.secondBrain?.dbPath+ ?? join(config.memory.dir, 'second-brain', 'second-brain.db');+ this.db = new SecondBrainDB(dbPath);+ this.db.init();+ }++ getSummary(): UserMemorySummary {+ const byType = this.db.countByType(this.userKey) as Partial<Record<UserMemoryType, number>>;+ return {+ total: this.db.totalActive(this.userKey),+ byType,+ learningPaused: this.isLearningPaused(),+ profileSummary: this.db.getMeta(`${this.userKey}:profile_summary`) ?? undefined,+ activeSummary: this.db.getMeta(`${this.userKey}:active_summary`) ?? undefined,+ };+ }++ getProfile(): string {+ return this.db.getMeta(`${this.userKey}:profile_summary`) || '';+ }++ getActiveSummary(): string {+ return this.db.getMeta(`${this.userKey}:active_summary`) || '';+ }++ getRecent(limit: number = 10): UserMemoryRecord[] {+ const stmt = this.db.getActive(this.userKey).slice(0, limit);+ return stmt.map(row => this.toRecord(row));+ }++ search(query: string, limit: number = 10): UserMemoryRecord[] {+ const rows = this.db.searchFTS(this.userKey, query, limit);+ return rows.map(row => this.toRecord(row));+ }++ getByType(type: UserMemoryType): UserMemoryRecord[] {+ const rows = this.db.getByType(this.userKey, type);+ return rows.map(row => this.toRecord(row));+ }++ retrieveRelevant(+ query: string,+ options?: { maxRecords?: number; maxChars?: number },+ ): RetrievedUserMemory {+ const maxRecords = options?.maxRecords ?? 5;+ const maxChars = options?.maxChars ?? 900;++ const ftsResults = this.db.searchRelevant(this.userKey, query, Math.max(maxRecords * 2, 10));+ const ranked = this.scoreAndRank(ftsResults, query);++ const selected: MemoryRow[] = [];+ let currentLength = 0;+ for (const row of ranked) {+ const line = `- [${row.type}] ${row.summary}`;+ if (selected.length >= maxRecords) break;+ if (selected.length > 0 && currentLength + line.length > maxChars) break;+ selected.push(row);+ currentLength += line.length + 1;+ }++ if (selected.length === 0) {+ const profile = this.getProfile().trim();+ if (!profile) {+ return { records: [], context: '' };+ }+ return {+ records: [],+ context: [+ this.getActiveSummary() ? `User active state:\n- ${this.getActiveSummary()}` : '',+ `User profile summary:\n- ${profile}`,+ ].filter(Boolean).join('\n\n'),+ };+ }++ const contextLines: string[] = [];+ const activeSummary = this.getActiveSummary();+ if (activeSummary) {+ contextLines.push('User active state:');+ contextLines.push(`- ${activeSummary}`);+ contextLines.push('');+ }+ const profileSummary = this.getProfile();+ if (profileSummary) {+ contextLines.push('User profile summary:');+ contextLines.push(`- ${profileSummary}`);+ contextLines.push('');+ }+ contextLines.push('Relevant user memory:');+ contextLines.push(...selected.map(row => `- [${row.type}] ${row.summary}`));++ this.markUsed(selected.map(r => r.id), query);+ return { records: selected.map(r => this.toRecord(r)), context: contextLines.join('\n') };+ }++ remember(+ candidates: UserMemoryCandidate[],+ source: UserMemoryRecord['source'] = 'conversation',+ ): UserMemoryRecord[] {+ if (this.isLearningPaused()) return [];++ const remembered: UserMemoryRecord[] = [];++ for (const candidate of candidates) {+ if (!shouldStoreCandidate(candidate)) continue;++ const terms = normalize(candidate.summary).split(/\s+/).filter(t => t.length > 2);++ const mergeTarget = this.db.findMergeCandidate(this.userKey, candidate.type, terms);+ if (mergeTarget && overlapScore(normalize(mergeTarget.summary), normalize(candidate.summary)) >= 0.74) {+ const merged = this.mergeRecord(mergeTarget, candidate);+ if (merged) remembered.push(merged);+ continue;+ }++ const conflictTarget = this.db.findConflictCandidate(this.userKey, candidate.type, terms);+ if (conflictTarget) {+ const conflictWinner = this.resolveConflict(conflictTarget, candidate);+ if (conflictWinner === 'existing') continue;+ }++ const record = this.insertRecord(candidate, source);+ if (record) remembered.push(record);+ }++ this.enforceMaxRecords();++ return remembered;+ }++ setLearningPaused(paused: boolean): void {+ this.db.setMeta(`${this.userKey}:learning_paused`, paused ? '1' : '0');+ }++ isLearningPaused(): boolean {+ return this.db.getMeta(`${this.userKey}:learning_paused`) === '1';+ }++ clear(): number {+ return this.db.clearByType(this.userKey);+ }++ consolidate(): { profileUpdated: boolean; reflectionCount: number } {+ const now = Date.now();+ if (now - this.lastConsolidateAt < this.consolidateThrottleMs && this.lastConsolidateAt > 0) {+ return { profileUpdated: false, reflectionCount: 0 };+ }+ this.lastConsolidateAt = now;++ const allActive = this.db.getActive(this.userKey);+ const nonReflection = allActive.filter(r => r.type !== 'reflection');++ const profileSummary = buildProfileSummary(nonReflection);+ const activeSummary = buildActiveSummary(nonReflection);++ const oldProfile = this.db.getMeta(`${this.userKey}:profile_summary`) || '';+ const oldActive = this.db.getMeta(`${this.userKey}:active_summary`) || '';+ const profileUpdated = profileSummary !== oldProfile || activeSummary !== oldActive;++ this.db.setMeta(`${this.userKey}:profile_summary`, profileSummary);+ this.db.setMeta(`${this.userKey}:active_summary`, activeSummary);++ const reflections = buildReflectionCandidates(nonReflection);+ let reflectionCount = 0;+ for (const reflection of reflections) {+ const sameType = this.db.getByType(this.userKey, 'reflection');+ const existing = findMergeTarget(sameType, reflection);+ if (existing) {+ this.db.update({+ id: existing.id,+ summary: reflection.summary,+ detail: reflection.detail || existing.detail,+ confidence: clamp(Math.max(existing.confidence, reflection.confidence), 0, 1),+ importance: clamp(Math.max(existing.importance, reflection.importance), 0, 1),+ durability: clamp(Math.max(existing.durability, reflection.durability), 0, 1),+ updated_at: Date.now(),+ last_seen_at: Date.now(),+ });+ } else {+ this.insertReflection(reflection);+ }+ reflectionCount += 1;+ }++ return { profileUpdated, reflectionCount };+ }++ prune(): { activePruned: number; durablePruned: number; promoted: number } {+ const promoted = this.db.promoteToDurable(this.userKey);+ const { activePruned, durablePruned } = this.db.pruneStale(this.userKey);+ const hardDeleted = this.db.hardDeleteDismissed(this.userKey);+ if (hardDeleted > 0) {+ logger.debug({ hardDeleted, userKey: this.userKey }, 'Hard deleted dismissed memories');+ }+ return { activePruned, durablePruned, promoted };+ }++ close(): void {+ this.db.close();+ }++ private insertRecord(candidate: UserMemoryCandidate, source: UserMemoryRecord['source']): UserMemoryRecord | null {+ const now = Date.now();+ const id = generateId('mem');+ const scope = inferScope(candidate);++ this.db.insert({+ id,+ user_key: this.userKey,+ type: candidate.type,+ summary: candidate.summary.trim(),+ detail: candidate.detail?.trim() ?? null,+ scope,+ evidence_kind: candidate.evidenceKind || (source === 'conversation' ? 'inferred' : 'system'),+ source,+ confidence: clamp(candidate.confidence, 0, 1),+ importance: clamp(candidate.importance, 0, 1),+ durability: clamp(candidate.durability, 0, 1),+ evidence_count: 1,+ provenance: candidate.detail?.trim() ?? null,+ dismissed: 0,+ superseded_by: null,+ created_at: now,+ updated_at: now,+ last_seen_at: now,+ last_used_at: null,+ last_used_query: null,+ });++ const row = this.db.getById(id);+ return row ? this.toRecord(row) : null;+ }++ private insertReflection(candidate: UserMemoryCandidate): void {+ const now = Date.now();+ const id = generateId('mem');++ this.db.insert({+ id,+ user_key: this.userKey,+ type: 'reflection',+ summary: candidate.summary,+ detail: candidate.detail ?? null,+ scope: 'durable',+ evidence_kind: 'system',+ source: 'system',+ confidence: candidate.confidence,+ importance: candidate.importance,+ durability: candidate.durability,+ evidence_count: 1,+ provenance: null,+ dismissed: 0,+ superseded_by: null,+ created_at: now,+ updated_at: now,+ last_seen_at: now,+ last_used_at: null,+ last_used_query: null,+ });+ }++ private mergeRecord(existing: MemoryRow, candidate: UserMemoryCandidate): UserMemoryRecord | null {+ const updatedAt = Date.now();+ this.db.update({+ id: existing.id,+ summary: pickBetterSummary(existing.summary, candidate.summary),+ detail: candidate.detail || existing.detail,+ provenance: candidate.detail || existing.provenance,+ evidence_kind: candidate.evidenceKind || existing.evidence_kind,+ confidence: clamp(Math.max(existing.confidence, candidate.confidence), 0, 1),+ importance: clamp(Math.max(existing.importance, candidate.importance), 0, 1),+ durability: clamp(Math.max(existing.durability, candidate.durability), 0, 1),+ evidence_count: existing.evidence_count + 1,+ updated_at: updatedAt,+ last_seen_at: updatedAt,+ });++ const row = this.db.getById(existing.id);+ return row ? this.toRecord(row) : null;+ }++ private resolveConflict(existing: MemoryRow, candidate: UserMemoryCandidate): 'incoming' | 'existing' {+ const incomingConfidence = candidate.confidence;+ const existingConfidence = existing.confidence;++ if (incomingConfidence > existingConfidence) {+ this.db.update({+ id: existing.id,+ dismissed: 1,+ superseded_by: 'auto_resolved',+ updated_at: Date.now(),+ });+ logger.debug(+ { existingId: existing.id, existingConfidence, incomingConfidence, type: candidate.type },+ 'Auto-resolved conflict: incoming wins',+ );+ return 'incoming';+ }++ if (incomingConfidence < existingConfidence) {+ logger.debug(+ { existingId: existing.id, existingConfidence, incomingConfidence, type: candidate.type },+ 'Auto-resolved conflict: existing wins',+ );+ return 'existing';+ }++ this.db.update({+ id: existing.id,+ dismissed: 1,+ superseded_by: 'auto_resolved',+ updated_at: Date.now(),+ });+ logger.debug(+ { existingId: existing.id, type: candidate.type },+ 'Auto-resolved conflict: equal confidence, newer wins',+ );+ return 'incoming';+ }++ private enforceMaxRecords(): void {+ const total = this.db.totalActive(this.userKey);+ if (total <= this.maxRecords) return;++ const allActive = this.db.getActive(this.userKey);+ const toDismiss = allActive+ .sort((a, b) => memoryHealthScore(b) - memoryHealthScore(a))+ .slice(this.maxRecords);++ for (const row of toDismiss) {+ this.db.softDelete(row.id);+ }++ if (toDismiss.length > 0) {+ logger.debug({ dismissed: toDismiss.length, userKey: this.userKey }, 'Enforced max records limit');+ }+ }++ private markUsed(ids: string[], query?: string): void {+ const now = Date.now();+ for (const id of ids) {+ this.db.update({+ id,+ last_used_at: now,+ last_used_query: query || undefined,+ updated_at: now,+ });+ }+ }++ private scoreAndRank(rows: MemoryRow[], query: string): MemoryRow[] {+ const now = Date.now();+ const tokens = query.toLowerCase().split(/\s+/).filter(t => t.length > 0);+ return rows+ .map(row => {+ let score = 0;+ score += row.confidence * 0.3;+ score += row.importance * 0.25;+ score += row.durability * 0.15;+ const ageDays = (now - row.updated_at) / (1000 * 60 * 60 * 24);+ score += Math.max(0, 0.2 - ageDays * 0.005);+ const lower = (row.summary + ' ' + (row.detail ?? '')).toLowerCase();+ const matchCount = tokens.filter(t => lower.includes(t)).length;+ score += (matchCount / Math.max(tokens.length, 1)) * 0.1;+ return { row, score };+ })+ .sort((a, b) => b.score - a.score)+ .map(r => r.row);+ }++ private toRecord(row: MemoryRow): UserMemoryRecord {+ return {+ id: row.id,+ type: row.type as UserMemoryType,+ summary: row.summary,+ detail: row.detail,+ scope: row.scope as 'durable' | 'active',+ evidenceKind: row.evidence_kind as UserMemoryRecord['evidenceKind'],+ source: row.source as UserMemoryRecord['source'],+ confidence: row.confidence,+ importance: row.importance,+ durability: row.durability,+ evidenceCount: row.evidence_count,+ provenance: row.provenance,+ dismissed: row.dismissed === 1,+ supersededBy: row.superseded_by,+ createdAt: row.created_at,+ updatedAt: row.updated_at,+ lastSeenAt: row.last_seen_at,+ lastUsedAt: row.last_used_at,+ lastUsedQuery: row.last_used_query,+ };+ }+}++function shouldStoreCandidate(candidate: UserMemoryCandidate): boolean {+ const summary = candidate.summary.trim();+ if (summary.length < 12 || summary.length > 220) return false;+ if (candidate.confidence < MIN_CONFIDENCE) return false;+ if (candidate.durability < 0.4 && candidate.importance < 0.7) return false;+ return true;+}++function findMergeTarget(rows: MemoryRow[], candidate: UserMemoryCandidate): MemoryRow | undefined {+ const normalizedCandidate = normalize(candidate.summary);+ return rows.find(row => {+ if (row.type !== candidate.type) return false;+ if (hasConflict(row.summary, candidate.summary)) return false;+ const normalizedRow = normalize(row.summary);+ if (normalizedRow === normalizedCandidate) return true;+ return overlapScore(normalizedRow, normalizedCandidate) >= 0.74;+ });+}++function memoryHealthScore(row: MemoryRow): number {+ return (row.importance * 0.35)+ + (row.durability * 0.25)+ + (effectiveConfidence(row) * 0.25)+ + (Math.min(row.evidence_count, 5) / 5 * 0.15)+ + (row.scope === 'active' ? 0.08 : 0)+ - (row.superseded_by ? 0.3 : 0)+ - (isRowStale(row) ? 0.12 : 0);+}++function effectiveConfidence(row: MemoryRow): number {+ const ageDays = (Date.now() - row.updated_at) / (1000 * 60 * 60 * 24);+ let confidence = row.confidence;++ if (row.evidence_kind === 'inferred') {+ confidence -= Math.min(0.2, ageDays / 365);+ } else if (row.evidence_kind === 'manual') {+ confidence += 0.06;+ } else if (row.evidence_kind === 'direct') {+ confidence += 0.03;+ }++ if (row.scope === 'active') {+ confidence -= Math.min(0.18, ageDays / 120);+ }++ return clamp(confidence, 0, 1);+}++function isRowStale(row: MemoryRow): boolean {+ const ageDays = (Date.now() - row.updated_at) / (1000 * 60 * 60 * 24);+ if (row.scope === 'active') {+ return ageDays > 21;+ }+ if (row.evidence_kind === 'inferred') {+ return ageDays > 120;+ }+ return ageDays > 365;+}++function tokenize(input: string): string[] {+ return input+ .toLowerCase()+ .split(/[^a-z0-9]+/i)+ .map(term => term.trim())+ .filter(term => term.length >= 3);+}++function normalize(input: string): string {+ return tokenize(input).join(' ');+}++function overlapScore(a: string, b: string): number {+ const aTerms = new Set(a.split(' ').filter(Boolean));+ const bTerms = new Set(b.split(' ').filter(Boolean));+ if (aTerms.size === 0 || bTerms.size === 0) return 0;++ let overlap = 0;+ for (const term of aTerms) {+ if (bTerms.has(term)) overlap += 1;+ }+ return overlap / Math.max(aTerms.size, bTerms.size);+}++function pickBetterSummary(existing: string, incoming: string): string {+ return incoming.length > existing.length && incoming.length <= 220 ? incoming.trim() : existing.trim();+}++function clamp(value: number, min: number, max: number): number {+ return Math.max(min, Math.min(max, value));+}++function generateId(prefix: string): string {+ return `${prefix}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;+}++function inferScope(candidate: UserMemoryCandidate): 'durable' | 'active' {+ if (['goal', 'project', 'decision', 'episode'].includes(candidate.type)) {+ return 'active';+ }+ return 'durable';+}++function hasConflict(a: string, b: string): boolean {+ const left = a.toLowerCase();+ const right = b.toLowerCase();+ if (left === right) return false;++ const polarityPairs = [+ ['prefers', 'does not prefer'],+ ['likes', 'does not like'],+ ['wants', 'does not want'],+ ['is building', 'is not building'],+ ['uses', 'does not use'],+ ['enabled', 'disabled'],+ ];++ for (const [positive, negative] of polarityPairs) {+ const leftPosRightNeg = left.includes(positive) && right.includes(negative);+ const leftNegRightPos = left.includes(negative) && right.includes(positive);+ if (leftPosRightNeg || leftNegRightPos) {+ return overlapScore(+ normalize(left.replace(positive, '').replace(negative, '')),+ normalize(right.replace(positive, '').replace(negative, '')),+ ) >= 0.5;+ }+ }++ const leftHasNegation = /\b(not|never|no longer|avoid|against|disabled)\b/.test(left);+ const rightHasNegation = /\b(not|never|no longer|avoid|against|disabled)\b/.test(right);+ if (leftHasNegation !== rightHasNegation) {+ return overlapScore(normalize(left), normalize(right)) >= 0.7;+ }++ return false;+}++function buildProfileSummary(records: MemoryRow[]): string {+ const selected: string[] = [];+ const preferredTypes: string[] = ['identity', 'preference', 'goal', 'project', 'constraint', 'habit'];++ for (const type of preferredTypes) {+ const match = records+ .filter(r => r.type === type)+ .sort((a, b) => memoryHealthScore(b) - memoryHealthScore(a))[0];+ if (match && !selected.includes(match.summary)) {+ selected.push(match.summary);+ }+ if (selected.length >= 4) break;+ }++ return selected.join(' ').slice(0, 420).trim();+}++function buildActiveSummary(records: MemoryRow[]): string {+ const cutoff = Date.now() - (14 * 24 * 60 * 60 * 1000);+ const activeCandidates = records+ .filter(r => !r.superseded_by)+ .filter(r => !isRowStale(r))+ .filter(r => r.updated_at >= cutoff)+ .filter(r => ['goal', 'project', 'decision', 'episode'].includes(r.type))+ .sort((a, b) => {+ const byUpdated = b.updated_at - a.updated_at;+ if (byUpdated !== 0) return byUpdated;+ return memoryHealthScore(b) - memoryHealthScore(a);+ })+ .slice(0, 3)+ .map(r => r.summary);+ return activeCandidates.join(' ').slice(0, 360).trim();+}++function buildReflectionCandidates(records: MemoryRow[]): UserMemoryCandidate[] {+ const candidates: UserMemoryCandidate[] = [];+ const groups = new Map<string, MemoryRow[]>();++ for (const record of records) {+ if (!groups.has(record.type)) groups.set(record.type, []);+ groups.get(record.type)!.push(record);+ }++ const prefGroup = groups.get('preference') || [];+ if (prefGroup.length >= 2) {+ const top = prefGroup+ .sort((a, b) => memoryHealthScore(b) - memoryHealthScore(a))+ .slice(0, 2)+ .map(r => r.summary);+ candidates.push({+ type: 'reflection',+ summary: `User consistently shows these preferences: ${top.join(' ')}`.slice(0, 220),+ detail: top.join('\n'),+ confidence: 0.86,+ importance: 0.86,+ durability: 0.9,+ });+ }++ const goalProjectGroup = [...(groups.get('goal') || []), ...(groups.get('project') || [])];+ if (goalProjectGroup.length >= 2) {+ const top = goalProjectGroup+ .sort((a, b) => memoryHealthScore(b) - memoryHealthScore(a))+ .slice(0, 2)+ .map(r => r.summary);+ candidates.push({+ type: 'reflection',+ summary: `Current long-term direction: ${top.join(' ')}`.slice(0, 220),+ detail: top.join('\n'),+ confidence: 0.84,+ importance: 0.9,+ durability: 0.86,+ });+ }++ const habitConstraintGroup = [...(groups.get('habit') || []), ...(groups.get('constraint') || [])];+ if (habitConstraintGroup.length >= 2) {+ const top = habitConstraintGroup+ .sort((a, b) => memoryHealthScore(b) - memoryHealthScore(a))+ .slice(0, 2)+ .map(r => r.summary);+ candidates.push({+ type: 'reflection',+ summary: `Working style pattern: ${top.join(' ')}`.slice(0, 220),+ detail: top.join('\n'),+ confidence: 0.82,+ importance: 0.8,+ durability: 0.82,+ });+ }++ return candidates;+}\ No newline at end of filediff --git a/src/utils/config.ts b/src/utils/config.tsindex 72677d49..78c7388a 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -89,6 +89,11 @@ export interface MercuryConfig {memory: {dir: string;shortTermMaxMessages: number;+ secondBrain: {+ enabled: boolean;+ maxRecords: number;+ dbPath: string;+ };};heartbeat: {intervalMinutes: number;@@ -191,6 +196,11 @@ export function getDefaultConfig(): MercuryConfig {memory: {dir: getEnv('MEMORY_DIR', join(home, 'memory')),shortTermMaxMessages: getEnvNum('SHORT_TERM_MAX_MESSAGES', 20),+ secondBrain: {+ enabled: getEnvBool('SECOND_BRAIN_ENABLED', true),+ maxRecords: getEnvNum('SECOND_BRAIN_MAX_RECORDS', 50),+ dbPath: getEnv('SECOND_BRAIN_DB_PATH', join(home, 'memory', 'second-brain', 'second-brain.db')),+ },},heartbeat: {intervalMinutes: getEnvNum('HEARTBEAT_INTERVAL_MINUTES', 60),