commit 85ecb086fb3c4113ca1a4e962a499cac6097a9c5 Author: Denis Markov Date: Thu Dec 3 16:59:52 2026 +0300 Память и сейф: первый публичный выпуск 1.0.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2a88daf --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +node_modules/ +.env +.env.local +*.sqlite +*.sqlite-shm +*.sqlite-wal +*.log +backups/ +pgdata/ +tests/*.local.json diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..eb7a9e3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +## 1.0.0 — 2026-12-03 + +Первый публичный выпуск. + +- Память агента: `memory_save`, `memory_search`, `memory_list`, `memory_update`, `memory_forget`, `memory_migrate`. +- Разделы заметок (`collection`): `personal`, `home-server`, имя проекта/сайта, `dsh`, `general`. +- Хранение: локальная SQLite всегда, зеркало в PostgreSQL, когда сервер доступен; чтение «сервер → локально → досыл»; отложенные удаления. +- Индексация: FTS5 в SQLite; GIN по словоформам, триграммам и тегам в PostgreSQL. +- Сейф: отдельная таблица секретов, `secret_save/list/get/forget`, менеджер паролей в карточке плагина и вкладке правой панели. +- Глобальные правила памяти и секретов в системном промпте. +- Команда `/memory`: `list`, `search`, `add`, `update`, `forget`, `secrets`, `migrate`, `status`. +- Встроенный скилл `dsh-memory-external-db` для развёртывания внешней базы по просьбе пользователя. +- Volatile-настройки хранилища без перезапуска; готовые `sql/schema.sql` и `sql/compose.yaml`. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a41fc81 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Denis Markov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b1dbe11 --- /dev/null +++ b/README.md @@ -0,0 +1,153 @@ +# Память и сейф (@itmarkov/dsh-memory-vault) + +Плагин DeepSeek Harness, который держит две вещи вместе: долговременную память агента (заметки, разделы, recall, правила в системном промпте) и сейф для паролей, токенов и ключей с менеджером прямо в интерфейсе. + +Данные пишутся в локальную SQLite и зеркалятся в PostgreSQL на домашнем сервере, когда он доступен; чтение сначала идёт на сервер, при пустом ответе — в локальную базу, а найденное локально досылается на сервер. Секреты лежат в отдельной таблице и не попадают в заметки. + +## Установка + +DSH, GUI: **Plugins → Add plugin** → `@itmarkov/dsh-memory-vault` → **Install**. + +CLI: + + dsh plugin add @itmarkov/dsh-memory-vault + +Локальная разработка (папка или tarball): **Add plugin** принимает абсолютный путь к этому каталогу или `.tgz` из `npm pack`. + +Требования: DeepSeek Harness 0.2.x и Node.js >= 22.13 (плагину нужен встроенный `node:sqlite`). PostgreSQL не обязателен — без него всё работает локально. + +## Публикация (для мейнтейнера) + + npm login + npm pack --dry-run # проверить состав пакета + npm publish --access public + +Версия в `package.json` — единственный триггер обновления у пользователей. Откат: `npm deprecate @itmarkov/dsh-memory-vault@ "reason"` и выпуск исправленной версии. + +## Внешняя база по просьбе + +В плагин встроен скилл `dsh-memory-external-db`. Пользователю достаточно попросить словами — «разверни внешнюю базу для памяти», «подключи плагин к серверному Postgres», «перенеси память на сервер». Агент по этому скиллу: + +1. Спросит, где разворачивать (свой SSH-хост, VPS, существующий Postgres), можно ли Docker, нужен ли доступ только по LAN, какие имена БД и пользователя, делать ли бэкапы. +2. Проверит доступ по SSH, наличие Docker, свободный порт и место на диске — и остановится, если что-то не так. +3. Поднимет контейнер `postgres:18-alpine` в `/opt/dsh-memory` с паролем только в `.env.local`, применит схему и дождётся healthcheck. +4. Пропишет `DSH_MEMORY_PG_URL` в `$DSH_HOME/.env` (или заполнит поля в карточке), переключит режим и проверит API-статус, recall и `secret_list`. +5. Напомнит про LAN-only, SCRAM, бэкапы `pg_dump` и то, что секреты лежат в открытом виде. + +Откат — `docker compose down` без `-v`, удалить каталог и строку из `.env`. + +## Разделы заметок (collections) + +У каждой заметки есть раздел — `collection`: + +- `personal` — всё о пользователе: предпочтения, стиль, привычки; +- `home-server` — инфраструктура: домашний сервер, docker, сети, сервисы; +- имя проекта или сайта (`autoan`, `itmarkov.ru`, …) — всё про конкретный проект; +- `dsh` — сам DeepSeek Harness и его плагины; +- `general` — если ничего не подходит. + +Раздел задаётся при `memory_save`/`memory_update` и фильтруется в `memory_search`/`memory_list` параметром `collection`. Старые заметки при первом подключении размечаются автоматически: по тегам (`home-server`, `инфраструктура`, `предпочтения`) и по имени рабочего каталога. + +## Индексация + +- **SQLite**: FTS5-таблица `memory_entries_fts` с триггерами на вставку/правку/удаление и префиксным поиском; плюс btree-индексы по `(collection, pinned, updated_at)` и `(scope, workspace)`. Если FTS не находит — обычный `instr` по тексту. +- **PostgreSQL**: `GIN` по `to_tsvector('russian', body)` для словоформ, `GIN pg_trgm` по тексту для подстроки, `GIN` по массиву тегов, btree по `(collection, pinned, updated_at)`. +- Поиск: сначала FTS/tsquery, затем подстрочный `ILIKE … ESCAPE`, затем точное совпадение тега — все три используют индексы. + +## Как работает + +- **Запись**: всегда в локальную SQLite и сразу же в PostgreSQL, если сервер доступен. Неудачное зеркалирование помечает строку `synced = 0`, и она догоняется при следующем подключении. Удаления при недоступном сервере откладываются в `memory_tombstones`. +- **Чтение**: сначала сервер; если там пусто — локальная база, и найденные локально записи досылаются на сервер. Поэтому память не теряется ни при падении сервера, ни при работе с локальной моделью. +- **Режим `local`/`server`** меняет только сторону чтения, а не сторону записи. +- **Фолбэк**: если сервер выбран, но недоступен, чтение идёт из локальной базы, а всё новое пишется локально и синхронизируется позже. + +## Пароли и ключи в карточке + +В карточке плагина (`Plugins → Memory`) под настройками есть менеджер паролей в духе Google Password Manager: карточки с аватаркой сервиса, поиск по названию/логину/сайту, кнопки показать, скопировать, изменить и удалить, редактор с полями и подсказками. Значение показывается на 30 секунд, копируется в буфер одной кнопкой. Список отдаёт только метаданные; значение выдаётся по кнопке «Показать» и сопровождается предупреждением. + +Менеджер работает в веб-интерфейсе по `http://`; в сборке, загруженной через `file://`, раздел скрыт. + +## Настройки (volatile, применяются сразу) + +| Поле | По умолчанию | Смысл | +|---|---|---| +| `mode` | `local` | `local` — SQLite, `server` — PostgreSQL | +| `host` | `192.168.31.4` | хост сервера | +| `port` | `5434` | порт PostgreSQL | +| `database` | `dsh_memory` | имя базы | +| `user` | `dsh_memory` | пользователь базы | +| `password` | — | секретное поле; пустое значение использует `DSH_MEMORY_PG_URL` | +| `autoFallback` | `true` | работать на локальной базе, пока сервер недоступен | +| `autoRecall` | `true` | вставлять блок recall в контекст | +| `maxRecall` | `12` | сколько заметок максимум в блоке | +| `maxRecallChars` | `2400` | предел длины блока | + +Пароль можно не вводить в карточке: строка подключения целиком берётся из `DSH_MEMORY_PG_URL` в `$DSH_HOME/.env`. + +## Что даёт агенту + +- `memory_save` — сохранить заметку (`scope: global | workspace`, теги, `pinned`); +- `memory_update` — переписать существующую заметку на месте по id (меняются только переданные поля, история и id сохраняются); +- `memory_search` — поиск по подстроке или точному тегу; +- `memory_list`, `memory_forget` — просмотр и удаление; +- `secret_save/list/get/forget` — отдельное хранилище паролей, токенов и ключей; +- `memory_migrate` — досинхронизировать локальные записи на сервер; +- автоматический recall закреплённых и свежих заметок; +- команда `/memory`: `list`, `search`, `add`, `update <текст>`, `forget`, `secrets`, `migrate`, `status`. + +## Внешняя база + +PostgreSQL не обязателен, но если нужен серверный режим: + +1. Поднять Postgres 16+ (проще всего контейнером — пример в `sql/compose.yaml`), привязать порт к LAN-адресу, не открывать его в интернет. +2. Применить схему: `psql "$DSH_MEMORY_PG_URL" -f sql/schema.sql` (плагин и сам создаст недостающее, файл нужен для индексов и `pg_trgm` заранее). +3. Положить строку подключения в `$DSH_HOME/.env`: + + DSH_MEMORY_PG_URL=postgresql://dsh_memory:<пароль>@:5434/dsh_memory + +4. Выбрать в карточке режим `server`, если читать нужно с сервера; запись всё равно идёт в оба хранилища. + +Либо попросить агента словами — он развернёт по встроенному скиллу `dsh-memory-external-db` (см. выше). + +## Хранилище секретов + +Пароли, токены, API-ключи и пары логин/пароль лежат в отдельной таблице `memory_secrets` — не в заметках памяти. + +- `secret_save` — сохранить или провернуть значение (одинаковое имя перезаписывает); ответ никогда не содержит само значение; +- `secret_list` — только метаданные: имя, логин, URL, теги, состояние синхронизации; +- `secret_get` — выдать значение по id или точному имени; перед показом пользователю модель предупреждает, что значение останется в логе сессии; +- `secret_forget` — удалить из обеих баз. + +**Порядок работы с доступом**: нужен доступ к внешнему ресурсу → `secret_list`; если запись есть — `secret_get` и передать значение через переменную окружения или аргумент инструмента; если записи нет — спросить у пользователя ровно недостающее (логин, пароль, токен, URL), сразу сохранить через `secret_save` и продолжить задачу. Угадывать пароли, подставлять чужие креды или пробовать значения по умолчанию запрещено. + +**Запись всегда в обе базы**, когда включён серверный режим: значение пишется в локальную SQLite и зеркалится в PostgreSQL. Если сервер в этот момент недоступен, запись помечается `synced = 0` и догоняется при первом успешном подключении. При выключенном серверном режиме всё остаётся локально. + +Значения хранятся **в открытом виде** в обеих базах: доступ к файлу SQLite или к PostgreSQL означает доступ к секретам. Для автоматизации лучше передавать их через переменные окружения или `$DSH_HOME/.env`, а не печатать в чат. + +Команда `/memory secrets` показывает список секретов без значений. + +## Глобальные правила работы с памятью + +Плагин добавляет в системный промпт каждой сессии секцию `memory:rules` — методику, перенесённую из thatch: + +- **одного сигнала достаточно** — сохранять сразу, не спрашивая пользователя, при появлении предпочтения, исправления, договорённости, архитектурного решения с причиной, факта об окружении или неочевидной ловушки; +- **сначала проверить, потом писать** — `memory_search`, затем обновление: старую заметку забыть, исправленную сохранить, без противоречащих дублей; +- **одна тема на заметку**, написанная для будущей сессии без контекста; `global` — про пользователя и окружение, `workspace` — про проект; +- **что не сохранять**: временное состояние задачи, секреты, то, что уже есть в репозитории или `AGENTS.md`, непроверенные утверждения, point-in-time значения (номера строк, счётчики, коммиты); +- **durability test**: будет ли это верно и полезно в будущей сессии, которая ничего не знает о текущей; +- **память — указатель, а не истина**: политики («пользователь хочет X») авторитетны для поведения, а утверждения о коде перед использованием перепроверяются по источнику и молча исправляются; +- явные «запомни X» / «забудь X» выполняются сразу; +- после содержательной работы — проверить, не появилось ли что-то долговечное, сохранить и только потом отвечать. + +Секцию можно отключить полем `rules: false` в настройках; при урезанном наборе инструментов (без `memory_save`/`memory_search`) она не вставляется. + +## Ограничения + +- Поиск — подстрока и точный тег; семантического поиска нет. +- Миграция копирует локальные заметки в сервер, но не удаляет их; после переключения правки идут только в выбранное хранилище. +- Заметки попадают в контекст модели: секреты туда не писать. +- Локальная база и сервер не синхронизируются в обе стороны — переключение меняет активное хранилище. + +## Лицензия + +MIT. См. [LICENSE](LICENSE). diff --git a/client.js b/client.js new file mode 100644 index 0000000..9d02de3 --- /dev/null +++ b/client.js @@ -0,0 +1,646 @@ +/** + * Browser half of @itmarkov/dsh-memory-vault. + * + * Настройки хранилища (volatile Config) и менеджер паролей в визуальном языке + * DeepSeek Harness: классы .dshmem-*, токены --dsw-alias-*, радиусы --dsw-radius-*. + */ +window.__ModuleLoader__.load({ + id: '@itmarkov/dsh-memory-vault', + factory(require) { + const React = require('react') + const h = React.createElement + + const NS = 'plugins.memory' + const ENTRY = 'memory' + const API = '/api/dsh-memory' + + const ru = { + title: 'Память и сейф', + mode: 'Хранилище для чтения', + modeLocal: 'Локальная SQLite', + modeServer: 'PostgreSQL на сервере', + host: 'Хост', + port: 'Порт', + database: 'База', + user: 'Пользователь', + password: 'Пароль', + passwordKeep: 'оставьте пустым, чтобы не менять', + autoFallback: 'Если сервер недоступен — читать локальную базу', + save: 'Сохранить', + saving: 'Сохраняем…', + saved: 'Сохранено', + failed: 'Не удалось сохранить', + unavailable: 'Настройки недоступны: плагин не запущен в этом профиле.', + loading: 'Загружаем настройки…', + hint: 'Запись всегда идёт в локальную SQLite и в PostgreSQL, когда сервер доступен. Чтение: сначала сервер, если там пусто — локальная база, найденное досылается на сервер. Пока сервер недоступен, всё работает локально и догоняется позже.', + secretsTitle: 'Пароли и ключи', + secretsCount: 'записей', + searchPlaceholder: 'Поиск по названию, логину или сайту', + secretsEmptyTitle: 'Пока пусто', + secretsEmptyText: 'Добавьте пароль, токен или ключ — он сохранится в обеих базах.', + noResultsTitle: 'Ничего не найдено', + noResultsText: 'Попробуйте другое название, логин или сайт.', + secretsGuide: 'Пароли, токены и ключи: добавить, изменить, удалить, показать.', + secretsLoading: 'Загружаем…', + secretsUnavailable: 'Менеджер паролей доступен только в веб-интерфейсе по http.', + addSecret: 'Добавить', + edit: 'Изменить', + remove: 'Удалить', + reveal: 'Показать', + hide: 'Скрыть', + copy: 'Копировать', + back: 'Назад', + nameLabel: 'Название', + loginLabel: 'Логин', + valueLabel: 'Пароль / ключ', + urlLabel: 'Сайт или сервис', + notesLabel: 'Заметка', + tagsLabel: 'Теги через запятую', + saveSecret: 'Сохранить', + cancel: 'Отмена', + confirmDelete: 'Удалить секрет без возможности восстановления?', + revealWarning: 'Значение скрывается через 30 секунд. Не пересылайте скриншоты; если покажете его агенту в чате — оно останется в логе сессии.', + syncLocal: 'не синхронизировано', + synced: 'синхронизировано', + error: 'Ошибка', + nameRequired: 'Укажите название', + valueRequired: 'Укажите пароль или ключ', + } + const en = { + title: 'Memory & Vault', + mode: 'Storage to read from', + modeLocal: 'Local SQLite', + modeServer: 'PostgreSQL on the server', + host: 'Host', + port: 'Port', + database: 'Database', + user: 'User', + password: 'Password', + passwordKeep: 'leave empty to keep the current one', + autoFallback: 'Fall back to the local base while the server is unavailable', + save: 'Save', + saving: 'Saving…', + saved: 'Saved', + failed: 'Save failed', + unavailable: 'Settings are unavailable: the plugin is not running in this profile.', + loading: 'Loading settings…', + hint: 'Every write goes to the local SQLite base and to PostgreSQL when the server is reachable. Reads ask the server first, fall back to the local base, and backfill what they find. While the server is down everything keeps working locally and syncs later.', + secretsTitle: 'Passwords and keys', + secretsCount: 'items', + searchPlaceholder: 'Search by name, login, or site', + secretsEmptyTitle: 'Nothing here yet', + secretsEmptyText: 'Add a password, token, or key — it is stored in both databases.', + noResultsTitle: 'Nothing found', + noResultsText: 'Try another name, login, or site.', + secretsGuide: 'Passwords, tokens, and keys: add, edit, delete, reveal.', + secretsLoading: 'Loading…', + secretsUnavailable: 'The password manager works only in the HTTP web interface.', + addSecret: 'Add', + edit: 'Edit', + remove: 'Delete', + reveal: 'Show', + hide: 'Hide', + copy: 'Copy', + back: 'Back', + nameLabel: 'Name', + loginLabel: 'Login', + valueLabel: 'Password / key', + urlLabel: 'Site or service', + notesLabel: 'Note', + tagsLabel: 'Tags, comma separated', + saveSecret: 'Save', + cancel: 'Cancel', + confirmDelete: 'Delete this secret permanently?', + revealWarning: 'The value hides after 30 seconds. Keep screenshots private; showing it to the agent in chat leaves it in the session log.', + syncLocal: 'not synced', + synced: 'synced', + error: 'Error', + nameRequired: 'Name is required', + valueRequired: 'Password or key is required', + } + + /** + * Стили на токенах DSH. Имена классов с префиксом dshmem-, чтобы не + * пересекаться с хостом; цвета и радиусы — только через --dsw-*. + */ + const CSS = ` +.dshmem { color: var(--dsw-alias-label-primary); font-family: var(--dsw-font-family); } +.dshmem-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; } +.dshmem-title { font-size: 14px; font-weight: 600; margin: 0; } +.dshmem-caption { font-size: 12px; color: var(--dsw-alias-label-tertiary); } +.dshmem-saved { color: var(--dsw-alias-state-success-primary); } +.dshmem-search { display: flex; align-items: center; gap: 8px; height: 34px; padding: 0 12px; + border-radius: var(--dsw-radius-sm); background: var(--dsw-specific-selector); + color: var(--dsw-alias-label-tertiary); margin-bottom: 12px; } +.dshmem-search input { flex: 1; min-width: 0; border: 0; outline: 0; background: transparent; + color: var(--dsw-alias-label-primary); font: inherit; font-size: 13px; } +.dshmem-search input::placeholder { color: var(--dsw-alias-label-caption); } +.dshmem-btn { display: inline-flex; align-items: center; gap: 6px; height: 32px; padding: 0 12px; + border-radius: var(--dsw-radius-sm); border: 1px solid transparent; font: inherit; font-size: 13px; + font-weight: 500; cursor: pointer; transition: background var(--ds-transition-duration-fast) var(--ds-ease-in-out), + border-color var(--ds-transition-duration-fast) var(--ds-ease-in-out); } +.dshmem-btn-primary { background: var(--dsw-alias-button-primary-fill); color: var(--dsw-alias-label-primary-inverted); } +.dshmem-btn-primary:hover { background: var(--dsw-alias-button-primary-hover); } +.dshmem-btn-ghost { background: transparent; color: var(--dsw-alias-label-primary); + border-color: var(--dsw-alias-border-l2); } +.dshmem-btn-ghost:hover { background: var(--dsw-alias-interactive-bg-hover); } +.dshmem-btn:disabled { opacity: .5; cursor: default; } +.dshmem-icon-btn { display: inline-flex; align-items: center; justify-content: center; + width: 28px; height: 28px; padding: 0; border: 0; border-radius: var(--dsw-radius-xs); + background: transparent; color: var(--dsw-alias-label-secondary); cursor: pointer; + transition: background var(--ds-transition-duration-fast) var(--ds-ease-in-out); } +.dshmem-icon-btn:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } +.dshmem-icon-btn-danger:hover { background: var(--dsw-alias-interactive-bg-hover-danger); + color: var(--dsw-alias-state-error-primary); } +.dshmem-row { display: flex; align-items: center; gap: 12px; padding: 10px 12px; + border-radius: var(--dsw-radius-md); background: var(--dsw-alias-card-fill); + border: 1px solid var(--dsw-alias-border-l1); margin-bottom: 8px; } +.dshmem-row:hover { background: var(--dsw-alias-card-fill-hover); } +.dshmem-avatar { width: 36px; height: 36px; flex: none; border-radius: 50%; + display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 600; + background: var(--dsw-alias-bg-layer-3); color: var(--dsw-alias-label-secondary); } +.dshmem-row-main { flex: 1; min-width: 0; } +.dshmem-row-name { font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.dshmem-row-sub { font-size: 12px; color: var(--dsw-alias-label-tertiary); + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.dshmem-tags { display: flex; gap: 4px; margin-top: 4px; flex-wrap: wrap; } +.dshmem-tag { font-size: 11px; padding: 1px 8px; border-radius: var(--dsw-radius-xs); + background: var(--dsw-alias-markdown-tag); color: var(--dsw-alias-label-tertiary); } +.dshmem-value { display: flex; align-items: center; gap: 8px; margin-top: 6px; padding: 6px 10px; + border-radius: var(--dsw-radius-sm); border: 1px solid var(--dsw-alias-border-l2); + background: var(--dsw-alias-markdown-code-block); font-family: var(--ds-font-family-code); + font-size: 12px; word-break: break-all; } +.dshmem-value code { flex: 1; min-width: 0; color: var(--dsw-alias-label-primary); } +.dshmem-warn { font-size: 11px; color: var(--dsw-alias-label-caption); margin-top: 4px; } +.dshmem-dot { width: 7px; height: 7px; border-radius: 50%; flex: none; } +.dshmem-dot-ok { background: var(--dsw-alias-state-success-primary); } +.dshmem-dot-pending { background: var(--dsw-alias-state-warn-primary); } +.dshmem-form { padding: 14px; border-radius: var(--dsw-radius-md); border: 1px solid var(--dsw-alias-border-l2); + background: var(--dsw-alias-bg-layer-2); margin-bottom: 12px; } +.dshmem-form-head { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; } +.dshmem-form-title { font-size: 13px; font-weight: 600; } +.dshmem-grid { display: flex; gap: 10px; } +.dshmem-field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; flex: 1; min-width: 0; } +.dshmem-label { font-size: 12px; color: var(--dsw-alias-label-secondary); } +.dshmem-input { height: 34px; box-sizing: border-box; width: 100%; padding: 0 10px; + border-radius: var(--dsw-radius-sm); border: 1px solid var(--dsw-alias-border-l2); + background: var(--dsw-specific-input-major); color: var(--dsw-alias-label-primary); + font: inherit; font-size: 13px; outline: none; } +.dshmem-input::placeholder { color: var(--dsw-alias-label-caption); } +.dshmem-input:focus { border-color: var(--dsw-alias-border-selected); } +.dshmem-empty { text-align: center; padding: 28px 12px; border-radius: var(--dsw-radius-md); + border: 1px dashed var(--dsw-alias-border-l2); color: var(--dsw-alias-label-tertiary); } +.dshmem-empty-icon { display: flex; justify-content: center; margin-bottom: 8px; } +.dshmem-empty-title { font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-secondary); } +.dshmem-empty-text { font-size: 12px; margin-top: 4px; } +.dshmem-error { font-size: 12px; color: var(--dsw-alias-state-error-primary); } +.dshmem-hint { font-size: 12px; line-height: 1.5; color: var(--dsw-alias-label-tertiary); margin: 0 0 10px; } +.dshmem-actions { display: flex; align-items: center; gap: 8px; } +.dshmem-check { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 12px; } +` + + const icon = (paths, size = 16) => h('svg', { + viewBox: '0 0 24 24', width: size, height: size, fill: 'none', + stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', + 'aria-hidden': true, style: { display: 'block', flex: 'none' }, + }, paths.map((d, index) => h('path', { key: index, d }))) + + const icons = { + search: icon(['M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14z', 'M20 20l-3.5-3.5']), + plus: icon(['M12 5v14', 'M5 12h14']), + eye: icon(['M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6z', 'M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z']), + eyeOff: icon(['M3 3l18 18', 'M10.6 5.2A10.8 10.8 0 0 1 12 5c6.5 0 10 7 10 7a17 17 0 0 1-3.2 4.1', 'M6.3 6.5A17 17 0 0 0 2 12s3.5 7 10 7c1.6 0 3-.4 4.3-1']), + copy: icon(['M9 9h10v10H9z', 'M5 15V5h10']), + edit: icon(['M4 20h4l10-10-4-4L4 16v4z', 'M13.5 6.5l4 4']), + trash: icon(['M4 7h16', 'M9 7V5h6v2', 'M6 7l1 13h10l1-13']), + lock: icon(['M6 11h12v9H6z', 'M9 11V8a3 3 0 0 1 6 0v3'], 22), + back: icon(['M15 5l-7 7 7 7']), + check: icon(['M4 12l5 5L20 6']), + } + + const avatarLetter = (name) => { + const match = /[a-zа-яё0-9]/i.exec(name) + return match === null ? '?' : match[0].toUpperCase() + } + + const apiAvailable = () => typeof location !== 'undefined' && location.protocol !== 'file:' + + async function api(action, body) { + const response = await fetch(`${API}?action=${encodeURIComponent(action)}`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-dsh-memory': '1' }, + body: JSON.stringify(body ?? {}), + }) + const data = await response.json().catch(() => ({})) + if (!response.ok) throw new Error(data.error ?? `HTTP ${response.status}`) + return data + } + + function textField(t, label, control) { + return h('label', { className: 'dshmem-field' }, + h('span', { className: 'dshmem-label' }, label), control) + } + + function textInput(value, onChange, options = {}) { + return h('input', { + className: 'dshmem-input', + type: options.type ?? 'text', value, placeholder: options.placeholder, + autoComplete: 'off', spellCheck: false, + onChange: event => onChange(event.target.value), + }) + } + + // ------------------------------------------------------------------ + // Настройки хранилища + + function fromSnapshot(value) { + const source = value !== null && typeof value === 'object' ? value : {} + return { + mode: source.mode === 'server' ? 'server' : 'local', + host: typeof source.host === 'string' ? source.host : '192.168.31.4', + port: typeof source.port === 'number' ? String(source.port) : '5434', + database: typeof source.database === 'string' ? source.database : 'dsh_memory', + user: typeof source.user === 'string' ? source.user : 'dsh_memory', + password: '', + autoFallback: source.autoFallback !== false, + } + } + + function MemorySettings(props) { + const form = props.form + const t = props.t ?? (key => ru[key] ?? key) + const subscribe = React.useCallback(callback => (form === undefined ? () => {} : form.subscribe(callback)), [form]) + const snapshot = React.useSyncExternalStore( + subscribe, + () => (form === undefined ? { status: 'unavailable' } : form.getSnapshot()), + () => ({ status: 'unavailable' }), + ) + const [draft, setDraft] = React.useState(null) + const [notice, setNotice] = React.useState('') + const [busy, setBusy] = React.useState(false) + + if (props.view !== 'page') return null + if (form === undefined || snapshot.status === 'unavailable') return h('p', { className: 'dshmem-caption' }, t('unavailable')) + if (snapshot.status === 'loading') return h('p', { className: 'dshmem-caption' }, t('loading')) + + const value = snapshot.value !== null && typeof snapshot.value === 'object' ? snapshot.value : {} + const state = draft ?? fromSnapshot(value) + const patch = (key, next) => setDraft({ ...state, [key]: next }) + + const save = async () => { + if (busy) return + setBusy(true) + setNotice('') + const current = fromSnapshot(value) + const ops = [] + const put = (key, next) => { if (next !== current[key]) ops.push({ op: 'set', path: [key], value: next }) } + put('mode', state.mode) + put('host', state.host.trim()) + put('port', Number.parseInt(state.port, 10)) + put('database', state.database.trim()) + put('user', state.user.trim()) + put('autoFallback', state.autoFallback) + if (state.password.length > 0) ops.push({ op: 'set', path: ['password'], value: state.password }) + if (ops.length === 0) { setBusy(false); setNotice(t('saved')); return } + try { + const accepted = await form.mutate(ops, snapshot.revision) + setNotice(accepted ? t('saved') : t('failed')) + if (accepted) setDraft(null) + } catch (error) { + setNotice(`${t('failed')}: ${String(error?.message ?? error)}`) + } finally { + setBusy(false) + } + } + + const serverFields = state.mode === 'server' + ? h('div', null, + h('div', { className: 'dshmem-grid' }, + textField(t, t('host'), textInput(state.host, next => patch('host', next))), + textField(t, t('port'), textInput(state.port, next => patch('port', next), { type: 'number' }))), + h('div', { className: 'dshmem-grid' }, + textField(t, t('database'), textInput(state.database, next => patch('database', next))), + textField(t, t('user'), textInput(state.user, next => patch('user', next)))), + textField(t, t('password'), textInput(state.password, next => patch('password', next), { type: 'password', placeholder: t('passwordKeep') })), + h('label', { className: 'dshmem-check' }, + h('input', { type: 'checkbox', checked: state.autoFallback, onChange: event => patch('autoFallback', event.target.checked) }), + t('autoFallback'))) + : null + + return h('div', { className: 'dshmem', style: { paddingBottom: '10px' } }, + h('h4', { className: 'dshmem-title', style: { marginBottom: '10px' } }, t('title')), + textField(t, t('mode'), h('select', { + className: 'dshmem-input', value: state.mode, + onChange: event => patch('mode', event.target.value), + }, + h('option', { value: 'local' }, t('modeLocal')), + h('option', { value: 'server' }, t('modeServer')))), + serverFields, + h('p', { className: 'dshmem-hint' }, t('hint')), + h('div', { className: 'dshmem-actions' }, + h('button', { type: 'button', className: 'dshmem-btn dshmem-btn-primary', disabled: busy, onClick: save }, + busy ? t('saving') : t('save')), + notice.length > 0 ? h('span', { className: 'dshmem-caption' }, notice) : null)) + } + + // ------------------------------------------------------------------ + // Менеджер паролей + + const EMPTY_FORM = { id: null, name: '', username: '', value: '', url: '', notes: '', tags: '' } + + function SecretsManager(props) { + const t = props.t ?? (key => ru[key] ?? key) + const [rows, setRows] = React.useState(null) + const [error, setError] = React.useState('') + const [busy, setBusy] = React.useState(false) + const [form, setForm] = React.useState(null) + const [formError, setFormError] = React.useState('') + const [query, setQuery] = React.useState('') + const [revealed, setRevealed] = React.useState({}) + const [copied, setCopied] = React.useState('') + const [flash, setFlash] = React.useState('') + const timers = React.useRef({}) + const available = apiAvailable() + + const load = React.useCallback(async () => { + if (!available) { setRows([]); return } + try { + const data = await api('list', { limit: 200 }) + setRows(Array.isArray(data.secrets) ? data.secrets : []) + setError('') + } catch (loadError) { + setError(String(loadError?.message ?? loadError)) + setRows([]) + } + }, [available]) + + React.useEffect(() => { load() }, [load]) + React.useEffect(() => () => { Object.values(timers.current).forEach(clearTimeout) }, []) + + const scheduleHide = (id) => { + if (timers.current[id] !== undefined) clearTimeout(timers.current[id]) + timers.current[id] = setTimeout(() => { + setRevealed(current => { + const next = { ...current } + delete next[id] + return next + }) + delete timers.current[id] + }, 30000) + } + + const run = async (action, body) => { + setBusy(true) + setError('') + try { + const data = await api(action, body) + await load() + return data + } catch (actionError) { + setError(String(actionError?.message ?? actionError)) + return undefined + } finally { + setBusy(false) + } + } + + const startEdit = (row) => { + setFormError('') + setForm({ + id: row.id, name: row.name, username: row.username ?? '', value: '', + url: row.url ?? '', notes: row.notes ?? '', tags: (row.tags ?? []).join(', '), + }) + } + + const saveForm = async () => { + if (form === null) return + if (form.name.trim().length === 0) { setFormError(t('nameRequired')); return } + let value = form.value + if (form.id !== null && value.length === 0) { + const data = await run('get', { match: form.id }) + value = data?.secret?.value ?? '' + if (value.length === 0) { setFormError(t('valueRequired')); return } + } + if (form.id === null && value.length === 0) { setFormError(t('valueRequired')); return } + const saved = await run('save', { + name: form.name.trim(), value, + username: form.username || undefined, + url: form.url || undefined, + notes: form.notes || undefined, + tags: form.tags.split(',').map(tag => tag.trim()).filter(tag => tag.length > 0), + }) + if (saved !== undefined) { + setForm(null) + setFormError('') + setFlash(t('saved')) + setTimeout(() => setFlash(''), 1800) + } + } + + const remove = async (row) => { + if (typeof window !== 'undefined' && !window.confirm(t('confirmDelete'))) return + await run('forget', { match: row.id }) + } + + const reveal = async (row) => { + if (revealed[row.id] !== undefined) { + if (timers.current[row.id] !== undefined) clearTimeout(timers.current[row.id]) + delete timers.current[row.id] + const next = { ...revealed } + delete next[row.id] + setRevealed(next) + return + } + const data = await run('get', { match: row.id }) + if (data?.secret !== undefined) { + setRevealed({ ...revealed, [row.id]: data.secret.value }) + scheduleHide(row.id) + } + } + + const copyValue = async (row) => { + try { + const data = await api('get', { match: row.id }) + const value = data?.secret?.value ?? '' + if (value.length === 0) return + if (typeof navigator !== 'undefined' && navigator.clipboard !== undefined) { + await navigator.clipboard.writeText(value) + } + setCopied(row.id) + setTimeout(() => setCopied(current => (current === row.id ? '' : current)), 1600) + } catch (copyError) { + setError(String(copyError?.message ?? copyError)) + } + } + + if (!available) return h('p', { className: 'dshmem-caption' }, t('secretsUnavailable')) + + const needle = query.trim().toLowerCase() + const visible = (rows ?? []).filter(row => needle.length === 0 + || row.name.toLowerCase().includes(needle) + || String(row.username ?? '').toLowerCase().includes(needle) + || String(row.url ?? '').toLowerCase().includes(needle) + || (Array.isArray(row.tags) && row.tags.some(tag => tag.includes(needle)))) + + const header = h('div', { className: 'dshmem-head' }, + h('div', null, + h('div', { style: { display: 'flex', alignItems: 'baseline', gap: '8px' } }, + h('h4', { className: 'dshmem-title' }, t('secretsTitle')), + h('span', { className: 'dshmem-caption' }, `${rows === null ? '—' : rows.length} ${t('secretsCount')}`)), + flash.length > 0 ? h('div', { className: 'dshmem-caption dshmem-saved' }, flash) : null), + h('button', { + type: 'button', className: 'dshmem-btn dshmem-btn-primary', + onClick: () => { setFormError(''); setForm({ ...EMPTY_FORM }) }, + }, icons.plus, t('addSecret'))) + + const search = h('label', { className: 'dshmem-search' }, + icons.search, + h('input', { + value: query, placeholder: t('searchPlaceholder'), + onChange: event => setQuery(event.target.value), + })) + + const formView = form === null ? null : h('div', { className: 'dshmem-form' }, + h('div', { className: 'dshmem-form-head' }, + h('button', { + type: 'button', className: 'dshmem-icon-btn', 'aria-label': t('back'), + onClick: () => { setForm(null); setFormError('') }, + }, icons.back), + h('span', { className: 'dshmem-form-title' }, form.id === null ? t('addSecret') : t('edit'))), + h('div', { className: 'dshmem-grid' }, + textField(t, t('nameLabel'), textInput(form.name, next => setForm({ ...form, name: next }))), + textField(t, t('loginLabel'), textInput(form.username, next => setForm({ ...form, username: next })))), + textField(t, t('valueLabel'), textInput(form.value, next => setForm({ ...form, value: next }), { + type: 'password', placeholder: form.id === null ? '' : t('passwordKeep'), + })), + h('div', { className: 'dshmem-grid' }, + textField(t, t('urlLabel'), textInput(form.url, next => setForm({ ...form, url: next }))), + textField(t, t('tagsLabel'), textInput(form.tags, next => setForm({ ...form, tags: next })))), + textField(t, t('notesLabel'), textInput(form.notes, next => setForm({ ...form, notes: next }))), + formError.length > 0 ? h('p', { className: 'dshmem-error' }, formError) : null, + h('div', { className: 'dshmem-actions' }, + h('button', { type: 'button', className: 'dshmem-btn dshmem-btn-primary', disabled: busy, onClick: saveForm }, t('saveSecret')), + h('button', { type: 'button', className: 'dshmem-btn dshmem-btn-ghost', onClick: () => { setForm(null); setFormError('') } }, t('cancel')))) + + const rowView = (row) => { + const value = revealed[row.id] + const subtitle = [row.username ? `login: ${row.username}` : null, row.url ?? null].filter(Boolean).join(' · ') + return h('div', { key: row.id, className: 'dshmem-row' }, + h('div', { className: 'dshmem-avatar' }, avatarLetter(row.name)), + h('div', { className: 'dshmem-row-main' }, + h('div', { className: 'dshmem-row-name' }, row.name), + h('div', { className: 'dshmem-row-sub' }, subtitle.length > 0 ? subtitle : '—'), + Array.isArray(row.tags) && row.tags.length > 0 + ? h('div', { className: 'dshmem-tags' }, row.tags.map(tag => h('span', { key: tag, className: 'dshmem-tag' }, `#${tag}`))) + : null, + value !== undefined + ? h('div', null, + h('div', { className: 'dshmem-value' }, + h('code', null, value), + h('button', { + type: 'button', className: 'dshmem-icon-btn', title: t('copy'), + onClick: () => copyValue(row), + }, copied === row.id ? icons.check : icons.copy)), + h('div', { className: 'dshmem-warn' }, t('revealWarning'))) + : null), + h('div', { className: 'dshmem-actions' }, + h('button', { + type: 'button', className: 'dshmem-icon-btn', title: value !== undefined ? t('hide') : t('reveal'), + onClick: () => reveal(row), + }, value !== undefined ? icons.eyeOff : icons.eye), + h('button', { + type: 'button', className: 'dshmem-icon-btn', title: t('copy'), + onClick: () => copyValue(row), + }, copied === row.id ? icons.check : icons.copy), + h('button', { type: 'button', className: 'dshmem-icon-btn', title: t('edit'), onClick: () => startEdit(row) }, icons.edit), + h('button', { + type: 'button', className: 'dshmem-icon-btn dshmem-icon-btn-danger', + title: t('remove'), disabled: busy, onClick: () => remove(row), + }, icons.trash)), + h('span', { + title: row.synced === false ? t('syncLocal') : t('synced'), + className: `dshmem-dot ${row.synced === false ? 'dshmem-dot-pending' : 'dshmem-dot-ok'}`, + })) + } + + const empty = rows !== null && visible.length === 0 + ? h('div', { className: 'dshmem-empty' }, + h('div', { className: 'dshmem-empty-icon' }, needle.length > 0 ? icons.search : icons.lock), + h('div', { className: 'dshmem-empty-title' }, needle.length > 0 ? t('noResultsTitle') : t('secretsEmptyTitle')), + h('div', { className: 'dshmem-empty-text' }, needle.length > 0 ? t('noResultsText') : t('secretsEmptyText'))) + : null + + return h('div', { className: 'dshmem', style: { paddingBottom: '10px' } }, + h('style', null, CSS), + header, + form !== null ? formView : null, + form === null ? search : null, + error.length > 0 ? h('p', { className: 'dshmem-error' }, `${t('error')}: ${error}`) : null, + rows === null + ? h('p', { className: 'dshmem-caption' }, t('secretsLoading')) + : h('div', null, visible.map(rowView), empty)) + } + + // ------------------------------------------------------------------ + + const TYPE_ID = '@itmarkov/dsh-memory-vault/secrets' + const KIND = 'memory-secrets' + + function SecretsPane(props) { + const t = props.t ?? (key => ru[key] ?? key) + return h('div', { + style: { padding: '12px', overflowY: 'auto', height: '100%', boxSizing: 'border-box' }, + }, h(SecretsManager, { t })) + } + + return { + inject: ['slots', 'configForms', 'locale'], + apply(ctx) { + let t = (key) => ru[key] ?? key + try { + ctx.locale.register(NS, { ru, en }) + const bound = ctx.locale.bind(NS) + if (typeof bound === 'function') t = bound + } catch {} + + const tabs = ctx.get('sidebarRightTabs') + if (tabs !== undefined && typeof tabs.register === 'function') { + try { + ctx.effect(() => tabs.register({ + id: TYPE_ID, + kind: KIND, + title: () => t('secretsTitle'), + guide: [{ + id: 'secrets', + order: 25, + title: () => t('secretsTitle'), + description: () => t('secretsGuide'), + }], + })) + ctx.effect(() => ctx.slots.register({ + name: 'sidebar.right.pane.tab', + key: TYPE_ID, + locale: NS, + inject: () => ({ t }), + }, SecretsPane)) + } catch {} + } + + let form + try { form = ctx.configForms.get(ENTRY) } catch {} + try { + ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ + name: 'plugins.bundle.config', + key: '@itmarkov/dsh-memory-vault', + locale: NS, + inject: () => ({ form, t }), + }, function MemoryCard(props) { + return h('div', null, + h(MemorySettings, props), + h(SecretsManager, { t: props.t })) + })) + } catch {} + }, + } + }, +}) diff --git a/cordis.patch.yml b/cordis.patch.yml new file mode 100644 index 0000000..4bbf407 --- /dev/null +++ b/cordis.patch.yml @@ -0,0 +1,9 @@ +# Memory: один Host-плагин с двумя хранилищами и настройками в карточке. +# По умолчанию — локальная SQLite; PostgreSQL включается в Plugins → Memory. +- insert: + - id: memory + name: '@itmarkov/dsh-memory-vault' + config: + mode: local + autoFallback: true + autoRecall: true diff --git a/icon.svg b/icon.svg new file mode 100644 index 0000000..3226ffb --- /dev/null +++ b/icon.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/index.js b/index.js new file mode 100644 index 0000000..a9ae4c3 --- /dev/null +++ b/index.js @@ -0,0 +1,1559 @@ +/** + * @itmarkov/dsh-memory-vault — durable memory and a secret vault for DeepSeek Harness. + * + * Модель хранения: + * - локальная SQLite ($DSH_HOME/memory/memory.sqlite) — всегда и сразу; + * - PostgreSQL на домашнем сервере — зеркало, когда доступен. + * + * Запись: локально всегда, затем зеркало в Postgres; если сервер недоступен, + * строка помечается synced = 0 и догоняется при следующем подключении. + * Удаление при недоступном сервере откладывается в memory_tombstones. + * Чтение: сначала сервер; если там пусто — локальная база, а найденное + * локально досылается на сервер. + */ + +import { readFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { mkdirSync } from 'node:fs' +import { randomBytes } from 'node:crypto' +import { DatabaseSync } from 'node:sqlite' +import pg from 'pg' +import z from '@deepseek-ai/schemastery' + +const { Pool } = pg + +export const name = 'memory' +export const inject = ['tools', 'systemPrompt'] + +const MAX_BODY = 4000 +const MAX_TAGS = 8 +const MAX_TAG_LEN = 32 +const RECALL_BODY_LIMIT = 280 +const RECALL_TTL_MS = 15_000 +const PG_COOLDOWN_MS = 30_000 +const ENTRY_ID = 'memory' +const API_PATH = '/api/dsh-memory' +const API_HEADER = 'x-dsh-memory' + +const MEMORY_RULES = `## Memory + +You have durable memory shared by every session in this installation (plugin \`memory\`). +The recall block in context is a cached digest and may lag behind the store. + +- **One signal is enough.** Save immediately, without asking and without waiting for confirmation, when any of these appear: a user preference, correction, or feedback; a project convention; an architectural decision together with its reason; an environment fact; a non-obvious gotcha that will outlive this session. Never ask the user whether to save. +- **Check before writing.** Call \`memory_search\` first. If a note already covers the topic but the fact changed, rewrite it in place with \`memory_update\` (same id, same history); use \`memory_forget\` + \`memory_save\` only when the old note is about something else. Do not keep two contradicting notes. +- **One topic per note, one collection per note.** Write for a future session that knows nothing about this conversation: name the paths, commands, services, and reasons. Give the note a collection: \`personal\` for user facts and preferences, \`home-server\` for infrastructure, the project or site name (e.g. \`autoan\`, \`itmarkov.ru\`) for project knowledge, \`dsh\` for the harness itself. Scope \`global\` for user-wide facts, \`workspace\` for this project's conventions and decisions. Pin only rules that must always apply. When searching, pass \`collection\` to narrow the store. +- **Do not save:** transient task state, secrets or credentials, anything already in the repository or AGENTS.md, unverified claims, point-in-time values (line numbers, counts, commit hashes), or facts that are cheaper to re-derive from the code than to recall. +- **Durability test:** will this still be true and useful in a future session that knows nothing about this one? If not, do not save it. +- **Memories are pointers, not truth.** Policy notes ("the user wants X") are authoritative for behavior. Artifact notes ("X lives in file Y") must be re-derived from the current source before you assert them; when reality has moved on, correct the note silently. +- **Explicit requests:** "remember X" means save it now; "forget X" means search for it, then forget it. +- **Before answering** after substantial work (investigation, debugging, a decision), check whether something durable was learned and save it, then answer. + +Notes are written to the local base always and mirrored to the server when it is reachable. Save and forget through \`memory_save\`, \`memory_search\`, \`memory_list\`, and \`memory_forget\`. The user can inspect and edit the same notes with the \`/memory\` command and the plugin card. +## Secrets + +Credentials — passwords, tokens, API keys, login/password pairs — live in a separate vault, not in notes: \`secret_save\`, \`secret_list\`, \`secret_get\`, \`secret_forget\`, and the password manager in the plugin card. Never pass a credential to \`memory_save\`. + +- **Need access? Look it up first.** Before reaching an external resource (server, site, API, mail, database, registry), call \`secret_list\`; when the credential is there, call \`secret_get\` and pass the value through an environment variable or a tool argument. +- **Missing credential? Ask the user.** Never guess, reuse another credential, or try a default password. Ask for exactly what is missing (login, password, token, URL), then save it with \`secret_save\` right after the user gives it, and continue the task. +- Save a credential as soon as the user provides one and asks or implies "remember it". Saving the same name again rotates the stored value. +- \`secret_list\` returns metadata only (name, login, URL, tags, sync state). Call \`secret_get\` only when the value is actually needed: a login, an API call, a config edit. +- Values are written to the local base always and mirrored to the server when it is reachable. They are stored as plain text in both databases; anyone with file or database access can read them. For unattended automation prefer environment variables or \`$DSH_HOME/.env\` over printing values. +- The user allows seeing values, but warn first that a value printed in chat stays in this session log. Do not put credentials into files, commits, URLs, or command lines unless the user asked; pass them through environment variables where possible. +- Rotate by saving the same name again; delete with \`secret_forget\` when the user asks or when an old credential no longer works.` + +/** Встроенный скилл: развернуть внешнюю PostgreSQL и подключить к ней плагин. */ +const SETUP_SKILL = { + name: 'dsh-memory-external-db', + description: 'Provision an external PostgreSQL database for Memory & Vault and connect the plugin to it.', + whenToUse: 'When the user asks to create a server or external database for memory/secrets, connect the plugin to an external PostgreSQL, or move memory off the local SQLite.', + content: `# External PostgreSQL for Memory & Vault + +Use this playbook when the user asks to create an external database for the memory plugin, connect it to a server, or move memory off the local SQLite. Follow the steps in order; ask before acting where a choice changes the outcome. + +## 1. Clarify before deploying + +Ask only what is not already known, in one message when possible: + +- Where to deploy: their own SSH host (address, login, sudo availability), a cloud VM, or an existing PostgreSQL the user already runs? Never guess credentials. +- Revision: is Docker allowed there, or must PostgreSQL be installed as a system package? +- Exposure: LAN/VPN only (default, safe) or public? Public requires TLS and firewall work; warn that a public database port with a password is a risk. +- Names: database, user, and port. Defaults: database and user \`dsh_memory\`, port 5434. +- Backups: should a daily \`pg_dump\` be added? + +## 2. Preflight the target + +Run read-only checks and stop on failure: + + ssh -o BatchMode=yes 'echo ok; hostname; docker --version; docker compose version' + ssh 'ss -ltn | grep -E ":(5432|5434)" || true; df -h /opt | tail -1' + +If SSH asks for a password, ask the user to install a key or to run the deployment themselves. Do not guess passwords and do not reuse another credential. + +## 3. Deploy with Docker (recommended) + +Create \`/opt/dsh-memory\` with three files. Keep secrets only in \`.env.local\` (mode 600), never in compose.yaml, and never print the generated password. + +compose.yaml: + + services: + db: + image: postgres:18-alpine + container_name: dsh-memory-db + restart: unless-stopped + environment: + POSTGRES_DB: \${POSTGRES_DB:?} + POSTGRES_USER: \${POSTGRES_USER:?} + POSTGRES_PASSWORD: \${POSTGRES_PASSWORD:?} + ports: + - ":5434:5432" + volumes: + - ./pgdata:/var/lib/postgresql + - ./init:/docker-entrypoint-initdb.d:ro + healthcheck: + test: ["CMD-SHELL", "pg_isready -U \$\${POSTGRES_USER} -d \$\${POSTGRES_DB}"] + interval: 10s + timeout: 5s + retries: 12 + +init/01-schema.sql — apply pg_trgm extension and the two tables (\`memory_entries\` with \`collection\`, \`memory_secrets\`), the btree indexes, and the GIN indexes for word forms and trigrams. The plugin also creates anything missing on first connection, so a minimal \`CREATE EXTENSION IF NOT EXISTS pg_trgm;\` is enough when the user prefers to start empty. + +Start and verify: + + cd /opt/dsh-memory && docker compose --env-file .env.local up -d + docker ps --filter name=dsh-memory-db + docker exec dsh-memory-db psql -U dsh_memory -d dsh_memory -c '\\dt' + docker exec dsh-memory-db psql -U dsh_memory -d dsh_memory -tAc 'select 1' + +## 4. Connect the plugin + +Preferred: put the connection string into \`$DSH_HOME/.env\` and leave the settings password empty: + + DSH_MEMORY_PG_URL=postgresql://dsh_memory:@:5434/dsh_memory + +Alternative: fill host, port, database, user, and password in Plugins → Память и сейф. + +Then: + +- \`mode\` = \`server\` if the user wants reads from the server. Writes always go to both stores, so local notes stay safe. +- Verify with the Host API: \`POST /api/dsh-memory?action=status\` and header \`x-dsh-memory: 1\`; expect \`server: true\`. +- Push pending local rows: the \`/memory migrate\` command or the \`memory_migrate\` tool. +- Check that recall and \`memory_search\` return notes and that \`secret_list\` shows the imported credentials. + +## 5. Keep it safe + +- Bind the published port to the host's LAN address, not 0.0.0.0, unless the user explicitly asked for public access with TLS. +- Keep PostgreSQL's default SCRAM authentication; never enable \`trust\` for network connections. +- Add a daily backup when asked: \`docker exec dsh-memory-db pg_dump -Fc -U dsh_memory dsh_memory > /opt/dsh-memory/backups/.dump\` from cron, keep seven files. +- Tell the user plainly: secret values are stored as plain text in both databases, so file or database access means access to the credentials. + +## 6. Rollback + + cd /opt/dsh-memory && docker compose down # keeps pgdata + # add -v only when the user wants the data deleted + rm -rf /opt/dsh-memory + # remove DSH_MEMORY_PG_URL from $DSH_HOME/.env and set mode back to local + +## 7. Report + +State the host, port, database, and user; how the port is reached (LAN/VPN); where the password lives; that writes mirror to both stores; and where backups are written. If any verification step failed, say which one and what is still unverified.`, +} + +export const Config = z.object({ + mode: z.union([z.const('local'), z.const('server')]) + .default('local') + .description('Где читать память: локальная SQLite или PostgreSQL. Запись всегда идёт в обе базы, когда сервер доступен.') + .volatile(), + host: z.string().default('192.168.31.4').description('Хост PostgreSQL.').volatile(), + port: z.number().step(1).min(1).max(65535).default(5434).description('Порт PostgreSQL.').volatile(), + database: z.string().default('dsh_memory').description('Имя базы.').volatile(), + user: z.string().default('dsh_memory').description('Пользователь базы.').volatile(), + password: z.string().role('secret') + .description('Пароль. Пустое значение использует сохранённый DSH_MEMORY_PG_URL.') + .volatile(), + autoFallback: z.boolean().default(true).description('Если сервер недоступен — читать локальную базу.').volatile(), + autoRecall: z.boolean().default(true).description('Добавлять закреплённые и свежие заметки в контекст модели.').volatile(), + rules: z.boolean().default(true).description('Добавлять в системный промпт глобальные правила памяти и секретов.').volatile(), + maxRecall: z.number().step(1).min(1).max(50).default(12).description('Сколько заметок максимум в блоке recall.').volatile(), + maxRecallChars: z.number().step(1).min(200).max(20000).default(2400).description('Предел длины блока recall.').volatile(), +}) + +// --------------------------------------------------------------------------- +// Настройки и утилиты + +function refValue(ref, fallback) { + try { + if (ref !== null && typeof ref === 'object' && typeof ref.get === 'function') return ref.get() + if (ref !== undefined) return ref + } catch { + return fallback + } + return fallback +} + +function readSettings(config) { + const number = (ref, fallback, min, max) => { + const value = Number(refValue(ref, fallback)) + if (!Number.isFinite(value)) return fallback + return Math.min(max, Math.max(min, Math.trunc(value))) + } + return { + mode: refValue(config?.mode, 'local') === 'server' ? 'server' : 'local', + host: String(refValue(config?.host, '192.168.31.4')), + port: number(config?.port, 5434, 1, 65535), + database: String(refValue(config?.database, 'dsh_memory')), + user: String(refValue(config?.user, 'dsh_memory')), + password: String(refValue(config?.password, '') ?? ''), + autoFallback: refValue(config?.autoFallback, true) !== false, + autoRecall: refValue(config?.autoRecall, true) !== false, + rules: refValue(config?.rules, true) !== false, + maxRecall: number(config?.maxRecall, 12, 1, 50), + maxRecallChars: number(config?.maxRecallChars, 2400, 200, 20000), + } +} + +function dshHome() { + return process.env.DSH_HOME && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homedir(), '.dsh') +} + +/** Строка подключения из $DSH_HOME/.env, если пароль не задан в настройках. */ +let envUrlCache = { at: 0, value: undefined } +async function readEnvUrl() { + if (Date.now() - envUrlCache.at < 10_000) return envUrlCache.value + let value + try { + const text = await readFile(join(dshHome(), '.env'), 'utf8') + const match = /^\s*DSH_MEMORY_PG_URL\s*=\s*(.+)$/m.exec(text) + if (match !== null) value = match[1].trim().replace(/^["']|["']$/g, '') + } catch {} + envUrlCache = { at: Date.now(), value } + return value +} + +async function connectionUrl(settings) { + if (settings.password.length > 0) { + return `postgresql://${encodeURIComponent(settings.user)}:${encodeURIComponent(settings.password)}` + + `@${settings.host}:${settings.port}/${encodeURIComponent(settings.database)}` + } + const fromEnv = process.env.DSH_MEMORY_PG_URL + if (typeof fromEnv === 'string' && fromEnv.trim().length > 0) return fromEnv.trim() + const fromFile = await readEnvUrl() + if (typeof fromFile === 'string' && fromFile.length > 0) return fromFile + return `postgresql://${encodeURIComponent(settings.user)}:@${settings.host}:${settings.port}/${encodeURIComponent(settings.database)}` +} + +/** Нормализация раздела: personal, home-server, имя проекта/сайта. */ +function normalizeCollection(value) { + if (typeof value !== 'string') return undefined + const collection = value.trim().toLowerCase().replace(/[^a-z0-9._\-\u0400-\u04ff]/g, '-').replace(/-+/g, '-').slice(0, 48) + return collection.length > 0 ? collection : undefined +} + +function normalizeBody(value) { + if (typeof value !== 'string') return '' + return value.replace(/\r\n/g, '\n').trim().slice(0, MAX_BODY) +} + +function normalizeTags(value) { + if (!Array.isArray(value)) return [] + const tags = [] + for (const item of value) { + if (typeof item !== 'string') continue + const tag = item.trim().toLowerCase().slice(0, MAX_TAG_LEN) + if (tag.length === 0 || tags.includes(tag)) continue + tags.push(tag) + if (tags.length >= MAX_TAGS) break + } + return tags +} + +function clampInt(value, min, max, fallback) { + const number = typeof value === 'number' ? value : Number.parseInt(String(value ?? ''), 10) + if (!Number.isFinite(number)) return fallback + return Math.min(max, Math.max(min, Math.trunc(number))) +} + +function sessionCwd(ctx, exec) { + const session = exec?.agent?.session + if (session === undefined) return undefined + const service = ctx.get('workingDirectory') + if (service === undefined || typeof service.get !== 'function') return undefined + try { + const value = service.get(session) + return typeof value === 'string' && value.length > 0 ? value : undefined + } catch { + return undefined + } +} + +function formatRow(row, options = {}) { + const flags = [row.collection ?? 'general', row.scope === 'workspace' ? 'workspace' : 'global'] + if (row.pinned) flags.push('pinned') + const tags = Array.isArray(row.tags) && row.tags.length > 0 ? ` #${row.tags.join(' #')}` : '' + const body = options.limit !== undefined && row.body.length > options.limit ? `${row.body.slice(0, options.limit)}…` : row.body + const date = row.updated_at instanceof Date ? row.updated_at.toISOString() : String(row.updated_at) + return `- ${row.id} [${flags.join(', ')}]${tags}: ${body}${options.showDate ? ` (обновлено ${date})` : ''}` +} + +function toRow(raw) { + return { + id: raw.id, + body: raw.body, + tags: JSON.parse(raw.tags), + scope: raw.scope, + workspace: raw.workspace, + pinned: raw.pinned === 1 || raw.pinned === true, + collection: raw.collection ?? 'general', + created_at: new Date(raw.created_at), + updated_at: new Date(raw.updated_at), + } +} + +/** + * Раздел заметки: personal — о пользователе, home-server — инфраструктура, + * имя проекта — конкретный сайт/сервис. Выводится из старых тегов и каталога. + */ +function inferCollection(workspace, tags) { + const list = Array.isArray(tags) ? tags.map(tag => String(tag).toLowerCase()) : [] + if (list.includes('home-server') || list.includes('инфраструктура') || list.includes('server')) return 'home-server' + if (list.includes('предпочтения') || list.includes('язык') || list.includes('personal') || list.includes('пользователь')) return 'personal' + if (typeof workspace === 'string' && workspace.length > 0) { + const base = workspace.replace(/[\\/]+$/, '').split(/[\\/]/).pop() + if (base !== undefined && base.length > 0) return base.toLowerCase() + } + if (list.includes('dsh') || list.includes('memory') || list.includes('память')) return 'dsh' + return 'general' +} + +/** Коллекция по умолчанию для новой заметки. */ +function defaultCollection(scope, cwd) { + if (scope === 'workspace' && typeof cwd === 'string' && cwd.length > 0) { + const base = cwd.replace(/[\\/]+$/, '').split(/[\\/]/).pop() + if (base !== undefined && base.length > 0) return base.toLowerCase() + } + return 'general' +} + +/** Запрос для FTS5: каждое слово в кавычках, последнее — с префиксом. */ +function buildFtsQuery(text) { + const words = text.split(/\s+/).filter(word => word.length > 0).map(word => `"${word.replace(/"/g, '""')}"`) + if (words.length === 0) return undefined + words[words.length - 1] += '*' + return words.join(' ') +} + +/** Экранирование LIKE-шаблона, чтобы % и _ искались буквально. */ +function escapeLike(value) { + return value.replace(/[\\%_]/g, character => `\\${character}`) +} + +function toSecret(raw) { + return { + id: raw.id, + name: raw.name, + username: raw.username, + value: raw.value, + url: raw.url, + notes: raw.notes, + tags: Array.isArray(raw.tags) ? raw.tags : JSON.parse(raw.tags), + created_at: new Date(raw.created_at), + updated_at: new Date(raw.updated_at), + synced: raw.synced === 1 || raw.synced === true, + } +} + +// --------------------------------------------------------------------------- +// Локальная SQLite + +function createLocalStore(logger) { + mkdirSync(join(dshHome(), 'memory'), { recursive: true }) + const db = new DatabaseSync(join(dshHome(), 'memory', 'memory.sqlite')) + db.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE IF NOT EXISTS memory_entries ( + id TEXT PRIMARY KEY, body TEXT NOT NULL, tags TEXT NOT NULL DEFAULT '[]', + scope TEXT NOT NULL, workspace TEXT, pinned INTEGER NOT NULL DEFAULT 0, + collection TEXT NOT NULL DEFAULT 'general', + created_at TEXT NOT NULL, updated_at TEXT NOT NULL, synced INTEGER NOT NULL DEFAULT 0 + ); + CREATE INDEX IF NOT EXISTS memory_entries_scope ON memory_entries (scope, workspace); + CREATE INDEX IF NOT EXISTS memory_entries_order ON memory_entries (pinned DESC, updated_at DESC); + CREATE TABLE IF NOT EXISTS memory_secrets ( + id TEXT PRIMARY KEY, name TEXT NOT NULL, username TEXT, value TEXT NOT NULL, + url TEXT, notes TEXT, tags TEXT NOT NULL DEFAULT '[]', + created_at TEXT NOT NULL, updated_at TEXT NOT NULL, synced INTEGER NOT NULL DEFAULT 0 + ); + CREATE UNIQUE INDEX IF NOT EXISTS memory_secrets_name ON memory_secrets (lower(name)); + CREATE INDEX IF NOT EXISTS memory_secrets_updated ON memory_secrets (updated_at DESC); + CREATE TABLE IF NOT EXISTS memory_tombstones ( + kind TEXT NOT NULL, key TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (kind, key) + ); + `) + // FTS5 может отсутствовать в сборке SQLite — тогда работает обычный instr. + let ftsReady = false + try { + // Триггеры и внешний контент FTS ломались на миграциях — ведём индекс вручную. + db.exec(`DROP TRIGGER IF EXISTS memory_entries_ai; DROP TRIGGER IF EXISTS memory_entries_ad; DROP TRIGGER IF EXISTS memory_entries_au;`) + const legacy = db.prepare(`SELECT sql FROM sqlite_master WHERE name = 'memory_entries_fts'`).get() + if (legacy !== undefined && /content=/.test(String(legacy.sql))) db.exec(`DROP TABLE memory_entries_fts`) + db.exec(` + CREATE VIRTUAL TABLE IF NOT EXISTS memory_entries_fts USING fts5( + body, tags, tokenize='unicode61 remove_diacritics 2' + ) + `) + const rows = db.prepare(`SELECT count(*) AS n FROM memory_entries`).get().n + const indexed = db.prepare(`SELECT count(*) AS n FROM memory_entries_fts`).get().n + if (rows !== indexed) { + db.exec(`DELETE FROM memory_entries_fts`) + db.exec(`INSERT INTO memory_entries_fts(rowid, body, tags) SELECT rowid, body, tags FROM memory_entries`) + } + ftsReady = true + } catch {} + + /** Переиндексировать одну запись по её id. */ + function ftsUpsert(id) { + if (!ftsReady) return + try { + const row = db.prepare(`SELECT rowid, body, tags FROM memory_entries WHERE id = ?`).get(id) + if (row === undefined) return + db.prepare(`DELETE FROM memory_entries_fts WHERE rowid = ?`).run(row.rowid) + db.prepare(`INSERT INTO memory_entries_fts(rowid, body, tags) VALUES (?, ?, ?)`).run(row.rowid, row.body, row.tags) + } catch {} + } + + /** Убрать запись из индекса перед удалением. */ + function ftsRemove(id) { + if (!ftsReady) return + try { + const row = db.prepare(`SELECT rowid FROM memory_entries WHERE id = ?`).get(id) + if (row !== undefined) db.prepare(`DELETE FROM memory_entries_fts WHERE rowid = ?`).run(row.rowid) + } catch {} + } + try { db.exec(`ALTER TABLE memory_entries ADD COLUMN collection TEXT NOT NULL DEFAULT 'general'`) } catch {} + try { db.exec(`ALTER TABLE memory_entries ADD COLUMN synced INTEGER NOT NULL DEFAULT 0`) } catch {} + try { db.exec(`CREATE INDEX IF NOT EXISTS memory_entries_collection ON memory_entries (collection, pinned DESC, updated_at DESC)`) } catch {} + // Бэкфилл раздела по старым тегам и рабочему каталогу. + try { + const pending = db.prepare(`SELECT id, workspace, tags FROM memory_entries WHERE collection = 'general'`).all() + const update = db.prepare(`UPDATE memory_entries SET collection = ? WHERE id = ?`) + for (const row of pending) { + const collection = inferCollection(row.workspace, JSON.parse(row.tags)) + if (collection !== 'general') update.run(collection, row.id) + } + } catch {} + + const scopeClause = (scope, cwd) => { + const cwdParam = cwd ?? null + if (scope === 'global') return { sql: `scope = 'global'`, params: [] } + if (scope === 'workspace') return { sql: `scope = 'workspace' AND workspace IS ?`, params: [cwdParam] } + return { sql: `(scope = 'global' OR (scope = 'workspace' AND workspace IS ?))`, params: [cwdParam] } + } + + return { + kind: 'local', + async list(scope, cwd, limit, collection) { + const where = scopeClause(scope, cwd) + const filters = [where.sql] + const params = [...where.params] + if (collection) { filters.push('collection = ?'); params.push(collection) } + return db.prepare(`SELECT * FROM memory_entries WHERE ${filters.join(' AND ')} ORDER BY pinned DESC, updated_at DESC LIMIT ?`) + .all(...params, limit).map(toRow) + }, + async search(needle, scope, cwd, limit, collection) { + const where = scopeClause(scope, cwd) + const collectionSql = collection ? ' AND collection = ?' : '' + const collectionParams = collection ? [collection] : [] + const fts = buildFtsQuery(needle) + if (fts !== undefined) { + try { + const rows = db.prepare( + `SELECT e.* FROM memory_entries e + JOIN memory_entries_fts f ON f.rowid = e.rowid + WHERE memory_entries_fts MATCH ? + AND ${where.sql}${collectionSql} + ORDER BY pinned DESC, updated_at DESC LIMIT ?`, + ).all(fts, ...where.params, ...collectionParams, limit) + if (rows.length > 0) return rows.map(toRow) + } catch {} + } + return db.prepare( + `SELECT * FROM memory_entries WHERE ${where.sql}${collectionSql} + AND (instr(lower(body), ?) > 0 + OR EXISTS (SELECT 1 FROM json_each(memory_entries.tags) WHERE json_each.value = ?)) + ORDER BY pinned DESC, updated_at DESC LIMIT ?`, + ).all(...where.params, ...collectionParams, needle, needle, limit).map(toRow) + }, + async save({ body, tags, scope, workspace, pinned, collection }) { + const now = new Date().toISOString() + const existing = db.prepare( + `SELECT id FROM memory_entries WHERE body = ? AND scope = ? AND workspace IS ?`, + ).get(body, scope, workspace ?? null) + if (existing !== undefined) { + db.prepare(`UPDATE memory_entries SET tags = ?, pinned = ?, collection = ?, updated_at = ?, synced = 0 WHERE id = ?`) + .run(JSON.stringify(tags), pinned ? 1 : 0, collection ?? 'general', now, existing.id) + ftsUpsert(existing.id) + return { id: existing.id, updated: true, row: toRow(db.prepare(`SELECT * FROM memory_entries WHERE id = ?`).get(existing.id)) } + } + const id = `mem-${randomBytes(4).toString('hex')}` + db.prepare( + `INSERT INTO memory_entries (id, body, tags, scope, workspace, pinned, collection, created_at, updated_at, synced) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)`, + ).run(id, body, JSON.stringify(tags), scope, workspace ?? null, pinned ? 1 : 0, collection ?? 'general', now, now) + ftsUpsert(id) + return { id, updated: false, row: toRow(db.prepare(`SELECT * FROM memory_entries WHERE id = ?`).get(id)) } + }, + async forget(id) { + const row = db.prepare(`SELECT * FROM memory_entries WHERE id = ?`).get(id) + if (row === undefined) return undefined + ftsRemove(id) + db.prepare(`DELETE FROM memory_entries WHERE id = ?`).run(id) + return toRow(row) + }, + /** Правка записи на месте: меняются только переданные поля. */ + async updateNote(id, patch) { + const row = db.prepare(`SELECT * FROM memory_entries WHERE id = ?`).get(id) + if (row === undefined) return undefined + const body = patch.body !== undefined ? patch.body : row.body + const tags = patch.tags !== undefined ? JSON.stringify(patch.tags) : row.tags + const scope = patch.scope !== undefined ? patch.scope : row.scope + const workspace = scope === 'global' ? null : (patch.workspace !== undefined ? patch.workspace : row.workspace) + const pinned = patch.pinned !== undefined ? (patch.pinned ? 1 : 0) : row.pinned + const collection = patch.collection !== undefined ? patch.collection : (row.collection ?? 'general') + db.prepare( + `UPDATE memory_entries SET body = ?, tags = ?, scope = ?, workspace = ?, pinned = ?, + collection = ?, updated_at = ?, synced = 0 WHERE id = ?`, + ).run(body, tags, scope, workspace ?? null, pinned, collection, new Date().toISOString(), id) + ftsUpsert(id) + return toRow(db.prepare(`SELECT * FROM memory_entries WHERE id = ?`).get(id)) + }, + async all() { + return db.prepare(`SELECT * FROM memory_entries ORDER BY updated_at`).all().map(toRow) + }, + async unsyncedNotes() { + return db.prepare(`SELECT * FROM memory_entries WHERE synced = 0 ORDER BY updated_at`).all().map(toRow) + }, + async markNotesSynced(ids) { + const statement = db.prepare(`UPDATE memory_entries SET synced = 1 WHERE id = ?`) + for (const id of ids) statement.run(id) + }, + async saveSecret({ name, username, value, url, notes, tags }) { + const now = new Date().toISOString() + const existing = db.prepare(`SELECT id FROM memory_secrets WHERE lower(name) = lower(?)`).get(name) + if (existing !== undefined) { + db.prepare( + `UPDATE memory_secrets SET name = ?, username = ?, value = ?, url = ?, notes = ?, tags = ?, + updated_at = ?, synced = 0 WHERE id = ?`, + ).run(name, username ?? null, value, url ?? null, notes ?? null, JSON.stringify(tags), now, existing.id) + return { id: existing.id, updated: true, row: toSecret(db.prepare(`SELECT * FROM memory_secrets WHERE id = ?`).get(existing.id)) } + } + const id = `sec-${randomBytes(4).toString('hex')}` + db.prepare( + `INSERT INTO memory_secrets (id, name, username, value, url, notes, tags, created_at, updated_at, synced) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)`, + ).run(id, name, username ?? null, value, url ?? null, notes ?? null, JSON.stringify(tags), now, now) + return { id, updated: false, row: toSecret(db.prepare(`SELECT * FROM memory_secrets WHERE id = ?`).get(id)) } + }, + async getSecret(match) { + const row = db.prepare( + `SELECT * FROM memory_secrets WHERE id = ? OR lower(name) = lower(?) ORDER BY updated_at DESC LIMIT 1`, + ).get(match, match) + return row === undefined ? undefined : toSecret(row) + }, + async listSecrets(limit) { + return db.prepare( + `SELECT id, name, username, url, notes, tags, created_at, updated_at, synced + FROM memory_secrets ORDER BY updated_at DESC LIMIT ?`, + ).all(limit).map(row => ({ ...toSecret({ ...row, value: '' }), value: undefined })) + }, + async forgetSecret(match) { + const row = db.prepare( + `SELECT * FROM memory_secrets WHERE id = ? OR lower(name) = lower(?) ORDER BY updated_at DESC LIMIT 1`, + ).get(match, match) + if (row === undefined) return undefined + db.prepare(`DELETE FROM memory_secrets WHERE id = ?`).run(row.id) + return toSecret(row) + }, + async unsyncedSecrets() { + return db.prepare(`SELECT * FROM memory_secrets WHERE synced = 0 ORDER BY updated_at`).all().map(toSecret) + }, + async markSecretsSynced(ids) { + const statement = db.prepare(`UPDATE memory_secrets SET synced = 1 WHERE id = ?`) + for (const id of ids) statement.run(id) + }, + async addTombstone(kind, key) { + db.prepare(`INSERT OR REPLACE INTO memory_tombstones (kind, key, created_at) VALUES (?, ?, ?)`) + .run(kind, key, new Date().toISOString()) + }, + async tombstones() { + return db.prepare(`SELECT kind, key FROM memory_tombstones`).all() + }, + async clearTombstone(kind, key) { + db.prepare(`DELETE FROM memory_tombstones WHERE kind = ? AND key = ?`).run(kind, key) + }, + async close() { try { db.close() } catch {} }, + } +} + +// --------------------------------------------------------------------------- +// PostgreSQL + +function createPgStore(pool, logger) { + let ready = false + return { + kind: 'server', + pool, + async ensureSchema() { + if (ready) return + await pool.query(` + ALTER TABLE memory_entries ADD COLUMN IF NOT EXISTS synced boolean NOT NULL DEFAULT true; + ALTER TABLE memory_entries ADD COLUMN IF NOT EXISTS collection text NOT NULL DEFAULT 'general'; + CREATE INDEX IF NOT EXISTS memory_entries_collection_idx + ON memory_entries (collection, pinned DESC, updated_at DESC); + CREATE INDEX IF NOT EXISTS memory_entries_body_tsv + ON memory_entries USING gin (to_tsvector('russian', body)); + CREATE TABLE IF NOT EXISTS memory_secrets ( + id text PRIMARY KEY, name text NOT NULL, username text, value text NOT NULL, + url text, notes text, tags text[] NOT NULL DEFAULT '{}', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + synced boolean NOT NULL DEFAULT true + ); + CREATE UNIQUE INDEX IF NOT EXISTS memory_secrets_name ON memory_secrets (lower(name)); + CREATE INDEX IF NOT EXISTS memory_secrets_updated ON memory_secrets (updated_at DESC); + `) + // Бэкфилл раздела по старым тегам и рабочему каталогу. + await pool.query(` + UPDATE memory_entries SET collection = CASE + WHEN 'home-server' = ANY(tags) OR 'инфраструктура' = ANY(tags) THEN 'home-server' + WHEN 'предпочтения' = ANY(tags) OR 'язык' = ANY(tags) OR 'пользователь' = ANY(tags) THEN 'personal' + WHEN workspace IS NOT NULL THEN lower(split_part(replace(workspace, '\\', '/'), '/', -1)) + WHEN 'dsh' = ANY(tags) OR 'память' = ANY(tags) THEN 'dsh' + ELSE collection END + WHERE collection = 'general' + `) + ready = true + }, + async list(scope, cwd, limit, collection) { + const where = scope === 'global' + ? `scope = 'global'` + : scope === 'workspace' + ? `scope = 'workspace' AND workspace = $1` + : `(scope = 'global' OR (scope = 'workspace' AND workspace = $1))` + const params = scope === 'global' ? [] : [cwd ?? null] + const filters = [where] + if (collection) { filters.push(`collection = $${params.length + 1}`); params.push(collection) } + params.push(limit) + const rows = await pool.query( + `SELECT id, body, tags, scope, workspace, pinned, collection, created_at, updated_at + FROM memory_entries WHERE ${filters.join(' AND ')} + ORDER BY pinned DESC, updated_at DESC LIMIT $${params.length}`, + params, + ) + return rows.rows + }, + async search(needle, scope, cwd, limit, collection) { + const where = scope === 'global' + ? `scope = 'global'` + : scope === 'workspace' + ? `scope = 'workspace' AND workspace = $2` + : `(scope = 'global' OR (scope = 'workspace' AND workspace = $2))` + const params = scope === 'global' ? [needle] : [needle, cwd ?? null] + let filters = [where] + if (collection) { filters.push(`collection = $${params.length + 1}`); params.push(collection) } + const likeIndex = params.length + 1 + params.push(`%${escapeLike(needle)}%`) + const likeRef = `$${likeIndex}` + params.push(limit) + const rows = await pool.query( + `SELECT id, body, tags, scope, workspace, pinned, collection, created_at, updated_at + FROM memory_entries + WHERE ${filters.join(' AND ')} + AND (to_tsvector('russian', body) @@ plainto_tsquery('russian', $1) + OR body ILIKE ${likeRef} ESCAPE '\\' + OR $1 = ANY(tags)) + ORDER BY pinned DESC, updated_at DESC LIMIT $${params.length}`, + params, + ) + return rows.rows + }, + async upsertNote(row) { + await pool.query( + `INSERT INTO memory_entries (id, body, tags, scope, workspace, pinned, collection, created_at, updated_at, synced) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, true) + ON CONFLICT (id) DO UPDATE SET body = EXCLUDED.body, tags = EXCLUDED.tags, + scope = EXCLUDED.scope, workspace = EXCLUDED.workspace, pinned = EXCLUDED.pinned, + collection = EXCLUDED.collection, updated_at = EXCLUDED.updated_at, synced = true`, + [row.id, row.body, row.tags, row.scope, row.workspace, row.pinned, row.collection ?? 'general', row.created_at, row.updated_at], + ) + }, + async deleteNote(id) { + await pool.query(`DELETE FROM memory_entries WHERE id = $1`, [id]) + }, + async updateNote(row) { + await pool.query( + `UPDATE memory_entries SET body = $2, tags = $3, scope = $4, workspace = $5, + pinned = $6, collection = $7, updated_at = $8, synced = true WHERE id = $1`, + [row.id, row.body, row.tags, row.scope, row.workspace, row.pinned, row.collection ?? 'general', row.updated_at], + ) + }, + async saveSecret({ name, username, value, url, notes, tags }) { + const existing = await pool.query( + `SELECT id FROM memory_secrets WHERE lower(name) = lower($1)`, [name], + ) + if (existing.rows.length > 0) { + await pool.query( + `UPDATE memory_secrets SET name = $2, username = $3, value = $4, url = $5, notes = $6, + tags = $7, updated_at = now(), synced = true WHERE id = $1`, + [existing.rows[0].id, name, username ?? null, value, url ?? null, notes ?? null, tags], + ) + return { id: existing.rows[0].id, updated: true } + } + const id = `sec-${randomBytes(4).toString('hex')}` + await pool.query( + `INSERT INTO memory_secrets (id, name, username, value, url, notes, tags, synced) + VALUES ($1, $2, $3, $4, $5, $6, $7, true)`, + [id, name, username ?? null, value, url ?? null, notes ?? null, tags], + ) + return { id, updated: false } + }, + async getSecret(match) { + const rows = await pool.query( + `SELECT * FROM memory_secrets WHERE id = $1 OR lower(name) = lower($1) ORDER BY updated_at DESC LIMIT 1`, + [match], + ) + return rows.rows[0] === undefined ? undefined : toSecret(rows.rows[0]) + }, + async listSecrets(limit) { + const rows = await pool.query( + `SELECT id, name, username, url, notes, tags, created_at, updated_at, synced + FROM memory_secrets ORDER BY updated_at DESC LIMIT $1`, [limit], + ) + return rows.rows + }, + async forgetSecret(match) { + const rows = await pool.query( + `DELETE FROM memory_secrets WHERE id = (SELECT id FROM memory_secrets + WHERE id = $1 OR lower(name) = lower($1) ORDER BY updated_at DESC LIMIT 1) RETURNING *`, + [match], + ) + return rows.rows[0] === undefined ? undefined : toSecret(rows.rows[0]) + }, + async deleteSecretByName(name) { + await pool.query(`DELETE FROM memory_secrets WHERE lower(name) = lower($1)`, [name]) + }, + async upsertSecret(row) { + await pool.query( + `INSERT INTO memory_secrets (id, name, username, value, url, notes, tags, created_at, updated_at, synced) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, true) + ON CONFLICT ((lower(name))) DO UPDATE SET name = EXCLUDED.name, username = EXCLUDED.username, + value = EXCLUDED.value, url = EXCLUDED.url, notes = EXCLUDED.notes, + tags = EXCLUDED.tags, updated_at = EXCLUDED.updated_at, synced = true`, + [row.id, row.name, row.username ?? null, row.value, row.url ?? null, row.notes ?? null, + Array.isArray(row.tags) ? row.tags : JSON.parse(row.tags), row.created_at, row.updated_at], + ) + }, + async ping() { await pool.query('SELECT 1'); return true }, + async close() { await pool.end().catch(() => {}) }, + } +} + +// --------------------------------------------------------------------------- +// Движок: локально + зеркало, чтение «сервер → локально → догнать» + +function createEngine({ settings, logger }) { + const local = createLocalStore(logger) + let pgCache = { key: null, store: null } + let downUntil = 0 + let lastSyncAt = 0 + + function getPg(current, url) { + const key = `${url}|${current.host}:${current.port}/${current.database}` + if (pgCache.key !== key) { + if (pgCache.store !== null) pgCache.store.close().catch(() => {}) + const pool = new Pool({ + connectionString: url, + max: 4, + idleTimeoutMillis: 30_000, + connectionTimeoutMillis: 3_000, + allowExitOnIdle: true, + application_name: 'dsh-memory', + }) + pool.on('error', error => logger?.warn?.(`memory: idle client error: ${String(error?.message ?? error)}`)) + pgCache = { key, store: createPgStore(pool, logger) } + downUntil = 0 + } + return pgCache.store + } + + /** Пул сервера, если он отвечает; иначе undefined (с кулдауном). */ + async function pgTry() { + if (Date.now() < downUntil) return undefined + try { + const current = settings() + const url = await connectionUrl(current) + const store = getPg(current, url) + await store.ping() + await store.ensureSchema() + await syncPending(store) + return store + } catch (error) { + downUntil = Date.now() + PG_COOLDOWN_MS + logger?.warn?.(`memory: server unavailable: ${String(error?.message ?? error)}`) + return undefined + } + } + + /** Догоняющая синхронизация: заметки, секреты, отложенные удаления. */ + async function syncPending(store) { + if (store === undefined) return + if (Date.now() - lastSyncAt < 2000) return + lastSyncAt = Date.now() + const notes = await local.unsyncedNotes() + for (const row of notes) await store.upsertNote(row) + if (notes.length > 0) await local.markNotesSynced(notes.map(row => row.id)) + const secrets = await local.unsyncedSecrets() + for (const secret of secrets) await store.upsertSecret(secret) + if (secrets.length > 0) await local.markSecretsSynced(secrets.map(secret => secret.id)) + const tombstones = await local.tombstones() + for (const stone of tombstones) { + if (stone.kind === 'note') await store.deleteNote(stone.key) + else await store.deleteSecretByName(stone.key) + await local.clearTombstone(stone.kind, stone.key) + } + if (notes.length + secrets.length + tombstones.length > 0) { + logger?.info?.(`memory: synced ${notes.length} note(s), ${secrets.length} secret(s), ${tombstones.length} deletion(s)`) + } + } + + /** Чтение: сервер → локальная → если нашлось локально, досылаем на сервер. */ + async function readThrough(run, isEmpty, push) { + const pgStore = await pgTry() + if (pgStore === undefined) return await run(local) + let remote + try { + remote = await run(pgStore) + } catch (error) { + logger?.warn?.(`memory: server read failed: ${String(error?.message ?? error)}`) + downUntil = Date.now() + PG_COOLDOWN_MS + return await run(local) + } + if (!isEmpty(remote)) return remote + const fromLocal = await run(local) + if (!isEmpty(fromLocal)) { + try { await push(pgStore, fromLocal) } catch (error) { + logger?.warn?.(`memory: backfill failed: ${String(error?.message ?? error)}`) + } + } + return fromLocal + } + + const emptyArray = value => value.length === 0 + + return { + async list(scope, cwd, limit, collection) { + return await readThrough( + store => store.list(scope, cwd, limit, collection), + emptyArray, + async (store, rows) => { for (const row of rows) await store.upsertNote(row) }, + ) + }, + async search(needle, scope, cwd, limit, collection) { + return await readThrough( + store => store.search(needle, scope, cwd, limit, collection), + emptyArray, + async (store, rows) => { for (const row of rows) await store.upsertNote(row) }, + ) + }, + async saveNote(input) { + const saved = await local.save(input) + const pgStore = await pgTry() + let mirrored = false + if (pgStore !== undefined) { + try { await pgStore.upsertNote(saved.row); await local.markNotesSynced([saved.id]); mirrored = true } catch (error) { + logger?.warn?.(`memory: note mirrored locally only: ${String(error?.message ?? error)}`) + } + } + return { id: saved.id, updated: saved.updated, mirrored } + }, + async forgetNote(id) { + const removed = await local.forget(id) + if (removed === undefined) return undefined + const pgStore = await pgTry() + if (pgStore !== undefined) { + try { await pgStore.deleteNote(id) } catch (error) { + logger?.warn?.(`memory: note deleted locally, server delete pending: ${String(error?.message ?? error)}`) + await local.addTombstone('note', id) + } + } else { + await local.addTombstone('note', id) + } + return removed + }, + /** Правка записи на месте, с зеркалом в серверную базу. */ + async updateNote(id, patch) { + const row = await local.updateNote(id, patch) + if (row === undefined) return undefined + const pgStore = await pgTry() + let mirrored = false + if (pgStore !== undefined) { + try { await pgStore.updateNote(row); await local.markNotesSynced([id]); mirrored = true } catch (error) { + logger?.warn?.(`memory: note updated locally only: ${String(error?.message ?? error)}`) + } + } + return { row, mirrored } + }, + async getSecret(match) { + const pgStore = await pgTry() + if (pgStore !== undefined) { + const remote = await pgStore.getSecret(match).catch(() => undefined) + if (remote !== undefined) return remote + } + const localSecret = await local.getSecret(match) + if (localSecret !== undefined && pgStore !== undefined) await pgStore.upsertSecret(localSecret).catch(() => {}) + return localSecret + }, + async listSecrets(limit) { + return await readThrough( + store => store.listSecrets(limit), + emptyArray, + async (store, rows) => { for (const row of rows) await store.upsertSecret(row) }, + ) + }, + async saveSecret(input) { + const saved = await local.saveSecret(input) + const pgStore = await pgTry() + let mirrored = false + if (pgStore !== undefined) { + try { await pgStore.upsertSecret(saved.row); await local.markSecretsSynced([saved.id]); mirrored = true } catch (error) { + logger?.warn?.(`memory: secret mirrored locally only: ${String(error?.message ?? error)}`) + } + } + return { id: saved.id, updated: saved.updated, mirrored } + }, + async forgetSecret(match) { + const removed = await local.forgetSecret(match) + if (removed === undefined) return undefined + const pgStore = await pgTry() + if (pgStore !== undefined) { + try { await pgStore.deleteSecretByName(removed.name) } catch { + await local.addTombstone('secret', removed.name.toLowerCase()) + } + } else { + await local.addTombstone('secret', removed.name.toLowerCase()) + } + return removed + }, + async status() { + const current = settings() + const pgStore = await pgTry() + return { + mode: current.mode, + target: current.mode === 'server' ? `${current.host}:${current.port}/${current.database}` : 'local SQLite', + server: pgStore !== undefined, + localNotes: (await local.all()).length, + localSecrets: (await local.listSecrets(1000)).length, + } + }, + async syncNow() { + const pgStore = await pgTry() + if (pgStore === undefined) throw new Error('memory: server is unavailable') + lastSyncAt = 0 + await syncPending(pgStore) + return await this.status() + }, + async close() { + await local.close() + if (pgCache.store !== null) await pgCache.store.close() + }, + } +} + +// --------------------------------------------------------------------------- +// Recall + +function createRecall(ctx, engine, settings, logger) { + let cache = { text: '', at: 0, key: '' } + let inFlight + + const keyOf = current => `${current.mode}|${current.host}:${current.port}/${current.database}` + + function refresh(assembleContext) { + const current = settings() + if (!current.autoRecall) return + const key = keyOf(current) + if (key === cache.key && Date.now() - cache.at < RECALL_TTL_MS && cache.text !== '') return + if (inFlight !== undefined) return + const cwd = typeof assembleContext?.agent?.session === 'object' + ? sessionCwd(ctx, { agent: assembleContext.agent }) + : undefined + inFlight = (async () => { + try { + const rows = await engine.list('all', cwd, current.maxRecall) + cache = { text: renderRecall(rows, current), at: Date.now(), key } + } catch (error) { + if (cache.text === '') cache = { text: '', at: Date.now(), key } + logger?.warn?.(`memory: recall refresh failed: ${String(error?.message ?? error)}`) + } finally { + inFlight = undefined + } + })() + } + + return { + read(assembleContext) { + if (!settings().autoRecall) return '' + refresh(assembleContext) + return cache.text + }, + invalidate() { cache = { text: cache.text, at: 0, key: '' } }, + async prime() { + const current = settings() + if (!current.autoRecall) return + try { + const rows = await engine.list('global', undefined, current.maxRecall) + cache = { text: renderRecall(rows, current), at: 0, key: keyOf(current) } + } catch (error) { + logger?.warn?.(`memory: initial recall failed: ${String(error?.message ?? error)}`) + } + }, + } +} + +function renderRecall(rows, settings) { + if (rows.length === 0) return '' + const lines = [ + 'Заметки из памяти (плагин memory; сохранены в прошлых сессиях, не часть текущего разговора).', + 'Нужное добавляй через memory_save, ищи через memory_search, удаляй через memory_forget.', + ] + let budget = settings.maxRecallChars + for (const row of rows) { + const line = formatRow(row, { limit: RECALL_BODY_LIMIT }) + if (line.length + 1 > budget) break + lines.push(line) + budget -= line.length + 1 + } + return lines.length > 2 ? lines.join('\n') : '' +} + +// --------------------------------------------------------------------------- +// Инструменты + +function createTools(ctx, engine, settings, recall) { + return [ + { + name: 'memory_save', + description: + 'Save a durable note that survives sessions and restarts: user preferences, project conventions, decisions and their reasons, environment facts. ' + + 'Do not save transient task state, secrets, or anything already in the repository. ' + + 'Give every note a collection: "personal" for facts about the user, "home-server" for infrastructure, the project or site name (e.g. "autoan", "itmarkov.ru") for project knowledge, "dsh" for the harness itself; otherwise it defaults to "general" or the workspace directory name. ' + + 'Use scope "workspace" for facts about the current project and "global" for facts that apply everywhere; pinned notes always appear in the recall block.', + parameters: { + type: 'object', + properties: { + text: { type: 'string', description: 'The note itself, written so it is understandable without this conversation.' }, + tags: { type: 'array', items: { type: 'string' }, description: 'Optional lowercase keywords used by memory_search.' }, + scope: { type: 'string', enum: ['global', 'workspace'], description: 'global (default) or workspace (current project only).' }, + collection: { type: 'string', description: 'personal, home-server, a project/site name, or dsh. Defaults to the workspace directory name for workspace scope, otherwise general.' }, + pinned: { type: 'boolean', description: 'Keep this note in the automatic recall block ahead of unpinned notes.' }, + }, + required: ['text'], + additionalProperties: false, + }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute(args, exec) { + const body = normalizeBody(args.text) + if (body.length === 0) throw new Error('memory: `text` must be a non-empty string') + const scope = args.scope === 'workspace' ? 'workspace' : 'global' + const cwd = scope === 'workspace' ? sessionCwd(ctx, exec) : undefined + if (scope === 'workspace' && cwd === undefined) throw new Error('memory: workspace scope needs a session working directory') + const result = await engine.saveNote({ + body, + tags: normalizeTags(args.tags), + scope, + workspace: cwd, + pinned: args.pinned === true, + collection: normalizeCollection(args.collection) ?? defaultCollection(scope, cwd), + }) + recall.invalidate() + return `${result.updated ? 'Updated' : 'Saved'} memory ${result.id} (${scope}${args.pinned === true ? ', pinned' : ''}).` + }, + }, + { + name: 'memory_search', + description: + 'Search saved memory notes by keyword (substring of the note or an exact tag). ' + + 'Call it when the user refers to something from an earlier session, an earlier decision, or a preference you do not see in the current conversation.', + parameters: { + type: 'object', + properties: { + query: { type: 'string', description: 'Keyword or phrase to look for.' }, + scope: { type: 'string', enum: ['global', 'workspace', 'all'], description: 'Limit to global notes, workspace notes, or both (default).' }, + collection: { type: 'string', description: 'Only notes from this collection (personal, home-server, project/site name). Optional.' }, + limit: { type: 'number', description: 'Maximum results, 1-20 (default 8).' }, + }, + required: ['query'], + additionalProperties: false, + }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute(args, exec) { + const text = normalizeBody(args.query) + if (text.length === 0) throw new Error('memory: `query` must be a non-empty string') + const limit = clampInt(args.limit, 1, 20, 8) + const scope = args.scope === 'global' || args.scope === 'workspace' ? args.scope : 'all' + const rows = await engine.search(text.toLowerCase(), scope, sessionCwd(ctx, exec), limit, normalizeCollection(args.collection)) + if (rows.length === 0) return `No memories match ${JSON.stringify(text)}.` + return `Found ${rows.length} memor${rows.length === 1 ? 'y' : 'ies'}:\n${rows.map(row => formatRow(row, { showDate: true })).join('\n')}` + }, + }, + { + name: 'memory_list', + description: 'List saved memory notes, newest and pinned first. Use it to inspect what is remembered before saving a duplicate.', + parameters: { + type: 'object', + properties: { + scope: { type: 'string', enum: ['global', 'workspace', 'all'], description: 'Limit to global notes, workspace notes, or both (default).' }, + collection: { type: 'string', description: 'Only notes from this collection (personal, home-server, project/site name). Optional.' }, + limit: { type: 'number', description: 'Maximum results, 1-50 (default 20).' }, + }, + additionalProperties: false, + }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute(args, exec) { + const limit = clampInt(args.limit, 1, 50, 20) + const scope = args.scope === 'global' || args.scope === 'workspace' ? args.scope : 'all' + const rows = await engine.list(scope, sessionCwd(ctx, exec), limit, normalizeCollection(args.collection)) + if (rows.length === 0) return 'No saved memories.' + return `Saved memories (${rows.length}):\n${rows.map(row => formatRow(row, { showDate: true })).join('\n')}` + }, + }, + { + name: 'memory_forget', + description: 'Delete one saved memory note by its id. Use it when the user asks to forget something or when a note became wrong; prefer this over saving a contradicting duplicate.', + parameters: { + type: 'object', + properties: { id: { type: 'string', description: 'Memory id as returned by memory_save, memory_search, or memory_list.' } }, + required: ['id'], + additionalProperties: false, + }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute(args) { + const id = typeof args.id === 'string' ? args.id.trim() : '' + if (id.length === 0) throw new Error('memory: `id` must be a non-empty string') + const removed = await engine.forgetNote(id) + if (removed === undefined) throw new Error(`memory: no memory with id ${JSON.stringify(id)}`) + recall.invalidate() + return `Forgot ${id}: ${removed.body.slice(0, 120)}` + }, + }, + { + name: 'memory_update', + description: + 'Rewrite one existing memory note in place, keeping its id and history. Use it when a fact changed, a decision was revised, or a note is stale: pass only the fields that change. ' + + 'Prefer this over memory_forget + memory_save when the topic stays the same; use forget + save only when the old note is about something else. Find the id with memory_search or memory_list first.', + parameters: { + type: 'object', + properties: { + id: { type: 'string', description: 'Memory id as returned by memory_search or memory_list.' }, + text: { type: 'string', description: 'New note text; omit to keep the current text.' }, + tags: { type: 'array', items: { type: 'string' }, description: 'Replacement tags; omit to keep them.' }, + scope: { type: 'string', enum: ['global', 'workspace'], description: 'New scope; omit to keep it.' }, + collection: { type: 'string', description: 'New collection (personal, home-server, project/site name, dsh); omit to keep it.' }, + pinned: { type: 'boolean', description: 'New pinned flag; omit to keep it.' }, + }, + required: ['id'], + additionalProperties: false, + }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute(args, exec) { + const id = typeof args.id === 'string' ? args.id.trim() : '' + if (id.length === 0) throw new Error('memory: `id` must be a non-empty string') + const patch = {} + if (args.text !== undefined) { + const body = normalizeBody(args.text) + if (body.length === 0) throw new Error('memory: `text` must be a non-empty string') + patch.body = body + } + if (args.tags !== undefined) patch.tags = normalizeTags(args.tags) + if (args.scope !== undefined) { + if (args.scope !== 'global' && args.scope !== 'workspace') throw new Error('memory: `scope` must be "global" or "workspace"') + patch.scope = args.scope + if (args.scope === 'workspace') { + const cwd = sessionCwd(ctx, exec) + if (cwd === undefined) throw new Error('memory: workspace scope needs a session working directory') + patch.workspace = cwd + } + } + if (args.collection !== undefined) { + const collection = normalizeCollection(args.collection) + if (collection === undefined) throw new Error('memory: `collection` must be a non-empty string') + patch.collection = collection + } + if (args.pinned !== undefined) patch.pinned = args.pinned === true + const changed = ['body', 'tags', 'scope', 'collection', 'pinned'].some(key => patch[key] !== undefined) + if (!changed) throw new Error('memory: nothing to update; pass text, tags, scope, collection, or pinned') + const result = await engine.updateNote(id, patch) + if (result === undefined) throw new Error(`memory: no memory with id ${JSON.stringify(id)}`) + recall.invalidate() + return `Updated memory ${id}${patch.body !== undefined ? ' (text rewritten)' : ''}.` + }, + }, + { + name: 'memory_migrate', + description: 'Force the pending local notes, secrets, and deletions to the PostgreSQL mirror right now. Use it when the user asks to sync memory to the server.', + parameters: { type: 'object', properties: {}, additionalProperties: false }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute() { + const status = await engine.syncNow() + recall.invalidate() + return `Synced to ${status.target}: ${status.localNotes} note(s), ${status.localSecrets} secret(s) locally.` + }, + }, + { + name: 'secret_save', + description: + 'Store a credential in the secret vault: passwords, tokens, API keys, logins. Lives in its own table, separate from memory notes, and is written to both databases when the server is reachable. ' + + 'Save a secret whenever the user gives one and says or implies "remember these credentials" — never echo the value back in the result. ' + + 'Do not put secrets into memory_save notes. Saving the same name rotates the stored value.', + parameters: { + type: 'object', + properties: { + name: { type: 'string', description: 'Human-readable identifier, e.g. "mail.itmarkov.ru admin" or "Cloudflare API token".' }, + value: { type: 'string', description: 'The password, token, or key itself. Never echoed in the result.' }, + username: { type: 'string', description: 'Login or account name, when the secret is a password.' }, + url: { type: 'string', description: 'Where the credential applies: host, URL, or service name.' }, + notes: { type: 'string', description: 'Short operational note: rotation date, scope, 2FA caveats.' }, + tags: { type: 'array', items: { type: 'string' }, description: 'Optional lowercase keywords.' }, + }, + required: ['name', 'value'], + additionalProperties: false, + }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute(args) { + const secret = normalizeSecretInput(args) + const saved = await engine.saveSecret(secret) + return `Saved secret ${saved.id} ("${secret.name}") ${saved.mirrored ? 'to local and server' : 'locally; the server copy syncs when it is reachable'}.${saved.updated ? ' Existing value rotated.' : ''} Value not echoed.` + }, + }, + { + name: 'secret_list', + description: 'List stored credentials as metadata only: name, login, URL, tags, sync state. Values are never returned here. Use secret_get when a value is actually needed.', + parameters: { + type: 'object', + properties: { limit: { type: 'number', description: 'Maximum results, 1-50 (default 20).' } }, + additionalProperties: false, + }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute(args) { + const rows = await engine.listSecrets(clampInt(args.limit, 1, 50, 20)) + return formatSecretList(rows) + }, + }, + { + name: 'secret_get', + description: + 'Reveal one stored credential by id or exact name. Call it only when the user asks to see the value or when the next step truly needs it. ' + + 'Before printing the value in chat, warn the user that it will remain in this session log; do not paste it into files, commands, or commits unless the user asked.', + parameters: { + type: 'object', + properties: { match: { type: 'string', description: 'Secret id (sec-…) or the exact saved name.' } }, + required: ['match'], + additionalProperties: false, + }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute(args) { + const match = requireMatch(args.match) + const secret = await engine.getSecret(match) + if (secret === undefined) throw new Error(`memory: no secret matches ${JSON.stringify(match)}`) + return [ + `Secret ${secret.id} "${secret.name}"`, + secret.username ? `login: ${secret.username}` : null, + `value: ${secret.value}`, + secret.url ? `url: ${secret.url}` : null, + secret.notes ? `notes: ${secret.notes}` : null, + secret.synced === false ? 'server copy: pending sync' : 'server copy: in sync', + 'The value is now in this tool result and therefore in the session log. If you show it to the user, say so first.', + ].filter(line => line !== null).join('\n') + }, + }, + { + name: 'secret_forget', + description: 'Delete one stored credential by id or exact name from both databases. Use it when the user asks to forget a credential or after rotating it away.', + parameters: { + type: 'object', + properties: { match: { type: 'string', description: 'Secret id (sec-…) or the exact saved name.' } }, + required: ['match'], + additionalProperties: false, + }, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute(args) { + const match = requireMatch(args.match) + const removed = await engine.forgetSecret(match) + if (removed === undefined) throw new Error(`memory: no secret matches ${JSON.stringify(match)}`) + return `Forgot secret ${removed.id} ("${removed.name}").` + }, + }, + ] +} + +function requireMatch(value) { + const match = typeof value === 'string' ? value.trim() : '' + if (match.length === 0) throw new Error('memory: `match` must be a non-empty string') + return match +} + +function normalizeSecretInput(args) { + const name = typeof args.name === 'string' ? args.name.trim().slice(0, 120) : '' + if (name.length === 0) throw new Error('memory: `name` must be a non-empty string') + const value = typeof args.value === 'string' ? args.value : '' + if (value.length === 0) throw new Error('memory: `value` must be a non-empty string') + if (value.length > 4000) throw new Error('memory: `value` is longer than 4000 characters') + const trim = (candidate) => (typeof candidate === 'string' && candidate.trim().length > 0 ? candidate.trim() : null) + return { name, value, username: trim(args.username), url: trim(args.url), notes: trim(args.notes), tags: normalizeTags(args.tags) } +} + +function formatSecretList(rows) { + if (rows.length === 0) return 'No saved secrets.' + const lines = rows.map(row => { + const parts = [row.name] + if (row.username) parts.push(`login: ${row.username}`) + if (row.url) parts.push(`@ ${row.url}`) + if (Array.isArray(row.tags) && row.tags.length > 0) parts.push(`#${row.tags.join(' #')}`) + if (row.notes) parts.push(`(${row.notes})`) + if (row.synced === false) parts.push('[not on server yet]') + return `- ${row.id} ${parts.join(' — ')}` + }) + return `Saved secrets (${rows.length}):\n${lines.join('\n')}` +} + +// --------------------------------------------------------------------------- +// Команда /memory + +function registerCommand(ctx, engine, settings, recall, logger) { + const commands = ctx.get('commands') + if (commands === undefined || typeof commands.register !== 'function') return + + const handler = async ({ agent, rawInput }) => { + const input = typeof rawInput === 'string' ? rawInput.trim() : '' + const [head, ...rest] = input.split(/\s+/) + const sub = (head ?? '').toLowerCase() + const tail = rest.join(' ').trim() + const cwd = sessionCwd(ctx, { agent }) + + try { + if (sub === '' || sub === 'list') { + const rows = await engine.list('all', cwd, 40) + if (rows.length === 0) return { kind: 'success', text: 'Память пуста. Агент заполнит её через memory_save.' } + return { kind: 'success', text: `Память (${rows.length}, показаны до 40):\n${rows.map(row => formatRow(row, { showDate: true })).join('\n')}` } + } + if (sub === 'search') { + if (tail.length === 0) return { kind: 'error', text: 'Использование: /memory search <запрос>' } + const rows = await engine.search(tail.toLowerCase(), 'all', cwd, 20) + return { + kind: 'success', + text: rows.length === 0 ? `Ничего не найдено по ${JSON.stringify(tail)}.` : rows.map(row => formatRow(row, { showDate: true })).join('\n'), + } + } + if (sub === 'add') { + if (tail.length === 0) return { kind: 'error', text: 'Использование: /memory add <текст заметки>' } + const result = await engine.saveNote({ body: normalizeBody(tail), tags: [], scope: 'global', workspace: undefined, pinned: false }) + recall.invalidate() + return { kind: 'success', text: `Сохранено ${result.id}.` } + } + if (sub === 'forget') { + if (tail.length === 0) return { kind: 'error', text: 'Использование: /memory forget ' } + const removed = await engine.forgetNote(tail) + if (removed === undefined) return { kind: 'error', text: `Нет заметки ${JSON.stringify(tail)}.` } + recall.invalidate() + return { kind: 'success', text: `Удалено ${tail}.` } + } + if (sub === 'update') { + const space = tail.indexOf(' ') + const id = space === -1 ? tail : tail.slice(0, space) + const next = space === -1 ? '' : tail.slice(space + 1).trim() + if (id.length === 0 || next.length === 0) return { kind: 'error', text: 'Использование: /memory update <новый текст>' } + const result = await engine.updateNote(id, { body: normalizeBody(next) }) + if (result === undefined) return { kind: 'error', text: `Нет заметки ${JSON.stringify(id)}.` } + recall.invalidate() + return { kind: 'success', text: `Обновлено ${id}.` } + } + if (sub === 'secrets') { + return { kind: 'success', text: formatSecretList(await engine.listSecrets(40)) } + } + if (sub === 'migrate') { + const status = await engine.syncNow() + recall.invalidate() + return { kind: 'success', text: `Синхронизировано с ${status.target}: заметок локально ${status.localNotes}, секретов ${status.localSecrets}.` } + } + if (sub === 'status') { + const status = await engine.status() + return { + kind: 'success', + text: `Чтение: ${status.mode === 'server' ? status.target : 'локальная SQLite'}. Сервер: ${status.server ? 'доступен' : 'недоступен'}. Локально: ${status.localNotes} заметок, ${status.localSecrets} секретов.`, + } + } + return { + kind: 'success', + text: [ + 'Команды памяти:', + '/memory — список заметок', + '/memory search <запрос> — поиск', + '/memory add <текст> — добавить глобальную заметку', + '/memory forget — удалить заметку', + '/memory update <текст> — переписать заметку на месте', + '/memory secrets — список секретов (без значений)', + '/memory migrate — досинхронизировать локальные записи на сервер', + '/memory status — где читается память и доступен ли сервер', + ].join('\n'), + } + } catch (error) { + logger?.warn?.(`memory: command failed: ${String(error?.message ?? error)}`) + return { kind: 'error', text: `Память недоступна: ${String(error?.message ?? error)}` } + } + } + + ctx.effect(() => commands.register({ + name: 'memory', + description: 'Show, search, add, forget, or sync saved memory notes and secrets.', + input: { hint: '[list | search | add | forget | secrets | migrate | status]' }, + recordInput: false, + handler, + })) +} + +// --------------------------------------------------------------------------- +// HTTP API для менеджера паролей в карточке плагина + +function registerApi(ctx, engine, settings, logger) { + const web = ctx.get('webServer') + if (web === undefined || typeof web.register !== 'function') return + + const send = (res, status, body) => { + const payload = JSON.stringify(body) + res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }) + res.end(payload) + } + + const readJson = async (req) => { + const chunks = [] + let size = 0 + for await (const chunk of req) { + size += chunk.length + if (size > 256 * 1024) throw new Error('payload too large') + chunks.push(chunk) + } + if (chunks.length === 0) return {} + return JSON.parse(Buffer.concat(chunks).toString('utf8')) + } + + const handler = async (req, res) => { + try { + const url = new URL(req.url ?? '/', 'http://localhost') + if (url.pathname !== API_PATH) { send(res, 404, { error: 'not found' }); return } + // Запросы принимаются только с тем же заголовком, который ставит наша + // карточка: чужой сайт такой запрос не отправит без preflight. + if (req.headers[API_HEADER] !== '1') { send(res, 403, { error: 'forbidden' }); return } + const origin = req.headers.origin + if (typeof origin === 'string' && origin.length > 0) { + let expected + try { expected = web.getOrigin?.() } catch {} + if (expected !== undefined && origin !== expected) { send(res, 403, { error: 'origin rejected' }); return } + } + if (req.method !== 'POST') { send(res, 405, { error: 'method not allowed' }); return } + + const action = url.searchParams.get('action') ?? '' + if (action === 'list') { + send(res, 200, { secrets: await engine.listSecrets(clampInt(url.searchParams.get('limit'), 1, 200, 100)) }) + return + } + if (action === 'status') { send(res, 200, await engine.status()); return } + + const body = await readJson(req) + if (action === 'get') { + const secret = await engine.getSecret(requireMatch(body.match ?? body.id ?? body.name)) + if (secret === undefined) { send(res, 404, { error: 'secret not found' }); return } + send(res, 200, { secret }) + return + } + if (action === 'save') { + const saved = await engine.saveSecret(normalizeSecretInput(body)) + send(res, 200, saved) + return + } + if (action === 'forget') { + const removed = await engine.forgetSecret(requireMatch(body.match ?? body.id ?? body.name)) + if (removed === undefined) { send(res, 404, { error: 'secret not found' }); return } + send(res, 200, { id: removed.id, name: removed.name }) + return + } + send(res, 400, { error: 'unknown action' }) + } catch (error) { + logger?.warn?.(`memory: api failed: ${String(error?.message ?? error)}`) + send(res, 500, { error: String(error?.message ?? error) }) + } + } + + ctx.effect(() => web.register({ path: API_PATH, handler })) +} + +// --------------------------------------------------------------------------- +// Плагин + +export async function apply(ctx, config) { + const logger = ctx.logger + const settings = () => readSettings(config) + const engine = createEngine({ settings, logger }) + const recall = createRecall(ctx, engine, settings, logger) + + await recall.prime() + + for (const definition of createTools(ctx, engine, settings, recall)) { + ctx.effect(() => ctx.tools.register(definition)) + } + + ctx.effect(() => ctx.systemPrompt.context({ + name: 'memory:recall', + order: 150, + interpolate: false, + text: assemble => recall.read(assemble), + })) + + ctx.effect(() => ctx.systemPrompt.section({ + name: 'memory:rules', + order: 300, + text: (assemble) => { + if (!settings().rules) return '' + const toolSet = assemble?.toolSet + if (toolSet !== undefined) { + try { + const visible = toolSet.view(assemble.scope) + if (!visible.has('memory_save') && !visible.has('memory_search')) return '' + } catch {} + } + return MEMORY_RULES + }, + })) + + registerCommand(ctx, engine, settings, recall, logger) + registerApi(ctx, engine, settings, logger) + + const skills = ctx.get('skills') + if (skills !== undefined && typeof skills.register === 'function') { + ctx.effect(() => skills.register({ + name: SETUP_SKILL.name, + description: SETUP_SKILL.description, + whenToUse: SETUP_SKILL.whenToUse, + content: SETUP_SKILL.content, + invocation: { modelInvocable: true, userInvocable: true }, + })) + } + + ctx.effect(() => ctx.on('settings/document-updated', (namespace) => { + if (namespace !== ENTRY_ID) return + recall.invalidate() + })) + + ctx.effect(() => async () => { + await engine.close() + }) +} diff --git a/locale/en.json b/locale/en.json new file mode 100644 index 0000000..d1cb5fc --- /dev/null +++ b/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Memory & Vault", + "description": "Agent memory and a password vault in one plugin. Notes live in a local SQLite base and are mirrored to PostgreSQL on the home server when it is reachable: every write goes to both databases, reads ask the server first, fall back to the local base on an empty answer, and backfill what they find. Passwords, tokens, and keys live separately in the memory_secrets table and never enter notes; the password manager with search, reveal (the value hides after 30 seconds), copy, add, edit, and delete opens in the plugin card (Plugins → Memory & Vault) and as the Passwords and keys tab in the right Start panel. The agent gets memory_save / memory_search / memory_list / memory_update / memory_forget / memory_migrate and secret_save / secret_list / secret_get / secret_forget tools, the /memory command (list, search, add, update, forget, secrets, migrate, status), and global rules in the system prompt: when to save, how to rewrite stale notes, what never to store, and how to handle credentials — look the credential up first, ask the user when it is missing and save it immediately, reveal a value only after warning that it will stay in the session log. Notes carry collections: personal (about the user), home-server (infrastructure), a project or site name, dsh (the harness itself). Search is indexed: FTS5 in SQLite and GIN indexes over word forms, trigrams, and tags in PostgreSQL. Storage settings (mode, host, port, database, user, password, fallback, recall, rules) are edited in the plugin card without a restart. Secret values are stored as plain text in both databases — prefer environment variables or $DSH_HOME/.env for automation." + } +} diff --git a/locale/ru.json b/locale/ru.json new file mode 100644 index 0000000..410cda1 --- /dev/null +++ b/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Память и сейф", + "description": "Долговременная память агента и хранилище паролей в одном плагине. Заметки живут в локальной SQLite и зеркалятся в PostgreSQL на домашнем сервере, когда он доступен: запись всегда идёт в обе базы, чтение сначала спрашивает сервер, при пустом ответе берёт локальную базу и досылает найденное на сервер. Пароли, токены и ключи лежат отдельно, в таблице memory_secrets, и не попадают в заметки; менеджер паролей с поиском, показом (значение скрывается через 30 секунд), копированием, добавлением, правкой и удалением открывается в карточке плагина (Plugins → Память и сейф) и вкладкой «Пароли и ключи» в правой панели «Старт». Агент получает инструменты memory_save / memory_search / memory_list / memory_update / memory_forget / memory_migrate и secret_save / secret_list / secret_get / secret_forget, команду /memory (list, search, add, update, forget, secrets, migrate, status) и глобальные правила в системном промпте: когда сохранять, как обновлять записи, чего не хранить и как обращаться с кредами — сначала искать в сейфе, при отсутствии спросить у пользователя и сразу сохранить, значение показывать только с предупреждением, что оно останется в логе сессии. Заметки размечены разделами: personal (о пользователе), home-server (инфраструктура), имя проекта или сайта, dsh (сам харнесс). Поиск индексирован: FTS5 в SQLite, GIN-индексы по словоформам, триграммам и тегам в PostgreSQL. Настройки хранилища (режим, хост, порт, база, пользователь, пароль, фолбэк, recall, правила) правятся в карточке плагина без перезапуска. Значения секретов хранятся в открытом виде в обеих базах — для автоматизации лучше передавать их через переменные окружения или $DSH_HOME/.env." + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..aba244c --- /dev/null +++ b/package.json @@ -0,0 +1,65 @@ +{ + "name": "@itmarkov/dsh-memory-vault", + "version": "1.0.0", + "description": "Memory & Vault: durable agent notes and a password/secret vault for DeepSeek Harness. Local SQLite plus an optional PostgreSQL mirror, indexed search, agent tools, /memory commands, global rules, a bundled setup skill, and an in-app password manager.", + "type": "module", + "license": "MIT", + "author": "Denis Markov", + "keywords": [ + "dsh", + "dsh-plugin", + "dsh-bundle", + "deepseek-harness", + "memory", + "vault", + "secrets", + "postgres", + "sqlite" + ], + "repository": { + "type": "git", + "url": "git+https://git.itmarkov.ru/dmarkov/dsh-memory-vault.git" + }, + "homepage": "https://git.itmarkov.ru/dmarkov/dsh-memory-vault", + "bugs": { + "url": "https://git.itmarkov.ru/dmarkov/dsh-memory-vault/issues" + }, + "engines": { + "node": ">=22.13" + }, + "publishConfig": { + "access": "public" + }, + "exports": { + ".": "./index.js", + "./client": "./client.js", + "./locale/*.json": "./locale/*.json", + "./icon": "./icon.svg" + }, + "files": [ + "index.js", + "client.js", + "cordis.patch.yml", + "README.md", + "LICENSE", + "locale/*.json", + "icon.svg", + "sql" + ], + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web", + "immediately": true, + "inject": [ + "@deepseek-ai/dsh-client-ui-plugin-manager" + ] + } + }, + "dependencies": { + "@deepseek-ai/schemastery": "~3.19.0", + "pg": "^8.23.1" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..07b0e37 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,145 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@deepseek-ai/schemastery': + specifier: ~3.19.0 + version: 3.19.0 + pg: + specifier: ^8.23.1 + version: 8.23.1 + +packages: + + '@deepseek-ai/cosmokit@1.9.0': + resolution: {integrity: sha512-5O1S53mZiJyZYcvxxD0Qv1EY7qFPSxbGyD8CbVK6gw7W9FvcXZj2YIX1ZkOqyQQ3Xt2rFkZDHJv0+V3Zmmp8CA==} + + '@deepseek-ai/schemastery@3.19.0': + resolution: {integrity: sha512-bDXoYQa7ghAhmdYD5VPlzKxEzJV/aKkz5l4V5h1u06z8GAPN1ROewSjvR9WiXhpa52E9fng8lpH5QdCRIQgnyQ==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + pg-cloudflare@1.4.1: + resolution: {integrity: sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==} + + pg-connection-string@2.14.1: + resolution: {integrity: sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==} + + pg-int8@1.0.1: + resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==} + engines: {node: '>=4.0.0'} + + pg-pool@3.14.0: + resolution: {integrity: sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==} + peerDependencies: + pg: '>=8.0' + + pg-protocol@1.16.1: + resolution: {integrity: sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==} + + pg-types@2.2.0: + resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==} + engines: {node: '>=4'} + + pg@8.23.1: + resolution: {integrity: sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==} + engines: {node: '>= 16.0.0'} + peerDependencies: + pg-native: '>=3.0.1' + peerDependenciesMeta: + pg-native: + optional: true + + pgpass@1.0.5: + resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==} + + postgres-array@2.0.0: + resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==} + engines: {node: '>=4'} + + postgres-bytea@1.0.1: + resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==} + engines: {node: '>=0.10.0'} + + postgres-date@1.0.7: + resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==} + engines: {node: '>=0.10.0'} + + postgres-interval@1.2.0: + resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==} + engines: {node: '>=0.10.0'} + + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + +snapshots: + + '@deepseek-ai/cosmokit@1.9.0': {} + + '@deepseek-ai/schemastery@3.19.0': + dependencies: + '@deepseek-ai/cosmokit': 1.9.0 + '@standard-schema/spec': 1.1.0 + + '@standard-schema/spec@1.1.0': {} + + pg-cloudflare@1.4.1: + optional: true + + pg-connection-string@2.14.1: {} + + pg-int8@1.0.1: {} + + pg-pool@3.14.0(pg@8.23.1): + dependencies: + pg: 8.23.1 + + pg-protocol@1.16.1: {} + + pg-types@2.2.0: + dependencies: + pg-int8: 1.0.1 + postgres-array: 2.0.0 + postgres-bytea: 1.0.1 + postgres-date: 1.0.7 + postgres-interval: 1.2.0 + + pg@8.23.1: + dependencies: + pg-connection-string: 2.14.1 + pg-pool: 3.14.0(pg@8.23.1) + pg-protocol: 1.16.1 + pg-types: 2.2.0 + pgpass: 1.0.5 + optionalDependencies: + pg-cloudflare: 1.4.1 + + pgpass@1.0.5: + dependencies: + split2: 4.2.0 + + postgres-array@2.0.0: {} + + postgres-bytea@1.0.1: {} + + postgres-date@1.0.7: {} + + postgres-interval@1.2.0: + dependencies: + xtend: 4.0.2 + + split2@4.2.0: {} + + xtend@4.0.2: {} diff --git a/sql/compose.yaml b/sql/compose.yaml new file mode 100644 index 0000000..4c9eb62 --- /dev/null +++ b/sql/compose.yaml @@ -0,0 +1,30 @@ +# Пример docker-compose для внешней базы Memory & Vault. +# Скопировать в /opt/dsh-memory/compose.yaml, положить рядом .env.local: +# +# POSTGRES_DB=dsh_memory +# POSTGRES_USER=dsh_memory +# POSTGRES_PASSWORD=<сгенерированный пароль> +# +# Запуск: docker compose --env-file .env.local up -d +# Порт публикуется только на LAN-адрес хоста. Для публичного доступа нужен +# TLS-терминатор или VPN — не открывайте 5434 в интернет напрямую. + +services: + db: + image: postgres:18-alpine + container_name: dsh-memory-db + restart: unless-stopped + environment: + POSTGRES_DB: ${POSTGRES_DB:?POSTGRES_DB is required} + POSTGRES_USER: ${POSTGRES_USER:?POSTGRES_USER is required} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} + ports: + - "192.168.31.4:5434:5432" + volumes: + - ./pgdata:/var/lib/postgresql + - ./init:/docker-entrypoint-initdb.d:ro + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 10s + timeout: 5s + retries: 12 diff --git a/sql/schema.sql b/sql/schema.sql new file mode 100644 index 0000000..b17d714 --- /dev/null +++ b/sql/schema.sql @@ -0,0 +1,54 @@ +-- Memory & Vault: схема PostgreSQL. +-- Выполнить один раз в базе плагина: psql "$DSH_MEMORY_PG_URL" -f sql/schema.sql +-- Плагин сам создаёт недостающие объекты при первом подключении, поэтому +-- минимально достаточно: CREATE EXTENSION IF NOT EXISTS pg_trgm; + +CREATE EXTENSION IF NOT EXISTS pg_trgm; + +CREATE TABLE IF NOT EXISTS memory_entries ( + id text PRIMARY KEY, + body text NOT NULL, + tags text[] NOT NULL DEFAULT '{}', + scope text NOT NULL CHECK (scope IN ('global', 'workspace')), + workspace text, + pinned boolean NOT NULL DEFAULT false, + collection text NOT NULL DEFAULT 'general', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + synced boolean NOT NULL DEFAULT true, + CONSTRAINT memory_scope_workspace CHECK ( + (scope = 'global' AND workspace IS NULL) + OR (scope = 'workspace' AND workspace IS NOT NULL) + ) +); + +CREATE INDEX IF NOT EXISTS memory_entries_scope_idx + ON memory_entries (scope, workspace); +CREATE INDEX IF NOT EXISTS memory_entries_updated_idx + ON memory_entries (pinned DESC, updated_at DESC); +CREATE INDEX IF NOT EXISTS memory_entries_collection_idx + ON memory_entries (collection, pinned DESC, updated_at DESC); +CREATE INDEX IF NOT EXISTS memory_entries_body_trgm + ON memory_entries USING gin (body gin_trgm_ops); +CREATE INDEX IF NOT EXISTS memory_entries_body_tsv + ON memory_entries USING gin (to_tsvector('russian', body)); +CREATE INDEX IF NOT EXISTS memory_entries_tags_idx + ON memory_entries USING gin (tags); + +CREATE TABLE IF NOT EXISTS memory_secrets ( + id text PRIMARY KEY, + name text NOT NULL, + username text, + value text NOT NULL, + url text, + notes text, + tags text[] NOT NULL DEFAULT '{}', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + synced boolean NOT NULL DEFAULT true +); + +CREATE UNIQUE INDEX IF NOT EXISTS memory_secrets_name + ON memory_secrets (lower(name)); +CREATE INDEX IF NOT EXISTS memory_secrets_updated + ON memory_secrets (updated_at DESC); diff --git a/tests/check-local.mjs b/tests/check-local.mjs new file mode 100644 index 0000000..eac00a5 --- /dev/null +++ b/tests/check-local.mjs @@ -0,0 +1,7 @@ +import { DatabaseSync } from 'node:sqlite' + +const db = new DatabaseSync('C:/Users/denis/.dsh/memory/memory.sqlite') +const row = db.prepare("select id, substr(body, 1, 40) as body from memory_entries where id = 'mem-658a012c'").get() +console.log('test note present:', JSON.stringify(row ?? null)) +console.log('collections:', db.prepare('select collection, count(*) as n from memory_entries group by collection').all().map(r => `${r.collection}=${r.n}`).join(', ')) +console.log('fts exists:', db.prepare("select count(*) as n from sqlite_master where name = 'memory_entries_fts'").get().n === 1) diff --git a/tests/memory-smoke.mjs b/tests/memory-smoke.mjs new file mode 100644 index 0000000..dd87fc1 --- /dev/null +++ b/tests/memory-smoke.mjs @@ -0,0 +1,75 @@ +/** Смоук-тест хостовой части: node memory-smoke.mjs local|server|fallback */ +import { apply } from '../index.js' + +const mode = process.argv[2] ?? 'local' +const CWD = 'C:\\Users\\denis\\Documents\\deepseek-harness\\default-workspace' +const tools = new Map() +const contexts = [] +const sections = [] + +const ctx = { + logger: { warn: (...a) => console.error('[warn]', ...a), info: (...a) => console.error('[info]', ...a) }, + get(name) { + if (name === 'workingDirectory') return { get: () => CWD } + if (name === 'commands') return { register: () => () => {} } + return undefined + }, + tools: { register(definition) { tools.set(definition.name, definition); return () => {} } }, + systemPrompt: { + context(definition) { contexts.push(definition); return () => {} }, + section(definition) { sections.push(definition); return () => {} }, + }, + on() { return () => {} }, + effect(callback) { callback() }, +} + +const config = mode === 'local' + ? { mode: 'local', host: '127.0.0.1', port: 1, database: 'x', user: 'x', password: 'x' } + : mode === 'mirror' + ? { mode: 'local', host: '192.168.31.4', port: 5434, database: 'dsh_memory', user: 'dsh_memory' } + : mode === 'fallback' + ? { mode: 'server', host: '127.0.0.1', port: 1, database: 'x', user: 'x', password: 'x', autoFallback: true } + : { mode: 'server', host: '192.168.31.4', port: 5434, database: 'dsh_memory', user: 'dsh_memory' } + +await apply(ctx, config) + +const exec = { agent: { session: {} }, signal: new AbortController().signal } +const call = async (name, args) => tools.get(name).execute(args, exec) + +const out = (...a) => console.log(...a) + +if (mode === 'local') { + out('TOOLS:', [...tools.keys()].join(',')) + out('CONTEXTS:', contexts.map(c => c.name).join(',')) + const rulesText = sections[0]?.text?.({}) ?? '' + out('RULES:', rulesText.length, JSON.stringify(rulesText.slice(0, 120))) + const saved = await call('memory_save', { text: 'Локальная заметка перед миграцией: проверка фолбэка и переноса.', tags: ['migrate'], scope: 'global', collection: 'home-server', pinned: true }) + out('SAVE:', saved) + const id = /mem-[0-9a-f]+/.exec(saved)?.[0] + out('UPDATE:', await call('memory_update', { id, text: 'Локальная заметка обновлена: проверка memory_update.', tags: ['updated'] })) + out('SEARCH_NEW:', await call('memory_search', { query: 'обновлена', collection: 'home-server' })) + out('SEARCH_OTHER_COLLECTION:', await call('memory_search', { query: 'обновлена', collection: 'personal' })) + out('SEARCH_OLD:', await call('memory_search', { query: 'фолбэка' })) + out('LIST_COLLECTION:', await call('memory_list', { collection: 'home-server', limit: 5 })) + out('SAVE_PERSONAL:', await call('memory_save', { text: 'Личная заметка пользователя: предпочитает короткие ответы.', scope: 'global', collection: 'personal' })) + await new Promise(r => setTimeout(r, 300)) + out('RECALL:', JSON.stringify(contexts[0].text({ agent: { session: {} } }).slice(0, 200))) + out('SECRET_SAVE:', await call('secret_save', { name: 'Тест: db admin', value: 'SuperSecret123', username: 'admin', url: 'db.local', notes: 'тест', tags: ['test'] })) + out('SECRET_LIST:', await call('secret_list', { limit: 5 })) + out('SECRET_GET:', await call('secret_get', { match: 'Тест: db admin' })) + out('SECRET_FORGET:', await call('secret_forget', { match: 'Тест: db admin' })) + out('SECRET_LIST_AFTER:', await call('secret_list', { limit: 5 })) +} else if (mode === 'server') { + out('SAVE_SERVER:', await call('memory_save', { text: 'Серверная заметка: проверка записи в обе базы.', tags: ['server'], scope: 'global' })) + out('SECRET_SAVE_SERVER:', await call('secret_save', { name: 'Тест: server token', value: 'tok_abc123', url: 'https://example.test', tags: ['test'] })) + out('LIST_SERVER:', await call('memory_list', { limit: 10 })) +} else if (mode === 'mirror') { + out('MIRROR_NOTE:', await call('memory_save', { text: 'Заметка в локальном режиме должна уйти и на сервер.', tags: ['mirror'], scope: 'global' })) + out('MIRROR_SECRET:', await call('secret_save', { name: 'Тест: mirror secret', value: 'mirror_value', tags: ['mirror'] })) + out('MIRROR_LIST:', await call('secret_list', { limit: 10 })) +} else { + out('FALLBACK_SAVE:', await call('memory_save', { text: 'Заметка при недоступном сервере: должна уйти в локальную SQLite.', scope: 'global' })) + out('FALLBACK_LIST:', await call('memory_list', { limit: 5 })) +} + +process.exit(0)