From 821d575b747e37e241cfd077f268dacff19b91c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D1=80=D1=83=D0=B1=D0=B8=D0=BD=20=D0=A4=D0=B8?= =?UTF-8?q?=D0=BB=D0=B8=D0=BF=D0=BF?= <289370046+zarubinphil@users.noreply.github.com> Date: Tue, 23 Jun 2026 18:25:58 +0300 Subject: [PATCH] Harden desktop protocol completion gate --- docs/deep-mode.ru.md | 7 +++- package.json | 1 + scripts/mnemazine-complete-check.mjs | 43 ++++++++++++++++++- scripts/mnemazine-desktop-protocol.sh | 50 ++++++++++++++++++++++ scripts/mnemazine-run.mjs | 60 ++++++++++++++++++++++++--- scripts/mnemazine-synthesize.mjs | 2 +- scripts/mnemazine-telegram-sync.sh | 5 ++- scripts/mnemazine-verify.mjs | 2 +- 8 files changed, 158 insertions(+), 12 deletions(-) create mode 100755 scripts/mnemazine-desktop-protocol.sh diff --git a/docs/deep-mode.ru.md b/docs/deep-mode.ru.md index 094e339..71c5576 100644 --- a/docs/deep-mode.ru.md +++ b/docs/deep-mode.ru.md @@ -10,6 +10,9 @@ Deep-режим **выключен, пока вы его не попросите ## Включение deep-режима ```bash +# рабочий запуск Desktop Inbox, строгий полный протокол: +npm run protocol:desktop + # весь прогон, deep: node scripts/mnemazine-run.mjs --deep # или через env (форвардится в synthesize): @@ -19,7 +22,9 @@ MNEMAZINE_DEEP=1 node scripts/mnemazine-run.mjs npm run synthesize -- --deep ``` -Если deep-режим запрошен, но движок LLM недоступен, прогон **откатывается на локальный шаблонный синтез** и сообщает `degraded: true` в JSON-выводе. Молча не падает. +Для рабочего Desktop Inbox используй `npm run protocol:desktop`. Он сам читает `.mnemazine/config.local.sh`, берёт inbox с рабочего стола, пишет в `~/Мозг`, включает `--deep`, требует атомизацию + обогащение и после этого запускает `complete-check`. + +Если deep-режим запрошен напрямую, но движок LLM недоступен, обычный `node scripts/mnemazine-run.mjs --deep` откатывается на локальный шаблонный синтез и сообщает `degraded: true` в JSON-выводе. Строгий запуск (`--require-deep` или `npm run protocol:desktop`) в такой ситуации падает до архива. ## Мост LLM diff --git a/package.json b/package.json index 6dc3d62..27ed7ba 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "scripts": { "install:local": "bash install.sh", "run": "node scripts/mnemazine-run.mjs", + "protocol:desktop": "bash scripts/mnemazine-desktop-protocol.sh", "graph:refresh": "node scripts/mnemazine-refresh-graphify.mjs --json", "graph:shards": "node scripts/mnemazine-semantic-shards.mjs", "graph:semantic-batches": "node scripts/mnemazine-semantic-batches.mjs", diff --git a/scripts/mnemazine-complete-check.mjs b/scripts/mnemazine-complete-check.mjs index f08c45e..ae3d88b 100644 --- a/scripts/mnemazine-complete-check.mjs +++ b/scripts/mnemazine-complete-check.mjs @@ -19,6 +19,7 @@ function arg(name, fallback = '') { const NEEDS_UPDATE_MAX_DAYS = Number(arg('needs-update-max-days', process.env.MNEMAZINE_NEEDS_UPDATE_MAX_DAYS || '1')) const STRICT_GRAPH = argv.includes('--strict-graph') +const REQUIRE_DEEP = argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1' function run(command, args) { return new Promise(resolve => { @@ -56,10 +57,35 @@ async function latestReport() { return reports.sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.file || '' } +async function activeInboxFiles() { + return (await fs.readdir(INBOX, { withFileTypes: true }).catch(() => [])) + .filter(item => item.isFile() && !item.name.startsWith('.')) + .map(item => item.name) +} + +async function readJson(file, fallback = null) { + try { return JSON.parse(await fs.readFile(file, 'utf8')) } catch { return fallback } +} + +function deepFailures(lastRun) { + const failures = [] + if (!lastRun) return ['last run state missing'] + 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.synthesize || lastRun.synthesize.skipped) { + if (Number(lastRun.processed || 0) > 0) failures.push('deep synthesis did not run') + return failures + } + if (lastRun.synthesize.degraded) failures.push('deep synthesis degraded to local template') + if (Number(lastRun.processed || 0) > 0 && Number(lastRun.synthesize.atomized || 0) <= 0) failures.push('deep synthesis produced zero atoms') + if (Number(lastRun.processed || 0) > 0 && lastRun.enrich_required && Number(lastRun.synthesize.enriched || 0) <= 0) failures.push('deep enrichment produced zero enriched clusters') + return failures +} + async function main() { const failures = [] const warnings = [] - const inboxFiles = (await fs.readdir(INBOX).catch(() => [])).filter(name => !name.startsWith('.')) + const inboxFiles = await activeInboxFiles() if (inboxFiles.length) failures.push(`inbox not empty: ${inboxFiles.length}`) const quality = await run(process.execPath, ['scripts/mnemazine-vault-quality-gate.mjs']) @@ -88,11 +114,26 @@ async function main() { else warnings.push(msg) } + const lastRunFile = path.join(STATE, 'last-run.json') + const lastRun = await readJson(lastRunFile) + if (REQUIRE_DEEP) { + for (const failure of deepFailures(lastRun)) failures.push(failure) + } + const result = { ok: failures.length === 0, failures, warnings, inbox: inboxFiles.length, + deep_required: REQUIRE_DEEP, + last_run: lastRun ? { + ok: lastRun.ok, + deep: lastRun.deep, + processed: lastRun.processed, + atomized: lastRun.synthesize?.atomized ?? null, + enriched: lastRun.synthesize?.enriched ?? null, + finished_at: lastRun.finished_at || null + } : null, report: report ? path.relative(ROOT, report) : null, brief: existsSync(brief) ? path.relative(ROOT, brief) : null } diff --git a/scripts/mnemazine-desktop-protocol.sh b/scripts/mnemazine-desktop-protocol.sh new file mode 100755 index 0000000..f35ce7b --- /dev/null +++ b/scripts/mnemazine-desktop-protocol.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" +ENV_INBOX="${MNEMAZINE_INBOX:-}" +ENV_VAULT="${MNEMAZINE_VAULT:-}" +ENV_DEEP="${MNEMAZINE_DEEP:-}" +ENV_REQUIRE_DEEP="${MNEMAZINE_REQUIRE_DEEP:-}" + +[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env" +[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh" + +export MNEMAZINE_ROOT="$REPO" +BASE_INBOX="${ENV_INBOX:-${MNEMAZINE_INBOX:-$HOME/Desktop/Mnemazine Inbox}}" +export MNEMAZINE_VAULT="${ENV_VAULT:-${MNEMAZINE_VAULT:-$HOME/Мозг}}" +export MNEMAZINE_DEEP="${ENV_DEEP:-${MNEMAZINE_DEEP:-1}}" +export MNEMAZINE_REQUIRE_DEEP="${ENV_REQUIRE_DEEP:-${MNEMAZINE_REQUIRE_DEEP:-1}}" + +active_count() { + find "$1" -maxdepth 1 -type f ! -name '.*' 2>/dev/null | wc -l | tr -d ' ' +} + +run_inbox() { + local inbox="$1" + local count + count="$(active_count "$inbox")" + [ "$count" = "0" ] && return 0 + echo "Mnemazine protocol: $inbox ($count files)" >&2 + ran=1 + MNEMAZINE_INBOX="${inbox%/}" npm run run -- --deep --require-deep +} + +mkdir -p "$BASE_INBOX" "$MNEMAZINE_VAULT" +ran=0 + +run_inbox "$BASE_INBOX" + +# Historical Telegram sync bug could create a nested inbox. Keep this guard so +# old leftovers do not silently sit outside the active top-level scan. +NESTED="$BASE_INBOX/mnemazine-inbox" +if [ -d "$NESTED" ]; then + run_inbox "$NESTED" +fi + +if [ "$ran" = "0" ]; then + echo "Mnemazine protocol: no active inbox files" >&2 + exit 0 +fi + +MNEMAZINE_INBOX="${BASE_INBOX%/}" npm run complete -- --require-deep diff --git a/scripts/mnemazine-run.mjs b/scripts/mnemazine-run.mjs index 94c621f..2e9aa52 100755 --- a/scripts/mnemazine-run.mjs +++ b/scripts/mnemazine-run.mjs @@ -10,6 +10,7 @@ const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox') const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault') const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports') +const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state') const CACHE = process.env.MNEMAZINE_CACHE || path.join(ROOT, '.mnemazine/cache/processed-hashes.json') const ARCHIVE = process.env.MNEMAZINE_ARCHIVE || path.join(ROOT, '.mnemazine/archive') const TRANSCRIPTS = path.join(ROOT, '.mnemazine/cache/video-transcripts') @@ -23,6 +24,8 @@ const FINISH = process.env.MNEMAZINE_FINISH !== '0' // Default OFF: the runner stays conservative — local only, no external calls. // Enable with `--deep` or MNEMAZINE_DEEP=1; forwarded to synthesize. 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 ENRICH_REQUIRED = DEEP && process.env.MNEMAZINE_ENRICH !== '0' && !process.argv.includes('--no-enrich') const WHISPER_MODEL = process.env.MNEMAZINE_WHISPER_MODEL || '' const WHISPER_LANGUAGE = process.env.MNEMAZINE_WHISPER_LANGUAGE || 'ru' const VIDEO_FRAME_LIMIT = Number(process.env.MNEMAZINE_VIDEO_FRAME_LIMIT || '8') @@ -305,6 +308,31 @@ function runLocalNodeScript(script, args = []) { } } +function parseJsonOutput(text) { + const raw = String(text || '').trim() + if (!raw) return null + const start = raw.indexOf('{') + const end = raw.lastIndexOf('}') + if (start === -1 || end < start) return null + try { return JSON.parse(raw.slice(start, end + 1)) } catch { return null } +} + +async function writeRunState(state) { + await ensureDir(STATE) + await fs.writeFile(path.join(STATE, 'last-run.json'), `${JSON.stringify(state, null, 2)}\n`, 'utf8') +} + +function validateDeepRun({ synthesize, processed }) { + const failures = [] + if (!DEEP) failures.push('deep mode was required but run did not use --deep') + if (processed <= 0) return failures + if (!synthesize || synthesize.skipped) failures.push('deep synthesis did not run') + if (synthesize?.degraded) failures.push('deep synthesis degraded to local template') + if (processed > 0 && Number(synthesize?.atomized || 0) <= 0) failures.push('deep synthesis produced zero atoms') + if (processed > 0 && ENRICH_REQUIRED && Number(synthesize?.enriched || 0) <= 0) failures.push('deep enrichment produced zero enriched clusters') + return failures +} + async function recentNotes(limit = 8) { const notes = [] async function walk(dir) { @@ -326,7 +354,7 @@ async function recentNotes(limit = 8) { } async function writeActionBrief(finishResult) { - const dir = path.join(ROOT, '.mnemazine/state') + const dir = STATE await ensureDir(dir) const notes = await recentNotes() const lines = [ @@ -423,16 +451,34 @@ async function main() { } } await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8') - if (SYNTHESIZE) { + let synthesize = { skipped: true, reason: processed > 0 ? 'disabled' : 'no newly extracted sources' } + if (SYNTHESIZE && processed > 0) { // Stages: extraction+understanding already done above; synthesize runs // research/verification/atomization (deep) and writes vault atoms. const synthArgs = [path.join(ROOT, 'scripts/mnemazine-synthesize.mjs')] if (DEEP) synthArgs.push('--deep') - const synth = spawnSync(process.execPath, synthArgs, { stdio: 'inherit', env: process.env }) - if (synth.status !== 0) process.exit(synth.status || 1) + const synth = spawnSync(process.execPath, synthArgs, { encoding: 'utf8', env: process.env }) + if (synth.stdout) process.stdout.write(synth.stdout) + if (synth.stderr) process.stderr.write(synth.stderr) + synthesize = parseJsonOutput(synth.stdout) || { ok: synth.status === 0, parse_error: true } + 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() }) + process.exit(synth.status || 1) + } + } + if (REQUIRE_DEEP) { + const deepFailures = validateDeepRun({ synthesize, processed }) + 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() }) + console.error(JSON.stringify({ ok: false, failures: deepFailures, synthesize }, null, 2)) + process.exit(1) + } } const quality = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs')], { stdio: 'inherit', env: process.env }) - if (quality.status !== 0) process.exit(quality.status || 1) + 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() }) + process.exit(quality.status || 1) + } const archived = [] for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash)) // Deep + final stage: Russian humanizer digest, AFTER the graph so connections @@ -441,7 +487,9 @@ async function main() { spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-digest.mjs')], { stdio: 'inherit', env: process.env }) } const finish = FINISH ? await finishRun() : { skipped: true } - console.log(JSON.stringify({ inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, finish, vault: VAULT }, null, 2)) + 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() } + await writeRunState(result) + console.log(JSON.stringify(result, null, 2)) } main().catch(err => { diff --git a/scripts/mnemazine-synthesize.mjs b/scripts/mnemazine-synthesize.mjs index 7549600..2a2f1e6 100644 --- a/scripts/mnemazine-synthesize.mjs +++ b/scripts/mnemazine-synthesize.mjs @@ -367,7 +367,7 @@ async function atomizeCluster(cluster, sources, materialOverride) { const ENRICH_SCHEMA = { type: 'object', additionalProperties: false, - required: ['enriched', 'sources'], + required: ['enriched', 'sources', 'added_facts'], properties: { enriched: { type: 'string' }, sources: { type: 'array', items: { type: 'string' } }, diff --git a/scripts/mnemazine-telegram-sync.sh b/scripts/mnemazine-telegram-sync.sh index b0d0e12..bd751f0 100755 --- a/scripts/mnemazine-telegram-sync.sh +++ b/scripts/mnemazine-telegram-sync.sh @@ -13,11 +13,12 @@ REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" VPS="${MNEMAZINE_VPS:-root@YOUR_VPS_HOST}" KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}" REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-/var/www/mnemazine-inbox/}" +REMOTE_INBOX="${REMOTE_INBOX%/}/" # Inbox honours MNEMAZINE_INBOX (from config.env); defaults to repo-local inbox. LOCAL_INBOX="${MNEMAZINE_INBOX:-$REPO/inbox}" LOCAL_INBOX="${LOCAL_INBOX%/}/" STAGING="${LOCAL_INBOX}.staging/" -# Export so `npm run run` (mnemazine-run.mjs) reads the same inbox. +# Export so the protocol runner reads the same inbox. export MNEMAZINE_INBOX="${LOCAL_INBOX%/}" if [ "$VPS" = "root@YOUR_VPS_HOST" ]; then @@ -47,7 +48,7 @@ shopt -u dotglob nullglob # 3) run the protocol; only AFTER it succeeds delete the taken files on the VPS. cd "$REPO" -if npm run run; then +if npm run protocol:desktop; then if [ "${#pulled[@]}" -gt 0 ]; then printf '%s\n' "${pulled[@]}" | $SSH_E "$VPS" "cd ${REMOTE_INBOX%/} && xargs -d '\n' -r rm -f --" fi diff --git a/scripts/mnemazine-verify.mjs b/scripts/mnemazine-verify.mjs index 35de550..af2ae92 100644 --- a/scripts/mnemazine-verify.mjs +++ b/scripts/mnemazine-verify.mjs @@ -17,7 +17,7 @@ export function verifyLocal(urls = []) { const VERIFY_SCHEMA = { type: 'object', additionalProperties: false, - required: ['status', 'evidence'], + required: ['status', 'evidence', 'checked'], properties: { status: { type: 'string', enum: ['verified', 'assumed', 'unknown'] }, evidence: { type: 'string' },