/** * @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 = 16000 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, recall) { 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 === 'import-notes') { const notes = Array.isArray(body.notes) ? body.notes : [] if (notes.length === 0) { send(res, 400, { error: 'notes[] is required' }); return } if (notes.length > 200) { send(res, 400, { error: 'at most 200 notes per call' }); return } let imported = 0 for (const note of notes) { const text = normalizeBody(note?.body) if (text.length === 0) continue const scope = note.scope === 'workspace' ? 'workspace' : 'global' await engine.saveNote({ body: text, tags: normalizeTags(note.tags), scope, workspace: scope === 'workspace' ? note.workspace : undefined, pinned: note.pinned === true, collection: normalizeCollection(note.collection) ?? 'general', }) imported += 1 } recall.invalidate() send(res, 200, { imported }) 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, recall) 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() }) }