Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add PostgreSQL + pgvector backend for memory system
Adam Eivy497e36897d82
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b01e64638c..b70af68c2f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,14 @@## Added+- PostgreSQL + pgvector backend for the memory system with HNSW vector search, tsvector full-text search replacing BM25, and auto-fallback to file-based JSON when Docker is unavailable+- Federation sync endpoint (`GET/POST /api/memory/sync`) for incremental memory replication between PortOS instances via sync_sequence+- Data migration script (`server/scripts/migrateMemoryToPg.js`) to move existing JSON memories into PostgreSQL+- `pg_dump` integration in backup service for database snapshots alongside rsync+- `setup-db.js` script integrated into setup, start, dev, and update flows — gracefully skips if Docker is not available+- `docker-compose.yml` for PostgreSQL + pgvector container on port 5561+- `GET /api/memory/backend/status` endpoint to check active backend and DB health+## Changed## Fixeddiff --git a/PLAN.md b/PLAN.mdindex 1b9c6bb642..ce5f97dc6c 100644--- a/PLAN.md+++ b/PLAN.md@@ -8,7 +8,7 @@ See [GOALS.md](./GOALS.md) for project goals and direction.- Frontend: React + Tailwind CSS + Vite (port 5555)- Backend: Express.js (port 5554)- Process Manager: PM2-- Data Storage: JSON files in `./data/`+- Data Storage: JSON files in `./data/`, PostgreSQL + pgvector (memory system)### Commands```bash@@ -75,6 +75,8 @@ pm2 logs- [x] **M43**: Moltworld Platform Support - Second platform integration for AI agents in a shared voxel world- [x] **M44 P1-P5**: MeatSpace - Health tracker with death clock, LEV 2045 tracker, alcohol logging, blood/body/epigenetic/eye tracking, lifestyle questionnaire, TSV import, dashboard widget, compact grid overview+- [x] **M51**: Memory System PostgreSQL Upgrade - PostgreSQL + pgvector backend with HNSW vector search, tsvector full-text search, federation sync, and pg_dump backup integration+### In Progress- [ ] **M44 P6**: MeatSpace - Genome/Epigenetic Migration cleanup (genome routes moved, but route comments still reference `/api/digital-twin/genome/` and IdentityTab still renders a Genome card with broken link to `/digital-twin/genome`)diff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 0000000000..0a33c9edaa--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,30 @@+# PortOS Docker Services+# PostgreSQL + pgvector for scalable memory storage+#+# Usage:+# docker compose up -d # Start services+# docker compose down # Stop services+# docker compose logs -f db # View database logs++services:+ db:+ image: pgvector/pgvector:pg17+ container_name: portos-db+ restart: unless-stopped+ ports:+ - "5561:5432"+ environment:+ POSTGRES_DB: portos+ POSTGRES_USER: portos+ POSTGRES_PASSWORD: portos+ volumes:+ - portos-pgdata:/var/lib/postgresql/data+ - ./server/scripts/init-db.sql:/docker-entrypoint-initdb.d/01-init.sql+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U portos"]+ interval: 5s+ timeout: 3s+ retries: 5++volumes:+ portos-pgdata:diff --git a/docs/PORTS.md b/docs/PORTS.mdindex 2c1c531bad..bb8e88067e 100644--- a/docs/PORTS.md+++ b/docs/PORTS.md@@ -30,6 +30,7 @@ Common port labels:| 5558 | portos-cos | api | CoS Agent Runner (isolated process) || 5559 | portos-autofixer | api | Autofixer daemon API || 5560 | portos-autofixer-ui | ui | Autofixer web UI |+| 5561 | portos-db | db | PostgreSQL + pgvector (Docker, memory system) |## Defining Ports in ecosystem.config.cjsdiff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex 4e3406289b..1e579cb389 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -18,7 +18,8 @@ const PORTS = {CDP_HEALTH: 5557, // Browser health check endpointCOS: 5558, // Chief of Staff agent runnerAUTOFIXER: 5559, // Autofixer API- AUTOFIXER_UI: 5560 // Autofixer UI+ AUTOFIXER_UI: 5560, // Autofixer UI+ POSTGRES: 5561 // PostgreSQL + pgvector (Docker, memory system)};module.exports = {@@ -35,7 +36,8 @@ module.exports = {env: {...BASE_ENV,PORT: PORTS.API,- HOST: '0.0.0.0'+ HOST: '0.0.0.0',+ PGPORT: PORTS.POSTGRES},watch: ['server'],ignore_watch: ['node_modules', '**/*.test.js'],diff --git a/package-lock.json b/package-lock.jsonindex 2f2d5588a4..caa91d0b3f 100644--- a/package-lock.json+++ b/package-lock.json@@ -97,6 +97,7 @@"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.29.0","@babel/generator": "^7.29.0",@@ -1085,7 +1086,6 @@"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==","license": "MIT","optional": true,- "peer": true,"engines": {"node": ">=18"}@@ -1102,7 +1102,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1125,7 +1124,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1148,7 +1146,6 @@"os": ["darwin"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1165,7 +1162,6 @@"os": ["darwin"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1182,7 +1178,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1199,7 +1194,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1216,7 +1210,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1233,7 +1226,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1250,7 +1242,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1267,7 +1258,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1284,7 +1274,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1301,7 +1290,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1318,7 +1306,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1341,7 +1328,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1364,7 +1350,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1387,7 +1372,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1410,7 +1394,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1433,7 +1416,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1456,7 +1438,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1479,7 +1460,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1499,7 +1479,6 @@],"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT","optional": true,- "peer": true,"dependencies": {"@emnapi/runtime": "^1.7.0"},@@ -1522,7 +1501,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1542,7 +1520,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1562,7 +1539,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1638,8 +1614,7 @@"version": "16.1.6","resolved": "https://registry.npmjs.org/@next/env/-/env-16.1.6.tgz","integrity": "sha512-N1ySLuZjnAtN3kFnwhAwPvZah8RJxKasD7x1f8shFqhncnWZn4JMfg37diLNuoHsLAlrDfM3g4mawVdtAG8XLQ==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/@next/swc-darwin-arm64": {"version": "16.1.6",@@ -1653,7 +1628,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 10"}@@ -1670,7 +1644,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 10"}@@ -1687,7 +1660,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1704,7 +1676,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1721,7 +1692,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1738,7 +1708,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1755,7 +1724,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 10"}@@ -1772,7 +1740,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 10"}@@ -2191,6 +2158,7 @@"resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.18.0.tgz","integrity": "sha512-FYZZqD0UUHUswKz3LQl2Z7H24AhD14XGTsIRw3SJaXUxyfVMi+1yiZGmqTcPt/CkPpdU7rrxqcyQ1zJE5DjvIQ==","license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.17.8","@types/react-reconciler": "^0.26.7",@@ -2668,7 +2636,6 @@"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz","integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==","license": "Apache-2.0",- "peer": true,"dependencies": {"tslib": "^2.8.0"}@@ -2677,8 +2644,7 @@"version": "2.8.1","resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz","integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",- "license": "0BSD",- "peer": true+ "license": "0BSD"},"node_modules/@tailwindcss/node": {"version": "4.2.1",@@ -3178,6 +3144,7 @@"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz","integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==","license": "MIT",+ "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -3202,6 +3169,7 @@"resolved": "https://registry.npmjs.org/@types/three/-/three-0.183.1.tgz","integrity": "sha512-f2Pu5Hrepfgavttdye3PsH5RWyY/AvdZQwIVhrc4uNtvF7nOWJacQKcoVJn0S4f0yYbmAE6AR+ve7xDcuYtMGw==","license": "MIT",+ "peer": true,"dependencies": {"@dimforge/rapier3d-compat": "~0.12.0","@tweenjs/tween.js": "~23.1.3",@@ -3786,6 +3754,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -4041,8 +4010,7 @@"version": "0.0.1","resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz","integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/clsx": {"version": "2.1.1",@@ -4259,7 +4227,8 @@"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz","integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/culvert": {"version": "0.1.2",@@ -5015,6 +4984,7 @@"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz","integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==","license": "MIT",+ "peer": true,"dependencies": {"accepts": "^2.0.0","body-parser": "^2.2.1",@@ -5608,6 +5578,7 @@"resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz","integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==","license": "MIT",+ "peer": true,"funding": {"type": "opencollective","url": "https://opencollective.com/immer"@@ -6023,7 +5994,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6045,7 +6015,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6067,7 +6036,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6089,7 +6057,6 @@"os": ["freebsd"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6111,7 +6078,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6133,7 +6099,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6155,7 +6120,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6177,7 +6141,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6199,7 +6162,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6221,7 +6183,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -6243,7 +6204,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 12.0.0"},@@ -7223,7 +7183,6 @@"resolved": "https://registry.npmjs.org/next/-/next-16.1.6.tgz","integrity": "sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw==","license": "MIT",- "peer": true,"dependencies": {"@next/env": "16.1.6","@swc/helpers": "0.5.15",@@ -7291,7 +7250,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"nanoid": "^3.3.6","picocolors": "^1.0.0",@@ -7554,6 +7512,96 @@"dev": true,"license": "MIT"},+ "node_modules/pg": {+ "version": "8.19.0",+ "resolved": "https://registry.npmjs.org/pg/-/pg-8.19.0.tgz",+ "integrity": "sha512-QIcLGi508BAHkQ3pJNptsFz5WQMlpGbuBGBaIaXsWK8mel2kQ/rThYI+DbgjUvZrIr7MiuEuc9LcChJoEZK1xQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "pg-connection-string": "^2.11.0",+ "pg-pool": "^3.12.0",+ "pg-protocol": "^1.12.0",+ "pg-types": "2.2.0",+ "pgpass": "1.0.5"+ },+ "engines": {+ "node": ">= 16.0.0"+ },+ "optionalDependencies": {+ "pg-cloudflare": "^1.3.0"+ },+ "peerDependencies": {+ "pg-native": ">=3.0.1"+ },+ "peerDependenciesMeta": {+ "pg-native": {+ "optional": true+ }+ }+ },+ "node_modules/pg-cloudflare": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz",+ "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/pg-connection-string": {+ "version": "2.11.0",+ "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.11.0.tgz",+ "integrity": "sha512-kecgoJwhOpxYU21rZjULrmrBJ698U2RxXofKVzOn5UDj61BPj/qMb7diYUR1nLScCDbrztQFl1TaQZT0t1EtzQ==",+ "license": "MIT"+ },+ "node_modules/pg-int8": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",+ "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",+ "license": "ISC",+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/pg-pool": {+ "version": "3.12.0",+ "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.12.0.tgz",+ "integrity": "sha512-eIJ0DES8BLaziFHW7VgJEBPi5hg3Nyng5iKpYtj3wbcAUV9A1wLgWiY7ajf/f/oO1wfxt83phXPY8Emztg7ITg==",+ "license": "MIT",+ "peerDependencies": {+ "pg": ">=8.0"+ }+ },+ "node_modules/pg-protocol": {+ "version": "1.12.0",+ "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.12.0.tgz",+ "integrity": "sha512-uOANXNRACNdElMXJ0tPz6RBM0XQ61nONGAwlt8da5zs/iUOOCLBQOHSXnrC6fMsvtjxbOJrZZl5IScGv+7mpbg==",+ "license": "MIT"+ },+ "node_modules/pg-types": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",+ "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",+ "license": "MIT",+ "dependencies": {+ "pg-int8": "1.0.1",+ "postgres-array": "~2.0.0",+ "postgres-bytea": "~1.0.0",+ "postgres-date": "~1.0.4",+ "postgres-interval": "^1.1.0"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/pgpass": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",+ "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",+ "license": "MIT",+ "dependencies": {+ "split2": "^4.1.0"+ }+ },"node_modules/picocolors": {"version": "1.1.1","resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",@@ -7816,6 +7864,45 @@"node": "^10 || ^12 || >=14"}},+ "node_modules/postgres-array": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",+ "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/postgres-bytea": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",+ "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/postgres-date": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",+ "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/postgres-interval": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",+ "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",+ "license": "MIT",+ "dependencies": {+ "xtend": "^4.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/potpack": {"version": "1.0.2","resolved": "https://registry.npmjs.org/potpack/-/potpack-1.0.2.tgz",@@ -7963,6 +8050,7 @@"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz","integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0"},@@ -8008,6 +8096,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz","integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0","scheduler": "^0.23.2"@@ -8097,6 +8186,7 @@"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz","integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==","license": "MIT",+ "peer": true,"dependencies": {"@types/use-sync-external-store": "^0.0.6","use-sync-external-store": "^1.4.0"@@ -8263,7 +8353,8 @@"version": "5.0.1","resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz","integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/redux-thunk": {"version": "3.1.0",@@ -8567,7 +8658,6 @@"hasInstallScript": true,"license": "Apache-2.0","optional": true,- "peer": true,"dependencies": {"@img/colour": "^1.0.0","detect-libc": "^2.1.2",@@ -8733,6 +8823,7 @@"resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.3.tgz","integrity": "sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==","license": "MIT",+ "peer": true,"dependencies": {"accepts": "~1.3.4","base64id": "~2.0.0",@@ -8914,6 +9005,15 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/split2": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",+ "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",+ "license": "ISC",+ "engines": {+ "node": ">= 10.x"+ }+ },"node_modules/sprintf-js": {"version": "1.1.2","resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.2.tgz",@@ -9023,7 +9123,6 @@"resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz","integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==","license": "MIT",- "peer": true,"dependencies": {"client-only": "0.0.1"},@@ -9169,7 +9268,8 @@"version": "0.182.0","resolved": "https://registry.npmjs.org/three/-/three-0.182.0.tgz","integrity": "sha512-GbHabT+Irv+ihI1/f5kIIsZ+Ef9Sl5A1Y7imvS5RQjWgtTPfPnZ43JmlYI7NtCRDK9zir20lQpfg8/9Yd02OvQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/three-mesh-bvh": {"version": "0.7.8",@@ -9268,6 +9368,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -9704,6 +9805,7 @@"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.27.0","fdir": "^6.5.0",@@ -9797,6 +9899,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -9810,6 +9913,7 @@"integrity": "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@vitest/expect": "4.0.18","@vitest/mocker": "4.0.18",@@ -9997,6 +10101,15 @@"node": ">=0.4.0"}},+ "node_modules/xtend": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",+ "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4"+ }+ },"node_modules/yallist": {"version": "4.0.0","resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",@@ -10069,6 +10182,7 @@"express": "^5.2.1","multer": "^2.0.2","node-pty": "^1.2.0-beta.10",+ "pg": "^8.19.0","pm2": "^5.4.3","portos-ai-toolkit": "^0.8.0","sax": "^1.4.4",diff --git a/package.json b/package.jsonindex 4ad8689de3..309c2ca76d 100644--- a/package.json+++ b/package.json@@ -14,7 +14,7 @@"dev": "node scripts/dev-start.js","dev:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs","build": "npm run build -w client",- "start": "npm run build && node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent; node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs && node ./node_modules/pm2/bin/pm2 save",+ "start": "npm run build && node scripts/setup-db.js && node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent; node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs && node ./node_modules/pm2/bin/pm2 save","pm2:start": "node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs","pm2:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs","pm2:restart": "node ./node_modules/pm2/bin/pm2 restart ecosystem.config.cjs",@@ -23,8 +23,9 @@"pm2:save": "node ./node_modules/pm2/bin/pm2 save","pm2:startup": "node ./node_modules/pm2/bin/pm2 startup","install:all": "npm install && npm run setup",- "setup": "node scripts/setup-data.js && node scripts/setup-browser.js",+ "setup": "node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-browser.js","setup:data": "node scripts/setup-data.js",+ "setup:db": "node scripts/setup-db.js","setup:browser": "node scripts/setup-browser.js","setup:ghostty": "node scripts/setup-ghostty.js","update": "npm install && npm run setup && npm run setup:ghostty",diff --git a/scripts/dev-start.js b/scripts/dev-start.jsindex 582c2f3bf2..868b4d44ed 100644--- a/scripts/dev-start.js+++ b/scripts/dev-start.js@@ -7,9 +7,11 @@*/import { execFileSync, spawn } from 'child_process';import { dirname, join } from 'path';+import { fileURLToPath } from 'url';import { createRequire } from 'module';const require = createRequire(import.meta.url);+const __dirname = dirname(fileURLToPath(import.meta.url));const PM2 = join(dirname(require.resolve('pm2/package.json')), 'bin', 'pm2');const ECO = 'ecosystem.config.cjs';@@ -20,6 +22,12 @@ function pm2(...args) {});}+// Ensure PostgreSQL is running (gracefully skips if Docker unavailable)+execFileSync(process.execPath, [join(__dirname, 'setup-db.js')], {+ stdio: 'inherit',+ windowsHide: true+});+// Stop and delete existing PortOS processes (ignore errors if none exist)try { pm2('stop', ECO); } catch {}try { pm2('delete', ECO); } catch {}diff --git a/scripts/setup-db.js b/scripts/setup-db.jsnew file mode 100644index 0000000000..32c9ec13bf--- /dev/null+++ b/scripts/setup-db.js@@ -0,0 +1,128 @@+#!/usr/bin/env node++/**+ * Database Setup Script+ *+ * Ensures PostgreSQL + pgvector is running via Docker Compose.+ * Gracefully skips if Docker is not available — the memory system+ * falls back to file-based JSON storage automatically.+ *+ * Called by: npm run setup, npm run update, npm start, npm run dev+ */++import { execFileSync, execSync } from 'child_process';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const rootDir = join(__dirname, '..');++// Check if Docker is available+function hasDocker() {+ try {+ execFileSync('docker', ['--version'], { stdio: 'pipe' });+ return true;+ } catch {+ return false;+ }+}++// Check if Docker daemon is running+function isDockerRunning() {+ try {+ execFileSync('docker', ['info'], { stdio: 'pipe' });+ return true;+ } catch {+ return false;+ }+}++// Check if docker compose is available (v2 plugin)+function hasCompose() {+ try {+ execFileSync('docker', ['compose', 'version'], { stdio: 'pipe' });+ return true;+ } catch {+ return false;+ }+}++// Check if the container is already running+function isContainerRunning() {+ try {+ const output = execFileSync('docker', ['compose', 'ps', '--format', 'json', 'db'], {+ stdio: 'pipe',+ cwd: rootDir+ }).toString();+ return output.includes('"running"') || output.includes('"Running"');+ } catch {+ return false;+ }+}++// Wait for PostgreSQL to accept connections+function waitForHealth(maxAttempts = 30) {+ for (let i = 0; i < maxAttempts; i++) {+ try {+ execFileSync('docker', ['compose', 'exec', '-T', 'db', 'pg_isready', '-U', 'portos'], {+ stdio: 'pipe',+ cwd: rootDir+ });+ return true;+ } catch {+ if (i < maxAttempts - 1) {+ execSync('sleep 1', { stdio: 'pipe' });+ }+ }+ }+ return false;+}++console.log('🗄️ Setting up PostgreSQL + pgvector...');++if (!hasDocker()) {+ console.log('⏭️ Docker not found — skipping database setup');+ console.log(' Memory system will use file-based JSON storage');+ console.log(' Install Docker to enable PostgreSQL: https://docs.docker.com/get-docker/');+ process.exit(0);+}++if (!isDockerRunning()) {+ console.log('⏭️ Docker daemon not running — skipping database setup');+ console.log(' Memory system will use file-based JSON storage');+ console.log(' Start Docker Desktop or run: sudo systemctl start docker');+ process.exit(0);+}++if (!hasCompose()) {+ console.log('⏭️ docker compose not available — skipping database setup');+ console.log(' Memory system will use file-based JSON storage');+ process.exit(0);+}++if (isContainerRunning()) {+ console.log('✅ PostgreSQL already running');+ process.exit(0);+}++// Start the container+console.log('🐳 Starting PostgreSQL container...');+try {+ execFileSync('docker', ['compose', 'up', '-d', 'db'], {+ stdio: 'inherit',+ cwd: rootDir+ });+} catch (err) {+ console.error(`⚠️ Failed to start PostgreSQL: ${err.message}`);+ console.log(' Memory system will use file-based JSON storage');+ process.exit(0);+}++// Wait for health+console.log('⏳ Waiting for PostgreSQL to be ready...');+if (waitForHealth()) {+ console.log('✅ PostgreSQL ready on port 5561');+} else {+ console.warn('⚠️ PostgreSQL started but not responding yet — it may still be initializing');+ console.log(' Check status: docker compose logs db');+}diff --git a/server/lib/db.js b/server/lib/db.jsnew file mode 100644index 0000000000..90721dcc2b--- /dev/null+++ b/server/lib/db.js@@ -0,0 +1,89 @@+/**+ * Database Connection Pool+ *+ * PostgreSQL connection management for the memory system.+ * Uses pg (node-postgres) with a connection pool for efficient query execution.+ */++import pg from 'pg';++const { Pool } = pg;++// Connection config from environment or defaults+const pool = new Pool({+ host: process.env.PGHOST || 'localhost',+ port: parseInt(process.env.PGPORT || '5561', 10),+ database: process.env.PGDATABASE || 'portos',+ user: process.env.PGUSER || 'portos',+ password: process.env.PGPASSWORD || 'portos',+ max: 10,+ idleTimeoutMillis: 30000,+ connectionTimeoutMillis: 5000+});++pool.on('error', (err) => {+ console.error(`🗄️ Database pool error: ${err.message}`);+});++/**+ * Execute a query against the connection pool.+ * @param {string} text - SQL query text with $1, $2, etc. placeholders+ * @param {Array} params - Parameter values+ * @returns {Promise<pg.QueryResult>}+ */+export async function query(text, params) {+ return pool.query(text, params);+}++/**+ * Get a client from the pool for transactions.+ * Caller must call client.release() when done.+ * @returns {Promise<pg.PoolClient>}+ */+export async function getClient() {+ return pool.connect();+}++/**+ * Run a function inside a database transaction.+ * Auto-commits on success, rolls back on error.+ * @param {function(pg.PoolClient): Promise<T>} fn+ * @returns {Promise<T>}+ */+export async function withTransaction(fn) {+ const client = await pool.connect();+ await client.query('BEGIN');+ let result;+ try {+ result = await fn(client);+ await client.query('COMMIT');+ } catch (err) {+ await client.query('ROLLBACK');+ throw err;+ } finally {+ client.release();+ }+ return result;+}++/**+ * Check if the database is reachable and the schema is initialized.+ * @returns {Promise<{connected: boolean, hasSchema: boolean, error?: string}>}+ */+export async function checkHealth() {+ try {+ const result = await pool.query(+ "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'memories') AS has_table"+ );+ return { connected: true, hasSchema: result.rows[0].has_table };+ } catch (err) {+ return { connected: false, hasSchema: false, error: err.message };+ }+}++/**+ * Gracefully shut down the pool.+ */+export async function close() {+ await pool.end();+}diff --git a/server/package.json b/server/package.jsonindex b97535e33f..ad5b907ed8 100644--- a/server/package.json+++ b/server/package.json@@ -16,6 +16,7 @@"express": "^5.2.1","multer": "^2.0.2","node-pty": "^1.2.0-beta.10",+ "pg": "^8.19.0","pm2": "^5.4.3","portos-ai-toolkit": "^0.8.0","sax": "^1.4.4",diff --git a/server/routes/memory.js b/server/routes/memory.jsindex 53080dec35..dc1e54d7dc 100644--- a/server/routes/memory.js+++ b/server/routes/memory.js@@ -3,8 +3,11 @@*/import { Router } from 'express';-import * as memory from '../services/memory.js';+import * as memory from '../services/memoryBackend.js';+import { getBackendName } from '../services/memoryBackend.js';import * as embeddings from '../services/memoryEmbeddings.js';+import * as memorySync from '../services/memorySync.js';+import { checkHealth } from '../lib/db.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import {@@ -73,6 +76,36 @@ router.get('/graph', asyncHandler(async (req, res) => {res.json(graph);}));+// GET /api/memory/backend/status - Check memory backend status+router.get('/backend/status', asyncHandler(async (req, res) => {+ const dbHealth = await checkHealth();+ res.json({ backend: getBackendName(), db: dbHealth });+}));++// GET /api/memory/sync - Federation sync: get changes since sequence+router.get('/sync', asyncHandler(async (req, res) => {+ if (getBackendName() !== 'postgres') {+ throw new ServerError('Sync requires PostgreSQL backend', { status: 400 });+ }+ const since = parseInt(req.query.since, 10) || 0;+ const limit = Math.min(parseInt(req.query.limit, 10) || 100, 1000);+ const result = await memorySync.getChangesSince(since, limit);+ res.json(result);+}));++// POST /api/memory/sync - Federation sync: apply remote changes+router.post('/sync', asyncHandler(async (req, res) => {+ if (getBackendName() !== 'postgres') {+ throw new ServerError('Sync requires PostgreSQL backend', { status: 400 });+ }+ const { memories } = req.body;+ if (!Array.isArray(memories)) {+ throw new ServerError('Request body must contain a memories array', { status: 400 });+ }+ const result = await memorySync.applyRemoteChanges(memories);+ res.json(result);+}));+// GET /api/memory/embeddings/status - Check embedding service statusrouter.get('/embeddings/status', asyncHandler(async (req, res) => {const status = await embeddings.checkAvailability();diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlnew file mode 100644index 0000000000..47b91e16b7--- /dev/null+++ b/server/scripts/init-db.sql@@ -0,0 +1,75 @@+-- PortOS Memory System Schema+-- PostgreSQL + pgvector++CREATE EXTENSION IF NOT EXISTS vector;++-- Core memories table+CREATE TABLE IF NOT EXISTS memories (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ type VARCHAR(20) NOT NULL,+ content TEXT NOT NULL,+ summary TEXT,+ category VARCHAR(100) DEFAULT 'other',+ tags TEXT[] DEFAULT '{}',+ embedding vector(768),+ embedding_model VARCHAR(100),+ confidence FLOAT DEFAULT 0.8,+ importance FLOAT DEFAULT 0.5,+ access_count INT DEFAULT 0,+ last_accessed TIMESTAMPTZ,+ status VARCHAR(20) DEFAULT 'active',+ source_task_id VARCHAR(100),+ source_agent_id VARCHAR(100),+ source_app_id VARCHAR(100),+ expires_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ -- Federation sync sequence (auto-incrementing on insert/update)+ sync_sequence BIGSERIAL+);++-- HNSW index for fast vector similarity search (O(log n) instead of O(n))+CREATE INDEX IF NOT EXISTS idx_memories_embedding+ ON memories USING hnsw (embedding vector_cosine_ops)+ WITH (m = 16, ef_construction = 64);++-- Full-text search index (replaces BM25)+CREATE INDEX IF NOT EXISTS idx_memories_fts+ ON memories USING gin (+ to_tsvector('english', coalesce(content, '') || ' ' || coalesce(summary, ''))+ );++-- Filtered queries+CREATE INDEX IF NOT EXISTS idx_memories_status ON memories (status);+CREATE INDEX IF NOT EXISTS idx_memories_type ON memories (type);+CREATE INDEX IF NOT EXISTS idx_memories_category ON memories (category);+CREATE INDEX IF NOT EXISTS idx_memories_source_app ON memories (source_app_id);+CREATE INDEX IF NOT EXISTS idx_memories_created_at ON memories (created_at);+CREATE INDEX IF NOT EXISTS idx_memories_importance ON memories (importance);+CREATE INDEX IF NOT EXISTS idx_memories_tags ON memories USING gin (tags);++-- Sync sequence index for federation+CREATE INDEX IF NOT EXISTS idx_memories_sync_sequence ON memories (sync_sequence);++-- Memory relationships (bidirectional links)+CREATE TABLE IF NOT EXISTS memory_links (+ source_id UUID REFERENCES memories(id) ON DELETE CASCADE,+ target_id UUID REFERENCES memories(id) ON DELETE CASCADE,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ PRIMARY KEY (source_id, target_id)+);++-- Auto-update updated_at and sync_sequence on modification+CREATE OR REPLACE FUNCTION update_memory_timestamp()+RETURNS TRIGGER AS $$+BEGIN+ NEW.updated_at = NOW();+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS trg_memory_updated_at ON memories;+CREATE TRIGGER trg_memory_updated_at+ BEFORE UPDATE ON memories+ FOR EACH ROW+ EXECUTE FUNCTION update_memory_timestamp();diff --git a/server/scripts/migrateMemoryToPg.js b/server/scripts/migrateMemoryToPg.jsnew file mode 100644index 0000000000..8f2968d024--- /dev/null+++ b/server/scripts/migrateMemoryToPg.js@@ -0,0 +1,246 @@+#!/usr/bin/env node++/**+ * Memory Migration Script: JSON Files → PostgreSQL + pgvector+ *+ * Reads all memories from data/cos/memory/ (index.json, embeddings.json,+ * and individual memory.json files) and inserts them into PostgreSQL.+ *+ * Usage:+ * node server/scripts/migrateMemoryToPg.js # Dry run+ * node server/scripts/migrateMemoryToPg.js --execute # Execute migration+ * node server/scripts/migrateMemoryToPg.js --execute --clear # Clear DB first, then migrate+ *+ * Requirements:+ * - PostgreSQL with pgvector must be running (docker compose up -d)+ * - Schema must be initialized (happens automatically via init-db.sql)+ */++import { readFile, readdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { query, close } from '../lib/db.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const DATA_DIR = join(__dirname, '../../data');+const MEMORY_DIR = join(DATA_DIR, 'cos/memory');+const INDEX_FILE = join(MEMORY_DIR, 'index.json');+const EMBEDDINGS_FILE = join(MEMORY_DIR, 'embeddings.json');+const MEMORIES_DIR = join(MEMORY_DIR, 'memories');++const args = process.argv.slice(2);+const execute = args.includes('--execute');+const clearFirst = args.includes('--clear');++async function loadJSON(path) {+ const content = await readFile(path, 'utf-8');+ return JSON.parse(content);+}++function arrayToPgvector(arr) {+ if (!arr) return null;+ return `[${arr.join(',')}]`;+}++async function migrate() {+ console.log('🧠 Memory Migration: JSON → PostgreSQL');+ console.log(` Mode: ${execute ? 'EXECUTE' : 'DRY RUN (add --execute to write)'}`);+ console.log('');++ // 1. Check source files exist+ if (!existsSync(INDEX_FILE)) {+ console.log('⚠️ No index.json found — nothing to migrate');+ return;+ }++ // 2. Load index and embeddings+ const index = await loadJSON(INDEX_FILE);+ console.log(`📋 Index: ${index.memories.length} memory entries`);++ let embeddings = { vectors: {} };+ if (existsSync(EMBEDDINGS_FILE)) {+ embeddings = await loadJSON(EMBEDDINGS_FILE);+ console.log(`🧮 Embeddings: ${Object.keys(embeddings.vectors).length} vectors`);+ }++ // 3. Load each full memory from disk+ const memoryDirs = existsSync(MEMORIES_DIR)+ ? await readdir(MEMORIES_DIR).catch(() => [])+ : [];+ console.log(`📁 Memory files: ${memoryDirs.length} directories`);+ console.log('');++ // 4. Check DB connection+ const dbCheck = await query('SELECT 1 AS ok').catch(err => {+ console.error(`❌ Cannot connect to PostgreSQL: ${err.message}`);+ console.error(' Is the database running? Try: docker compose up -d');+ process.exit(1);+ });+ console.log('✅ PostgreSQL connected');++ // Check schema+ const schemaCheck = await query(+ "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'memories') AS has_table"+ );+ if (!schemaCheck.rows[0].has_table) {+ console.error('❌ memories table not found. Run init-db.sql first.');+ process.exit(1);+ }+ console.log('✅ Schema verified');++ // 5. Clear if requested+ if (execute && clearFirst) {+ await query('DELETE FROM memory_links');+ await query('DELETE FROM memories');+ console.log('🗑️ Cleared existing data');+ }++ // 6. Check existing count+ const existing = await query('SELECT COUNT(*) AS count FROM memories');+ console.log(`📊 Existing DB records: ${existing.rows[0].count}`);+ console.log('');++ // 7. Migrate each memory+ let inserted = 0;+ let skipped = 0;+ let errors = 0;++ for (const meta of index.memories) {+ const memoryFile = join(MEMORIES_DIR, meta.id, 'memory.json');++ let memory;+ if (existsSync(memoryFile)) {+ memory = await loadJSON(memoryFile);+ } else {+ // Use index metadata as fallback (no full content)+ memory = {+ id: meta.id,+ type: meta.type,+ content: meta.summary || '',+ summary: meta.summary || '',+ category: meta.category || 'other',+ tags: meta.tags || [],+ relatedMemories: [],+ sourceTaskId: null,+ sourceAgentId: null,+ sourceAppId: meta.sourceAppId || null,+ confidence: 0.8,+ importance: meta.importance || 0.5,+ accessCount: 0,+ lastAccessed: null,+ createdAt: meta.createdAt || new Date().toISOString(),+ updatedAt: meta.createdAt || new Date().toISOString(),+ expiresAt: null,+ status: meta.status || 'active'+ };+ }++ const embedding = embeddings.vectors[meta.id] || null;++ if (!execute) {+ console.log(` [DRY] ${meta.id} — ${memory.type}: ${(memory.summary || '').substring(0, 60)}...`);+ inserted++;+ continue;+ }++ // Check if already exists+ const existCheck = await query('SELECT 1 FROM memories WHERE id = $1', [memory.id]);+ if (existCheck.rows.length > 0) {+ skipped++;+ continue;+ }++ const insertResult = await query(+ `INSERT INTO memories (+ id, type, content, summary, category, tags,+ embedding, embedding_model, confidence, importance,+ access_count, last_accessed,+ source_task_id, source_agent_id, source_app_id,+ expires_at, status, created_at, updated_at+ ) VALUES (+ $1, $2, $3, $4, $5, $6,+ $7, $8, $9, $10,+ $11, $12,+ $13, $14, $15,+ $16, $17, $18, $19+ )`,+ [+ memory.id, memory.type, memory.content, memory.summary,+ memory.category || 'other', memory.tags || [],+ embedding ? arrayToPgvector(embedding) : null,+ memory.embeddingModel || (embedding ? 'text-embedding-nomic-embed-text-v2-moe' : null),+ memory.confidence ?? 0.8, memory.importance ?? 0.5,+ memory.accessCount || 0, memory.lastAccessed || null,+ memory.sourceTaskId || null, memory.sourceAgentId || null, memory.sourceAppId || null,+ memory.expiresAt || null, memory.status || 'active',+ memory.createdAt || new Date().toISOString(), memory.updatedAt || new Date().toISOString()+ ]+ ).catch(err => {+ console.error(` ❌ ${meta.id}: ${err.message}`);+ errors++;+ return null;+ });++ if (insertResult) {+ inserted++;++ // Migrate related memory links+ if (memory.relatedMemories?.length > 0) {+ for (const relId of memory.relatedMemories) {+ await query(+ 'INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',+ [memory.id, relId]+ ).catch(() => {}); // Skip if target doesn't exist yet+ }+ }+ }+ }++ // 8. Second pass: retry links (some targets may not have existed on first pass)+ if (execute) {+ let linksFixed = 0;+ for (const meta of index.memories) {+ const memoryFile = join(MEMORIES_DIR, meta.id, 'memory.json');+ if (!existsSync(memoryFile)) continue;++ const memory = await loadJSON(memoryFile);+ if (!memory.relatedMemories?.length) continue;++ for (const relId of memory.relatedMemories) {+ const result = await query(+ 'INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',+ [memory.id, relId]+ ).catch(() => null);+ if (result?.rowCount > 0) linksFixed++;+ }+ }+ if (linksFixed > 0) console.log(`🔗 Fixed ${linksFixed} memory links on second pass`);+ }++ // 9. Report+ console.log('');+ console.log('📊 Migration Summary:');+ console.log(` Inserted: ${inserted}`);+ console.log(` Skipped (already exists): ${skipped}`);+ console.log(` Errors: ${errors}`);++ if (execute) {+ const finalCount = await query('SELECT COUNT(*) AS count FROM memories');+ console.log(` Total in DB: ${finalCount.rows[0].count}`);+ }++ if (!execute) {+ console.log('');+ console.log('ℹ️ This was a dry run. Add --execute to perform the migration.');+ }+}++migrate()+ .catch(err => {+ console.error(`💥 Migration failed: ${err.message}`);+ console.error(err.stack);+ process.exit(1);+ })+ .finally(() => close());diff --git a/server/services/backup.js b/server/services/backup.jsindex 1c93219453..f68344b652 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -13,6 +13,7 @@ import { access, readFile, readdir, stat, writeFile } from 'fs/promises';import { join } from 'path';import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { getEvent } from './eventScheduler.js';+import { checkHealth } from '../lib/db.js';// Module-level statelet isRunning = false;@@ -121,6 +122,10 @@ export async function runBackup(destPath, io = null, { excludePaths = [] } = {})changedFiles = await runRsync(PATHS.data, dataDestDir, excludeFlags).catch(fail);console.log(`💾 Backup rsync complete: ${changedFiles.length} files changed (exit 0)`);+ // Dump PostgreSQL alongside the file backup+ const pgDumpPath = join(snapshotDir, 'portos-db.sql');+ const pgResult = await dumpPostgres(pgDumpPath).catch(() => ({ success: false }));+manifest = await generateManifest(dataDestDir, join(snapshotDir, 'manifest.json')).catch(fail);const lastRun = new Date().toISOString();@@ -134,7 +139,60 @@ export async function runBackup(destPath, io = null, { excludePaths = [] } = {})if (io) io.emit('backup:completed', { snapshotId, filesChanged: changedFiles.length });- return complete({ snapshotId, filesChanged: changedFiles.length, lastRun, manifest });+ return complete({ snapshotId, filesChanged: changedFiles.length, lastRun, manifest, pgDump: pgResult });+}++/**+ * Run pg_dump to create a PostgreSQL backup alongside the rsync snapshot.+ * Silently skips if PostgreSQL is not available.+ * @param {string} outputPath - Path to write the SQL dump file+ * @returns {Promise<{success: boolean, size?: number, error?: string}>}+ */+export async function dumpPostgres(outputPath) {+ const health = await checkHealth();+ if (!health.connected || !health.hasSchema) {+ return { success: false, error: 'PostgreSQL not available' };+ }++ const pgHost = process.env.PGHOST || 'localhost';+ const pgPort = process.env.PGPORT || '5561';+ const pgDb = process.env.PGDATABASE || 'portos';+ const pgUser = process.env.PGUSER || 'portos';++ return new Promise((resolve) => {+ const proc = spawn('pg_dump', [+ '-h', pgHost,+ '-p', pgPort,+ '-U', pgUser,+ '-d', pgDb,+ '--no-owner',+ '--no-acl',+ '-f', outputPath+ ], {+ shell: false,+ env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' }+ });++ let stderr = '';+ proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });++ proc.on('close', async (code) => {+ if (code === 0) {+ const info = await stat(outputPath).catch(() => null);+ console.log(`💾 pg_dump complete: ${info ? Math.round(info.size / 1024) + 'KB' : 'unknown size'}`);+ resolve({ success: true, size: info?.size ?? 0 });+ } else {+ console.warn(`⚠️ pg_dump failed (code ${code}): ${stderr.trim()}`);+ resolve({ success: false, error: stderr.trim() });+ }+ });++ proc.on('error', (err) => {+ // pg_dump not installed — skip silently+ console.warn(`⚠️ pg_dump not available: ${err.message}`);+ resolve({ success: false, error: err.message });+ });+ });}/**diff --git a/server/services/memoryBackend.js b/server/services/memoryBackend.jsnew file mode 100644index 0000000000..9cd43bd3f6--- /dev/null+++ b/server/services/memoryBackend.js@@ -0,0 +1,185 @@+/**+ * Memory Backend Switcher+ *+ * Selects between file-based (memory.js) and PostgreSQL (memoryDB.js) backends.+ * Checks for MEMORY_BACKEND env var or falls back to DB health check.+ *+ * Usage:+ * import * as memory from './memoryBackend.js';+ * // All functions are the same regardless of backend+ */++import { checkHealth } from '../lib/db.js';++let backend = null;+let backendName = null;++/**+ * Initialize and return the appropriate backend module.+ * Caches the result after first call.+ */+async function getBackend() {+ if (backend) return backend;++ const envBackend = process.env.MEMORY_BACKEND;++ if (envBackend === 'file') {+ backend = await import('./memory.js');+ backendName = 'file';+ console.log('🧠 Memory backend: file-based (JSON)');+ return backend;+ }++ if (envBackend === 'postgres') {+ backend = await import('./memoryDB.js');+ backendName = 'postgres';+ console.log('🧠 Memory backend: PostgreSQL + pgvector');+ return backend;+ }++ // Auto-detect: try PostgreSQL first, fall back to file+ const health = await checkHealth();+ if (health.connected && health.hasSchema) {+ backend = await import('./memoryDB.js');+ backendName = 'postgres';+ console.log('🧠 Memory backend: PostgreSQL + pgvector (auto-detected)');+ } else {+ backend = await import('./memory.js');+ backendName = 'file';+ console.log(`🧠 Memory backend: file-based (PostgreSQL unavailable: ${health.error || 'no schema'})`);+ }++ return backend;+}++/**+ * Get the name of the active backend+ */+export function getBackendName() {+ return backendName;+}++// Re-export all functions with lazy initialization+// Each function loads the backend on first call, then delegates++export async function createMemory(data, embedding) {+ const b = await getBackend();+ return b.createMemory(data, embedding);+}++export async function getMemory(id) {+ const b = await getBackend();+ return b.getMemory(id);+}++export async function getMemories(options) {+ const b = await getBackend();+ return b.getMemories(options);+}++export async function updateMemory(id, updates) {+ const b = await getBackend();+ return b.updateMemory(id, updates);+}++export async function updateMemoryEmbedding(id, embedding) {+ const b = await getBackend();+ return b.updateMemoryEmbedding(id, embedding);+}++export async function deleteMemory(id, hard) {+ const b = await getBackend();+ return b.deleteMemory(id, hard);+}++export async function approveMemory(id) {+ const b = await getBackend();+ return b.approveMemory(id);+}++export async function rejectMemory(id) {+ const b = await getBackend();+ return b.rejectMemory(id);+}++export async function searchMemories(queryEmbedding, options) {+ const b = await getBackend();+ return b.searchMemories(queryEmbedding, options);+}++export async function hybridSearchMemories(query, queryEmbedding, options) {+ const b = await getBackend();+ return b.hybridSearchMemories(query, queryEmbedding, options);+}++export async function rebuildBM25Index() {+ const b = await getBackend();+ return b.rebuildBM25Index();+}++export async function getBM25Stats() {+ const b = await getBackend();+ return b.getBM25Stats();+}++export async function getTimeline(options) {+ const b = await getBackend();+ return b.getTimeline(options);+}++export async function getCategories() {+ const b = await getBackend();+ return b.getCategories();+}++export async function getTags() {+ const b = await getBackend();+ return b.getTags();+}++export async function getRelatedMemories(id, limit) {+ const b = await getBackend();+ return b.getRelatedMemories(id, limit);+}++export async function getGraphData() {+ const b = await getBackend();+ return b.getGraphData();+}++export async function linkMemories(sourceId, targetId) {+ const b = await getBackend();+ return b.linkMemories(sourceId, targetId);+}++export async function consolidateMemories(threshold, dryRun) {+ const b = await getBackend();+ return b.consolidateMemories(threshold, dryRun);+}++export async function applyDecay(decayRate) {+ const b = await getBackend();+ return b.applyDecay(decayRate);+}++export async function clearExpired() {+ const b = await getBackend();+ return b.clearExpired();+}++export async function getStats() {+ const b = await getBackend();+ return b.getStats();+}++export function invalidateCaches() {+ if (backend) backend.invalidateCaches();+}++export async function flushBM25Index() {+ const b = await getBackend();+ return b.flushBM25Index();+}++// Re-export the config constant (same in both backends)+export { DEFAULT_MEMORY_CONFIG } from './memory.js';diff --git a/server/services/memoryDB.js b/server/services/memoryDB.jsnew file mode 100644index 0000000000..edbcee242a--- /dev/null+++ b/server/services/memoryDB.js@@ -0,0 +1,1030 @@+/**+ * Memory Service — PostgreSQL + pgvector Backend+ *+ * Drop-in replacement for memory.js (file-based) using PostgreSQL with pgvector+ * for vector similarity search and tsvector for full-text search.+ *+ * Same exported interface as memory.js so routes/consumers don't change.+ */++import { v4 as uuidv4 } from 'uuid';+import { query, withTransaction } from '../lib/db.js';+import { cosEvents, updateAgent } from './cos.js';+import * as notifications from './notifications.js';++// Default memory configuration (same as file-based version)+export const DEFAULT_MEMORY_CONFIG = {+ enabled: true,+ embeddingProvider: 'lmstudio',+ embeddingEndpoint: 'http://localhost:1234/v1/embeddings',+ embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',+ embeddingDimension: 768,+ maxMemories: 10000,+ maxContextTokens: 2000,+ minRelevanceThreshold: 0.7,+ autoExtractEnabled: true,+ consolidationIntervalMs: 86400000,+ decayIntervalMs: 86400000+};++/**+ * Generate summary from content using simple truncation+ */+function generateSummary(content, maxLength = 150) {+ if (content.length <= maxLength) return content;+ return content.substring(0, maxLength - 3) + '...';+}++/**+ * Convert a database row to the memory object format matching the file-based API+ */+function rowToMemory(row) {+ return {+ id: row.id,+ type: row.type,+ content: row.content,+ summary: row.summary,+ category: row.category,+ tags: row.tags || [],+ relatedMemories: row.related_memories || [],+ sourceTaskId: row.source_task_id,+ sourceAgentId: row.source_agent_id,+ sourceAppId: row.source_app_id,+ embedding: row.embedding ? pgvectorToArray(row.embedding) : null,+ embeddingModel: row.embedding_model,+ confidence: row.confidence,+ importance: row.importance,+ accessCount: row.access_count,+ lastAccessed: row.last_accessed?.toISOString() ?? null,+ createdAt: row.created_at.toISOString(),+ updatedAt: row.updated_at.toISOString(),+ expiresAt: row.expires_at?.toISOString() ?? null,+ status: row.status+ };+}++/**+ * Convert a database row to index-style metadata (lightweight)+ */+function rowToMeta(row) {+ return {+ id: row.id,+ type: row.type,+ category: row.category,+ tags: row.tags || [],+ summary: row.summary,+ importance: row.importance,+ createdAt: row.created_at.toISOString(),+ status: row.status,+ sourceAppId: row.source_app_id+ };+}++/**+ * Convert pgvector string representation to float array.+ * pgvector returns vectors as '[0.1,0.2,...]' strings.+ */+function pgvectorToArray(vec) {+ if (Array.isArray(vec)) return vec;+ if (typeof vec === 'string') {+ return vec.replace(/^\[|\]$/g, '').split(',').map(Number);+ }+ return null;+}++/**+ * Format a float array as pgvector literal '[0.1,0.2,...]'+ */+function arrayToPgvector(arr) {+ if (!arr) return null;+ return `[${arr.join(',')}]`;+}++// =============================================================================+// CRUD Operations+// =============================================================================++/**+ * Create a new memory+ */+export async function createMemory(data, embedding = null) {+ const id = uuidv4();+ const summary = data.summary || generateSummary(data.content);+ const now = new Date().toISOString();++ const result = await query(+ `INSERT INTO memories (+ id, type, content, summary, category, tags,+ embedding, embedding_model, confidence, importance,+ source_task_id, source_agent_id, source_app_id,+ expires_at, status, created_at, updated_at+ ) VALUES (+ $1, $2, $3, $4, $5, $6,+ $7, $8, $9, $10,+ $11, $12, $13,+ $14, $15, $16, $17+ ) RETURNING *`,+ [+ id, data.type, data.content, summary, data.category || 'other', data.tags || [],+ embedding ? arrayToPgvector(embedding) : null,+ embedding ? DEFAULT_MEMORY_CONFIG.embeddingModel : null,+ data.confidence ?? 0.8, data.importance ?? 0.5,+ data.sourceTaskId || null, data.sourceAgentId || null, data.sourceAppId || null,+ data.expiresAt || null, data.status || 'active', now, now+ ]+ );++ const memory = rowToMemory(result.rows[0]);+ // Attach the original embedding array (pgvector may return string representation)+ if (embedding) memory.embedding = embedding;+ // Store related memories as links+ if (data.relatedMemories?.length > 0) {+ for (const relId of data.relatedMemories) {+ await query(+ 'INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',+ [id, relId]+ );+ }+ memory.relatedMemories = data.relatedMemories;+ }++ console.log(`🧠 Memory created: ${memory.type} - ${memory.summary.substring(0, 50)}...`);+ cosEvents.emit('memory:created', { id, type: memory.type, summary: memory.summary });++ return memory;+}++/**+ * Get a memory by ID+ */+export async function getMemory(id) {+ const result = await query('SELECT * FROM memories WHERE id = $1', [id]);+ if (result.rows.length === 0) return null;++ // Update access stats+ await query(+ 'UPDATE memories SET access_count = access_count + 1, last_accessed = NOW() WHERE id = $1',+ [id]+ );++ const memory = rowToMemory(result.rows[0]);+ memory.accessCount += 1;+ memory.lastAccessed = new Date().toISOString();++ // Load related memory IDs from links table+ const links = await query(+ 'SELECT target_id FROM memory_links WHERE source_id = $1',+ [id]+ );+ memory.relatedMemories = links.rows.map(r => r.target_id);++ return memory;+}++/**+ * Get memories with filters+ */+export async function getMemories(options = {}) {+ const conditions = [];+ const params = [];+ let paramIdx = 1;++ // Filter by status+ const status = options.status || 'active';+ conditions.push(`status = $${paramIdx++}`);+ params.push(status);++ // Filter by types+ if (options.types?.length > 0) {+ conditions.push(`type = ANY($${paramIdx++})`);+ params.push(options.types);+ }++ // Filter by categories+ if (options.categories?.length > 0) {+ conditions.push(`category = ANY($${paramIdx++})`);+ params.push(options.categories);+ }++ // Filter by tags (any match)+ if (options.tags?.length > 0) {+ conditions.push(`tags && $${paramIdx++}`);+ params.push(options.tags);+ }++ // Filter by app+ if (options.appId) {+ conditions.push(`source_app_id = $${paramIdx++}`);+ params.push(options.appId);+ }++ const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';++ // Count total+ const countResult = await query(`SELECT COUNT(*) as total FROM memories ${where}`, params);+ const total = parseInt(countResult.rows[0].total, 10);++ // Sort and paginate+ const sortBy = {+ createdAt: 'created_at',+ updatedAt: 'updated_at',+ importance: 'importance',+ accessCount: 'access_count'+ }[options.sortBy] || 'created_at';+ const sortOrder = options.sortOrder === 'asc' ? 'ASC' : 'DESC';+ const offset = options.offset || 0;+ const limit = options.limit || 50;++ const dataResult = await query(+ `SELECT id, type, category, tags, summary, importance, created_at, status, source_app_id+ FROM memories ${where}+ ORDER BY ${sortBy} ${sortOrder}+ LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,+ [...params, limit, offset]+ );++ const memories = dataResult.rows.map(rowToMeta);+ return { total, memories };+}++/**+ * Update a memory+ */+export async function updateMemory(id, updates) {+ // Check memory exists+ const existing = await query('SELECT * FROM memories WHERE id = $1', [id]);+ if (existing.rows.length === 0) return null;++ const fields = [];+ const params = [];+ let paramIdx = 1;++ const fieldMap = {+ content: 'content',+ summary: 'summary',+ category: 'category',+ tags: 'tags',+ confidence: 'confidence',+ importance: 'importance',+ status: 'status',+ expiresAt: 'expires_at',+ sourceAppId: 'source_app_id'+ };++ for (const [jsField, dbField] of Object.entries(fieldMap)) {+ if (updates[jsField] !== undefined) {+ fields.push(`${dbField} = $${paramIdx++}`);+ params.push(updates[jsField]);+ }+ }++ // Update summary if content changed but no explicit summary+ if (updates.content && !updates.summary) {+ fields.push(`summary = $${paramIdx++}`);+ params.push(generateSummary(updates.content));+ }++ if (fields.length === 0) return rowToMemory(existing.rows[0]);++ params.push(id);+ const result = await query(+ `UPDATE memories SET ${fields.join(', ')} WHERE id = $${paramIdx} RETURNING *`,+ params+ );++ const memory = rowToMemory(result.rows[0]);++ // Load related memories+ const links = await query('SELECT target_id FROM memory_links WHERE source_id = $1', [id]);+ memory.relatedMemories = links.rows.map(r => r.target_id);++ // Update related memories if provided+ if (updates.relatedMemories) {+ await query('DELETE FROM memory_links WHERE source_id = $1', [id]);+ for (const relId of updates.relatedMemories) {+ await query(+ 'INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',+ [id, relId]+ );+ }+ memory.relatedMemories = updates.relatedMemories;+ }++ console.log(`🧠 Memory updated: ${id}`);+ cosEvents.emit('memory:updated', { id, updates });++ return memory;+}++/**+ * Update a memory's embedding+ */+export async function updateMemoryEmbedding(id, embedding) {+ const result = await query(+ `UPDATE memories SET embedding = $1, embedding_model = $2 WHERE id = $3 RETURNING *`,+ [arrayToPgvector(embedding), DEFAULT_MEMORY_CONFIG.embeddingModel, id]+ );++ if (result.rows.length === 0) return null;++ const memory = rowToMemory(result.rows[0]);+ memory.embedding = embedding;++ console.log(`🧠 Memory embedding updated: ${id}`);+ return memory;+}++/**+ * Delete a memory (soft delete by default)+ */+export async function deleteMemory(id, hard = false) {+ if (hard) {+ // Hard delete — cascades to memory_links via ON DELETE CASCADE+ await query('DELETE FROM memories WHERE id = $1', [id]);+ } else {+ // Soft delete — mark as archived+ await query("UPDATE memories SET status = 'archived' WHERE id = $1", [id]);+ }++ console.log(`🧠 Memory deleted: ${id} (hard: ${hard})`);+ cosEvents.emit('memory:deleted', { id, hard });++ return { success: true, id };+}++/**+ * Helper to decrement agent's pendingApproval count+ */+async function decrementAgentPendingApproval(sourceAgentId) {+ if (!sourceAgentId) return;++ const { getAgent } = await import('./cos.js');+ const agent = await getAgent(sourceAgentId).catch(() => null);+ if (!agent?.memoryExtraction?.pendingApproval) return;++ const currentPending = agent.memoryExtraction.pendingApproval;+ if (currentPending > 0) {+ await updateAgent(sourceAgentId, {+ memoryExtraction: {+ ...agent.memoryExtraction,+ pendingApproval: currentPending - 1+ }+ });+ }+}++/**+ * Approve a pending memory+ */+export async function approveMemory(id) {+ const existing = await query('SELECT * FROM memories WHERE id = $1', [id]);+ if (existing.rows.length === 0) return { success: false, error: 'Memory not found' };++ const row = existing.rows[0];+ if (row.status !== 'pending_approval') {+ return { success: false, error: 'Memory is not pending approval' };+ }++ await query("UPDATE memories SET status = 'active' WHERE id = $1", [id]);++ console.log(`🧠 Memory approved: ${id}`);+ const memory = rowToMemory({ ...row, status: 'active' });+ cosEvents.emit('memory:approved', { id, memory });++ await notifications.removeByMetadata('memoryId', id);+ await decrementAgentPendingApproval(row.source_agent_id);++ return { success: true, memory };+}++/**+ * Reject a pending memory (hard deletes it)+ */+export async function rejectMemory(id) {+ const existing = await query('SELECT * FROM memories WHERE id = $1', [id]);+ if (existing.rows.length === 0) return { success: false, error: 'Memory not found' };++ const row = existing.rows[0];+ if (row.status !== 'pending_approval') {+ return { success: false, error: 'Memory is not pending approval' };+ }++ const sourceAgentId = row.source_agent_id;++ await query('DELETE FROM memories WHERE id = $1', [id]);++ console.log(`🧠 Memory rejected: ${id}`);+ cosEvents.emit('memory:rejected', { id });++ await notifications.removeByMetadata('memoryId', id);+ await decrementAgentPendingApproval(sourceAgentId);++ return { success: true, id };+}++// =============================================================================+// Search Operations+// =============================================================================++/**+ * Search memories semantically using pgvector cosine similarity+ */+export async function searchMemories(queryEmbedding, options = {}) {+ if (!queryEmbedding) return { total: 0, memories: [] };++ const minRelevance = options.minRelevance || 0.7;+ const limit = options.limit || 20;++ const conditions = ["status = 'active'"];+ const params = [arrayToPgvector(queryEmbedding), minRelevance, limit];+ let paramIdx = 4;++ if (options.types?.length > 0) {+ conditions.push(`type = ANY($${paramIdx++})`);+ params.push(options.types);+ }+ if (options.categories?.length > 0) {+ conditions.push(`category = ANY($${paramIdx++})`);+ params.push(options.categories);+ }+ if (options.tags?.length > 0) {+ conditions.push(`tags && $${paramIdx++}`);+ params.push(options.tags);+ }+ if (options.appId) {+ conditions.push(`source_app_id = $${paramIdx++}`);+ params.push(options.appId);+ }++ const where = conditions.join(' AND ');++ // Use pgvector cosine distance operator <=>+ // Cosine distance = 1 - cosine_similarity, so similarity = 1 - distance+ const result = await query(+ `SELECT id, type, category, tags, summary, importance, created_at, status, source_app_id,+ 1 - (embedding <=> $1) AS similarity+ FROM memories+ WHERE embedding IS NOT NULL AND ${where}+ AND 1 - (embedding <=> $1) >= $2+ ORDER BY embedding <=> $1+ LIMIT $3`,+ params+ );++ const memories = result.rows.map(row => ({+ ...rowToMeta(row),+ similarity: parseFloat(row.similarity)+ }));++ return { total: memories.length, memories };+}++/**+ * Hybrid search combining full-text (tsvector) and vector similarity+ * Uses Reciprocal Rank Fusion (RRF) to merge rankings+ */+export async function hybridSearchMemories(queryText, queryEmbedding, options = {}) {+ const { limit = 20, minRelevance = 0.5, bm25Weight = 0.4, vectorWeight = 0.6 } = options;+ const RRF_K = 60;++ const filterConditions = ["status = 'active'"];+ const filterParams = [];+ let paramIdx = 1;++ if (options.types?.length > 0) {+ filterConditions.push(`type = ANY($${paramIdx++})`);+ filterParams.push(options.types);+ }+ if (options.categories?.length > 0) {+ filterConditions.push(`category = ANY($${paramIdx++})`);+ filterParams.push(options.categories);+ }+ if (options.tags?.length > 0) {+ filterConditions.push(`tags && $${paramIdx++}`);+ filterParams.push(options.tags);+ }+ if (options.appId) {+ filterConditions.push(`source_app_id = $${paramIdx++}`);+ filterParams.push(options.appId);+ }++ const filterWhere = filterConditions.join(' AND ');+ const fetchLimit = limit * 2;++ // Get full-text search results (replaces BM25)+ let ftsResults = [];+ if (queryText) {+ const ftsQuery = queryText.split(/\s+/).filter(Boolean).join(' & ');+ const ftsResult = await query(+ `SELECT id, type, category, tags, summary, importance, created_at, status, source_app_id,+ ts_rank(to_tsvector('english', coalesce(content, '') || ' ' || coalesce(summary, '')),+ to_tsquery('english', $${paramIdx})) AS fts_score+ FROM memories+ WHERE ${filterWhere}+ AND to_tsvector('english', coalesce(content, '') || ' ' || coalesce(summary, ''))+ @@ to_tsquery('english', $${paramIdx})+ ORDER BY fts_score DESC+ LIMIT $${paramIdx + 1}`,+ [...filterParams, ftsQuery, fetchLimit]+ );+ ftsResults = ftsResult.rows;+ }++ // Get vector similarity results+ let vectorResults = [];+ if (queryEmbedding) {+ const vecParamStart = paramIdx + 2;+ const vectorResult = await query(+ `SELECT id, type, category, tags, summary, importance, created_at, status, source_app_id,+ 1 - (embedding <=> $${vecParamStart}) AS similarity+ FROM memories+ WHERE embedding IS NOT NULL AND ${filterWhere}+ AND 1 - (embedding <=> $${vecParamStart}) >= $${vecParamStart + 1}+ ORDER BY embedding <=> $${vecParamStart}+ LIMIT $${vecParamStart + 2}`,+ [...filterParams, arrayToPgvector(queryEmbedding), minRelevance * 0.5, fetchLimit]+ );+ vectorResults = vectorResult.rows;+ }++ // Apply Reciprocal Rank Fusion+ const rrfScores = new Map();++ ftsResults.forEach((row, rank) => {+ const current = rrfScores.get(row.id) || { row, bm25Rank: null, vectorRank: null, rrfScore: 0 };+ current.row = row;+ current.bm25Rank = rank + 1;+ current.rrfScore += bm25Weight / (RRF_K + rank + 1);+ rrfScores.set(row.id, current);+ });++ vectorResults.forEach((row, rank) => {+ const current = rrfScores.get(row.id) || { row, bm25Rank: null, vectorRank: null, rrfScore: 0 };+ if (!current.row) current.row = row;+ current.vectorRank = rank + 1;+ current.rrfScore += vectorWeight / (RRF_K + rank + 1);+ rrfScores.set(row.id, current);+ });++ const results = Array.from(rrfScores.values())+ .map(data => ({+ ...rowToMeta(data.row),+ rrfScore: data.rrfScore,+ bm25Rank: data.bm25Rank,+ vectorRank: data.vectorRank,+ searchMethod: data.bm25Rank && data.vectorRank ? 'hybrid' :+ data.bm25Rank ? 'bm25' : 'vector'+ }))+ .sort((a, b) => b.rrfScore - a.rrfScore)+ .slice(0, limit);++ return { total: results.length, memories: results };+}++/**+ * Rebuild the BM25 index — no-op for PostgreSQL (tsvector is automatic)+ */+export async function rebuildBM25Index() {+ // tsvector indexes are maintained automatically by PostgreSQL+ // This function exists for API compatibility+ const result = await query("SELECT COUNT(*) as count FROM memories WHERE status = 'active'");+ return { rebuilt: true, documents: parseInt(result.rows[0].count, 10) };+}++/**+ * Get BM25/FTS stats+ */+export async function getBM25Stats() {+ const result = await query(`+ SELECT COUNT(*) as doc_count,+ COUNT(DISTINCT unnest_tag) as unique_tags+ FROM memories, LATERAL unnest(tags) AS unnest_tag+ WHERE status = 'active'+ `).catch(() => ({ rows: [{ doc_count: 0, unique_tags: 0 }] }));++ const totalResult = await query("SELECT COUNT(*) as total FROM memories WHERE status = 'active'");++ return {+ documentCount: parseInt(totalResult.rows[0].total, 10),+ backend: 'postgresql-tsvector'+ };+}++// =============================================================================+// Aggregation & Timeline+// =============================================================================++/**+ * Get timeline data (memories grouped by date)+ */+export async function getTimeline(options = {}) {+ const conditions = ["status = 'active'"];+ const params = [];+ let paramIdx = 1;++ if (options.startDate) {+ conditions.push(`created_at >= $${paramIdx++}`);+ params.push(options.startDate);+ }+ if (options.endDate) {+ conditions.push(`created_at <= $${paramIdx++}`);+ params.push(options.endDate);+ }+ if (options.types?.length > 0) {+ conditions.push(`type = ANY($${paramIdx++})`);+ params.push(options.types);+ }+ if (options.appId) {+ conditions.push(`source_app_id = $${paramIdx++}`);+ params.push(options.appId);+ }++ const where = conditions.join(' AND ');+ const limit = options.limit || 100;++ const result = await query(+ `SELECT id, type, category, tags, summary, importance, created_at, status, source_app_id+ FROM memories WHERE ${where}+ ORDER BY created_at DESC+ LIMIT $${paramIdx}`,+ [...params, limit]+ );++ // Group by date+ const timeline = {};+ for (const row of result.rows) {+ const meta = rowToMeta(row);+ const date = meta.createdAt.split('T')[0];+ if (!timeline[date]) timeline[date] = [];+ timeline[date].push(meta);+ }++ return timeline;+}++/**+ * Get all unique categories with counts+ */+export async function getCategories() {+ const result = await query(`+ SELECT category AS name, COUNT(*) AS count+ FROM memories WHERE status = 'active'+ GROUP BY category+ ORDER BY count DESC+ `);+ return result.rows.map(r => ({ name: r.name, count: parseInt(r.count, 10) }));+}++/**+ * Get all unique tags with counts+ */+export async function getTags() {+ const result = await query(`+ SELECT tag AS name, COUNT(*) AS count+ FROM memories, LATERAL unnest(tags) AS tag+ WHERE status = 'active'+ GROUP BY tag+ ORDER BY count DESC+ `);+ return result.rows.map(r => ({ name: r.name, count: parseInt(r.count, 10) }));+}++// =============================================================================+// Relationships+// =============================================================================++/**+ * Get related memories (by links + embedding similarity)+ */+export async function getRelatedMemories(id, limit = 10) {+ const existing = await query('SELECT embedding FROM memories WHERE id = $1', [id]);+ if (existing.rows.length === 0) return [];++ const related = [];++ // Get explicitly linked memories+ const links = await query(`+ SELECT m.id, m.type, m.category, m.tags, m.summary, m.importance, m.created_at, m.status, m.source_app_id+ FROM memory_links ml+ JOIN memories m ON m.id = ml.target_id+ WHERE ml.source_id = $1 AND m.status = 'active'+ `, [id]);++ for (const row of links.rows) {+ related.push({ ...rowToMeta(row), relationship: 'linked', similarity: 1.0 });+ }++ // Get similar by embedding+ const embedding = existing.rows[0].embedding;+ if (embedding) {+ const seenIds = new Set([id, ...related.map(r => r.id)]);+ const remaining = limit - related.length + seenIds.size;++ const similar = await query(`+ SELECT id, type, category, tags, summary, importance, created_at, status, source_app_id,+ 1 - (embedding <=> $1) AS similarity+ FROM memories+ WHERE id != $2 AND embedding IS NOT NULL AND status = 'active'+ ORDER BY embedding <=> $1+ LIMIT $3+ `, [embedding, id, remaining]);++ for (const row of similar.rows) {+ if (seenIds.has(row.id)) continue;+ related.push({+ ...rowToMeta(row),+ relationship: 'similar',+ similarity: parseFloat(row.similarity)+ });+ }+ }++ return related.slice(0, limit);+}++/**+ * Get graph data for visualization+ */+export async function getGraphData() {+ // Build nodes+ const nodesResult = await query(`+ SELECT id, type, category, summary, importance+ FROM memories WHERE status = 'active'+ `);++ const nodes = nodesResult.rows.map(r => ({+ id: r.id,+ type: r.type,+ category: r.category,+ summary: r.summary,+ importance: r.importance+ }));++ // Build edges from explicit links+ const linksResult = await query(`+ SELECT DISTINCT ON (LEAST(source_id, target_id), GREATEST(source_id, target_id))+ source_id AS source, target_id AS target+ FROM memory_links ml+ JOIN memories ms ON ms.id = ml.source_id AND ms.status = 'active'+ JOIN memories mt ON mt.id = ml.target_id AND mt.status = 'active'+ `);++ const edges = linksResult.rows.map(r => ({+ source: r.source,+ target: r.target,+ type: 'linked',+ weight: 1.0+ }));++ // Add similarity edges (top 3 per node, > 0.8 similarity)+ // Using a limited approach to avoid O(n^2) for large graphs+ const seenEdges = new Set(edges.map(e => [e.source, e.target].sort().join('-')));++ const simResult = await query(`+ SELECT a.id AS source_id, b.id AS target_id,+ 1 - (a.embedding <=> b.embedding) AS similarity+ FROM memories a+ CROSS JOIN LATERAL (+ SELECT id, embedding+ FROM memories+ WHERE id != a.id AND embedding IS NOT NULL AND status = 'active'+ ORDER BY embedding <=> a.embedding+ LIMIT 3+ ) b+ WHERE a.embedding IS NOT NULL AND a.status = 'active'+ AND 1 - (a.embedding <=> b.embedding) >= 0.8+ `);++ for (const row of simResult.rows) {+ const edgeKey = [row.source_id, row.target_id].sort().join('-');+ if (!seenEdges.has(edgeKey)) {+ seenEdges.add(edgeKey);+ edges.push({+ source: row.source_id,+ target: row.target_id,+ type: 'similar',+ weight: parseFloat(row.similarity)+ });+ }+ }++ return { nodes, edges };+}++/**+ * Link two memories+ */+export async function linkMemories(sourceId, targetId) {+ // Verify both exist+ const check = await query(+ 'SELECT id FROM memories WHERE id = ANY($1)',+ [[sourceId, targetId]]+ );+ if (check.rows.length < 2) return { success: false, error: 'Memory not found' };++ // Insert bidirectional links+ await query(+ `INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2), ($2, $1)+ ON CONFLICT DO NOTHING`,+ [sourceId, targetId]+ );++ return { success: true, sourceId, targetId };+}++// =============================================================================+// Maintenance Operations+// =============================================================================++/**+ * Consolidate similar memories (merge duplicates)+ */+export async function consolidateMemories(threshold = 0.9, dryRun = false) {+ // Find pairs of active memories with similarity above threshold+ const result = await query(`+ SELECT a.id AS id_a, a.summary AS summary_a, a.importance AS importance_a,+ b.id AS id_b, b.summary AS summary_b, b.importance AS importance_b,+ 1 - (a.embedding <=> b.embedding) AS similarity+ FROM memories a+ JOIN memories b ON a.id < b.id+ WHERE a.embedding IS NOT NULL AND b.embedding IS NOT NULL+ AND a.status = 'active' AND b.status = 'active'+ AND 1 - (a.embedding <=> b.embedding) >= $1+ ORDER BY similarity DESC+ `, [threshold]);++ // Build clusters using union-find+ const parent = new Map();+ const find = (x) => {+ if (!parent.has(x)) parent.set(x, x);+ if (parent.get(x) !== x) parent.set(x, find(parent.get(x)));+ return parent.get(x);+ };+ const union = (a, b) => parent.set(find(a), find(b));++ for (const row of result.rows) {+ union(row.id_a, row.id_b);+ }++ // Group by cluster root+ const clusters = new Map();+ const allIds = new Set();+ for (const row of result.rows) {+ allIds.add(row.id_a);+ allIds.add(row.id_b);+ }++ const importanceMap = new Map();+ const summaryMap = new Map();+ for (const row of result.rows) {+ importanceMap.set(row.id_a, row.importance_a);+ importanceMap.set(row.id_b, row.importance_b);+ summaryMap.set(row.id_a, row.summary_a);+ summaryMap.set(row.id_b, row.summary_b);+ }++ for (const id of allIds) {+ const root = find(id);+ if (!clusters.has(root)) clusters.set(root, []);+ clusters.get(root).push(id);+ }++ const duplicateClusters = Array.from(clusters.values()).filter(c => c.length > 1);++ if (dryRun) {+ return {+ dryRun: true,+ clustersFound: duplicateClusters.length,+ memoriesAffected: duplicateClusters.reduce((sum, c) => sum + c.length, 0),+ clusters: duplicateClusters.map(c => c.map(id => ({+ id,+ summary: summaryMap.get(id) || ''+ })))+ };+ }++ let merged = 0;+ for (const cluster of duplicateClusters) {+ // Sort by importance, keep highest+ cluster.sort((a, b) => (importanceMap.get(b) || 0) - (importanceMap.get(a) || 0));++ for (let i = 1; i < cluster.length; i++) {+ await query("UPDATE memories SET status = 'archived' WHERE id = $1", [cluster[i]]);+ merged++;+ }+ }++ console.log(`🧠 Consolidated ${merged} duplicate memories into ${duplicateClusters.length} clusters`);+ return { merged, clusters: duplicateClusters.length };+}++/**+ * Apply importance decay to old memories+ */+export async function applyDecay(decayRate = 0.01) {+ const result = await query(`+ SELECT id, importance, created_at, last_accessed+ FROM memories WHERE status = 'active'+ `);++ const now = Date.now();+ let updated = 0;++ for (const row of result.rows) {+ const ageInDays = (now - new Date(row.created_at).getTime()) / (1000 * 60 * 60 * 24);+ const accessRecency = row.last_accessed+ ? (now - new Date(row.last_accessed).getTime()) / (1000 * 60 * 60 * 24)+ : ageInDays;++ const accessBoost = Math.max(0, 0.1 - accessRecency * 0.001);+ const newImportance = Math.max(0.1, row.importance * (1 - decayRate * Math.sqrt(ageInDays)) + accessBoost);++ if (newImportance < 0.15 && ageInDays > 30) {+ await query("UPDATE memories SET status = 'archived', importance = $1 WHERE id = $2", [newImportance, row.id]);+ updated++;+ } else if (Math.abs(newImportance - row.importance) > 0.01) {+ await query("UPDATE memories SET importance = $1 WHERE id = $2", [newImportance, row.id]);+ updated++;+ }+ }++ console.log(`🧠 Decay applied to ${updated} memories`);+ return { updated };+}++/**+ * Clear expired memories+ */+export async function clearExpired() {+ const result = await query(`+ UPDATE memories SET status = 'expired'+ WHERE status = 'active' AND expires_at IS NOT NULL AND expires_at < NOW()+ `);++ const cleared = result.rowCount;+ console.log(`🧠 Cleared ${cleared} expired memories`);+ return { cleared };+}++// =============================================================================+// Stats+// =============================================================================++/**+ * Get memory stats+ */+export async function getStats() {+ const result = await query(`+ SELECT+ COUNT(*) AS total,+ COUNT(*) FILTER (WHERE status = 'active') AS active,+ COUNT(*) FILTER (WHERE status = 'archived') AS archived,+ COUNT(*) FILTER (WHERE status = 'expired') AS expired,+ COUNT(*) FILTER (WHERE status = 'pending_approval') AS pending_approval,+ COUNT(*) FILTER (WHERE embedding IS NOT NULL) AS with_embeddings,+ MAX(updated_at) AS last_updated+ FROM memories+ `);++ const row = result.rows[0];++ // Type breakdown+ const typeResult = await query(`+ SELECT type, COUNT(*) AS count FROM memories GROUP BY type+ `);+ const byType = {};+ for (const r of typeResult.rows) byType[r.type] = parseInt(r.count, 10);++ // Category breakdown+ const catResult = await query(`+ SELECT category, COUNT(*) AS count FROM memories GROUP BY category+ `);+ const byCategory = {};+ for (const r of catResult.rows) byCategory[r.category] = parseInt(r.count, 10);++ return {+ total: parseInt(row.total, 10),+ active: parseInt(row.active, 10),+ archived: parseInt(row.archived, 10),+ expired: parseInt(row.expired, 10),+ pendingApproval: parseInt(row.pending_approval, 10),+ withEmbeddings: parseInt(row.with_embeddings, 10),+ byType,+ byCategory,+ lastUpdated: row.last_updated?.toISOString() ?? null+ };+}++/**+ * Invalidate caches — no-op for PostgreSQL (no in-memory caches)+ */+export function invalidateCaches() {+ // PostgreSQL handles all caching internally+}++/**+ * Flush BM25 index — no-op for PostgreSQL (tsvector is always consistent)+ */+export async function flushBM25Index() {+ // No-op: tsvector indexes are maintained transactionally+}diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.jsindex 67ec39cf4d..a784fecd4c 100644--- a/server/services/memoryEmbeddings.js+++ b/server/services/memoryEmbeddings.js@@ -5,7 +5,7 @@* Provides semantic search capabilities for the memory system.*/-import { DEFAULT_MEMORY_CONFIG } from './memory.js';+import { DEFAULT_MEMORY_CONFIG } from './memoryBackend.js';import { getProviderById } from './providers.js';import { getConfig as getCosConfig } from './cos.js';diff --git a/server/services/memoryExtractor.js b/server/services/memoryExtractor.jsindex 6258357acb..4f35a30942 100644--- a/server/services/memoryExtractor.js+++ b/server/services/memoryExtractor.js@@ -5,7 +5,7 @@* Supports structured MEMORY blocks and pattern-based extraction.*/-import { createMemory } from './memory.js';+import { createMemory } from './memoryBackend.js';import { generateMemoryEmbedding } from './memoryEmbeddings.js';import { cosEvents } from './cosEvents.js';import * as notifications from './notifications.js';diff --git a/server/services/memoryRetriever.js b/server/services/memoryRetriever.jsindex dda02e155a..a60d6a581d 100644--- a/server/services/memoryRetriever.js+++ b/server/services/memoryRetriever.js@@ -5,9 +5,9 @@* Combines semantic search with importance scoring.*/-import { getMemories, searchMemories, hybridSearchMemories, getMemory } from './memory.js';+import { getMemories, searchMemories, hybridSearchMemories, getMemory } from './memoryBackend.js';import { generateQueryEmbedding, estimateTokens, truncateToTokens } from './memoryEmbeddings.js';-import { DEFAULT_MEMORY_CONFIG } from './memory.js';+import { DEFAULT_MEMORY_CONFIG } from './memoryBackend.js';// Search mode preferenceconst SEARCH_MODE = 'hybrid'; // 'hybrid' | 'vector' | 'bm25'diff --git a/server/services/memorySync.js b/server/services/memorySync.jsnew file mode 100644index 0000000000..33bd1c2442--- /dev/null+++ b/server/services/memorySync.js@@ -0,0 +1,161 @@+/**+ * Memory Federation Sync Service+ *+ * Enables memory synchronization between PortOS instances via the+ * sync_sequence column in PostgreSQL. Peers pull changes since their+ * last known sequence number.+ *+ * Sync Protocol:+ * 1. Each memory row has an auto-incrementing sync_sequence (BIGSERIAL)+ * 2. Peers request GET /api/memory/sync?since={lastSequence}&limit=100+ * 3. Response includes memories changed since that sequence + the max sequence+ * 4. Peer stores the max sequence and uses it for the next poll+ * 5. Conflict resolution: last-writer-wins by updated_at timestamp+ */++import { query, withTransaction } from '../lib/db.js';++/**+ * Get memories changed since a given sync sequence.+ * Used by peers to pull incremental updates.+ *+ * @param {number} sinceSequence - Return changes after this sequence number (0 = all)+ * @param {number} limit - Max records to return per batch+ * @returns {Promise<{memories: Array, maxSequence: number, hasMore: boolean}>}+ */+export async function getChangesSince(sinceSequence = 0, limit = 100) {+ const result = await query(+ `SELECT id, type, content, summary, category, tags,+ embedding, embedding_model, confidence, importance,+ access_count, last_accessed, status,+ source_task_id, source_agent_id, source_app_id,+ expires_at, created_at, updated_at, sync_sequence+ FROM memories+ WHERE sync_sequence > $1+ ORDER BY sync_sequence ASC+ LIMIT $2`,+ [sinceSequence, limit]+ );++ const memories = result.rows.map(row => ({+ id: row.id,+ type: row.type,+ content: row.content,+ summary: row.summary,+ category: row.category,+ tags: row.tags || [],+ embedding: row.embedding,+ embeddingModel: row.embedding_model,+ confidence: row.confidence,+ importance: row.importance,+ accessCount: row.access_count,+ lastAccessed: row.last_accessed?.toISOString() ?? null,+ status: row.status,+ sourceTaskId: row.source_task_id,+ sourceAgentId: row.source_agent_id,+ sourceAppId: row.source_app_id,+ expiresAt: row.expires_at?.toISOString() ?? null,+ createdAt: row.created_at.toISOString(),+ updatedAt: row.updated_at.toISOString(),+ syncSequence: parseInt(row.sync_sequence, 10)+ }));++ const maxSequence = memories.length > 0+ ? memories[memories.length - 1].syncSequence+ : sinceSequence;++ // Check if there are more records beyond this batch+ const countResult = await query(+ 'SELECT COUNT(*) AS remaining FROM memories WHERE sync_sequence > $1',+ [maxSequence]+ );+ const hasMore = parseInt(countResult.rows[0].remaining, 10) > 0;++ return { memories, maxSequence, hasMore };+}++/**+ * Apply incoming changes from a remote peer.+ * Uses last-writer-wins conflict resolution based on updated_at.+ *+ * @param {Array} incomingMemories - Array of memory objects from remote peer+ * @returns {Promise<{applied: number, skipped: number, conflicts: number}>}+ */+export async function applyRemoteChanges(incomingMemories) {+ let applied = 0;+ let skipped = 0;+ let conflicts = 0;++ return withTransaction(async (client) => {+ for (const mem of incomingMemories) {+ // Check if memory exists locally+ const existing = await client.query(+ 'SELECT id, updated_at FROM memories WHERE id = $1',+ [mem.id]+ );++ if (existing.rows.length === 0) {+ // New memory — insert it+ await client.query(+ `INSERT INTO memories (+ id, type, content, summary, category, tags,+ embedding, embedding_model, confidence, importance,+ access_count, last_accessed, status,+ source_task_id, source_agent_id, source_app_id,+ expires_at, created_at, updated_at+ ) VALUES (+ $1, $2, $3, $4, $5, $6,+ $7, $8, $9, $10,+ $11, $12, $13,+ $14, $15, $16,+ $17, $18, $19+ )`,+ [+ mem.id, mem.type, mem.content, mem.summary, mem.category, mem.tags || [],+ mem.embedding, mem.embeddingModel, mem.confidence, mem.importance,+ mem.accessCount || 0, mem.lastAccessed,+ mem.status, mem.sourceTaskId, mem.sourceAgentId, mem.sourceAppId,+ mem.expiresAt, mem.createdAt, mem.updatedAt+ ]+ );+ applied++;+ } else {+ // Exists — last-writer-wins by updated_at+ const localUpdatedAt = existing.rows[0].updated_at;+ const remoteUpdatedAt = new Date(mem.updatedAt);++ if (remoteUpdatedAt > localUpdatedAt) {+ await client.query(+ `UPDATE memories SET+ type = $2, content = $3, summary = $4, category = $5, tags = $6,+ embedding = $7, embedding_model = $8, confidence = $9, importance = $10,+ status = $11, expires_at = $12, updated_at = $13+ WHERE id = $1`,+ [+ mem.id, mem.type, mem.content, mem.summary, mem.category, mem.tags || [],+ mem.embedding, mem.embeddingModel, mem.confidence, mem.importance,+ mem.status, mem.expiresAt, mem.updatedAt+ ]+ );+ applied++;+ conflicts++;+ } else {+ skipped++; // Local version is newer or equal+ }+ }+ }++ return { applied, skipped, conflicts };+ });+}++/**+ * Get the current maximum sync sequence number.+ * Used by peers to determine if they're up-to-date.+ *+ * @returns {Promise<number>}+ */+export async function getMaxSequence() {+ const result = await query('SELECT COALESCE(MAX(sync_sequence), 0) AS max_seq FROM memories');+ return parseInt(result.rows[0].max_seq, 10);+}diff --git a/server/services/search.js b/server/services/search.jsindex 8ac5bfbcec..9599644334 100644--- a/server/services/search.js+++ b/server/services/search.js@@ -11,7 +11,7 @@import { getInboxLog, getPeople, getProjects, getIdeas, getAdminItems, getMemoryEntries, getLinks } from './brainStorage.js';import { searchBM25 } from './memoryBM25.js';-import { getMemories } from './memory.js';+import { getMemories } from './memoryBackend.js';import { getAllApps } from './apps.js';import { getHistory } from './history.js';