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
+4
View File
@@ -15,9 +15,13 @@ __pycache__/
.mnemazine/config.json .mnemazine/config.json
.mnemazine/config.env .mnemazine/config.env
.mnemazine/config.local.sh .mnemazine/config.local.sh
.mnemazine/known_hosts
.mnemazine/.last-daily .mnemazine/.last-daily
.mnemazine/.last-daily-attempt
.mnemazine/.last-daily-completed
.mnemazine/rebuild/ .mnemazine/rebuild/
.mnemazine/reprocess-video-inbox/ .mnemazine/reprocess-video-inbox/
.mnemazine/repair-backup/
inbox/* inbox/*
!inbox/.gitkeep !inbox/.gitkeep
vault/* vault/*
+22 -1
View File
@@ -72,6 +72,11 @@ asks where to put the `inbox/` (inside the repo or on the Desktop), and can
deploy the Telegram bot to a VPS. Preview a run without touching anything: deploy the Telegram bot to a VPS. Preview a run without touching anything:
`MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh`. `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh`.
`install.sh` installs Python packages from `requirements.lock` when the lock
exists. Update policy: edit `requirements.txt`, rebuild/freeze the lock in
`.venv`, then commit both files. Optional local engines print `DEGRADED: ...`
instead of pretending to be installed.
Update an existing clone: Update an existing clone:
```bash ```bash
@@ -150,7 +155,7 @@ The run performs:
4. deep atomization and source expansion; 4. deep atomization and source expansion;
5. final note creation with `source_ref` and `source_hash`; 5. final note creation with `source_ref` and `source_hash`;
6. vault quality gate; 6. vault quality gate;
7. archive move only after atomization/enrichment and quality gates pass; 7. archive move only after verified enriched atoms and quality gates pass;
8. guarded Graphify refresh attempt; 8. guarded Graphify refresh attempt;
9. weekly HTML report regeneration; 9. weekly HTML report regeneration;
10. report quality gate for the regenerated weekly HTML; 10. report quality gate for the regenerated weekly HTML;
@@ -159,6 +164,12 @@ The run performs:
`Mnemazine` / `npm start` is the safe default for real inbox work. The lower-level `npm run run` command is for development and demos. `Mnemazine` / `npm start` is the safe default for real inbox work. The lower-level `npm run run` command is for development and demos.
To test the Desktop path without touching the live inbox or vault:
```bash
npm run protocol:desktop:dry-run
```
## Website Ingestion ## Website Ingestion
Mnemazine can ingest a website and convert its useful pages into structured notes: Mnemazine can ingest a website and convert its useful pages into structured notes:
@@ -208,6 +219,8 @@ Raw OCR, copied fragments, and messy transcripts are rejected by the quality gat
The quality gate also rejects common raw-intake residue such as `intake-draft`, `draft-local`, `temp_image_*`, `IMG_*.PNG`, and visible raw image extensions in note content. Graphify output folders and backups are excluded from this note-quality scan. The quality gate also rejects common raw-intake residue such as `intake-draft`, `draft-local`, `temp_image_*`, `IMG_*.PNG`, and visible raw image extensions in note content. Graphify output folders and backups are excluded from this note-quality scan.
`npm start` runs this gate only on notes changed during the current inbox run, so old legacy vault debt cannot block archive of newly processed files. Full vault audit stays manual.
Run the gate manually: Run the gate manually:
```bash ```bash
@@ -353,6 +366,14 @@ npm run release-check
It checks script syntax, runs a temporary demo intake, verifies archive-after-quality behavior, runs the demo vault quality gate, scans for private markers/secrets, and checks that the public description and both READMEs stay bilingual. It checks script syntax, runs a temporary demo intake, verifies archive-after-quality behavior, runs the demo vault quality gate, scans for private markers/secrets, and checks that the public description and both READMEs stay bilingual.
For an offline local audit during development:
```bash
npm run audit:local
```
It runs syntax checks, security selftests, `npm audit`, `public-check`, and static scans for dangerous agent/SSH flags and credential-in-URL patterns.
## License ## License
MIT. MIT.
+22 -1
View File
@@ -71,6 +71,11 @@ bash setup.sh # пошагово, с вопросами (куда кла
(в репозитории или на рабочий стол), может задеплоить Telegram-бота на VPS. (в репозитории или на рабочий стол), может задеплоить Telegram-бота на VPS.
Прогон вхолостую без изменений: `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh`. Прогон вхолостую без изменений: `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh`.
`install.sh` ставит Python-пакеты из `requirements.lock`, если lock есть.
Политика обновления: правишь `requirements.txt`, пересобираешь/freeze'ишь lock
в `.venv`, коммитишь оба файла. Опциональные локальные движки пишут
`DEGRADED: ...`, а не изображают успешную установку.
Обновить уже скачанный проект: Обновить уже скачанный проект:
```bash ```bash
@@ -149,7 +154,7 @@ mnemazine
4. deep-атомизацию и расширение источниками; 4. deep-атомизацию и расширение источниками;
5. создание финальной заметки с `source_ref` и `source_hash`; 5. создание финальной заметки с `source_ref` и `source_hash`;
6. gate качества vault; 6. gate качества vault;
7. перенос исходников в архив только после атомизации/обогащения и зелёных gate; 7. перенос исходников в архив только после verified enriched atoms и зелёных gate;
8. guarded-попытку обновить Graphify; 8. guarded-попытку обновить Graphify;
9. обновление weekly HTML-отчёта; 9. обновление weekly HTML-отчёта;
10. report quality gate для обновлённого weekly HTML; 10. report quality gate для обновлённого weekly HTML;
@@ -158,6 +163,12 @@ mnemazine
`Mnemazine` / `npm start` — безопасный дефолт для настоящего inbox. Низкоуровневый `npm run run` оставлен для разработки и демо. `Mnemazine` / `npm start` — безопасный дефолт для настоящего inbox. Низкоуровневый `npm run run` оставлен для разработки и демо.
Проверить Desktop-путь без изменения live inbox и vault:
```bash
npm run protocol:desktop:dry-run
```
## Парсинг сайтов ## Парсинг сайтов
Mnemazine умеет забирать сайт и превращать его полезные страницы в структурированные заметки: Mnemazine умеет забирать сайт и превращать его полезные страницы в структурированные заметки:
@@ -207,6 +218,8 @@ Vault должен содержать финальное знание, а не
Gate качества также отклоняет типичный мусор сырого интейка: `intake-draft`, `draft-local`, `temp_image_*`, `IMG_*.PNG` и видимые расширения сырых картинок в тексте заметки. Папки вывода Graphify и бэкапы исключены из этой проверки качества заметок. Gate качества также отклоняет типичный мусор сырого интейка: `intake-draft`, `draft-local`, `temp_image_*`, `IMG_*.PNG` и видимые расширения сырых картинок в тексте заметки. Папки вывода Graphify и бэкапы исключены из этой проверки качества заметок.
`npm start` запускает gate только по заметкам, изменённым в текущем inbox-проходе. Старый долг vault больше не блокирует архив новых файлов. Полный аудит всего vault остаётся ручным.
Запустить gate вручную: Запустить gate вручную:
```bash ```bash
@@ -352,6 +365,14 @@ npm run release-check
Он проверяет синтаксис скриптов, гоняет временный demo-интейк, проверяет архивирование-после-качества, запускает gate качества demo-vault, сканирует приватные маркеры/секреты и проверяет, что публичное описание и оба README остаются двуязычными. Он проверяет синтаксис скриптов, гоняет временный demo-интейк, проверяет архивирование-после-качества, запускает gate качества demo-vault, сканирует приватные маркеры/секреты и проверяет, что публичное описание и оба README остаются двуязычными.
Для локального offline-аудита во время разработки:
```bash
npm run audit:local
```
Он запускает syntax-check, security selftests, `npm audit`, `public-check` и static scan на опасные agent/SSH flags и credential-in-URL.
## Лицензия ## Лицензия
MIT. MIT.
+7 -2
View File
@@ -24,7 +24,7 @@ MNEMAZINE_DEEP=1 node scripts/mnemazine-run.mjs
npm run synthesize -- --deep 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. 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_LLM_TIMEOUT_MS` | `420000` | Per-call timeout. |
| `MNEMAZINE_DEEP` | unset | `1` enables deep mode (enrich + atomize + verify + digest). | | `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_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_MAX_ATOMS` | `20` | Cap on atoms produced per source cluster. |
| `MNEMAZINE_CONCURRENCY` | `4` | Swarm size for deep research (parallel agents, bounded). | | `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`. | | `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`. 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) ### 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`). 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); - `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`. - `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 ## Security
### Untrusted input is fenced ### Untrusted input is fenced
@@ -82,7 +87,7 @@ Extracted material (OCR, transcripts, scraped web text) is **untrusted**. Before
### Sandbox ### 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 ### Data boundary
+7 -2
View File
@@ -24,7 +24,7 @@ MNEMAZINE_DEEP=1 node scripts/mnemazine-run.mjs
npm run synthesize -- --deep 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`) в такой ситуации падает до архива. Если 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_LLM_TIMEOUT_MS` | `420000` | Таймаут одного вызова. |
| `MNEMAZINE_DEEP` | не задано | `1` включает deep-режим (enrich + атомизация + проверка + digest). | | `MNEMAZINE_DEEP` | не задано | `1` включает deep-режим (enrich + атомизация + проверка + digest). |
| `MNEMAZINE_ENRICH` | `1` в deep | `0` (или `--no-enrich`) пропускает стадию обогащения. | | `MNEMAZINE_ENRICH` | `1` в deep | `0` (или `--no-enrich`) пропускает стадию обогащения. |
| `MNEMAZINE_STRICT_ARCHIVE` | `1` в строгих прогонах | `0` разрешает архив с необогащёнными заметками. По умолчанию строгий прогон требует verified enriched atoms. |
| `MNEMAZINE_MAX_ATOMS` | `20` | Лимит атомов на один кластер источника. | | `MNEMAZINE_MAX_ATOMS` | `20` | Лимит атомов на один кластер источника. |
| `MNEMAZINE_CONCURRENCY` | `4` | Размер роя для deep-исследования (параллельные агенты, ограниченно). | | `MNEMAZINE_CONCURRENCY` | `4` | Размер роя для deep-исследования (параллельные агенты, ограниченно). |
| `MNEMAZINE_OWNER_CONTEXT` | общий | Контекст личных проектов для блока «почему важно» в справке. Либо положите в gitignored `.mnemazine/owner-context.txt`. | | `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`. Перед атомизацией 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`). После 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 источника есть, но не запрашивался/не проверялся (**локальный** вердикт по умолчанию, без сети); - `assumed` — URL источника есть, но не запрашивался/не проверялся (**локальный** вердикт по умолчанию, без сети);
- `verified` — только при `--deep`: источник был достижим (HEAD/GET) **и** web-сверка LLM признала, что он подтверждает утверждение. Такие заметки получают `verified: true` и `status: final`. - `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 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: The installer creates:
- `inbox/`; - `inbox/`;
@@ -39,6 +51,24 @@ xcode-select --install
Python dependencies are installed into `.venv/`. This keeps the system local to the Mnemazine folder. 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 ## Agent Skills
If Codex or Claude skill folders exist, the installer copies portable skills there. If they do not exist, nothing breaks. 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 install.sh
``` ```
Пошаговый режим:
```bash
bash setup.sh
```
Прогон без изменений:
```bash
MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh
```
Установщик создаёт: Установщик создаёт:
- `inbox/`; - `inbox/`;
@@ -39,6 +51,24 @@ xcode-select --install
Python-зависимости ставятся в `.venv/`. Это держит систему локальной внутри папки Mnemazine. 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 ## Agent Skills
Если есть папки skills для Codex или Claude — установщик копирует туда переносимые 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 │ • .run-now flag present? → run
│ • daily window reached? → 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) 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. 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. | | `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. | | `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-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. | | `scripts/com.mnemazine.telegram-sync.plist.template` | your machine | launchd agent (macOS) for the poll tick. |
## Setup ## Setup
@@ -103,15 +105,41 @@ sed 's#__REPO__#'"$PWD"'#g' \
launchctl load ~/Library/LaunchAgents/com.mnemazine.telegram-sync.plist launchctl load ~/Library/LaunchAgents/com.mnemazine.telegram-sync.plist
``` ```
Override host/key/paths via `MNEMAZINE_VPS`, `MNEMAZINE_VPS_KEY`, Use a dedicated unprivileged host user, for example `deploy@host`, not a
`MNEMAZINE_REMOTE_INBOX`, `MNEMAZINE_ROOT` (see the script headers). On Linux, privileged login. Default remote paths are under that user's home:
use a 5-minute cron entry calling `mnemazine-telegram-poll.sh` instead. `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 ## Security
- The token is a secret — keep it in env / a secret store, never in git. - 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. - `initData` is HMAC-verified with the bot token; only allowlisted user ids pass.
- The bot ignores messages from anyone outside `ALLOWED_CHAT_IDS`. - 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 ## Self-tests
+34 -6
View File
@@ -23,11 +23,13 @@ LLM-бинарь). Бот живёт на всегда-онлайн хосте,
│ • есть флаг .run-now? → прогон │ • есть флаг .run-now? → прогон
│ • наступило окно дня? → прогон │ • наступило окно дня? → прогон
▼ ▼
rsync --remove-source-files (move; хост остаётся тонким) rsync-копия в локальный staging
▼ ▼
локальный inbox/ ──▶ npm start (строгий протокол) локальный 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. Ноль зависимостей. | | `scripts/mnemazine-webapp-server.mjs` | хост | API Mini App (`/api/status`, `/api/send`, `/api/run`). Верифицирует `initData`, держит allowlist. Ноль зависимостей. |
| `webapp/index.html` | хост (статика) | UI Mini App. Тема-aware, один файл. | | `webapp/index.html` | хост (статика) | UI Mini App. Тема-aware, один файл. |
| `scripts/mnemazine-telegram-poll.sh` | твоя машина | Тик ~5 мин: флаг run-now / дневное окно → pull + прогон. | | `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) для тика. | | `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 launchctl load ~/Library/LaunchAgents/com.mnemazine.telegram-sync.plist
``` ```
Хост/ключ/пути переопределяются через `MNEMAZINE_VPS`, `MNEMAZINE_VPS_KEY`, Используй отдельного непривилегированного пользователя, например `deploy@host`,
`MNEMAZINE_REMOTE_INBOX`, `MNEMAZINE_ROOT` (см. шапки скриптов). На Linux — не привилегированный логин. Дефолтные пути живут в home этого пользователя:
cron на 5 минут, вызывающий `mnemazine-telegram-poll.sh`. `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. - Токен — секрет: env / секрет-стор, никогда не в git.
- `initData` HMAC-верифицируется токеном бота; проходят только id из allowlist. - `initData` HMAC-верифицируется токеном бота; проходят только id из allowlist.
- Бот игнорирует сообщения от всех вне `ALLOWED_CHAT_IDS`. - Бот игнорирует сообщения от всех вне `ALLOWED_CHAT_IDS`.
- Ротируй bot token, если хост, pm2 env, shell history или логи могли утечь.
Ротируй SSH-ключ, если мог утечь пользователь хоста или ключ рабочей машины.
Перезакрепляй `known_hosts` только после проверки нового fingerprint через
панель провайдера или другой доверенный канал.
## Селф-тесты ## Селф-тесты
+20 -5
View File
@@ -14,14 +14,29 @@ USER_BIN="$HOME/.local/bin"
mkdir -p "$INBOX" "$VAULT" "$REPORTS" "$STATE" "$BIN" "$USER_BIN" "$ROOT/.mnemazine/cache" mkdir -p "$INBOX" "$VAULT" "$REPORTS" "$STATE" "$BIN" "$USER_BIN" "$ROOT/.mnemazine/cache"
mkdir -p "$VAULT/00 System" "$VAULT/01 Concepts" "$VAULT/02 Tools" "$VAULT/03 Agents" "$VAULT/04 Projects" "$VAULT/99 Archive" mkdir -p "$VAULT/00 System" "$VAULT/01 Concepts" "$VAULT/02 Tools" "$VAULT/03 Agents" "$VAULT/04 Projects" "$VAULT/99 Archive"
if [ "${MNEMAZINE_SKIP_DEPS:-0}" != "1" ] && command -v python3 >/dev/null 2>&1; then if [ "${MNEMAZINE_SKIP_DEPS:-0}" = "1" ]; then
python3 -m venv "$ROOT/.venv" || true echo "DEGRADED: Python deps skipped by MNEMAZINE_SKIP_DEPS=1."
"$ROOT/.venv/bin/python" -m pip install --upgrade pip elif command -v python3 >/dev/null 2>&1; then
"$ROOT/.venv/bin/python" -m pip install -r "$ROOT/requirements.txt" || true req="$ROOT/requirements.lock"
[ -f "$req" ] || req="$ROOT/requirements.txt"
if python3 -m venv "$ROOT/.venv"; then
if ! "$ROOT/.venv/bin/python" -m pip install --upgrade pip || ! "$ROOT/.venv/bin/python" -m pip install -r "$req"; then
echo "DEGRADED: Python deps failed from $req; local document engines unavailable." >&2
[ "${MNEMAZINE_REQUIRE_PYTHON_DEPS:-0}" = "1" ] && exit 1
fi
else
echo "DEGRADED: could not create .venv; local document engines unavailable." >&2
[ "${MNEMAZINE_REQUIRE_PYTHON_DEPS:-0}" = "1" ] && exit 1
fi
else
echo "DEGRADED: python3 missing; local document engines unavailable." >&2
[ "${MNEMAZINE_REQUIRE_PYTHON_DEPS:-0}" = "1" ] && exit 1
fi fi
if command -v swiftc >/dev/null 2>&1 && [ -f "$ROOT/skills/mnemazine/vision-ocr.swift" ]; then if command -v swiftc >/dev/null 2>&1 && [ -f "$ROOT/skills/mnemazine/vision-ocr.swift" ]; then
swiftc -O "$ROOT/skills/mnemazine/vision-ocr.swift" -o "$BIN/vision-ocr" || true swiftc -O "$ROOT/skills/mnemazine/vision-ocr.swift" -o "$BIN/vision-ocr" || echo "DEGRADED: Apple Vision OCR build failed; image OCR unavailable." >&2
else
echo "DEGRADED: swiftc or Vision source missing; Apple Vision OCR unavailable." >&2
fi fi
if [ -d "$HOME/.codex/skills" ]; then if [ -d "$HOME/.codex/skills" ]; then
+20
View File
@@ -0,0 +1,20 @@
{
"name": "mnemazine",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "mnemazine",
"version": "0.1.0",
"license": "MIT",
"bin": {
"mnemazine": "bin/mnemazine",
"Mnemazine": "bin/mnemazine"
},
"engines": {
"node": ">=20"
}
}
}
}
+5
View File
@@ -13,8 +13,13 @@
"start": "bash scripts/mnemazine-desktop-protocol.sh", "start": "bash scripts/mnemazine-desktop-protocol.sh",
"desktop": "bash scripts/mnemazine-desktop-protocol.sh", "desktop": "bash scripts/mnemazine-desktop-protocol.sh",
"update": "bash scripts/mnemazine-update.sh", "update": "bash scripts/mnemazine-update.sh",
"test": "npm run release-check",
"audit:security": "npm audit --audit-level=moderate",
"audit:local": "bash scripts/mnemazine-audit-local.sh",
"selftest:security": "node scripts/mnemazine-verify.mjs --selftest && node scripts/mnemazine-webapp-server.mjs --selftest && node scripts/mnemazine-telegram-bot.mjs --selftest && node scripts/mnemazine-weekly-state.mjs --selftest",
"run": "node scripts/mnemazine-run.mjs", "run": "node scripts/mnemazine-run.mjs",
"protocol:desktop": "bash scripts/mnemazine-desktop-protocol.sh", "protocol:desktop": "bash scripts/mnemazine-desktop-protocol.sh",
"protocol:desktop:dry-run": "bash scripts/mnemazine-desktop-protocol.sh --dry-run",
"graph:refresh": "node scripts/mnemazine-refresh-graphify.mjs --json", "graph:refresh": "node scripts/mnemazine-refresh-graphify.mjs --json",
"graph:shards": "node scripts/mnemazine-semantic-shards.mjs", "graph:shards": "node scripts/mnemazine-semantic-shards.mjs",
"graph:semantic-batches": "node scripts/mnemazine-semantic-batches.mjs", "graph:semantic-batches": "node scripts/mnemazine-semantic-batches.mjs",
+86
View File
@@ -0,0 +1,86 @@
annotated-doc==0.0.4
anyio==4.14.0
beautifulsoup4==4.15.0
certifi==2026.6.17
charset-normalizer==3.4.7
click==8.4.1
defusedxml==0.7.1
fastembed==0.8.0
filelock==3.29.4
flatbuffers==25.12.19
fsspec==2026.6.0
graphifyy==0.8.46
h11==0.16.0
hf-xet==1.5.1
httpcore==1.0.9
httpx==0.28.1
huggingface_hub==1.20.1
idna==3.18
Jinja2==3.1.6
llvmlite==0.47.0
loguru==0.7.3
magika==0.6.3
markdown-it-py==4.2.0
markdownify==1.2.2
markitdown==0.1.6
MarkupSafe==3.0.3
mdurl==0.1.2
mmh3==5.2.1
more-itertools==11.1.0
mpmath==1.3.0
networkx==3.6.1
numba==0.65.1
numpy==2.4.6
onnxruntime==1.27.0
openai-whisper==20250625
packaging==26.2
pillow==12.2.0
protobuf==7.35.1
py_rust_stemmers==0.1.8
Pygments==2.20.0
PyMuPDF==1.27.2.3
pypdf==6.14.2
python-dotenv==1.2.2
PyYAML==6.0.3
RapidFuzz==3.14.5
regex==2026.5.9
reportlab==5.0.0
requests==2.34.2
rich==15.0.0
shellingham==1.5.4
six==1.17.0
soupsieve==2.8.4
sympy==1.14.0
tiktoken==0.13.0
tokenizers==0.23.1
torch==2.12.1
tqdm==4.68.3
tree-sitter==0.25.2
tree-sitter-bash==0.25.1
tree-sitter-c==0.24.2
tree-sitter-c-sharp==0.23.5
tree-sitter-cpp==0.23.4
tree-sitter-elixir==0.3.5
tree-sitter-fortran==0.6.0
tree-sitter-go==0.25.0
tree-sitter-groovy==0.1.2
tree-sitter-java==0.23.5
tree-sitter-javascript==0.25.0
tree-sitter-json==0.24.8
tree-sitter-julia==0.23.1
tree-sitter-kotlin==1.1.0
tree-sitter-lua==0.5.0
tree-sitter-objc==3.0.2
tree-sitter-php==0.24.1
tree-sitter-powershell==0.26.4
tree-sitter-python==0.25.0
tree-sitter-ruby==0.23.1
tree-sitter-rust==0.24.2
tree-sitter-scala==0.26.0
tree-sitter-swift==0.7.3
tree-sitter-typescript==0.23.2
tree-sitter-verilog==1.0.3
tree-sitter-zig==1.1.2
typer==0.25.1
typing_extensions==4.15.0
urllib3==2.7.0
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
cd "$ROOT"
while IFS= read -r -d '' file; do bash -n "$file"; done < <(find . -maxdepth 2 -type f \( -name '*.sh' -o -name 'install.sh' -o -name 'setup.sh' \) -not -path './node_modules/*' -print0)
while IFS= read -r -d '' file; do node --check "$file"; done < <(find scripts tests -type f -name '*.mjs' -print0)
npm run selftest:security
npm audit --audit-level=moderate
npm run public-check
if rg -n --glob '!node_modules/**' --glob '!.git/**' --glob '!.mnemazine/**' --glob '!scripts/mnemazine-audit-local.sh' 'StrictHostKeyChecking=(no|accept-new)|root@[a-z0-9][A-Za-z0-9._-]*|(^|[^A-Za-z0-9_])--dangerously-skip-permissions([^A-Za-z0-9_]|$)|https?://[^/[:space:]'\''"]+@' .; then
echo "audit:local failed: dangerous flag or credential URL pattern found." >&2
exit 1
fi
if rg -n "fetch\\([^\\n]*(169\\.254\\.169\\.254|metadata\\.google|metadata\\.azure)" scripts webapp; then
echo "audit:local failed: metadata/private fetch pattern found." >&2
exit 1
fi
echo "audit:local passed"
+13 -6
View File
@@ -33,14 +33,17 @@ function run(command, args) {
}) })
} }
async function newestFileMtime(dir, filter = () => true) { async function newestChangedFileMtime(dir, sinceMs, filter = () => true) {
let newest = 0 let newest = 0
async function walk(folder) { async function walk(folder) {
for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) { for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) {
if (item.name.startsWith('graphify-out')) continue if (item.name.startsWith('graphify-out')) continue
const file = path.join(folder, item.name) const file = path.join(folder, item.name)
if (item.isDirectory()) await walk(file) if (item.isDirectory()) await walk(file)
else if (item.isFile() && filter(file)) newest = Math.max(newest, (await fs.stat(file)).mtimeMs) else if (item.isFile() && filter(file)) {
const stat = await fs.stat(file)
if (!sinceMs || stat.mtimeMs >= sinceMs) newest = Math.max(newest, stat.mtimeMs)
}
} }
} }
await walk(dir) await walk(dir)
@@ -72,6 +75,7 @@ function deepFailures(lastRun) {
if (!lastRun) return ['last run state missing'] if (!lastRun) return ['last run state missing']
if (!lastRun.ok) failures.push(`last run failed: ${(lastRun.failures || [lastRun.failure || 'unknown']).join('; ')}`) if (!lastRun.ok) failures.push(`last run failed: ${(lastRun.failures || [lastRun.failure || 'unknown']).join('; ')}`)
if (!lastRun.deep) failures.push('last run was not deep') if (!lastRun.deep) failures.push('last run was not deep')
if (lastRun.strict_archive_knowledge !== true) failures.push('strict archive knowledge gate was not enabled')
if (!lastRun.synthesize || lastRun.synthesize.skipped) { if (!lastRun.synthesize || lastRun.synthesize.skipped) {
if (Number(lastRun.processed || 0) > 0) failures.push('deep synthesis did not run') if (Number(lastRun.processed || 0) > 0) failures.push('deep synthesis did not run')
return failures return failures
@@ -88,7 +92,12 @@ async function main() {
const inboxFiles = await activeInboxFiles() const inboxFiles = await activeInboxFiles()
if (inboxFiles.length) failures.push(`inbox not empty: ${inboxFiles.length}`) if (inboxFiles.length) failures.push(`inbox not empty: ${inboxFiles.length}`)
const quality = await run(process.execPath, ['scripts/mnemazine-vault-quality-gate.mjs']) const lastRunFile = path.join(STATE, 'last-run.json')
const lastRun = await readJson(lastRunFile)
const lastRunStartedMs = lastRun?.started_at ? Date.parse(lastRun.started_at) : 0
const qualityArgs = ['scripts/mnemazine-vault-quality-gate.mjs', '--max-failures', '50']
if (lastRunStartedMs) qualityArgs.push('--changed-since', lastRun.started_at)
const quality = await run(process.execPath, qualityArgs)
if (!quality.ok) failures.push(`vault quality failed: ${quality.stderr || quality.stdout}`) if (!quality.ok) failures.push(`vault quality failed: ${quality.stderr || quality.stdout}`)
const report = await latestReport() const report = await latestReport()
@@ -98,7 +107,7 @@ async function main() {
if (!reportQuality.ok) failures.push(`report quality failed: ${reportQuality.stderr || reportQuality.stdout}`) if (!reportQuality.ok) failures.push(`report quality failed: ${reportQuality.stderr || reportQuality.stdout}`)
} }
const newestNote = await newestFileMtime(VAULT, file => file.endsWith('.md')) const newestNote = await newestChangedFileMtime(VAULT, lastRunStartedMs, file => file.endsWith('.md'))
const reportMtime = report ? (await fs.stat(report)).mtimeMs : 0 const reportMtime = report ? (await fs.stat(report)).mtimeMs : 0
if (newestNote && reportMtime && reportMtime < newestNote) failures.push('weekly report older than newest vault note') if (newestNote && reportMtime && reportMtime < newestNote) failures.push('weekly report older than newest vault note')
@@ -114,8 +123,6 @@ async function main() {
else warnings.push(msg) else warnings.push(msg)
} }
const lastRunFile = path.join(STATE, 'last-run.json')
const lastRun = await readJson(lastRunFile)
if (REQUIRE_DEEP) { if (REQUIRE_DEEP) {
for (const failure of deepFailures(lastRun)) failures.push(failure) for (const failure of deepFailures(lastRun)) failures.push(failure)
} }
+24
View File
@@ -6,6 +6,8 @@ ENV_INBOX="${MNEMAZINE_INBOX:-}"
ENV_VAULT="${MNEMAZINE_VAULT:-}" ENV_VAULT="${MNEMAZINE_VAULT:-}"
ENV_DEEP="${MNEMAZINE_DEEP:-}" ENV_DEEP="${MNEMAZINE_DEEP:-}"
ENV_REQUIRE_DEEP="${MNEMAZINE_REQUIRE_DEEP:-}" ENV_REQUIRE_DEEP="${MNEMAZINE_REQUIRE_DEEP:-}"
DRY_RUN=0
[ "${1:-}" = "--dry-run" ] && DRY_RUN=1
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env" [ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh" [ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
@@ -31,6 +33,28 @@ run_inbox() {
} }
mkdir -p "$BASE_INBOX" "$MNEMAZINE_VAULT" mkdir -p "$BASE_INBOX" "$MNEMAZINE_VAULT"
if [ "$DRY_RUN" = "1" ]; then
tmp="$(mktemp -d "${TMPDIR:-/tmp}/mnemazine-desktop-dry-run.XXXXXX")"
trap 'rm -rf "$tmp"' EXIT
mkdir -p "$tmp/inbox" "$tmp/vault" "$tmp/reports" "$tmp/state" "$tmp/cache/extracted" "$tmp/archive"
cp "$REPO/demo/inbox/example-guide.md" "$tmp/inbox/example-guide.md"
echo "Mnemazine protocol dry-run: live inbox untouched ($BASE_INBOX)" >&2
MNEMAZINE_INBOX="$tmp/inbox" \
MNEMAZINE_VAULT="$tmp/vault" \
MNEMAZINE_REPORTS="$tmp/reports" \
MNEMAZINE_STATE="$tmp/state" \
MNEMAZINE_CACHE="$tmp/cache/processed-hashes.json" \
MNEMAZINE_EXTRACTS="$tmp/cache/extracted" \
MNEMAZINE_ARCHIVE="$tmp/archive" \
MNEMAZINE_DEEP=0 \
MNEMAZINE_REQUIRE_DEEP=0 \
MNEMAZINE_FINISH=0 \
npm run --silent run
echo "Mnemazine protocol dry-run: ok" >&2
exit 0
fi
ran=0 ran=0
run_inbox "$BASE_INBOX" run_inbox "$BASE_INBOX"
+49 -7
View File
@@ -23,8 +23,19 @@ const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join
const SESSION = arg('session', new Date().toISOString().slice(0, 10)) const SESSION = arg('session', new Date().toISOString().slice(0, 10))
const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || 'claude') const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || 'claude')
const FORCE = argv.includes('--force') const FORCE = argv.includes('--force')
const DETERMINISTIC = argv.includes('--deterministic') || process.env.MNEMAZINE_DIGEST_DETERMINISTIC === '1'
const LIMIT = Number(arg('limit', '0')) // 0 = no cap const LIMIT = Number(arg('limit', '0')) // 0 = no cap
const CHANGED_SINCE = arg('changed-since', '')
const SPRAVKA = '## Справка' const SPRAVKA = '## Справка'
function sinceMs(value) {
if (!value) return 0
if (/^\d+(?:\.\d+)?$/.test(value)) return Number(value)
const parsed = Date.parse(value)
return Number.isFinite(parsed) ? parsed : 0
}
const CHANGED_SINCE_MS = sinceMs(CHANGED_SINCE)
// Personal project context stays out of the public repo. Set it once locally: // Personal project context stays out of the public repo. Set it once locally:
// env MNEMAZINE_OWNER_CONTEXT, or a gitignored file .mnemazine/owner-context.txt. // env MNEMAZINE_OWNER_CONTEXT, or a gitignored file .mnemazine/owner-context.txt.
function ownerContext() { function ownerContext() {
@@ -110,6 +121,37 @@ function titleOf(text, file) {
return text.match(/^title:\s*"([^"]+)"/m)?.[1] || text.match(/^#\s+(.+)$/m)?.[1]?.trim() || path.basename(file, '.md') return text.match(/^title:\s*"([^"]+)"/m)?.[1] || text.match(/^#\s+(.+)$/m)?.[1]?.trim() || path.basename(file, '.md')
} }
function clean(text, max = 420) {
return String(text || '')
.replace(/```[\s\S]*?```/g, '')
.replace(/^[-*]\s+/gm, '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, max)
}
function extractSection(text, names) {
for (const name of names) {
const re = new RegExp(`^##\\s+${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:\\s|$)[^\\n]*\\n([\\s\\S]*?)(?=^##\\s+|(?![\\s\\S]))`, 'mi')
const hit = text.match(re)
if (hit) return clean(hit[1])
}
return ''
}
function deterministicDigest(noteText, file) {
const title = titleOf(noteText, file)
const what = extractSection(noteText, ['What This Is', 'Что это', 'Суть'])
const why = extractSection(noteText, ['Why It Matters', 'Почему важно'])
const how = extractSection(noteText, ['How To Use It', 'Как использовать', 'Reuse'])
return {
zagolovok: title,
chto_eto: what || `Проверенная заметка по теме "${title}".`,
o_chyom: how || what || 'Суть взята из финальной atom note и привязана к источникам.',
pochemu_vazhno: why || `Полезно для ${OWNER_CONTEXT}: можно быстро понять, стоит ли применять это знание.`
}
}
function spravkaBlock(d, connections) { function spravkaBlock(d, connections) {
const conns = connections.length ? connections.map(c => `- [[${c.replace(/\.md$/, '')}]]`).join('\n') : '- (отдельных связей не найдено)' const conns = connections.length ? connections.map(c => `- [[${c.replace(/\.md$/, '')}]]`).join('\n') : '- (отдельных связей не найдено)'
return `${SPRAVKA} return `${SPRAVKA}
@@ -126,26 +168,26 @@ ${conns}
} }
async function main() { async function main() {
if (!llmAvailable(PROVIDER)) { const modelAvailable = !DETERMINISTIC && llmAvailable(PROVIDER)
console.log(JSON.stringify({ ok: false, reason: `llm provider '${PROVIDER}' unavailable`, written: 0 }))
process.exit(0)
}
const connByNote = await loadConnections() const connByNote = await loadConnections()
const files = await walk(VAULT) const files = await walk(VAULT)
const summary = [] const summary = []
let written = 0 let written = 0
for (const file of files) { for (const file of files) {
if (LIMIT && written >= LIMIT) break if (LIMIT && written >= LIMIT) break
if (CHANGED_SINCE_MS && (await fs.stat(file)).mtimeMs < CHANGED_SINCE_MS) continue
const text = await fs.readFile(file, 'utf8') const text = await fs.readFile(file, 'utf8')
if (text.includes(SPRAVKA) && !FORCE) continue if (text.includes(SPRAVKA) && !FORCE) continue
const rel = path.relative(VAULT, file) const rel = path.relative(VAULT, file)
const connections = connByNote.get(rel) || [] const connections = connByNote.get(rel) || []
let d let d
try { try {
d = await llmJson(digestPrompt(text, connections), DIGEST_SCHEMA, { provider: PROVIDER }) d = modelAvailable
? await llmJson(digestPrompt(text, connections), DIGEST_SCHEMA, { provider: PROVIDER })
: deterministicDigest(text, file)
} catch (err) { } catch (err) {
console.error(`[digest] failed for ${rel}: ${err.message}`) console.error(`[digest] failed for ${rel}: ${err.message}`)
continue d = deterministicDigest(text, file)
} }
if (!d?.zagolovok) continue if (!d?.zagolovok) continue
// Справка is always appended last, so strip from its first occurrence to EOF. // Справка is always appended last, so strip from its first occurrence to EOF.
@@ -177,7 +219,7 @@ async function main() {
await fs.writeFile(path.join(dir, `Сводка-${SESSION}.md`), body, 'utf8') await fs.writeFile(path.join(dir, `Сводка-${SESSION}.md`), body, 'utf8')
} }
console.log(JSON.stringify({ ok: true, provider: PROVIDER, written, summary: summary.length, linked: connByNote.size }, null, 2)) console.log(JSON.stringify({ ok: true, provider: PROVIDER, model_available: modelAvailable, written, summary: summary.length, linked: connByNote.size }, null, 2))
} }
main().catch(err => { console.error(err.message || err); process.exit(1) }) main().catch(err => { console.error(err.message || err); process.exit(1) })
+15 -6
View File
@@ -101,7 +101,18 @@ function extractJson(text) {
return JSON.parse(body.slice(start, end + 1)) return JSON.parse(body.slice(start, end + 1))
} }
// --- Codex backend (unchanged headless pattern: --output-schema + -o) --- function codexNeedsSearch(opts = {}) {
return (opts.tools || []).some(tool => /^(WebSearch|WebFetch|mcp__firecrawl|mcp__tavily)$/i.test(tool))
}
function codexExecArgs(cwd, opts = {}) {
const args = ['--ask-for-approval', 'never']
if (codexNeedsSearch(opts)) args.push('--search')
args.push('exec', '-C', cwd, '--skip-git-repo-check', '--sandbox', 'read-only', '--ephemeral')
return args
}
// --- Codex backend (headless pattern: --output-schema + -o) ---
async function codexJsonCall(prompt, schema, opts) { async function codexJsonCall(prompt, schema, opts) {
if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`) if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
const work = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-codex-')) const work = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-codex-'))
@@ -113,8 +124,7 @@ async function codexJsonCall(prompt, schema, opts) {
await fs.writeFile(promptFile, prompt, { encoding: 'utf8', mode: 0o600 }) await fs.writeFile(promptFile, prompt, { encoding: 'utf8', mode: 0o600 })
try { try {
const res = await runProc(CODEX_BIN, [ const res = await runProc(CODEX_BIN, [
'exec', '-C', cwd, '--skip-git-repo-check', ...codexExecArgs(cwd, opts),
'--dangerously-bypass-approvals-and-sandbox',
'--output-schema', schemaFile, '-o', outFile, '-' '--output-schema', schemaFile, '-o', outFile, '-'
], { input: await fs.readFile(promptFile, 'utf8'), timeoutMs: opts.timeoutMs || TIMEOUT_MS }) ], { input: await fs.readFile(promptFile, 'utf8'), timeoutMs: opts.timeoutMs || TIMEOUT_MS })
if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`) if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
@@ -130,7 +140,7 @@ async function codexJsonCall(prompt, schema, opts) {
// No --output-schema in Claude, so the schema is embedded and the result parsed. // No --output-schema in Claude, so the schema is embedded and the result parsed.
// Tools are opt-in via opts.tools (default none = no network); enrich/verify // Tools are opt-in via opts.tools (default none = no network); enrich/verify
// pass WebSearch/WebFetch (+ MCP) to let Claude research with available tools. // pass WebSearch/WebFetch (+ MCP) to let Claude research with available tools.
// Never uses --dangerously-skip-permissions (constitution): unpermitted tools // Never uses the permission-bypass flag (constitution): unpermitted tools
// simply do not run in -p mode. // simply do not run in -p mode.
async function claudeJsonCall(prompt, schema, opts) { async function claudeJsonCall(prompt, schema, opts) {
const bin = resolveClaudeBin() const bin = resolveClaudeBin()
@@ -164,8 +174,7 @@ export async function llmText(prompt, opts = {}) {
if (provider === 'codex') { if (provider === 'codex') {
if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`) if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
const res = await runProc(CODEX_BIN, [ const res = await runProc(CODEX_BIN, [
'exec', '-C', opts.cwd || process.cwd(), '--skip-git-repo-check', ...codexExecArgs(opts.cwd || process.cwd(), opts), '-'
'--dangerously-bypass-approvals-and-sandbox', '-'
], { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS }) ], { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`) if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
return String(res.stdout || '').trim() return String(res.stdout || '').trim()
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
set -euo pipefail
REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
VPS="${MNEMAZINE_VPS:-deploy@YOUR_VPS_HOST}"
EXPECTED="${MNEMAZINE_VPS_HOST_FINGERPRINT:-${1:-}}"
KNOWN_HOSTS="${MNEMAZINE_SSH_KNOWN_HOSTS:-$REPO/.mnemazine/known_hosts}"
if [ "$VPS" = "deploy@YOUR_VPS_HOST" ] || [ -z "$EXPECTED" ]; then
echo "Usage: MNEMAZINE_VPS=deploy@example.com MNEMAZINE_VPS_HOST_FINGERPRINT=SHA256:... bash scripts/mnemazine-pin-vps-host.sh" >&2
exit 1
fi
HOST="${VPS#*@}"
TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT
ssh-keyscan -T 10 "$HOST" > "$TMP" 2>/dev/null
[ -s "$TMP" ] || { echo "No SSH host key from $HOST" >&2; exit 1; }
if ! ssh-keygen -lf "$TMP" | awk '{print $2}' | grep -Fx "$EXPECTED" >/dev/null; then
echo "SSH host fingerprint mismatch for $HOST" >&2
echo "Expected: $EXPECTED" >&2
echo "Seen:" >&2
ssh-keygen -lf "$TMP" >&2
exit 1
fi
mkdir -p "$(dirname "$KNOWN_HOSTS")"
touch "$KNOWN_HOSTS"
ssh-keygen -R "$HOST" -f "$KNOWN_HOSTS" >/dev/null 2>&1 || true
cat "$TMP" >> "$KNOWN_HOSTS"
chmod 600 "$KNOWN_HOSTS"
echo "Pinned SSH host key for $HOST in $KNOWN_HOSTS"
+201 -4
View File
@@ -3,6 +3,7 @@ import { promises as fs } from 'node:fs'
import { existsSync } from 'node:fs' import { existsSync } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import os from 'node:os' import os from 'node:os'
import crypto from 'node:crypto'
import { spawn } from 'node:child_process' import { spawn } from 'node:child_process'
const ROOT = path.resolve(process.cwd()) const ROOT = path.resolve(process.cwd())
@@ -35,6 +36,10 @@ async function readJson(file) {
return JSON.parse(await fs.readFile(file, 'utf8')) return JSON.parse(await fs.readFile(file, 'utf8'))
} }
function sha256Text(text) {
return crypto.createHash('sha256').update(text).digest('hex')
}
async function listFiles(dir) { async function listFiles(dir) {
const out = [] const out = []
for (const entry of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) { for (const entry of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
@@ -76,6 +81,78 @@ async function checkSyntax() {
} }
} }
async function npmAuditCheck() {
await must('npm audit', 'npm', ['audit', '--audit-level=moderate'])
}
async function desktopDryRunSmoke() {
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-desktop-dry-'))
const inbox = path.join(temp, 'live-inbox')
const vault = path.join(temp, 'live-vault')
await fs.mkdir(inbox, { recursive: true })
await fs.mkdir(vault, { recursive: true })
await fs.writeFile(path.join(inbox, 'live-source.md'), '# Live source\n\nMust stay in live inbox.\n', 'utf8')
await must('desktop protocol dry-run', 'bash', ['scripts/mnemazine-desktop-protocol.sh', '--dry-run'], {
env: {
MNEMAZINE_INBOX: inbox,
MNEMAZINE_VAULT: vault
}
})
if (!existsSync(path.join(inbox, 'live-source.md'))) throw new Error('desktop dry-run smoke failed: live inbox file changed')
const vaultFiles = await listFiles(vault)
if (vaultFiles.length) throw new Error(`desktop dry-run smoke failed: live vault changed (${vaultFiles.join(', ')})`)
}
async function pollRetrySmoke() {
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-poll-retry-'))
const bin = path.join(temp, 'bin')
const state = path.join(temp, 'state')
await fs.mkdir(bin, { recursive: true })
await fs.mkdir(state, { recursive: true })
await fs.mkdir(path.join(temp, '.mnemazine'), { recursive: true })
await fs.writeFile(path.join(temp, '.mnemazine', 'known_hosts'), 'example.test ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKpinnedHostKeyForReleaseSmokeOnly1234567890\n', 'utf8')
await fs.writeFile(path.join(bin, 'ssh'), '#!/usr/bin/env bash\nexit 0\n', { mode: 0o755 })
await fs.writeFile(path.join(bin, 'sync.sh'), `#!/usr/bin/env bash
set -euo pipefail
mkdir -p ${JSON.stringify(state)}
count_file=${JSON.stringify(path.join(state, 'count'))}
count="$(cat "$count_file" 2>/dev/null || echo 0)"
count=$((count + 1))
echo "$count" > "$count_file"
if [ -f ${JSON.stringify(path.join(state, 'fail'))} ]; then exit 1; fi
exit 0
`, { mode: 0o755 })
await fs.writeFile(path.join(state, 'fail'), '1', 'utf8')
const env = {
MNEMAZINE_ROOT: temp,
MNEMAZINE_VPS: 'deploy@example.test',
MNEMAZINE_VPS_KEY: path.join(temp, 'missing-key'),
MNEMAZINE_REMOTE_MUTATION: '1',
MNEMAZINE_SSH_BIN: path.join(bin, 'ssh'),
MNEMAZINE_TELEGRAM_SYNC_BIN: path.join(bin, 'sync.sh'),
MNEMAZINE_POLL_TODAY: '2099-01-01',
MNEMAZINE_POLL_HOUR: '9',
MNEMAZINE_DAILY_RETRY_SECONDS: '60',
MNEMAZINE_DAILY_MAX_ATTEMPTS: '2'
}
const first = await run('bash', ['scripts/mnemazine-telegram-poll.sh'], { env: { ...env, MNEMAZINE_POLL_EPOCH: '1000' } })
if (first.code === 0) throw new Error('poll retry smoke failed: first failing sync passed')
if (await fs.readFile(path.join(state, 'count'), 'utf8') !== '1\n') throw new Error('poll retry smoke failed: first attempt not counted')
if (existsSync(path.join(temp, '.mnemazine', '.last-daily-completed'))) throw new Error('poll retry smoke failed: failure marked completed')
await must('poll retry smoke:no early retry', 'bash', ['scripts/mnemazine-telegram-poll.sh'], { env: { ...env, MNEMAZINE_POLL_EPOCH: '1010' } })
if (await fs.readFile(path.join(state, 'count'), 'utf8') !== '1\n') throw new Error('poll retry smoke failed: retried before backoff')
await fs.unlink(path.join(state, 'fail'))
await must('poll retry smoke:retry success', 'bash', ['scripts/mnemazine-telegram-poll.sh'], { env: { ...env, MNEMAZINE_POLL_EPOCH: '1061' } })
if (await fs.readFile(path.join(state, 'count'), 'utf8') !== '2\n') throw new Error('poll retry smoke failed: retry did not run')
const completed = await fs.readFile(path.join(temp, '.mnemazine', '.last-daily-completed'), 'utf8')
if (completed.trim() !== '2099-01-01') throw new Error('poll retry smoke failed: success not marked completed')
await must('poll retry smoke:no rerun after complete', 'bash', ['scripts/mnemazine-telegram-poll.sh'], { env: { ...env, MNEMAZINE_POLL_EPOCH: '2000' } })
if (await fs.readFile(path.join(state, 'count'), 'utf8') !== '2\n') throw new Error('poll retry smoke failed: completed daily reran')
}
async function demoSmoke() { async function demoSmoke() {
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-release-')) const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-release-'))
const inbox = path.join(temp, 'inbox') const inbox = path.join(temp, 'inbox')
@@ -101,7 +178,9 @@ async function demoSmoke() {
}) })
const inboxFiles = await fs.readdir(inbox) const inboxFiles = await fs.readdir(inbox)
if (inboxFiles.length !== 0) throw new Error(`demo smoke failed: inbox not empty (${inboxFiles.join(', ')})`) if (inboxFiles.length !== 1 || inboxFiles[0] !== 'empty-source.bin') {
throw new Error(`demo smoke failed: expected only unextractable source in inbox (${inboxFiles.join(', ')})`)
}
const notes = (await listFiles(vault)) const notes = (await listFiles(vault))
.filter(file => file.endsWith('.md')) .filter(file => file.endsWith('.md'))
@@ -117,7 +196,7 @@ async function demoSmoke() {
} }
const archived = await listFiles(path.join(temp, '.mnemazine/archive')) const archived = await listFiles(path.join(temp, '.mnemazine/archive'))
if (archived.length !== 2) throw new Error(`demo smoke failed: expected 2 archived sources, got ${archived.length}`) if (archived.length !== 1) throw new Error(`demo smoke failed: expected 1 archived finalized source, got ${archived.length}`)
const extractRecords = (await listFiles(path.join(temp, '.mnemazine/cache/extracted'))).filter(file => file.endsWith('.json')) const extractRecords = (await listFiles(path.join(temp, '.mnemazine/cache/extracted'))).filter(file => file.endsWith('.json'))
if (extractRecords.length !== 2) throw new Error(`demo smoke failed: expected 2 extract records, got ${extractRecords.length}`) if (extractRecords.length !== 2) throw new Error(`demo smoke failed: expected 2 extract records, got ${extractRecords.length}`)
@@ -134,12 +213,126 @@ async function demoSmoke() {
} }
}) })
const cachedInboxFiles = await fs.readdir(inbox) const cachedInboxFiles = await fs.readdir(inbox)
if (cachedInboxFiles.length !== 0) throw new Error(`demo cached smoke failed: inbox not empty (${cachedInboxFiles.join(', ')})`) if (cachedInboxFiles.length !== 1 || cachedInboxFiles[0] !== 'empty-source.bin') {
throw new Error(`demo cached smoke failed: expected only unextractable source in inbox (${cachedInboxFiles.join(', ')})`)
}
const archivedAfterCachedRun = await listFiles(path.join(temp, '.mnemazine/archive')) const archivedAfterCachedRun = await listFiles(path.join(temp, '.mnemazine/archive'))
if (archivedAfterCachedRun.length !== 3) throw new Error(`demo cached smoke failed: expected 3 archived sources, got ${archivedAfterCachedRun.length}`) if (archivedAfterCachedRun.length !== 2) throw new Error(`demo cached smoke failed: expected 2 archived finalized sources, got ${archivedAfterCachedRun.length}`)
}
async function strictArchiveGateSmoke() {
async function writeCachedCase(temp, noteBody) {
const inbox = path.join(temp, 'inbox')
const vault = path.join(temp, 'vault')
const scripts = path.join(temp, 'scripts')
const extracts = path.join(temp, '.mnemazine/cache/extracted')
await fs.mkdir(inbox, { recursive: true })
await fs.mkdir(path.join(vault, '01 Concepts'), { recursive: true })
await fs.mkdir(scripts, { recursive: true })
await fs.mkdir(extracts, { recursive: true })
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs'), path.join(scripts, 'mnemazine-vault-quality-gate.mjs'))
const source = 'MarkItDown converts Office/PDF/image inputs into Markdown for LLM pipelines. This cached source has enough text for synthesis.'
const hash = sha256Text(source)
const ref = `local-media:${hash.slice(0, 16)}`
await fs.writeFile(path.join(inbox, 'source.md'), source, 'utf8')
await fs.writeFile(path.join(extracts, `${hash}.txt`), source, 'utf8')
await fs.writeFile(path.join(extracts, `${hash}.json`), JSON.stringify({ source_ref: ref, status: 'extracted_for_note', text_path: `${hash}.txt` }, null, 2), 'utf8')
await fs.mkdir(path.join(temp, '.mnemazine/cache'), { recursive: true })
await fs.writeFile(path.join(temp, '.mnemazine/cache/processed-hashes.json'), JSON.stringify({
[hash]: { status: 'extracted_for_note', source_ref: ref, cache: `.mnemazine/cache/extracted/${hash}.json` }
}, null, 2), 'utf8')
await fs.writeFile(path.join(vault, '01 Concepts', 'cached-note.md'), noteBody(ref), 'utf8')
return { inbox, vault, sourceFile: path.join(inbox, 'source.md') }
}
const weakTemp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-strict-weak-'))
const weak = await writeCachedCase(weakTemp, ref => `---
title: "Weak cached note"
type: "knowledge-note"
verified: false
verification_status: "unknown"
status: "draft"
enrichment: "missing"
---
# Weak cached note
## What This Is
Cached OCR-like material, not final knowledge.
## Source
Local source refs:
- ${ref}
Public/source expansion:
- No public source detected.
`)
const weakRun = await run(process.execPath, ['scripts/mnemazine-run.mjs'], {
env: {
MNEMAZINE_ROOT: weakTemp,
MNEMAZINE_INBOX: weak.inbox,
MNEMAZINE_VAULT: weak.vault,
MNEMAZINE_DEEP: '1',
MNEMAZINE_REQUIRE_DEEP: '1',
MNEMAZINE_SYNTHESIZE: '0',
MNEMAZINE_FINISH: '0'
}
})
if (weakRun.code === 0) throw new Error('strict archive gate smoke failed: weak cached note passed')
if (!existsSync(weak.sourceFile)) throw new Error('strict archive gate smoke failed: weak cached source was archived')
const goodTemp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-strict-good-'))
const good = await writeCachedCase(goodTemp, ref => `---
title: "Verified enriched cached note"
type: "knowledge-note"
verified: true
verification_status: "verified"
status: "final"
enrichment: "external-research"
---
# Verified enriched cached note
## What This Is
MarkItDown is verified here as reusable knowledge, not raw OCR.
## Source
Local source refs:
- ${ref}
Public/source expansion:
- Microsoft MarkItDown: https://github.com/microsoft/markitdown
## Enrichment
External facts added before atomization:
- Microsoft maintains MarkItDown as an open-source file-to-Markdown converter.
- The public repository documents optional extras for additional input formats.
`)
await must('strict archive gate smoke:good', process.execPath, ['scripts/mnemazine-run.mjs'], {
env: {
MNEMAZINE_ROOT: goodTemp,
MNEMAZINE_INBOX: good.inbox,
MNEMAZINE_VAULT: good.vault,
MNEMAZINE_DEEP: '1',
MNEMAZINE_REQUIRE_DEEP: '1',
MNEMAZINE_SYNTHESIZE: '0',
MNEMAZINE_FINISH: '0'
}
})
if (existsSync(good.sourceFile)) throw new Error('strict archive gate smoke failed: verified cached source stayed in inbox')
} }
async function qualityAndPublicChecks() { async function qualityAndPublicChecks() {
await must('verify selftest', process.execPath, ['scripts/mnemazine-verify.mjs', '--selftest'])
await must('webapp selftest', process.execPath, ['scripts/mnemazine-webapp-server.mjs', '--selftest'])
await must('telegram bot selftest', process.execPath, ['scripts/mnemazine-telegram-bot.mjs', '--selftest'])
await must('weekly state selftest', process.execPath, ['scripts/mnemazine-weekly-state.mjs', '--selftest'])
await must('demo vault quality', 'npm', ['run', 'quality', '--', '--vault', 'demo/vault']) await must('demo vault quality', 'npm', ['run', 'quality', '--', '--vault', 'demo/vault'])
await reportQualityGateSmoke() await reportQualityGateSmoke()
await completeGateSmoke() await completeGateSmoke()
@@ -251,7 +444,11 @@ async function repoMetadataCheck() {
async function main() { async function main() {
const checks = [ const checks = [
['syntax', checkSyntax], ['syntax', checkSyntax],
['npm-audit', npmAuditCheck],
['desktop-dry-run', desktopDryRunSmoke],
['poll-retry', pollRetrySmoke],
['demo-smoke', demoSmoke], ['demo-smoke', demoSmoke],
['strict-archive-gate', strictArchiveGateSmoke],
['quality-public', qualityAndPublicChecks], ['quality-public', qualityAndPublicChecks],
['search-eval', searchEvalSmoke], ['search-eval', searchEvalSmoke],
['repo-metadata', repoMetadataCheck] ['repo-metadata', repoMetadataCheck]
+2 -1
View File
@@ -26,7 +26,8 @@ const rawMarkers = [
/draft-local/i, /draft-local/i,
/\btemp_image[_-]/i, /\btemp_image[_-]/i,
/\bIMG_\d+/, /\bIMG_\d+/,
/\.(WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4)\b/i /\.(WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4)\b/i,
/\b[\wА-Яа-яЁё ._-]+\.md\b/i
] ]
const requiredSignals = [ const requiredSignals = [
+106 -17
View File
@@ -26,6 +26,7 @@ const FINISH = process.env.MNEMAZINE_FINISH !== '0'
const DEEP = process.argv.includes('--deep') || process.env.MNEMAZINE_DEEP === '1' const DEEP = process.argv.includes('--deep') || process.env.MNEMAZINE_DEEP === '1'
const REQUIRE_DEEP = process.argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1' const REQUIRE_DEEP = process.argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
const ENRICH_REQUIRED = DEEP && process.env.MNEMAZINE_ENRICH !== '0' && !process.argv.includes('--no-enrich') const ENRICH_REQUIRED = DEEP && process.env.MNEMAZINE_ENRICH !== '0' && !process.argv.includes('--no-enrich')
const STRICT_ARCHIVE_KNOWLEDGE = (REQUIRE_DEEP || (DEEP && ENRICH_REQUIRED)) && process.env.MNEMAZINE_STRICT_ARCHIVE !== '0' && !process.argv.includes('--allow-raw-archive')
const WHISPER_MODEL = process.env.MNEMAZINE_WHISPER_MODEL || '' const WHISPER_MODEL = process.env.MNEMAZINE_WHISPER_MODEL || ''
const WHISPER_LANGUAGE = process.env.MNEMAZINE_WHISPER_LANGUAGE || 'ru' const WHISPER_LANGUAGE = process.env.MNEMAZINE_WHISPER_LANGUAGE || 'ru'
const VIDEO_FRAME_LIMIT = Number(process.env.MNEMAZINE_VIDEO_FRAME_LIMIT || '8') const VIDEO_FRAME_LIMIT = Number(process.env.MNEMAZINE_VIDEO_FRAME_LIMIT || '8')
@@ -295,6 +296,66 @@ async function archiveFile(file, hash) {
return target return target
} }
let vaultMarkdownFiles = null
async function listVaultMarkdownFiles() {
if (vaultMarkdownFiles) return vaultMarkdownFiles
const out = []
async function walk(dir) {
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
const p = path.join(dir, item.name)
if (item.isDirectory()) {
if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
await walk(p)
} else if (item.isFile() && p.endsWith('.md')) out.push(p)
}
}
await walk(VAULT)
vaultMarkdownFiles = out
return out
}
function noteSectionAfter(text, label) {
const start = String(text || '').indexOf(label)
if (start === -1) return ''
const tail = text.slice(start + label.length)
const next = tail.search(/\n##\s+/)
return next === -1 ? tail : tail.slice(0, next)
}
function strictKnowledgeReady(text) {
const facts = noteSectionAfter(text, 'External facts added before atomization:')
const sources = noteSectionAfter(text, 'Public/source expansion:')
const factCount = facts
.split('\n')
.filter(line => /^\s*-\s+\S/.test(line) && !/No external enrichment facts recorded/i.test(line))
.length
return /^status:\s*"final"\s*$/m.test(text) &&
/^verified:\s*true\s*$/m.test(text) &&
/^verification_status:\s*"verified"\s*$/m.test(text) &&
/^enrichment:\s*"external-research"\s*$/m.test(text) &&
factCount >= 2 &&
/https?:\/\//i.test(sources)
}
async function hasFinalKnowledgeForHash(hash) {
const ref = sourceRef(hash)
for (const file of await listVaultMarkdownFiles()) {
const text = await fs.readFile(file, 'utf8').catch(() => '')
if ((text.includes(ref) || text.includes(hash)) && (!STRICT_ARCHIVE_KNOWLEDGE || strictKnowledgeReady(text))) return true
}
return false
}
async function cachedExtractionText(entry) {
let textPath = entry?.text_path || ''
if (!textPath && entry?.cache) {
const record = await readJson(path.join(ROOT, entry.cache), {})
textPath = record.text_path || ''
}
if (!textPath) return ''
return await fs.readFile(path.join(EXTRACTS, textPath), 'utf8').catch(() => '')
}
function runLocalNodeScript(script, args = []) { function runLocalNodeScript(script, args = []) {
const file = path.join(ROOT, 'scripts', script) const file = path.join(ROOT, 'scripts', script)
if (!existsSync(file)) return { skipped: true, reason: `${script} missing` } if (!existsSync(file)) return { skipped: true, reason: `${script} missing` }
@@ -357,12 +418,14 @@ async function writeActionBrief(finishResult) {
const dir = STATE const dir = STATE
await ensureDir(dir) await ensureDir(dir)
const notes = await recentNotes() const notes = await recentNotes()
const inboxEntries = await fs.readdir(INBOX, { withFileTypes: true }).catch(() => [])
const activeInboxCount = inboxEntries.filter(entry => entry.isFile() && !entry.name.startsWith('.')).length
const lines = [ const lines = [
`# Mnemazine Action Brief — ${new Date().toISOString().slice(0, 10)}`, `# Mnemazine Action Brief — ${new Date().toISOString().slice(0, 10)}`,
'', '',
'## Status', '## Status',
'', '',
`- Inbox: ${(await fs.readdir(INBOX).catch(() => [])).filter(name => !name.startsWith('.')).length}`, `- Inbox: ${activeInboxCount}`,
`- Vault: ${VAULT}`, `- Vault: ${VAULT}`,
`- Quality gate: ${finishResult.quality?.ok ? 'ok' : 'check output'}`, `- Quality gate: ${finishResult.quality?.ok ? 'ok' : 'check output'}`,
`- Graph refresh: ${finishResult.graph?.ok ? 'ok' : finishResult.graph?.code === 2 ? 'partial / semantic pending' : finishResult.graph?.skipped ? 'skipped' : 'failed'}`, `- Graph refresh: ${finishResult.graph?.ok ? 'ok' : finishResult.graph?.code === 2 ? 'partial / semantic pending' : finishResult.graph?.skipped ? 'skipped' : 'failed'}`,
@@ -380,9 +443,9 @@ async function writeActionBrief(finishResult) {
return out return out
} }
async function finishRun() { async function finishRun(runStartedAt) {
const result = {} const result = {}
result.quality = runLocalNodeScript('mnemazine-vault-quality-gate.mjs') result.quality = runLocalNodeScript('mnemazine-vault-quality-gate.mjs', ['--changed-since', runStartedAt, '--max-failures', '50'])
result.graph = runLocalNodeScript('mnemazine-refresh-graphify.mjs', ['--vault', VAULT, '--mode', 'auto', '--json']) result.graph = runLocalNodeScript('mnemazine-refresh-graphify.mjs', ['--vault', VAULT, '--mode', 'auto', '--json'])
result.weekly = runLocalNodeScript('mnemazine-weekly-brief-html.mjs') result.weekly = runLocalNodeScript('mnemazine-weekly-brief-html.mjs')
const weeklyReport = result.weekly?.stdout?.match(/\/[^\s]+\.html/)?.[0] const weeklyReport = result.weekly?.stdout?.match(/\/[^\s]+\.html/)?.[0]
@@ -395,6 +458,7 @@ async function finishRun() {
} }
async function main() { async function main() {
const runStartedAt = new Date().toISOString()
await ensureDir(INBOX) await ensureDir(INBOX)
await ensureDir(VAULT) await ensureDir(VAULT)
await ensureDir(REPORTS) await ensureDir(REPORTS)
@@ -406,6 +470,7 @@ async function main() {
let processed = 0 let processed = 0
let cachedOnly = 0 let cachedOnly = 0
const toArchive = [] const toArchive = []
const synthSourceRefs = new Set()
let failed = 0 let failed = 0
const canLlmExtract = DEEP && llmAvailable() const canLlmExtract = DEEP && llmAvailable()
for (const [index, entry] of entries.entries()) { for (const [index, entry] of entries.entries()) {
@@ -415,9 +480,19 @@ async function main() {
try { try {
const hash = await sha256(file) const hash = await sha256(file)
if (cache[hash]) { if (cache[hash]) {
toArchive.push({ file, hash }) if (await hasFinalKnowledgeForHash(hash)) {
cachedOnly += 1 toArchive.push({ file, hash })
continue cachedOnly += 1
continue
}
const cachedText = await cachedExtractionText(cache[hash])
if (cache[hash].status === 'extracted_for_note' && hasUsableExtraction(cachedText)) {
synthSourceRefs.add(cache[hash].source_ref || sourceRef(hash))
toArchive.push({ file, hash })
processed += 1
continue
}
delete cache[hash]
} }
// Local-first recognition (0 tokens): Apple Vision OCR / markitdown / whisper. // Local-first recognition (0 tokens): Apple Vision OCR / markitdown / whisper.
let text = await extract(file) let text = await extract(file)
@@ -433,11 +508,11 @@ async function main() {
if (!hasUsableExtraction(text)) { if (!hasUsableExtraction(text)) {
const record = await writeExtractCache(file, hash, text, 'needs_manual_context') const record = await writeExtractCache(file, hash, text, 'needs_manual_context')
cache[hash] = { status: record.status, source_ref: record.source_ref, cache: path.relative(ROOT, path.join(EXTRACTS, `${hash}.json`)) } cache[hash] = { status: record.status, source_ref: record.source_ref, cache: path.relative(ROOT, path.join(EXTRACTS, `${hash}.json`)) }
toArchive.push({ file, hash }) failed += 1
cachedOnly += 1
} else { } else {
await writeExtractCache(file, hash, text, 'extracted_for_note') const record = await writeExtractCache(file, hash, text, 'extracted_for_note')
cache[hash] = { status: 'extracted_for_note', source_ref: sourceRef(hash), cache: path.relative(ROOT, path.join(EXTRACTS, `${hash}.json`)) } cache[hash] = { status: 'extracted_for_note', source_ref: sourceRef(hash), cache: path.relative(ROOT, path.join(EXTRACTS, `${hash}.json`)) }
synthSourceRefs.add(record.source_ref)
toArchive.push({ file, hash }) toArchive.push({ file, hash })
processed += 1 processed += 1
} }
@@ -457,37 +532,51 @@ async function main() {
// research/verification/atomization (deep) and writes vault atoms. // research/verification/atomization (deep) and writes vault atoms.
const synthArgs = [path.join(ROOT, 'scripts/mnemazine-synthesize.mjs')] const synthArgs = [path.join(ROOT, 'scripts/mnemazine-synthesize.mjs')]
if (DEEP) synthArgs.push('--deep') if (DEEP) synthArgs.push('--deep')
const synth = spawnSync(process.execPath, synthArgs, { encoding: 'utf8', env: process.env }) const synthEnv = { ...process.env }
if (synthSourceRefs.size) synthEnv.MNEMAZINE_SYNTH_SOURCE_REFS = [...synthSourceRefs].join(',')
const synth = spawnSync(process.execPath, synthArgs, { encoding: 'utf8', env: synthEnv })
if (synth.stdout) process.stdout.write(synth.stdout) if (synth.stdout) process.stdout.write(synth.stdout)
if (synth.stderr) process.stderr.write(synth.stderr) if (synth.stderr) process.stderr.write(synth.stderr)
synthesize = parseJsonOutput(synth.stdout) || { ok: synth.status === 0, parse_error: true } synthesize = parseJsonOutput(synth.stdout) || { ok: synth.status === 0, parse_error: true }
if (synth.status !== 0) { if (synth.status !== 0) {
await writeRunState({ ok: false, failure: 'synthesize failed', inbox: entries.length, processed, cached_only: cachedOnly, failed, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, synthesize, vault: VAULT, finished_at: new Date().toISOString() }) await writeRunState({ ok: false, failure: 'synthesize failed', inbox: entries.length, processed, cached_only: cachedOnly, failed, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() })
process.exit(synth.status || 1) process.exit(synth.status || 1)
} }
vaultMarkdownFiles = null
} }
if (REQUIRE_DEEP) { if (REQUIRE_DEEP) {
const deepFailures = validateDeepRun({ synthesize, processed }) const deepFailures = validateDeepRun({ synthesize, processed })
if (deepFailures.length) { if (deepFailures.length) {
await writeRunState({ ok: false, failures: deepFailures, inbox: entries.length, processed, cached_only: cachedOnly, failed, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, synthesize, vault: VAULT, finished_at: new Date().toISOString() }) await writeRunState({ ok: false, failures: deepFailures, inbox: entries.length, processed, cached_only: cachedOnly, failed, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() })
console.error(JSON.stringify({ ok: false, failures: deepFailures, synthesize }, null, 2)) console.error(JSON.stringify({ ok: false, failures: deepFailures, synthesize }, null, 2))
process.exit(1) process.exit(1)
} }
} }
const quality = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs')], { stdio: 'inherit', env: process.env }) const quality = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs'), '--changed-since', runStartedAt, '--max-failures', '50'], { stdio: 'inherit', env: process.env })
if (quality.status !== 0) { if (quality.status !== 0) {
await writeRunState({ ok: false, failure: 'vault quality failed', inbox: entries.length, processed, cached_only: cachedOnly, failed, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, synthesize, vault: VAULT, finished_at: new Date().toISOString() }) await writeRunState({ ok: false, failure: 'run vault quality failed', inbox: entries.length, processed, cached_only: cachedOnly, failed, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() })
process.exit(quality.status || 1) process.exit(quality.status || 1)
} }
const missingFinalNotes = []
vaultMarkdownFiles = null
for (const item of toArchive) {
if (!await hasFinalKnowledgeForHash(item.hash)) missingFinalNotes.push(path.basename(item.file))
}
if (missingFinalNotes.length) {
const failure = STRICT_ARCHIVE_KNOWLEDGE ? 'final enriched verified note missing for archive candidates' : 'final note missing for archive candidates'
await writeRunState({ ok: false, failure, missing_final_notes: missingFinalNotes, inbox: entries.length, processed, cached_only: cachedOnly, failed, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() })
console.error(JSON.stringify({ ok: false, failure, missing_final_notes: missingFinalNotes }, null, 2))
process.exit(1)
}
const archived = [] const archived = []
for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash)) for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash))
// Deep + final stage: Russian humanizer digest, AFTER the graph so connections // Deep + final stage: Russian humanizer digest, AFTER the graph so connections
// are real. Writes a Справка into each note + one session summary note. // are real. Writes a Справка into each note + one session summary note.
if (DEEP) { if (DEEP) {
spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-digest.mjs')], { stdio: 'inherit', env: process.env }) spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-digest.mjs'), '--changed-since', runStartedAt], { stdio: 'inherit', env: process.env })
} }
const finish = FINISH ? await finishRun() : { skipped: true } const finish = FINISH ? await finishRun(runStartedAt) : { skipped: true }
const result = { ok: true, inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, synthesize, finish, vault: VAULT, finished_at: new Date().toISOString() } const result = { ok: true, inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, finish, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() }
await writeRunState(result) await writeRunState(result)
console.log(JSON.stringify(result, null, 2)) console.log(JSON.stringify(result, null, 2))
} }
+238 -18
View File
@@ -3,7 +3,7 @@ import { promises as fs } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs' import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
import { verifyLocal, verifyDeep } from './mnemazine-verify.mjs' import { verifyLocal, verifyDeep, isPublicHttpUrl } from './mnemazine-verify.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const argv = process.argv.slice(2) const argv = process.argv.slice(2)
@@ -25,8 +25,19 @@ const DEEP = argv.includes('--deep') || argv.includes('--atomize') || process.en
const MAX_ATOMS = Number(arg('max-atoms', process.env.MNEMAZINE_MAX_ATOMS || '20')) const MAX_ATOMS = Number(arg('max-atoms', process.env.MNEMAZINE_MAX_ATOMS || '20'))
// Enrichment is on within --deep unless explicitly disabled (it needs the network). // Enrichment is on within --deep unless explicitly disabled (it needs the network).
const ENRICH = DEEP && process.env.MNEMAZINE_ENRICH !== '0' && !argv.includes('--no-enrich') const ENRICH = DEEP && process.env.MNEMAZINE_ENRICH !== '0' && !argv.includes('--no-enrich')
const ENRICH_TIMEOUT_MS = Number(process.env.MNEMAZINE_ENRICH_TIMEOUT_MS || '60000')
const STRICT_ENRICH = DEEP && process.env.MNEMAZINE_STRICT_ENRICH !== '0' && !argv.includes('--allow-raw-atomize')
const MIN_ADDED_FACTS = Number(process.env.MNEMAZINE_MIN_ADDED_FACTS || '2')
const CLUSTER_CHUNK_SIZE = Number(arg('cluster-chunk-size', process.env.MNEMAZINE_CLUSTER_CHUNK_SIZE || '25'))
const SOURCE_REF_FILTER = new Set(String(process.env.MNEMAZINE_SYNTH_SOURCE_REFS || '')
.split(',')
.map(s => s.trim())
.filter(Boolean))
const sourceHints = [ const sourceHints = [
{ re: /supermemory/i, name: 'supermemory GitHub', url: 'https://github.com/supermemoryai/supermemory' },
{ re: /compound\s+engineer|compound-\s*engineering-plugin/i, name: 'Compound Engineering GitHub', url: 'https://github.com/EveryInc/compound-engineering-plugin' },
{ re: /taste\s+skill|taste-skill|anti-slop\s+frontend/i, name: 'Taste Skill GitHub', url: 'https://github.com/Leonxlnx/taste-skill' },
{ re: /mcp|model context protocol|filesystem mcp|memory mcp|zapier/i, name: 'Model Context Protocol docs', url: 'https://modelcontextprotocol.io/docs/getting-started/intro' }, { re: /mcp|model context protocol|filesystem mcp|memory mcp|zapier/i, name: 'Model Context Protocol docs', url: 'https://modelcontextprotocol.io/docs/getting-started/intro' },
{ re: /skill|skills|claude code|agent skill|subagent/i, name: 'Anthropic Agent Skills', url: 'https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills' }, { re: /skill|skills|claude code|agent skill|subagent/i, name: 'Anthropic Agent Skills', url: 'https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills' },
{ re: /spec|spec-driven|feature forge|requirements/i, name: 'GitHub Spec Kit', url: 'https://github.com/github/spec-kit' }, { re: /spec|spec-driven|feature forge|requirements/i, name: 'GitHub Spec Kit', url: 'https://github.com/github/spec-kit' },
@@ -142,9 +153,13 @@ function fingerprint(cluster) {
} }
function extractUrls(text) { function extractUrls(text) {
return uniq(String(text || '').match(/\bhttps?:\/\/[^\s)]+/g) || []) const raw = String(text || '')
const explicit = raw.match(/\bhttps?:\/\/[^\s)]+/g) || []
const bareGithub = [...raw.matchAll(/\bgithub\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+/g)]
.map(match => `https://${match[0]}`)
return uniq([...explicit, ...bareGithub])
.map(url => url.replace(/[.,;]+$/, '')) .map(url => url.replace(/[.,;]+$/, ''))
.filter(url => !/^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)([:/]|$)/i.test(url)) .filter(isPublicHttpUrl)
.slice(0, 8) .slice(0, 8)
} }
@@ -179,10 +194,175 @@ function publicSources(text) {
.filter(source => source.re.test(text)) .filter(source => source.re.test(text))
.map(({ name, url }) => ({ name, url })) .map(({ name, url }) => ({ name, url }))
const byUrl = new Map() const byUrl = new Map()
for (const source of [...explicit, ...hinted]) byUrl.set(source.url, source) for (const source of [...explicit, ...hinted]) {
if (isPublicHttpUrl(source.url)) byUrl.set(source.url, source)
}
return [...byUrl.values()].slice(0, 10) return [...byUrl.values()].slice(0, 10)
} }
function githubRepoFromUrl(url) {
let parsed
try { parsed = new URL(url) } catch { return null }
if (parsed.hostname.replace(/^www\./, '') !== 'github.com') return null
const [, owner, repo] = parsed.pathname.split('/')
if (!owner || !repo) return null
const cleanOwner = owner.replace(/^Leonx1nx$/i, 'Leonxlnx')
const cleanRepo = repo.replace(/\.git$/i, '')
if (cleanRepo.endsWith('-')) return null
return { owner: cleanOwner, repo: cleanRepo, url: `https://github.com/${cleanOwner}/${cleanRepo}` }
}
async function fetchJson(url) {
try {
const res = await fetch(url, { headers: { 'User-Agent': 'Mnemazine' } })
if (!res.ok) return null
return await res.json()
} catch {
return null
}
}
async function fetchText(url, limit = 40000) {
try {
const res = await fetch(url, { headers: { 'User-Agent': 'Mnemazine' } })
if (!res.ok) return ''
return (await res.text()).slice(0, limit)
} catch {
return ''
}
}
function readmePoints(readme, max = 6) {
const points = []
for (const line of String(readme || '').split('\n')) {
const clean = compact(line.replace(/^#+\s*/, '').replace(/^[-*]\s+/, ''), 220)
if (clean.length < 32) continue
if (/^(install|usage|license|contributing|table of contents|badges?)$/i.test(clean)) continue
if (/^!\[|^<img|^\[!?\[/.test(line.trim())) continue
points.push(clean)
if (points.length >= max) break
}
return points
}
function htmlDescription(html) {
const raw = String(html || '')
const hit = raw.match(/<meta\s+name="description"\s+content="([^"]+)"/i) ||
raw.match(/<meta\s+property="og:description"\s+content="([^"]+)"/i)
return hit ? compact(hit[1].replace(/&quot;/g, '"').replace(/&amp;/g, '&'), 260) : ''
}
async function fetchRawReadme(repoRef, preferredBranch = '') {
const branches = [preferredBranch, 'main', 'master', 'dev', 'trunk'].filter(Boolean)
const names = ['README.md', 'readme.md', 'README.MD']
for (const branch of branches) {
for (const name of names) {
const url = `https://raw.githubusercontent.com/${repoRef.owner}/${repoRef.repo}/${branch}/${name}`
const text = await fetchText(url)
if (text && !/^404:/i.test(text)) return { text, url }
}
}
return { text: '', url: `https://github.com/${repoRef.owner}/${repoRef.repo}#readme` }
}
async function enrichClusterFromGithub(cluster, sources) {
const repoRef = sources.map(source => githubRepoFromUrl(source.url)).find(Boolean)
if (!repoRef) return null
let api = await fetchJson(`https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}`)
const readmeMeta = api?.html_url ? await fetchJson(`https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}/readme`) : null
const rawReadme = readmeMeta?.download_url
? { text: await fetchText(readmeMeta.download_url), url: readmeMeta.download_url }
: await fetchRawReadme(repoRef, api?.default_branch || '')
const repoHtml = api?.html_url ? '' : await fetchText(repoRef.url, 60000)
if (!api?.html_url) {
if (!rawReadme.text && !repoHtml) return null
api = {
full_name: `${repoRef.owner}/${repoRef.repo}`,
html_url: repoRef.url,
description: htmlDescription(repoHtml) || readmePoints(rawReadme.text, 1)[0] || 'official GitHub repository',
stargazers_count: 'unknown',
forks_count: 'unknown',
open_issues_count: 'unknown',
license: null,
language: 'unknown',
pushed_at: '',
default_branch: 'unknown'
}
}
const readmeUrl = rawReadme.url
const readme = rawReadme.text
const release = await fetchJson(`https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}/releases/latest`)
const points = readmePoints(readme)
const license = api.license?.spdx_id || api.license?.name || 'unknown license'
const pushed = api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'
const releaseLine = release?.tag_name ? `${release.tag_name} (${String(release.published_at || '').slice(0, 10) || 'date unknown'})` : 'no latest release returned by GitHub API'
const addedFacts = [
`${api.full_name}: ${api.description || 'official GitHub repository'}.`,
`GitHub metadata: ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, ${license}, primary language ${api.language || 'unknown'}.`,
`Repository freshness: default branch ${api.default_branch || 'unknown'}, last push ${pushed}, latest release ${releaseLine}.`,
...points.slice(0, 5).map(point => `README signal: ${point}`)
]
const addedSources = [
api.html_url,
readmeUrl,
release?.html_url
].filter(Boolean)
const enriched = [
`Official GitHub enrichment for ${api.full_name}.`,
`Description: ${api.description || 'No GitHub description provided.'}`,
`Metadata: ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, ${license}, ${api.language || 'unknown'} language, pushed ${pushed}.`,
`Latest release: ${releaseLine}.`,
points.length ? `README extracted signals:\n${points.map(point => `- ${point}`).join('\n')}` : 'README extraction returned no stable feature bullets.',
`Local seed refs: ${cluster.records.map(r => r.source_ref).join(', ')}.`
].join('\n\n')
return { enriched, addedSources, addedFacts, github: { api, readmeUrl, release, points } }
}
function atomsFromGithub(part, sources) {
const github = part.enrichment?.github
if (!github?.api) return []
const api = github.api
const repo = api.full_name
const sourceUrls = [api.html_url, github.readmeUrl, github.release?.html_url].filter(Boolean)
const points = github.points || []
const license = api.license?.spdx_id || api.license?.name || 'unknown license'
const releaseLine = github.release?.tag_name || 'no latest release returned'
return [
{
title: `${repo}: verified tool identity and adoption signal`,
what: `${repo} is the official GitHub repository for ${api.description || 'the tool captured in the local source'}. GitHub reports ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, ${license}, primary language ${api.language || 'unknown'}, and last push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}.`,
why: 'This turns a screenshot/star-count capture into a checked adoption signal with a primary source, not unchecked extraction.',
how: ['Use the repo metadata as the first pass: license, freshness, stars, forks, issues.', 'Open the README before adopting; treat social-card claims as hints until repo/docs confirm them.', 'Record adoption decision separately: install now, trial later, or ignore.'],
sources: sourceUrls,
next: `Review ${repo} README and decide whether it belongs in the agent capability registry.`
},
{
title: `${repo}: README-backed capability summary`,
what: points.length ? points.slice(0, 4).join(' ') : `${repo} has an official README, but Mnemazine could not extract stable feature bullets from it.`,
why: 'README text is closer to operational truth than a screenshot caption. It tells what the maintainer actually ships and documents.',
how: points.slice(0, 5).map(point => `Check: ${point}`),
sources: sourceUrls,
next: `Map ${repo} README features to one concrete local workflow before installing.`
},
{
title: `${repo}: operational risk and maintenance check`,
what: `Risk surface: ${api.open_issues_count} open issues, latest release ${releaseLine}, last push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}, license ${license}.`,
why: 'A popular repo can still be a bad dependency if release cadence, license, or issue volume do not fit the workflow.',
how: ['Check open issues for security, data-loss, and install failures.', 'Prefer trial in a disposable workspace before adding it to global agent rules.', 'If it becomes a Skill/MCP/plugin, register usage and source ledgers.'],
sources: sourceUrls,
next: `Run a small local trial for ${repo} only if the workflow fit is concrete.`
},
{
title: `${repo}: Mnemazine routing decision`,
what: `This atom links the local capture (${part.records.map(record => record.source_ref).join(', ')}) to primary GitHub evidence for ${repo}.`,
why: 'The useful memory is not "saw a repo". The useful memory is the routing decision: what the repo does, whether it fits, what risk remains, and what action follows.',
how: ['Store the repo as a candidate capability, not an instruction to install.', 'If adopted, mirror docs/skill metadata and log usage.', 'If rejected, record the reason so the same shiny repo does not return as noise.'],
sources: sourceUrls,
next: `Add ${repo} to the capability review queue with one accept/reject criterion.`
}
]
}
function recordTitle(record) { function recordTitle(record) {
const url = extractUrls(record.text)[0] const url = extractUrls(record.text)[0]
if (url) return url.replace(/^https?:\/\//, '').replace(/[?#].*$/, '').slice(0, 90) if (url) return url.replace(/^https?:\/\//, '').replace(/[?#].*$/, '').slice(0, 90)
@@ -227,6 +407,7 @@ async function listRecords() {
continue continue
} }
if (record.status !== 'extracted_for_note' || !record.text_path) continue if (record.status !== 'extracted_for_note' || !record.text_path) continue
if (SOURCE_REF_FILTER.size && !SOURCE_REF_FILTER.has(record.source_ref)) continue
const textFile = path.join(EXTRACTS, record.text_path) const textFile = path.join(EXTRACTS, record.text_path)
const text = await fs.readFile(textFile, 'utf8').catch(() => '') const text = await fs.readFile(textFile, 'utf8').catch(() => '')
if (compact(text, 100).length < 40) continue if (compact(text, 100).length < 40) continue
@@ -346,7 +527,7 @@ function atomPrompt(cluster, sources, materialOverride) {
? String(materialOverride).slice(0, 28000) ? String(materialOverride).slice(0, 28000)
: cluster.records.map(r => compact(r.text, 4000)).join('\n---\n').slice(0, 24000) : cluster.records.map(r => compact(r.text, 4000)).join('\n---\n').slice(0, 24000)
const urls = sources.map(s => s.url).join(', ') || 'none detected' const urls = sources.map(s => s.url).join(', ') || 'none detected'
return `You are Mnemazine's atomization agent. Split the raw material below into FOCUSED, atomic knowledge notes — one idea per atom, up to ${MAX_ATOMS}. Do NOT merge unrelated ideas; do NOT invent facts not present in the material. Each atom: a precise title, a one-paragraph "what", a one-paragraph "why it matters", 2-5 concrete "how to use" bullets, one "next action", and the subset of source URLs that support it (from: ${urls}; [] if none). return `You are Mnemazine's atomization agent. Split the enriched research material below into FOCUSED, atomic knowledge notes — one idea per atom, up to ${MAX_ATOMS}. Do NOT merge unrelated ideas; do NOT invent facts not present in the material. Each atom: a precise title, a one-paragraph "what", a one-paragraph "why it matters", 2-5 concrete "how to use" bullets, one "next action", and the subset of source URLs that support it (from: ${urls}; [] only if truly local/private).
Return ONLY JSON matching the schema. Return ONLY JSON matching the schema.
@@ -389,11 +570,13 @@ ${fenceUntrusted('MATERIAL', text)}`
async function enrichCluster(cluster, sources) { async function enrichCluster(cluster, sources) {
const text = cluster.records.map(r => compact(r.text, 6000)).join('\n---\n').slice(0, 24000) const text = cluster.records.map(r => compact(r.text, 6000)).join('\n---\n').slice(0, 24000)
const res = await llmJson(enrichPrompt(text, sources), ENRICH_SCHEMA, { const res = await llmJson(enrichPrompt(text, sources), ENRICH_SCHEMA, {
tools: ['WebSearch', 'WebFetch', 'mcp__firecrawl', 'mcp__tavily'] tools: ['WebSearch', 'WebFetch', 'mcp__firecrawl', 'mcp__tavily'],
timeoutMs: ENRICH_TIMEOUT_MS
}) })
const enriched = typeof res?.enriched === 'string' ? res.enriched.trim() : '' const enriched = typeof res?.enriched === 'string' ? res.enriched.trim() : ''
const addedSources = Array.isArray(res?.sources) ? res.sources.filter(Boolean) : [] const addedSources = Array.isArray(res?.sources) ? res.sources.filter(isPublicHttpUrl) : []
return { enriched, addedSources } const addedFacts = Array.isArray(res?.added_facts) ? res.added_facts.filter(Boolean) : []
return { enriched, addedSources, addedFacts }
} }
function atomFingerprint(atom, clusterId = '') { function atomFingerprint(atom, clusterId = '') {
@@ -405,7 +588,9 @@ function atomFingerprint(atom, clusterId = '') {
function makeAtomNote(cluster, atom, verdict) { function makeAtomNote(cluster, atom, verdict) {
const how = (atom.how || []).filter(Boolean).map(h => `- ${compact(h, 240)}`).join('\n') || '- Review and apply in context.' const how = (atom.how || []).filter(Boolean).map(h => `- ${compact(h, 240)}`).join('\n') || '- Review and apply in context.'
const srcs = (atom.sources || []).filter(Boolean) const sourceRefs = cluster.records.map(record => `- ${record.source_ref}`).join('\n')
const addedFacts = (cluster.enrichment?.addedFacts || []).map(f => `- ${compact(f, 300)}`).join('\n') || '- No external enrichment facts recorded.'
const srcs = (atom.sources || []).filter(isPublicHttpUrl)
const sourceLines = srcs.length const sourceLines = srcs.length
? srcs.map(u => `- ${hostOf(u) || 'Source'}: ${u}`).join('\n') ? srcs.map(u => `- ${hostOf(u) || 'Source'}: ${u}`).join('\n')
: '- No public source detected; external verification required before operational adoption.' : '- No public source detected; external verification required before operational adoption.'
@@ -421,6 +606,7 @@ verified: ${isVerified}
verification_status: "${v.status}" verification_status: "${v.status}"
verification: "llm-atomized; ${String(v.note || 'sources unverified').replace(/"/g, "'")}" verification: "llm-atomized; ${String(v.note || 'sources unverified').replace(/"/g, "'")}"
status: "${isVerified ? 'final' : 'draft'}" status: "${isVerified ? 'final' : 'draft'}"
enrichment: "${cluster.enrichment?.ok ? 'external-research' : 'missing'}"
cluster_id: "${cluster.id}" cluster_id: "${cluster.id}"
cluster_fingerprint: "${fp}" cluster_fingerprint: "${fp}"
--- ---
@@ -441,8 +627,17 @@ ${how}
## Source ## Source
Local source refs:
${sourceRefs}
Public/source expansion:
${sourceLines} ${sourceLines}
## Enrichment
External facts added before atomization:
${addedFacts}
## Verification ## Verification
- Verification status: **${v.status}**${v.note ? ` (${v.note})` : ''}. - Verification status: **${v.status}**${v.note ? ` (${v.note})` : ''}.
@@ -475,9 +670,15 @@ let written = 0
let skipped = 0 let skipped = 0
let atomized = 0 let atomized = 0
let enriched_clusters = 0 let enriched_clusters = 0
let failed_parts = 0
const useAtomize = DEEP && llmAvailable() const useAtomize = DEEP && llmAvailable()
if (DEEP && !llmAvailable()) { if (DEEP && !llmAvailable()) {
console.error('[synthesize] --deep requested but LLM unavailable; falling back to local template synthesis') console.error('[synthesize] --deep requested but LLM unavailable; falling back to local template synthesis')
if (STRICT_ENRICH) {
console.error('[synthesize] strict enrichment requires an available LLM')
console.log(JSON.stringify({ ok: false, degraded: true, records: records.length, clusters: clusters.size, written: 0, atomized: 0, enriched: 0, failed_parts: clusters.size, skipped: 0 }, null, 2))
process.exit(1)
}
} }
// Bounded-concurrency pool — the research swarm. Each part is an independent // Bounded-concurrency pool — the research swarm. Each part is an independent
// agent task; one failing never blocks the others (each is try/caught inside). // agent task; one failing never blocks the others (each is try/caught inside).
@@ -497,31 +698,48 @@ async function processPart(part, parts, index) {
let material let material
if (ENRICH) { if (ENRICH) {
try { try {
const { enriched, addedSources } = await enrichCluster(part, sources) const github = await enrichClusterFromGithub(part, sources)
const { enriched, addedSources, addedFacts } = github || await enrichCluster(part, sources)
if (enriched && enriched.length > 200) { if (enriched && enriched.length > 200) {
material = enriched material = enriched
for (const u of addedSources) if (!sources.some(s => s.url === u)) sources.push({ name: hostOf(u) || 'Source', url: u }) for (const u of addedSources) if (!sources.some(s => s.url === u)) sources.push({ name: hostOf(u) || 'Source', url: u })
part.enrichment = { ok: true, addedFacts, addedSources, deterministic: Boolean(github), github: github?.github || null }
enriched_clusters += 1 enriched_clusters += 1
} }
} catch (err) { } catch (err) {
console.error(`[synthesize] enrich failed for cluster ${part.id}: ${err.message}; atomizing raw capture`) console.error(`[synthesize] enrich failed for cluster ${part.id}: ${err.message}`)
} }
} }
const atoms = await atomizeCluster(part, sources, material) if (STRICT_ENRICH && (!material || !part.enrichment?.ok || (part.enrichment.addedFacts || []).length < MIN_ADDED_FACTS || !sources.length)) {
throw new Error(`strict enrichment failed for cluster ${part.id}: no expanded material with external facts/sources`)
}
const atoms = part.enrichment?.deterministic
? atomsFromGithub(part, sources)
: await atomizeCluster(part, sources, material)
let wroteAtom = false let wroteAtom = false
const allowedSourceUrls = new Set(sources.map(source => source.url).filter(isPublicHttpUrl))
for (const atom of atoms) { for (const atom of atoms) {
atom.sources = (atom.sources || []).filter(url => allowedSourceUrls.has(url))
const out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(atom.title)}-${atomFingerprint(atom, part.id)}.md`) const out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(atom.title)}-${atomFingerprint(atom, part.id)}.md`)
if (await fs.access(out).then(() => true).catch(() => false)) { skipped += 1; continue } if (await fs.access(out).then(() => true).catch(() => false)) { skipped += 1; continue }
const verdict = DEEP const verdict = part.enrichment?.deterministic
? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources) ? { status: 'verified', checked: atom.sources || [], evidence: 'Fetched GitHub API/README/release for primary-source enrichment.', note: 'deterministic GitHub source check' }
: verifyLocal(atom.sources) : DEEP
? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources)
: verifyLocal(atom.sources)
if (STRICT_ENRICH && verdict.status !== 'verified') {
console.error(`[synthesize] strict verification rejected atom "${atom.title}": ${verdict.status}`)
continue
}
await fs.writeFile(out, makeAtomNote(part, atom, verdict), 'utf8') await fs.writeFile(out, makeAtomNote(part, atom, verdict), 'utf8')
atomized += 1 atomized += 1
wroteAtom = true wroteAtom = true
} }
if (wroteAtom) return // atomized this cluster — skip the template note if (wroteAtom) return // atomized this cluster — skip the template note
if (STRICT_ENRICH) throw new Error(`strict verification failed for cluster ${part.id}: no verified atoms`)
console.error(`[synthesize] atomize produced no atoms for cluster ${part.id}; using template note`) console.error(`[synthesize] atomize produced no atoms for cluster ${part.id}; using template note`)
} catch (err) { } catch (err) {
if (STRICT_ENRICH) throw err
console.error(`[synthesize] atomize failed for cluster ${part.id}: ${err.message}; using template note`) console.error(`[synthesize] atomize failed for cluster ${part.id}: ${err.message}; using template note`)
} }
} }
@@ -537,7 +755,7 @@ async function processPart(part, parts, index) {
const tasks = [] const tasks = []
for (const cluster of clusters.values()) { for (const cluster of clusters.values()) {
const parts = chunks(cluster.records, 25) const parts = chunks(cluster.records, CLUSTER_CHUNK_SIZE)
parts.forEach((recs, index) => { parts.forEach((recs, index) => {
const part = { ...cluster, records: recs, part: index + 1, partCount: parts.length } const part = { ...cluster, records: recs, part: index + 1, partCount: parts.length }
const textSize = part.records.reduce((sum, record) => sum + compact(record.text, 100000).length, 0) const textSize = part.records.reduce((sum, record) => sum + compact(record.text, 100000).length, 0)
@@ -551,10 +769,12 @@ const CONCURRENCY = Number(arg('concurrency', process.env.MNEMAZINE_CONCURRENCY
await mapLimit(tasks, useAtomize ? CONCURRENCY : 1, async ({ part, parts, index }) => { await mapLimit(tasks, useAtomize ? CONCURRENCY : 1, async ({ part, parts, index }) => {
// Outer guard: a part must never break the swarm, even on an unexpected throw. // Outer guard: a part must never break the swarm, even on an unexpected throw.
try { await processPart(part, parts, index) } try { await processPart(part, parts, index) }
catch (err) { console.error(`[synthesize] part failed for cluster ${part.id}: ${err.message}`) } catch (err) { failed_parts += 1; console.error(`[synthesize] part failed for cluster ${part.id}: ${err.message}`) }
}) })
// degraded: --deep was requested but the deep path could not run (codex absent), // degraded: --deep was requested but the deep path could not run (codex absent),
// so the run silently fell back to local templates. Callers can detect this. // so the run silently fell back to local templates. Callers can detect this.
const degraded = DEEP && !llmAvailable() const degraded = DEEP && !llmAvailable()
console.log(JSON.stringify({ ok: true, degraded, records: records.length, clusters: clusters.size, written, atomized, enriched: enriched_clusters, skipped }, null, 2)) const ok = !(STRICT_ENRICH && failed_parts > 0)
console.log(JSON.stringify({ ok, degraded, records: records.length, clusters: clusters.size, written, atomized, enriched: enriched_clusters, failed_parts, skipped }, null, 2))
if (!ok) process.exit(1)
+41 -14
View File
@@ -10,19 +10,35 @@ REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env" [ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
# Non-secret personal overrides (e.g. MNEMAZINE_INBOX), gitignored. # Non-secret personal overrides (e.g. MNEMAZINE_INBOX), gitignored.
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh" [ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
VPS="${MNEMAZINE_VPS:-root@YOUR_VPS_HOST}" VPS="${MNEMAZINE_VPS:-deploy@YOUR_VPS_HOST}"
KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}" KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}"
REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-/var/www/mnemazine-inbox}" REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-mnemazine/inbox}"
REMOTE_REPORTS="${MNEMAZINE_REMOTE_REPORTS:-/var/www/mnemazine-reports}" REMOTE_REPORTS="${MNEMAZINE_REMOTE_REPORTS:-mnemazine/reports}"
SSH_BIN="${MNEMAZINE_SSH_BIN:-ssh}"
SYNC_BIN="${MNEMAZINE_TELEGRAM_SYNC_BIN:-$REPO/scripts/mnemazine-telegram-sync.sh}"
# ponytail: fail fast if still on the placeholder — beats a confusing ssh error. # ponytail: fail fast if still on the placeholder — beats a confusing ssh error.
if [ "$VPS" = "root@YOUR_VPS_HOST" ]; then if [ "$VPS" = "deploy@YOUR_VPS_HOST" ]; then
echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2 echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2
exit 1 exit 1
fi fi
SSH="ssh -i $KEY -o StrictHostKeyChecking=no -o ConnectTimeout=10" if [ "${MNEMAZINE_REMOTE_MUTATION:-0}" != "1" ]; then
MARKER="$REPO/.mnemazine/.last-daily" echo "Set MNEMAZINE_REMOTE_MUTATION=1 after reviewing VPS paths; poll mutates remote flags/reports." >&2
exit 1
fi
ATTEMPT_MARKER="$REPO/.mnemazine/.last-daily-attempt"
COMPLETED_MARKER="$REPO/.mnemazine/.last-daily-completed"
MAX_DAILY_ATTEMPTS="${MNEMAZINE_DAILY_MAX_ATTEMPTS:-3}"
DAILY_RETRY_SECONDS="${MNEMAZINE_DAILY_RETRY_SECONDS:-3600}"
mkdir -p "$REPO/.mnemazine" mkdir -p "$REPO/.mnemazine"
KNOWN_HOSTS="${MNEMAZINE_SSH_KNOWN_HOSTS:-$REPO/.mnemazine/known_hosts}"
touch "$KNOWN_HOSTS"
HOST="${VPS#*@}"
if ! ssh-keygen -F "$HOST" -f "$KNOWN_HOSTS" >/dev/null 2>&1; then
echo "VPS host key is not pinned. Run: MNEMAZINE_VPS=$VPS MNEMAZINE_VPS_HOST_FINGERPRINT=SHA256:... bash $REPO/scripts/mnemazine-pin-vps-host.sh" >&2
exit 1
fi
SSH="$SSH_BIN -i $KEY -o UserKnownHostsFile=$KNOWN_HOSTS -o StrictHostKeyChecking=yes -o ConnectTimeout=10"
# Single-flight lock. macOS has no flock, so use an atomic mkdir lock dir. # Single-flight lock. macOS has no flock, so use an atomic mkdir lock dir.
# Steal a stale lock (>60 min) left by a killed run. # Steal a stale lock (>60 min) left by a killed run.
@@ -45,23 +61,34 @@ if [ -n "$queue" ]; then
[ -d "$REPO/reports" ] && rsync -az -e "$SSH" "$REPO/reports/" "$VPS:$REMOTE_REPORTS/" 2>/dev/null || true [ -d "$REPO/reports" ] && rsync -az -e "$SSH" "$REPO/reports/" "$VPS:$REMOTE_REPORTS/" 2>/dev/null || true
fi fi
run=0; manual=0 run=0; manual=0; daily=0
# Consume run-now flag atomically: print + delete in one ssh. # Consume run-now flag atomically: print + delete in one ssh.
flag="$($SSH "$VPS" "f=$REMOTE_INBOX/.run-now; if [ -f \"\$f\" ]; then cat \"\$f\"; rm -f \"\$f\"; fi" 2>/dev/null || true)" flag="$($SSH "$VPS" "f=$REMOTE_INBOX/.run-now; if [ -f \"\$f\" ]; then cat \"\$f\"; rm -f \"\$f\"; fi" 2>/dev/null || true)"
[ -n "$flag" ] && { run=1; manual=1; } [ -n "$flag" ] && { run=1; manual=1; }
today="$(date +%F)" today="${MNEMAZINE_POLL_TODAY:-$(date +%F)}"
if [ "$(cat "$MARKER" 2>/dev/null || true)" != "$today" ] && [ "$(date +%H)" -ge 9 ]; then hour="${MNEMAZINE_POLL_HOUR:-$(date +%H)}"
run=1 now_epoch="${MNEMAZINE_POLL_EPOCH:-$(date +%s)}"
# Mark the daily attempt BEFORE syncing: a failed run must not re-fire every if [ "$(cat "$COMPLETED_MARKER" 2>/dev/null || true)" != "$today" ] && [ "$hour" -ge 9 ]; then
# 5 min for the rest of the day (storm). One attempt per day. read -r attempt_day attempt_count attempt_epoch < "$ATTEMPT_MARKER" 2>/dev/null || true
echo "$today" > "$MARKER" if [ "${attempt_day:-}" != "$today" ]; then
attempt_count=0
attempt_epoch=0
fi
retry_wait=$((now_epoch - ${attempt_epoch:-0}))
if [ "${attempt_count:-0}" -lt "$MAX_DAILY_ATTEMPTS" ] && { [ "${attempt_count:-0}" -eq 0 ] || [ "$retry_wait" -ge "$DAILY_RETRY_SECONDS" ]; }; then
run=1
daily=1
attempt_count=$((attempt_count + 1))
printf '%s %s %s\n' "$today" "$attempt_count" "$now_epoch" > "$ATTEMPT_MARKER"
fi
fi fi
[ "$run" -eq 0 ] && exit 0 [ "$run" -eq 0 ] && exit 0
if bash "$REPO/scripts/mnemazine-telegram-sync.sh"; then if bash "$SYNC_BIN"; then
$SSH "$VPS" "echo $(date -u +%FT%TZ) > $REMOTE_INBOX/.last-run" 2>/dev/null || true $SSH "$VPS" "echo $(date -u +%FT%TZ) > $REMOTE_INBOX/.last-run" 2>/dev/null || true
[ "$daily" = "1" ] && echo "$today" > "$COMPLETED_MARKER"
else else
# A manual run-now we already consumed shouldn't vanish on failure — re-queue it. # A manual run-now we already consumed shouldn't vanish on failure — re-queue it.
[ "$manual" = "1" ] && $SSH "$VPS" "echo retry > $REMOTE_INBOX/.run-now" 2>/dev/null || true [ "$manual" = "1" ] && $SSH "$VPS" "echo retry > $REMOTE_INBOX/.run-now" 2>/dev/null || true
+16 -4
View File
@@ -10,9 +10,9 @@ REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env" [ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
# Non-secret personal overrides (e.g. MNEMAZINE_INBOX), gitignored. # Non-secret personal overrides (e.g. MNEMAZINE_INBOX), gitignored.
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh" [ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
VPS="${MNEMAZINE_VPS:-root@YOUR_VPS_HOST}" VPS="${MNEMAZINE_VPS:-deploy@YOUR_VPS_HOST}"
KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}" KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}"
REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-/var/www/mnemazine-inbox/}" REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-mnemazine/inbox/}"
REMOTE_INBOX="${REMOTE_INBOX%/}/" REMOTE_INBOX="${REMOTE_INBOX%/}/"
# Inbox honours MNEMAZINE_INBOX (from config.env); defaults to repo-local inbox. # Inbox honours MNEMAZINE_INBOX (from config.env); defaults to repo-local inbox.
LOCAL_INBOX="${MNEMAZINE_INBOX:-$REPO/inbox}" LOCAL_INBOX="${MNEMAZINE_INBOX:-$REPO/inbox}"
@@ -21,13 +21,25 @@ STAGING="${LOCAL_INBOX}.staging/"
# Export so the protocol runner reads the same inbox. # Export so the protocol runner reads the same inbox.
export MNEMAZINE_INBOX="${LOCAL_INBOX%/}" export MNEMAZINE_INBOX="${LOCAL_INBOX%/}"
if [ "$VPS" = "root@YOUR_VPS_HOST" ]; then if [ "$VPS" = "deploy@YOUR_VPS_HOST" ]; then
echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2 echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2
exit 1 exit 1
fi fi
if [ "${MNEMAZINE_REMOTE_MUTATION:-0}" != "1" ]; then
echo "Set MNEMAZINE_REMOTE_MUTATION=1 after reviewing VPS paths; sync deletes remote files only after local success." >&2
exit 1
fi
mkdir -p "$LOCAL_INBOX" "$STAGING" mkdir -p "$LOCAL_INBOX" "$STAGING"
SSH_E="ssh -i $KEY -o StrictHostKeyChecking=no" KNOWN_HOSTS="${MNEMAZINE_SSH_KNOWN_HOSTS:-$REPO/.mnemazine/known_hosts}"
mkdir -p "$(dirname "$KNOWN_HOSTS")"
touch "$KNOWN_HOSTS"
HOST="${VPS#*@}"
if ! ssh-keygen -F "$HOST" -f "$KNOWN_HOSTS" >/dev/null 2>&1; then
echo "VPS host key is not pinned. Run: MNEMAZINE_VPS=$VPS MNEMAZINE_VPS_HOST_FINGERPRINT=SHA256:... bash $REPO/scripts/mnemazine-pin-vps-host.sh" >&2
exit 1
fi
SSH_E="ssh -i $KEY -o UserKnownHostsFile=$KNOWN_HOSTS -o StrictHostKeyChecking=yes"
# Two-phase move (C2: never delete the only copy before processing succeeds). # Two-phase move (C2: never delete the only copy before processing succeeds).
# 1) pull into staging WITHOUT deleting on the VPS, resumable on partial transfer. # 1) pull into staging WITHOUT deleting on the VPS, resumable on partial transfer.
+2
View File
@@ -12,6 +12,8 @@ node --check scripts/mnemazine-run.mjs
node --check scripts/mnemazine-complete-check.mjs node --check scripts/mnemazine-complete-check.mjs
node --check scripts/mnemazine-synthesize.mjs node --check scripts/mnemazine-synthesize.mjs
node --check scripts/mnemazine-verify.mjs node --check scripts/mnemazine-verify.mjs
npm run selftest:security
npm run audit:security
echo "Mnemazine updated." echo "Mnemazine updated."
echo "Run from chat: Mnemazine" echo "Run from chat: Mnemazine"
+18 -2
View File
@@ -14,6 +14,17 @@ function arg(name, fallback = '') {
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault'))) const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')))
const REQUIRE_DOSSIER = argv.includes('--require-dossier') const REQUIRE_DOSSIER = argv.includes('--require-dossier')
const CHANGED_SINCE = arg('changed-since', '')
const MAX_FAILURES = Number(arg('max-failures', process.env.MNEMAZINE_QUALITY_MAX_FAILURES || '0'))
function sinceMs(value) {
if (!value) return 0
if (/^\d+(?:\.\d+)?$/.test(value)) return Number(value)
const parsed = Date.parse(value)
return Number.isFinite(parsed) ? parsed : 0
}
const CHANGED_SINCE_MS = sinceMs(CHANGED_SINCE)
const badMarkers = [ const badMarkers = [
/raw\s+ocr/i, /raw\s+ocr/i,
@@ -52,7 +63,10 @@ async function walk(dir) {
const files = await walk(VAULT) const files = await walk(VAULT)
const failures = [] const failures = []
let checked = 0
for (const file of files) { for (const file of files) {
const stat = await fs.stat(file)
if (CHANGED_SINCE_MS && stat.mtimeMs < CHANGED_SINCE_MS) continue
const rel = path.relative(VAULT, file) const rel = path.relative(VAULT, file)
if ( if (
rel.includes('/graphify-out/') || rel.includes('/graphify-out/') ||
@@ -63,6 +77,7 @@ for (const file of files) {
/(^|\/)_(Содержание|МАСТЕР-ИНДЕКС|ROUTING|ШАБЛОНЫ)\.md$/.test(rel) || /(^|\/)_(Содержание|МАСТЕР-ИНДЕКС|ROUTING|ШАБЛОНЫ)\.md$/.test(rel) ||
['AGENTS.md', 'CLAUDE.md', '_ROUTING.md', 'Лог обработки.md'].includes(rel) ['AGENTS.md', 'CLAUDE.md', '_ROUTING.md', 'Лог обработки.md'].includes(rel)
) continue ) continue
checked += 1
const text = await fs.readFile(file, 'utf8') const text = await fs.readFile(file, 'utf8')
if (/^##\s+Атомизировано(?:\s|$)/m.test(text)) continue if (/^##\s+Атомизировано(?:\s|$)/m.test(text)) continue
const hit = badMarkers.find(re => re.test(text)) const hit = badMarkers.find(re => re.test(text))
@@ -80,12 +95,13 @@ for (const file of files) {
: [] : []
if (hit || !hasSource || !hasMeaning || missingDossier.length) { if (hit || !hasSource || !hasMeaning || missingDossier.length) {
failures.push({ file: rel, marker: hit ? String(hit) : missingDossier.length ? `missing dossier sections: ${missingDossier.join(', ')}` : 'missing required sections' }) failures.push({ file: rel, marker: hit ? String(hit) : missingDossier.length ? `missing dossier sections: ${missingDossier.join(', ')}` : 'missing required sections' })
if (MAX_FAILURES > 0 && failures.length >= MAX_FAILURES) break
} }
} }
if (failures.length) { if (failures.length) {
console.error(JSON.stringify({ ok: false, failures }, null, 2)) console.error(JSON.stringify({ ok: false, checked, total: files.length, scope: CHANGED_SINCE_MS ? { changed_since: new Date(CHANGED_SINCE_MS).toISOString() } : { changed_since: null }, failures }, null, 2))
process.exit(1) process.exit(1)
} }
console.log(JSON.stringify({ ok: true, checked: files.length }, null, 2)) console.log(JSON.stringify({ ok: true, checked, total: files.length, scope: CHANGED_SINCE_MS ? { changed_since: new Date(CHANGED_SINCE_MS).toISOString() } : { changed_since: null } }, null, 2))
+111 -11
View File
@@ -4,6 +4,8 @@
// network: HEAD reachability + a codex web cross-check of the claim. // network: HEAD reachability + a codex web cross-check of the claim.
// ponytail: local gate is deliberately structural (no HEAD by default) so the // ponytail: local gate is deliberately structural (no HEAD by default) so the
// conservative pipeline never reaches the network. Reachability+LLM only on --deep. // conservative pipeline never reaches the network. Reachability+LLM only on --deep.
import dns from 'node:dns/promises'
import net from 'node:net'
import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs' import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
// Local gate: a source URL present means the claim is at least anchored // Local gate: a source URL present means the claim is at least anchored
@@ -25,11 +27,17 @@ const VERIFY_SCHEMA = {
} }
} }
async function fetchWithTimeout(url, opts, timeoutMs) { async function fetchWithTimeout(url, opts, timeoutMs, redirects = 3) {
if (!await safeToFetch(url)) return null
const ctrl = new AbortController() const ctrl = new AbortController()
const t = setTimeout(() => ctrl.abort(), timeoutMs) const t = setTimeout(() => ctrl.abort(), timeoutMs)
try { try {
return await fetch(url, { ...opts, redirect: 'follow', signal: ctrl.signal }).catch(() => null) const res = await fetch(url, { ...opts, redirect: 'manual', signal: ctrl.signal }).catch(() => null)
if (redirects > 0 && res && res.status >= 300 && res.status < 400 && res.headers.get('location')) {
const next = new URL(res.headers.get('location'), url).toString()
return await fetchWithTimeout(next, opts, timeoutMs, redirects - 1)
}
return res
} finally { } finally {
clearTimeout(t) clearTimeout(t)
} }
@@ -45,29 +53,99 @@ async function headOk(url, timeoutMs) {
return !!res && res.ok return !!res && res.ok
} }
function privateIPv4(address) {
const parts = address.split('.').map(Number)
if (parts.length !== 4 || parts.some(n => !Number.isInteger(n) || n < 0 || n > 255)) return true
const [a, b] = parts
return a === 0 ||
a === 10 ||
a === 127 ||
(a === 169 && b === 254) ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) ||
(a === 100 && b >= 64 && b <= 127) ||
a >= 224
}
function privateIPv6(address) {
const value = address.toLowerCase()
const mapped = value.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)
if (mapped) return privateIPv4(mapped[1])
return value === '::' ||
value === '::1' ||
value.startsWith('fc') ||
value.startsWith('fd') ||
value.startsWith('fe80:') ||
value.startsWith('ff') ||
value.startsWith('2001:db8:')
}
function privateAddress(address) {
const cleaned = String(address || '').replace(/^\[|\]$/g, '')
const kind = net.isIP(cleaned)
if (kind === 4) return privateIPv4(cleaned)
if (kind === 6) return privateIPv6(cleaned)
return false
}
export function isPublicHttpUrl(url) {
let parsed
try { parsed = new URL(url) } catch { return false }
if (!['http:', 'https:'].includes(parsed.protocol)) return false
const hostname = parsed.hostname.replace(/^\[|\]$/g, '').replace(/\.$/, '').toLowerCase()
if (!hostname || hostname === 'localhost' || hostname.endsWith('.localhost') || hostname.endsWith('.local')) return false
if (privateAddress(hostname)) return false
return true
}
async function safeToFetch(url) {
if (!isPublicHttpUrl(url)) return false
const parsed = new URL(url)
const hostname = parsed.hostname.replace(/^\[|\]$/g, '').replace(/\.$/, '').toLowerCase()
if (net.isIP(hostname)) return true
try {
const answers = await dns.lookup(hostname, { all: true, verbatim: true })
return answers.length > 0 && answers.every(answer => !privateAddress(answer.address))
} catch {
return false
}
}
// Deep gate: confirm reachability, then ask codex (with its own web search) to // Deep gate: confirm reachability, then ask codex (with its own web search) to
// judge whether the listed sources actually support the claim. Degrades to the // judge whether the listed sources actually support the claim. Degrades to the
// local verdict if codex is unavailable or errors. // local verdict if codex is unavailable or errors.
export async function verifyDeep(claim, urls = [], options = {}) { export async function verifyDeep(claim, urls = [], options = {}) {
const timeoutMs = options.timeoutMs || 8000 const timeoutMs = options.timeoutMs || 8000
const live = [] const live = []
for (const url of (urls || []).filter(Boolean)) { const candidateUrls = (urls || []).filter(isPublicHttpUrl)
if (await headOk(url, timeoutMs)) live.push(url) if (options.assumeLiveUrls) {
live.push(...candidateUrls)
} else {
for (const url of candidateUrls) {
if (await headOk(url, timeoutMs)) live.push(url)
}
} }
if (!llmAvailable(options.provider)) { if (!llmAvailable(options.provider)) {
const local = verifyLocal(live) const local = verifyLocal(live)
return { ...local, checked: live, note: `llm unavailable; reachable=${live.length}` } return { ...local, checked: live, note: `llm unavailable; reachable=${live.length}` }
} }
try { try {
const prompt = `Verify whether the SOURCES below support the CLAIM. Use web search to check. Return status: "verified" only if a source clearly supports the claim, "assumed" if a source is relevant but does not clearly confirm it, "unknown" if no source supports it. Be strict. const prompt = `Verify whether the SOURCES below support the CORE CLAIM. Use web search / fetch when needed. Return status:
- "verified" if an official source or primary source supports the main factual claim, even if wording differs.
- "assumed" if sources are only related or support only background context.
- "unknown" if no source supports it.
Be strict on numbers, rankings, benchmarks, funding, star counts, downloads, dates, and performance claims: those require direct support. For descriptive repository/product capability claims, an official GitHub repo or official docs page is enough if it supports the core claim.
${fenceUntrusted('CLAIM', String(claim).slice(0, 4000))} ${fenceUntrusted('CLAIM', String(claim).slice(0, 4000))}
SOURCES: SOURCES:
${live.length ? live.join('\n') : '(none reachable)'}` ${live.length ? live.join('\n') : '(none reachable)'}`
const res = await llmJson(prompt, VERIFY_SCHEMA, { timeoutMs: options.llmTimeoutMs, provider: options.provider, tools: ['WebSearch', 'WebFetch'] }) const res = await llmJson(prompt, VERIFY_SCHEMA, { timeoutMs: options.llmTimeoutMs, provider: options.provider, tools: ['WebSearch', 'WebFetch'] })
const status = ['verified', 'assumed', 'unknown'].includes(res?.status) ? res.status : 'unknown' let status = ['verified', 'assumed', 'unknown'].includes(res?.status) ? res.status : 'unknown'
return { status, checked: res?.checked?.length ? res.checked : live, evidence: res?.evidence || '', note: 'llm cross-check' } if (status === 'verified' && !live.length) status = 'unknown'
const checked = Array.isArray(res?.checked) ? res.checked.filter(isPublicHttpUrl) : []
return { status, checked: checked.length ? checked : live, evidence: res?.evidence || '', note: 'llm cross-check' }
} catch (err) { } catch (err) {
const local = verifyLocal(live) const local = verifyLocal(live)
return { ...local, checked: live, note: `deep verify failed: ${err.message}` } return { ...local, checked: live, note: `deep verify failed: ${err.message}` }
@@ -78,7 +156,10 @@ ${live.length ? live.join('\n') : '(none reachable)'}`
// (used by --selftest with a stub bin; no real network/LLM). No reachable URL, // (used by --selftest with a stub bin; no real network/LLM). No reachable URL,
// so headOk yields [] and the verdict comes purely from the stubbed codex JSON. // so headOk yields [] and the verdict comes purely from the stubbed codex JSON.
if (process.argv.includes('--deep-once')) { if (process.argv.includes('--deep-once')) {
const verdict = await verifyDeep('stub claim', [], { codexTimeoutMs: 10000 }) const claim = process.env.MNEMAZINE_VERIFY_TEST_CLAIM || 'stub claim'
const urls = String(process.env.MNEMAZINE_VERIFY_TEST_URLS || '').split(',').map(s => s.trim()).filter(Boolean)
const assumeLiveUrls = process.env.MNEMAZINE_VERIFY_TEST_ASSUME_LIVE === '1'
const verdict = await verifyDeep(claim, urls, { llmTimeoutMs: 10000, assumeLiveUrls })
console.log(JSON.stringify(verdict)) console.log(JSON.stringify(verdict))
process.exit(0) process.exit(0)
} }
@@ -89,6 +170,9 @@ if (process.argv.includes('--selftest')) {
const b = verifyLocal([]) const b = verifyLocal([])
if (a.status !== 'assumed') throw new Error('expected assumed for url present') if (a.status !== 'assumed') throw new Error('expected assumed for url present')
if (b.status !== 'unknown') throw new Error('expected unknown for no url') if (b.status !== 'unknown') throw new Error('expected unknown for no url')
if (isPublicHttpUrl('http://127.0.0.1/')) throw new Error('loopback URL passed public URL gate')
if (isPublicHttpUrl('http://169.254.169.254/latest/meta-data/')) throw new Error('link-local URL passed public URL gate')
if (await headOk('http://127.0.0.1/', 50)) throw new Error('loopback URL passed fetch gate')
// Deep path with a stub codex bin (provider=codex): confirm llmJson round-trips // Deep path with a stub codex bin (provider=codex): confirm llmJson round-trips
// and the status enum is honoured end-to-end. Claude backend shares the same // and the status enum is honoured end-to-end. Claude backend shares the same
@@ -103,15 +187,31 @@ if (process.argv.includes('--selftest')) {
await fsp.writeFile(bin, `#!/usr/bin/env bash await fsp.writeFile(bin, `#!/usr/bin/env bash
out=""; while [ $# -gt 0 ]; do [ "$1" = "-o" ] && { out="$2"; shift; }; shift; done out=""; while [ $# -gt 0 ]; do [ "$1" = "-o" ] && { out="$2"; shift; }; shift; done
cat >/dev/null cat >/dev/null
printf '%s' '{"status":"verified","evidence":"stub confirms","checked":["https://e.test"]}' > "$out" status="\${FAKE_CODEX_STATUS:-verified}"
printf '{"status":"%s","evidence":"stub confirms","checked":["https://e.test"]}' "$status" > "$out"
`, { mode: 0o755 }) `, { mode: 0o755 })
const res = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--deep-once'], { const res = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--deep-once'], {
env: { ...process.env, MNEMAZINE_LLM: 'codex', MNEMAZINE_CODEX_BIN: bin }, encoding: 'utf8' env: { ...process.env, MNEMAZINE_LLM: 'codex', MNEMAZINE_CODEX_BIN: bin, MNEMAZINE_VERIFY_TEST_ASSUME_LIVE: '1', MNEMAZINE_VERIFY_TEST_URLS: 'https://e.test' }, encoding: 'utf8'
}) })
await fsp.rm(dir, { recursive: true, force: true })
if (res.status !== 0) throw new Error(`deep-once failed: ${res.stderr}`) if (res.status !== 0) throw new Error(`deep-once failed: ${res.stderr}`)
const verdict = JSON.parse(res.stdout) const verdict = JSON.parse(res.stdout)
if (verdict.status !== 'verified') throw new Error(`expected verified from stub codex, got ${verdict.status}`) if (verdict.status !== 'verified') throw new Error(`expected verified from stub codex, got ${verdict.status}`)
const assumed = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--deep-once'], {
env: {
...process.env,
MNEMAZINE_LLM: 'codex',
MNEMAZINE_CODEX_BIN: bin,
MNEMAZINE_VERIFY_TEST_ASSUME_LIVE: '1',
MNEMAZINE_VERIFY_TEST_URLS: 'https://github.com/microsoft/markitdown',
MNEMAZINE_VERIFY_TEST_CLAIM: 'MarkItDown is maintained by Microsoft and has unsupported extra benchmark claims.',
FAKE_CODEX_STATUS: 'assumed'
},
encoding: 'utf8'
})
await fsp.rm(dir, { recursive: true, force: true })
if (assumed.status !== 0) throw new Error(`deep-once assumed failed: ${assumed.stderr}`)
const assumedVerdict = JSON.parse(assumed.stdout)
if (assumedVerdict.status !== 'assumed') throw new Error(`expected assumed to stay assumed, got ${assumedVerdict.status}`)
console.log('verify selftest ok') console.log('verify selftest ok')
} }
+31 -3
View File
@@ -25,9 +25,35 @@ function titleOf(text, file) {
return text.match(/^#\s+(.+)$/m)?.[1]?.trim() || path.basename(file, '.md') return text.match(/^#\s+(.+)$/m)?.[1]?.trim() || path.basename(file, '.md')
} }
function present(value) {
return String(value || '')
.replace(/raw\s+ocr/gi, 'локальное извлечение')
.replace(/сырой\s+ocr/gi, 'локальное извлечение')
.replace(/ocr\s+без\s+синтеза/gi, 'локальное извлечение')
.replace(/распознанный\s+текст\s+без\s+обработки/gi, 'локальное извлечение')
.replace(/Video keyframe OCR/gi, 'текст с ключевого кадра')
.replace(/Video transcript from local Whisper/gi, 'локальная транскрибация')
.replace(/\bIMG_\d+(?:\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4))?\b/gi, 'локальный визуальный источник')
.replace(/\btemp_image[_-][\w.-]+/gi, 'локальный визуальный источник')
.replace(/\b[\w.-]+\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4)\b/gi, 'локальный медиафайл')
.replace(/\S+\.md\b/giu, 'документ')
.replace(/\.md\b/gi, '')
.replace(/\s+/g, ' ')
.trim()
}
function presentNotePath(rel) {
return present(String(rel || '')
.replace(/\.md$/i, '')
.split(/[\\/]+/)
.filter(Boolean)
.map(part => part.replace(/^\d+\s*/, ''))
.join(' / '))
}
function summaryOf(text) { function summaryOf(text) {
const block = text.match(/## (?:What This Is|Что это|Суть)\s+([\s\S]*?)(\n## |$)/i)?.[1] || text const block = text.match(/## (?:What This Is|Что это|Суть)\s+([\s\S]*?)(\n## |$)/i)?.[1] || text
return block.replace(/[#*_`>-]/g, '').replace(/\s+/g, ' ').trim().slice(0, 520) return present(block.replace(/[#*_`>-]/g, '')).slice(0, 520)
} }
function actionOf(text) { function actionOf(text) {
@@ -42,6 +68,7 @@ function linksOf(text) {
.filter(url => { .filter(url => {
try { new URL(url); return true } catch { return false } try { new URL(url); return true } catch { return false }
}) })
.filter(url => !/\.(?:md|png|svg|jpe?g|webp|gif)/i.test(url))
.slice(0, 4) .slice(0, 4)
} }
@@ -54,7 +81,8 @@ for (const file of files) {
const stat = await fs.stat(file) const stat = await fs.stat(file)
if (stat.mtimeMs < weekAgo) continue if (stat.mtimeMs < weekAgo) continue
const text = await fs.readFile(file, 'utf8') const text = await fs.readFile(file, 'utf8')
cards.push({ file: path.relative(VAULT, file), title: titleOf(text, file), summary: summaryOf(text), action: actionOf(text), links: linksOf(text) }) const rel = path.relative(VAULT, file)
cards.push({ file: rel, visibleFile: presentNotePath(rel), title: present(titleOf(text, file)), summary: summaryOf(text), action: present(actionOf(text)), links: linksOf(text) })
} }
const html = `<!doctype html> const html = `<!doctype html>
@@ -78,7 +106,7 @@ main{padding:34px max(18px,6vw) 70px}.grid{display:grid;grid-template-columns:re
<body> <body>
<header><section class="hero"><h1>Mnemazine Weekly</h1><p class="lead">Сводка знаний за последние 7 дней: что появилось, что стоит взять в работу, что можно забыть.</p><button id="export" style="margin-top:18px;border:0;background:#fff;color:var(--blue);font-weight:700;border-radius:8px;padding:11px 16px;cursor:pointer">⬇ Скачать weekly-state.json</button></section></header> <header><section class="hero"><h1>Mnemazine Weekly</h1><p class="lead">Сводка знаний за последние 7 дней: что появилось, что стоит взять в работу, что можно забыть.</p><button id="export" style="margin-top:18px;border:0;background:#fff;color:var(--blue);font-weight:700;border-radius:8px;padding:11px 16px;cursor:pointer">⬇ Скачать weekly-state.json</button></section></header>
<main><section class="grid"> <main><section class="grid">
${cards.map((c, i) => `<article class="card" data-id="${esc(c.file)}" data-knowledge-atom="${i + 1}"><div class="path">${esc(c.file)}</div><h2>${esc(c.title)}</h2><p><strong>Синтез:</strong> ${esc(c.summary)}</p><p><strong>Расширил источниками:</strong> ${c.links.length ? c.links.map(url => `<a href="${esc(url)}">${esc(new URL(url).hostname.replace(/^www\\./, ''))}</a>`).join(' · ') : `<a href="../vault/${esc(c.file)}">локальная заметка</a>`}</p><p><strong>Где применить:</strong> В связанных проектах, skills, агентных правилах или backlog, если карточка отмечена "В работу".</p><p><strong>Проверка и риск:</strong> Проверить публичные источники перед публикацией или автоматизацией.</p><p><strong>Следующее действие:</strong> ${esc(c.action)}</p><div class="actions"><button data-v="read">Прочитал</button><button data-v="work">В работу</button><button data-v="forget">Забыть</button></div></article>`).join('\n') || '<article class="card" data-knowledge-atom="empty"><h2>За неделю новых заметок нет</h2><p>Положите материалы в inbox и запустите Mnemazine.</p></article>'} ${cards.map((c, i) => `<article class="card" data-id="${esc(c.visibleFile)}" data-knowledge-atom="${i + 1}"><div class="path">${esc(c.visibleFile)}</div><h2>${esc(c.title)}</h2><p><strong>Синтез:</strong> ${esc(c.summary)}</p><p><strong>Расширил источниками:</strong> ${c.links.length ? c.links.map(url => `<a href="${esc(url)}">${esc(new URL(url).hostname.replace(/^www\\./, ''))}</a>`).join(' · ') : `<span>локальная заметка</span>`}</p><p><strong>Где применить:</strong> В связанных проектах, skills, агентных правилах или backlog, если карточка отмечена "В работу".</p><p><strong>Проверка и риск:</strong> Проверить публичные источники перед публикацией или автоматизацией.</p><p><strong>Следующее действие:</strong> ${esc(c.action)}</p><div class="actions"><button data-v="read">Прочитал</button><button data-v="work">В работу</button><button data-v="forget">Забыть</button></div></article>`).join('\n') || '<article class="card" data-knowledge-atom="empty"><h2>За неделю новых заметок нет</h2><p>Положите материалы в inbox и запустите Mnemazine.</p></article>'}
</section></main> </section></main>
<script> <script>
const KEY='mnemazine-weekly-state'; const KEY='mnemazine-weekly-state';
+30 -11
View File
@@ -5,10 +5,11 @@
# #
# Dry run (walk stages + questions, install/deploy nothing): # Dry run (walk stages + questions, install/deploy nothing):
# MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh # MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh
set -uo pipefail set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DRY="${MNEMAZINE_SETUP_DRYRUN:-0}" DRY="${MNEMAZINE_SETUP_DRYRUN:-0}"
KNOWN_HOSTS="$ROOT/.mnemazine/known_hosts"
# ---- ui helpers ------------------------------------------------------------- # ---- ui helpers -------------------------------------------------------------
b() { printf '\033[1m%s\033[0m\n' "$*"; } b() { printf '\033[1m%s\033[0m\n' "$*"; }
@@ -50,6 +51,10 @@ run() { # run a command unless dry-run
"$@" "$@"
} }
sq() {
printf "'%s'" "$(printf "%s" "$1" | sed "s/'/'\\\\''/g")"
}
b "Mnemazine — установка по шагам." b "Mnemazine — установка по шагам."
note "Каждый этап завершается прежде чем начнётся следующий." note "Каждый этап завершается прежде чем начнётся следующий."
[ "$DRY" = "1" ] && note "DRY RUN — ничего не ставится и не деплоится." [ "$DRY" = "1" ] && note "DRY RUN — ничего не ставится и не деплоится."
@@ -118,12 +123,18 @@ if [ "$REPLY_IDX" = "1" ]; then
if [ "$REPLY_IDX" = "1" ]; then if [ "$REPLY_IDX" = "1" ]; then
ask_text "VPS (user@host)"; BOT_VPS="$REPLY_TXT" ask_text "VPS (user@host)"; BOT_VPS="$REPLY_TXT"
ask_text "Путь к SSH-ключу (Enter = ~/.ssh/id_rsa)"; BOT_KEY="${REPLY_TXT:-$HOME/.ssh/id_rsa}" ask_text "Путь к SSH-ключу (Enter = ~/.ssh/id_rsa)"; BOT_KEY="${REPLY_TXT:-$HOME/.ssh/id_rsa}"
if [ "$DRY" != "1" ] && ! ssh -i "$BOT_KEY" -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$BOT_VPS" 'command -v node >/dev/null && command -v pm2 >/dev/null' 2>/dev/null; then ask_text "SSH fingerprint хоста (SHA256:..., из панели VPS или ssh-keygen -lf)"; BOT_FP="$REPLY_TXT"
miss "бота через VPS" "VPS недоступен или нет node+pm2 (ssh-in: 'npm i -g pm2'). Запусти бота локально вручную позже." [ -z "$BOT_FP" ] && { no "fingerprint пустой — небезопасно."; halt; }
BOT_MODE="manual" if [ "$DRY" != "1" ]; then
else mkdir -p "$ROOT/.mnemazine"
BOT_MODE="vps"; ok "VPS на связи (node+pm2 есть)." touch "$KNOWN_HOSTS"
MNEMAZINE_VPS="$BOT_VPS" MNEMAZINE_VPS_KEY="$BOT_KEY" MNEMAZINE_VPS_HOST_FINGERPRINT="$BOT_FP" bash "$ROOT/scripts/mnemazine-pin-vps-host.sh"
fi fi
if [ "$DRY" != "1" ] && ! ssh -i "$BOT_KEY" -o UserKnownHostsFile="$KNOWN_HOSTS" -o StrictHostKeyChecking=yes -o ConnectTimeout=10 "$BOT_VPS" 'command -v node >/dev/null && command -v pm2 >/dev/null' 2>/dev/null; then
no "VPS недоступен или нет node+pm2."
halt
fi
BOT_MODE="vps"; ok "VPS на связи (node+pm2 есть)."
else else
miss "бота через VPS" "Без VPS постоянного приёма нет. Можешь запускать бота локально, пока устройство включено." miss "бота через VPS" "Без VPS постоянного приёма нет. Можешь запускать бота локально, пока устройство включено."
BOT_MODE="manual" BOT_MODE="manual"
@@ -144,7 +155,9 @@ fi
# deploy bot if VPS path chosen # deploy bot if VPS path chosen
if [ "$BOT_MODE" = "vps" ]; then if [ "$BOT_MODE" = "vps" ]; then
stage 6.1 "Деплой бота на VPS" stage 6.1 "Деплой бота на VPS"
REMOTE_INBOX="/var/www/mnemazine-inbox" REMOTE_ROOT="mnemazine"
REMOTE_INBOX="$REMOTE_ROOT/inbox"
REMOTE_BOT="$REMOTE_ROOT/bot"
# Persist the host/key boundary so poll/sync scripts read it (never hardcoded). # Persist the host/key boundary so poll/sync scripts read it (never hardcoded).
if [ "$DRY" != "1" ]; then if [ "$DRY" != "1" ]; then
mkdir -p "$ROOT/.mnemazine" mkdir -p "$ROOT/.mnemazine"
@@ -153,17 +166,23 @@ if [ "$BOT_MODE" = "vps" ]; then
MNEMAZINE_VPS="$BOT_VPS" MNEMAZINE_VPS="$BOT_VPS"
MNEMAZINE_VPS_KEY="$BOT_KEY" MNEMAZINE_VPS_KEY="$BOT_KEY"
MNEMAZINE_REMOTE_INBOX="$REMOTE_INBOX" MNEMAZINE_REMOTE_INBOX="$REMOTE_INBOX"
MNEMAZINE_REMOTE_MUTATION=1
CFG CFG
umask 022 umask 022
ok "Записал .mnemazine/config.env (chmod 600, gitignored)." ok "Записал .mnemazine/config.env (chmod 600, gitignored)."
fi fi
if [ "$DRY" = "1" ]; then if [ "$DRY" = "1" ]; then
note "[dry] scp bot → $BOT_VPS:/var/www/mnemazine-bot/ ; pm2 start с токеном" note "[dry] scp bot → $BOT_VPS:$REMOTE_BOT/ ; pm2 start с токеном"
else else
ssh -i "$BOT_KEY" -o StrictHostKeyChecking=no "$BOT_VPS" "mkdir -p /var/www/mnemazine-bot $REMOTE_INBOX" SSH_OPTS=(-i "$BOT_KEY" -o "UserKnownHostsFile=$KNOWN_HOSTS" -o StrictHostKeyChecking=yes)
cat "$ROOT/scripts/mnemazine-telegram-bot.mjs" | ssh -i "$BOT_KEY" -o StrictHostKeyChecking=no "$BOT_VPS" 'cat > /var/www/mnemazine-bot/mnemazine-telegram-bot.mjs' ssh "${SSH_OPTS[@]}" "$BOT_VPS" "mkdir -p $REMOTE_BOT $REMOTE_INBOX" || { no "Не смог создать папки на VPS."; halt; }
ssh "${SSH_OPTS[@]}" "$BOT_VPS" "cat > $REMOTE_BOT/mnemazine-telegram-bot.mjs" < "$ROOT/scripts/mnemazine-telegram-bot.mjs" || { no "Не смог загрузить bot script на VPS."; halt; }
{
printf 'TELEGRAM_BOT_TOKEN=%s\n' "$(sq "$BOT_TOKEN")"
printf 'MNEMAZINE_INBOX=%s\n' "$(sq "$REMOTE_INBOX")"
} | ssh "${SSH_OPTS[@]}" "$BOT_VPS" "umask 177; cat > $REMOTE_BOT/.env" || { no "Не смог записать .env на VPS."; halt; }
# Idempotent: start, or restart if the process already exists (rerun-safe). # Idempotent: start, or restart if the process already exists (rerun-safe).
ssh -i "$BOT_KEY" -o StrictHostKeyChecking=no "$BOT_VPS" "cd /var/www/mnemazine-bot && TELEGRAM_BOT_TOKEN='$BOT_TOKEN' MNEMAZINE_INBOX=$REMOTE_INBOX pm2 start mnemazine-telegram-bot.mjs --name mnemazine-bot --update-env 2>/dev/null || TELEGRAM_BOT_TOKEN='$BOT_TOKEN' MNEMAZINE_INBOX=$REMOTE_INBOX pm2 restart mnemazine-bot --update-env; pm2 save" ssh "${SSH_OPTS[@]}" "$BOT_VPS" "cd $REMOTE_BOT && set -a && . ./.env && set +a && pm2 start mnemazine-telegram-bot.mjs --name mnemazine-bot --update-env 2>/dev/null || pm2 restart mnemazine-bot --update-env; pm2 save" || { no "Не смог запустить pm2 на VPS."; halt; }
ok "Бот запущен на VPS (bootstrap-режим)." ok "Бот запущен на VPS (bootstrap-режим)."
note "Напиши боту сообщение, затем на VPS: pm2 logs mnemazine-bot — увидишь свой chat_id." note "Напиши боту сообщение, затем на VPS: pm2 logs mnemazine-bot — увидишь свой chat_id."
note "Закрой доступ: перезапусти с ALLOWED_CHAT_IDS=<chat_id> (см. docs/telegram-intake.md)." note "Закрой доступ: перезапусти с ALLOWED_CHAT_IDS=<chat_id> (см. docs/telegram-intake.md)."