Harden Mnemazine production gates

This commit is contained in:
Зарубин Филипп
2026-06-24 12:12:36 +03:00
parent 1a9b73614f
commit dd6b69b893
30 changed files with 1278 additions and 127 deletions
+7 -2
View File
@@ -24,7 +24,7 @@ MNEMAZINE_DEEP=1 node scripts/mnemazine-run.mjs
npm run synthesize -- --deep
```
For live Desktop Inbox work, use `npm start` or `mnemazine`. It reads local config, enables deep mode, requires atomization + enrichment, and then runs the completion gate.
For live Desktop Inbox work, use `npm start` or `mnemazine`. It reads local config, enables deep mode, requires atomization + enrichment, and then runs the completion gate. The desktop completion gate checks notes changed during that run; use `npm run quality` for a full vault audit.
If deep mode is requested directly but no LLM engine is available, plain `node scripts/mnemazine-run.mjs --deep` falls back to local template synthesis and reports `degraded: true` in JSON. Strict runs (`--require-deep` or `npm start`) fail before archive.
@@ -42,6 +42,7 @@ All LLM calls go through one provider-abstracted module: `scripts/mnemazine-llm.
| `MNEMAZINE_LLM_TIMEOUT_MS` | `420000` | Per-call timeout. |
| `MNEMAZINE_DEEP` | unset | `1` enables deep mode (enrich + atomize + verify + digest). |
| `MNEMAZINE_ENRICH` | `1` within deep | `0` (or `--no-enrich`) skips the enrichment stage. |
| `MNEMAZINE_STRICT_ARCHIVE` | `1` in strict runs | `0` permits archiving with non-enriched notes. Default strict runs require verified enriched atoms. |
| `MNEMAZINE_MAX_ATOMS` | `20` | Cap on atoms produced per source cluster. |
| `MNEMAZINE_CONCURRENCY` | `4` | Swarm size for deep research (parallel agents, bounded). |
| `MNEMAZINE_OWNER_CONTEXT` | generic | Personal project context for the digest's "why it matters". Or put it in the gitignored `.mnemazine/owner-context.txt`. |
@@ -58,6 +59,8 @@ In deep mode, files/clusters are researched concurrently by a bounded pool of ag
Before atomization, deep mode runs a web-capable LLM agent that **researches and expands** the captured material "as much as is genuinely useful" — primary sources, current facts/versions, practitioner experience — with every added fact tied to a fetched URL (anti-hallucination). Atoms are then built from the **expanded** knowledge, not just the raw capture. Disable with `--no-enrich` / `MNEMAZINE_ENRICH=0`.
Strict runs (`npm start` / `--require-deep`) fail instead of archiving when enrichment or verification is missing. A cached OCR result is never enough.
### Digest (Russian human-readable summary)
After Graphify, `scripts/mnemazine-digest.mjs` (`npm run digest`) writes a humanizer-style Russian **Справка** into each note — *Что это / О чём / Почему важно мне / Связи* — plus one session summary note mapping all atoms. Connections (*Связи*) are derived directly from note metadata: atoms sharing a `cluster_id` (siblings from one source) and atoms sharing a source-URL host. Deterministic, no model key needed. (`graphify update` builds only the intra-note structural code-graph; richer note-to-note semantic links would need the separate `graphify --update` pass and are not relied upon here.) This is the reuse surface: open one note, understand the knowledge and how it connects. Idempotent (skips notes that already have a Справка unless `--force`).
@@ -74,6 +77,8 @@ After Graphify, `scripts/mnemazine-digest.mjs` (`npm run digest`) writes a human
- `assumed` — a source URL is present but was not fetched/checked (the **default local** verdict, zero network);
- `verified` — only under `--deep`: the source was reachable (HEAD/GET) **and** an LLM web cross-check judged it to support the claim. Such notes get `verified: true` and `status: final`.
In strict runs, only notes with `verified: true`, `verification_status: "verified"`, `enrichment: "external-research"`, public source URLs, and at least two recorded external facts can release an inbox file to archive.
## Security
### Untrusted input is fenced
@@ -82,7 +87,7 @@ Extracted material (OCR, transcripts, scraped web text) is **untrusted**. Before
### Sandbox
The Claude backend runs `claude -p` without `--dangerously-skip-permissions`; unpermitted tools simply do not run. The Codex backend runs headless with the bypass flag the repo's `kb-*-codex.sh` pipeline uses (non-interactive execution needs it). Either way the prompt-layer fencing above is the active mitigation, and tightening a backend sandbox further is a deliberate, separate decision — not required for default (conservative) operation, which never invokes Codex at all.
The Claude backend runs `claude -p` without the permission-bypass flag; unpermitted tools simply do not run. The Codex backend runs headless with `--sandbox read-only`, `--ask-for-approval never`, and an ephemeral session. Web search is enabled only for deep calls that explicitly request web tools. The prompt-layer fencing above is still required, but the backend sandbox now matches the local-first boundary: inbox content can be analyzed, not executed.
### Data boundary
+7 -2
View File
@@ -24,7 +24,7 @@ MNEMAZINE_DEEP=1 node scripts/mnemazine-run.mjs
npm run synthesize -- --deep
```
Для рабочего Desktop Inbox используй `npm start` или `mnemazine`. Он сам читает `.mnemazine/config.local.sh`, берёт inbox с рабочего стола, пишет в `~/Мозг`, включает `--deep`, требует атомизацию + обогащение и после этого запускает `complete-check`.
Для рабочего Desktop Inbox используй `npm start` или `mnemazine`. Он сам читает `.mnemazine/config.local.sh`, берёт inbox с рабочего стола, пишет в `~/Мозг`, включает `--deep`, требует атомизацию + обогащение и после этого запускает `complete-check`. Desktop-gate проверяет заметки, изменённые в этом проходе; полный аудит всего vault запускается отдельно через `npm run quality`.
Если deep-режим запрошен напрямую, но движок LLM недоступен, обычный `node scripts/mnemazine-run.mjs --deep` откатывается на локальный шаблонный синтез и сообщает `degraded: true` в JSON-выводе. Строгий запуск (`--require-deep` или `npm start`) в такой ситуации падает до архива.
@@ -42,6 +42,7 @@ npm run synthesize -- --deep
| `MNEMAZINE_LLM_TIMEOUT_MS` | `420000` | Таймаут одного вызова. |
| `MNEMAZINE_DEEP` | не задано | `1` включает deep-режим (enrich + атомизация + проверка + digest). |
| `MNEMAZINE_ENRICH` | `1` в deep | `0` (или `--no-enrich`) пропускает стадию обогащения. |
| `MNEMAZINE_STRICT_ARCHIVE` | `1` в строгих прогонах | `0` разрешает архив с необогащёнными заметками. По умолчанию строгий прогон требует verified enriched atoms. |
| `MNEMAZINE_MAX_ATOMS` | `20` | Лимит атомов на один кластер источника. |
| `MNEMAZINE_CONCURRENCY` | `4` | Размер роя для deep-исследования (параллельные агенты, ограниченно). |
| `MNEMAZINE_OWNER_CONTEXT` | общий | Контекст личных проектов для блока «почему важно» в справке. Либо положите в gitignored `.mnemazine/owner-context.txt`. |
@@ -58,6 +59,8 @@ npm run synthesize -- --deep
Перед атомизацией deep-режим запускает web-агента LLM, который **исследует и расширяет** захваченный материал «насколько реально полезно» — первоисточники, актуальные факты/версии, опыт практиков — каждый добавленный факт привязан к fetched-URL (антигаллюцинация). Атомы строятся из **расширенного** знания, не только из сырого захвата. Отключение: `--no-enrich` / `MNEMAZINE_ENRICH=0`.
Строгие прогоны (`npm start` / `--require-deep`) падают, если обогащения или проверки нет. Cached OCR сам по себе больше не открывает архив.
### Справка (русская человеческая сводка)
После Graphify `scripts/mnemazine-digest.mjs` (`npm run digest`) пишет в каждую заметку русскую **Справку** в стиле humanizer — *Что это / О чём / Почему важно мне / Связи* — плюс одну ноту-сводку прогона с картой всех атомов. Связи берутся прямо из метаданных заметок: атомы с общим `cluster_id` (родня из одного источника) и атомы с общим хостом source-URL. Детерминированно, без ключа модели. (`graphify update` строит только внутридокументный структурный код-граф; более богатые семантические связи нота↔нота потребовали бы отдельного прохода `graphify --update` и здесь не используются.) Это поверхность переиспользования: открыл одну заметку — понял знание и как оно связано. Идемпотентно (пропускает заметки со Справкой, если не `--force`).
@@ -74,6 +77,8 @@ npm run synthesize -- --deep
- `assumed` — URL источника есть, но не запрашивался/не проверялся (**локальный** вердикт по умолчанию, без сети);
- `verified` — только при `--deep`: источник был достижим (HEAD/GET) **и** web-сверка LLM признала, что он подтверждает утверждение. Такие заметки получают `verified: true` и `status: final`.
В строгом прогоне файл уходит в архив только если найдена заметка с `verified: true`, `verification_status: "verified"`, `enrichment: "external-research"`, публичными URL и минимум двумя записанными внешними фактами.
## Безопасность
### Недоверенный ввод изолируется
@@ -82,7 +87,7 @@ npm run synthesize -- --deep
### Песочница
Backend Claude запускает `claude -p` без `--dangerously-skip-permissions`; неразрешённые инструменты просто не выполняются. Backend Codex идёт headless с bypass-флагом конвейера `kb-*-codex.sh` (неинтерактивный запуск требует). В обоих случаях активная митигация — изоляция на уровне промпта выше, а дальнейшее ужесточение песочницы backend-а — отдельное осознанное решение, не требуется для консервативного режима по умолчанию, который Codex вообще не зовёт.
Backend Claude запускает `claude -p` без флага обхода разрешений; неразрешённые инструменты просто не выполняются. Backend Codex идёт headless с `--sandbox read-only`, `--ask-for-approval never` и ephemeral-сессией. Web search включается только для deep-вызовов, где явно запрошены web-инструменты. Изоляция на уровне промпта всё ещё нужна, но backend-песочница теперь совпадает с local-first границей: inbox-контент можно анализировать, нельзя исполнять.
### Граница данных
+30
View File
@@ -10,6 +10,18 @@ cd "$HOME/Desktop/Mnemazine"
bash install.sh
```
For the guided flow use:
```bash
bash setup.sh
```
Dry run:
```bash
MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh
```
The installer creates:
- `inbox/`;
@@ -39,6 +51,24 @@ xcode-select --install
Python dependencies are installed into `.venv/`. This keeps the system local to the Mnemazine folder.
`install.sh` uses `requirements.lock` when present, falling back to
`requirements.txt` only when the lock is absent. Update policy: change
`requirements.txt`, rebuild the local `.venv`, freeze to `requirements.lock`,
then commit both files. Set `MNEMAZINE_REQUIRE_PYTHON_DEPS=1` when Python
document engines must fail hard instead of degrading.
Missing optional engines are explicit: the installer prints `DEGRADED: ...` for
Python deps, Apple Vision OCR, or skipped local engines.
## Desktop Dry Run
```bash
npm run protocol:desktop:dry-run
```
This runs the Desktop protocol against temporary inbox/vault/cache/archive paths.
It never archives, deletes, or rewrites the live Desktop inbox.
## Agent Skills
If Codex or Claude skill folders exist, the installer copies portable skills there. If they do not exist, nothing breaks.
+30
View File
@@ -10,6 +10,18 @@ cd "$HOME/Desktop/Mnemazine"
bash install.sh
```
Пошаговый режим:
```bash
bash setup.sh
```
Прогон без изменений:
```bash
MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh
```
Установщик создаёт:
- `inbox/`;
@@ -39,6 +51,24 @@ xcode-select --install
Python-зависимости ставятся в `.venv/`. Это держит систему локальной внутри папки Mnemazine.
`install.sh` использует `requirements.lock`, если он есть, и откатывается на
`requirements.txt` только когда lock отсутствует. Политика обновления: меняешь
`requirements.txt`, пересобираешь локальный `.venv`, freeze'ишь
`requirements.lock`, коммитишь оба файла. Если Python-движки обязательны,
запускай с `MNEMAZINE_REQUIRE_PYTHON_DEPS=1`.
Отсутствующие опциональные движки видны явно: установщик пишет `DEGRADED: ...`
для Python deps, Apple Vision OCR или пропущенных локальных движков.
## Desktop dry-run
```bash
npm run protocol:desktop:dry-run
```
Команда гоняет Desktop-протокол на временных inbox/vault/cache/archive. Live
Desktop inbox не архивируется, не удаляется и не переписывается.
## Agent Skills
Если есть папки skills для Codex или Claude — установщик копирует туда переносимые skills. Если их нет, ничего не ломается.
+34 -6
View File
@@ -23,11 +23,13 @@ only a transit buffer, never a second store.
│ • .run-now flag present? → run
│ • daily window reached? → run
▼
rsync --remove-source-files (move; host stays thin)
rsync copy to local staging
▼
local inbox/ ──▶ npm start (the strict protocol)
▼
vault/ ──writes .last-run──▶ Mini App status
vault/ ──success only: delete pulled host files
│
└───────────writes .last-run──▶ Mini App status
```
Reverse channel without a public machine: the host never reaches your machine.
@@ -42,7 +44,7 @@ that flag; the next poll consumes it.
| `scripts/mnemazine-webapp-server.mjs` | host | Mini App API (`/api/status`, `/api/send`, `/api/run`). Verifies Telegram `initData`, enforces an allowlist. Zero deps. |
| `webapp/index.html` | host (static) | The Mini App UI. Theme-aware, single file. |
| `scripts/mnemazine-telegram-poll.sh` | your machine | ~5-min tick: consume run-now flag / daily window → pull + run. |
| `scripts/mnemazine-telegram-sync.sh` | your machine | rsync pull (move) + `npm start`. |
| `scripts/mnemazine-telegram-sync.sh` | your machine | rsync copy to staging + `npm start` + delete pulled host files only after success. |
| `scripts/com.mnemazine.telegram-sync.plist.template` | your machine | launchd agent (macOS) for the poll tick. |
## Setup
@@ -103,15 +105,41 @@ sed 's#__REPO__#'"$PWD"'#g' \
launchctl load ~/Library/LaunchAgents/com.mnemazine.telegram-sync.plist
```
Override host/key/paths via `MNEMAZINE_VPS`, `MNEMAZINE_VPS_KEY`,
`MNEMAZINE_REMOTE_INBOX`, `MNEMAZINE_ROOT` (see the script headers). On Linux,
use a 5-minute cron entry calling `mnemazine-telegram-poll.sh` instead.
Use a dedicated unprivileged host user, for example `deploy@host`, not a
privileged login. Default remote paths are under that user's home:
`mnemazine/inbox`, `mnemazine/reports`, and `mnemazine/bot`.
Pin the SSH host key before enabling polling:
```bash
MNEMAZINE_VPS=deploy@example.com \
MNEMAZINE_VPS_HOST_FINGERPRINT=SHA256:... \
bash scripts/mnemazine-pin-vps-host.sh
```
Then put reviewed settings in `.mnemazine/config.env`:
```bash
MNEMAZINE_VPS=deploy@example.com
MNEMAZINE_VPS_KEY=$HOME/.ssh/id_ed25519_mnemazine
MNEMAZINE_REMOTE_INBOX=mnemazine/inbox
MNEMAZINE_REMOTE_MUTATION=1
```
`MNEMAZINE_REMOTE_MUTATION=1` is deliberate: the poller consumes `.run-now`,
updates `.last-run`, and the sync deletes remote copies only after local success.
Without that flag the scripts fail closed. On Linux, use a 5-minute cron entry
calling `mnemazine-telegram-poll.sh` instead.
## Security
- The token is a secret — keep it in env / a secret store, never in git.
- `initData` is HMAC-verified with the bot token; only allowlisted user ids pass.
- The bot ignores messages from anyone outside `ALLOWED_CHAT_IDS`.
- Rotate the bot token if the host, pm2 env, shell history, or logs may have
leaked. Rotate the SSH key if the host user or your workstation key may have
leaked. Re-pin `known_hosts` only after verifying the new host fingerprint
from the provider console or another trusted channel.
## Self-tests
+34 -6
View File
@@ -23,11 +23,13 @@ LLM-бинарь). Бот живёт на всегда-онлайн хосте,
│ • есть флаг .run-now? → прогон
│ • наступило окно дня? → прогон
▼
rsync --remove-source-files (move; хост остаётся тонким)
rsync-копия в локальный staging
▼
локальный inbox/ ──▶ npm start (строгий протокол)
▼
vault/ ──пишет .last-run──▶ статус Mini App
vault/ ──только после success: delete на хосте
│
└─────────пишет .last-run──▶ статус Mini App
```
Обратный канал без публичной машины: хост не достучится до машины. Машина
@@ -42,7 +44,7 @@ LLM-бинарь). Бот живёт на всегда-онлайн хосте,
| `scripts/mnemazine-webapp-server.mjs` | хост | API Mini App (`/api/status`, `/api/send`, `/api/run`). Верифицирует `initData`, держит allowlist. Ноль зависимостей. |
| `webapp/index.html` | хост (статика) | UI Mini App. Тема-aware, один файл. |
| `scripts/mnemazine-telegram-poll.sh` | твоя машина | Тик ~5 мин: флаг run-now / дневное окно → pull + прогон. |
| `scripts/mnemazine-telegram-sync.sh` | твоя машина | rsync pull (move) + `npm start`. |
| `scripts/mnemazine-telegram-sync.sh` | твоя машина | rsync-копия в staging + `npm start` + удаление забранных файлов на хосте только после success. |
| `scripts/com.mnemazine.telegram-sync.plist.template` | твоя машина | launchd-агент (macOS) для тика. |
## Установка
@@ -103,15 +105,41 @@ sed 's#__REPO__#'"$PWD"'#g' \
launchctl load ~/Library/LaunchAgents/com.mnemazine.telegram-sync.plist
```
Хост/ключ/пути переопределяются через `MNEMAZINE_VPS`, `MNEMAZINE_VPS_KEY`,
`MNEMAZINE_REMOTE_INBOX`, `MNEMAZINE_ROOT` (см. шапки скриптов). На Linux —
cron на 5 минут, вызывающий `mnemazine-telegram-poll.sh`.
Используй отдельного непривилегированного пользователя, например `deploy@host`,
не привилегированный логин. Дефолтные пути живут в home этого пользователя:
`mnemazine/inbox`, `mnemazine/reports`, `mnemazine/bot`.
Сначала закрепи SSH host key:
```bash
MNEMAZINE_VPS=deploy@example.com \
MNEMAZINE_VPS_HOST_FINGERPRINT=SHA256:... \
bash scripts/mnemazine-pin-vps-host.sh
```
Потом положи проверенные настройки в `.mnemazine/config.env`:
```bash
MNEMAZINE_VPS=deploy@example.com
MNEMAZINE_VPS_KEY=$HOME/.ssh/id_ed25519_mnemazine
MNEMAZINE_REMOTE_INBOX=mnemazine/inbox
MNEMAZINE_REMOTE_MUTATION=1
```
`MNEMAZINE_REMOTE_MUTATION=1` ставится осознанно: poller потребляет `.run-now`,
обновляет `.last-run`, а sync удаляет remote-копии только после локального
успеха. Без этого флага скрипты падают закрыто. На Linux — cron на 5 минут,
вызывающий `mnemazine-telegram-poll.sh`.
## Безопасность
- Токен — секрет: env / секрет-стор, никогда не в git.
- `initData` HMAC-верифицируется токеном бота; проходят только id из allowlist.
- Бот игнорирует сообщения от всех вне `ALLOWED_CHAT_IDS`.
- Ротируй bot token, если хост, pm2 env, shell history или логи могли утечь.
Ротируй SSH-ключ, если мог утечь пользователь хоста или ключ рабочей машины.
Перезакрепляй `known_hosts` только после проверки нового fingerprint через
панель провайдера или другой доверенный канал.
## Селф-тесты