Harden desktop protocol completion gate

This commit is contained in:
Зарубин Филипп
2026-06-23 18:25:58 +03:00
parent 727ecc03d3
commit 821d575b74
8 changed files with 158 additions and 12 deletions
+6 -1
View File
@@ -10,6 +10,9 @@ Deep-режим **выключен, пока вы его не попросите
## Включение deep-режима ## Включение deep-режима
```bash ```bash
# рабочий запуск Desktop Inbox, строгий полный протокол:
npm run protocol:desktop
# весь прогон, deep: # весь прогон, deep:
node scripts/mnemazine-run.mjs --deep node scripts/mnemazine-run.mjs --deep
# или через env (форвардится в synthesize): # или через env (форвардится в synthesize):
@@ -19,7 +22,9 @@ MNEMAZINE_DEEP=1 node scripts/mnemazine-run.mjs
npm run synthesize -- --deep 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 ## Мост LLM
+1
View File
@@ -7,6 +7,7 @@
"scripts": { "scripts": {
"install:local": "bash install.sh", "install:local": "bash install.sh",
"run": "node scripts/mnemazine-run.mjs", "run": "node scripts/mnemazine-run.mjs",
"protocol:desktop": "bash scripts/mnemazine-desktop-protocol.sh",
"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",
+42 -1
View File
@@ -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 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 STRICT_GRAPH = argv.includes('--strict-graph')
const REQUIRE_DEEP = argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
function run(command, args) { function run(command, args) {
return new Promise(resolve => { return new Promise(resolve => {
@@ -56,10 +57,35 @@ async function latestReport() {
return reports.sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.file || '' 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() { async function main() {
const failures = [] const failures = []
const warnings = [] 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}`) if (inboxFiles.length) failures.push(`inbox not empty: ${inboxFiles.length}`)
const quality = await run(process.execPath, ['scripts/mnemazine-vault-quality-gate.mjs']) const quality = await run(process.execPath, ['scripts/mnemazine-vault-quality-gate.mjs'])
@@ -88,11 +114,26 @@ 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) {
for (const failure of deepFailures(lastRun)) failures.push(failure)
}
const result = { const result = {
ok: failures.length === 0, ok: failures.length === 0,
failures, failures,
warnings, warnings,
inbox: inboxFiles.length, 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, report: report ? path.relative(ROOT, report) : null,
brief: existsSync(brief) ? path.relative(ROOT, brief) : null brief: existsSync(brief) ? path.relative(ROOT, brief) : null
} }
+50
View File
@@ -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
+54 -6
View File
@@ -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 INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault') const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports') 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 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 ARCHIVE = process.env.MNEMAZINE_ARCHIVE || path.join(ROOT, '.mnemazine/archive')
const TRANSCRIPTS = path.join(ROOT, '.mnemazine/cache/video-transcripts') 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. // Default OFF: the runner stays conservative — local only, no external calls.
// Enable with `--deep` or MNEMAZINE_DEEP=1; forwarded to synthesize. // Enable with `--deep` or MNEMAZINE_DEEP=1; forwarded to synthesize.
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 ENRICH_REQUIRED = DEEP && process.env.MNEMAZINE_ENRICH !== '0' && !process.argv.includes('--no-enrich')
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')
@@ -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) { async function recentNotes(limit = 8) {
const notes = [] const notes = []
async function walk(dir) { async function walk(dir) {
@@ -326,7 +354,7 @@ async function recentNotes(limit = 8) {
} }
async function writeActionBrief(finishResult) { async function writeActionBrief(finishResult) {
const dir = path.join(ROOT, '.mnemazine/state') const dir = STATE
await ensureDir(dir) await ensureDir(dir)
const notes = await recentNotes() const notes = await recentNotes()
const lines = [ const lines = [
@@ -423,16 +451,34 @@ async function main() {
} }
} }
await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8') 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 // Stages: extraction+understanding already done above; synthesize runs
// 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, { stdio: 'inherit', env: process.env }) const synth = spawnSync(process.execPath, synthArgs, { encoding: 'utf8', env: process.env })
if (synth.status !== 0) process.exit(synth.status || 1) 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 }) 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 = [] 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
@@ -441,7 +487,9 @@ async function main() {
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')], { stdio: 'inherit', env: process.env })
} }
const finish = FINISH ? await finishRun() : { skipped: true } 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 => { main().catch(err => {
+1 -1
View File
@@ -367,7 +367,7 @@ async function atomizeCluster(cluster, sources, materialOverride) {
const ENRICH_SCHEMA = { const ENRICH_SCHEMA = {
type: 'object', type: 'object',
additionalProperties: false, additionalProperties: false,
required: ['enriched', 'sources'], required: ['enriched', 'sources', 'added_facts'],
properties: { properties: {
enriched: { type: 'string' }, enriched: { type: 'string' },
sources: { type: 'array', items: { type: 'string' } }, sources: { type: 'array', items: { type: 'string' } },
+3 -2
View File
@@ -13,11 +13,12 @@ REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
VPS="${MNEMAZINE_VPS:-root@YOUR_VPS_HOST}" VPS="${MNEMAZINE_VPS:-root@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:-/var/www/mnemazine-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}"
LOCAL_INBOX="${LOCAL_INBOX%/}/" LOCAL_INBOX="${LOCAL_INBOX%/}/"
STAGING="${LOCAL_INBOX}.staging/" 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%/}" export MNEMAZINE_INBOX="${LOCAL_INBOX%/}"
if [ "$VPS" = "root@YOUR_VPS_HOST" ]; then 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. # 3) run the protocol; only AFTER it succeeds delete the taken files on the VPS.
cd "$REPO" cd "$REPO"
if npm run run; then if npm run protocol:desktop; then
if [ "${#pulled[@]}" -gt 0 ]; then if [ "${#pulled[@]}" -gt 0 ]; then
printf '%s\n' "${pulled[@]}" | $SSH_E "$VPS" "cd ${REMOTE_INBOX%/} && xargs -d '\n' -r rm -f --" printf '%s\n' "${pulled[@]}" | $SSH_E "$VPS" "cd ${REMOTE_INBOX%/} && xargs -d '\n' -r rm -f --"
fi fi
+1 -1
View File
@@ -17,7 +17,7 @@ export function verifyLocal(urls = []) {
const VERIFY_SCHEMA = { const VERIFY_SCHEMA = {
type: 'object', type: 'object',
additionalProperties: false, additionalProperties: false,
required: ['status', 'evidence'], required: ['status', 'evidence', 'checked'],
properties: { properties: {
status: { type: 'string', enum: ['verified', 'assumed', 'unknown'] }, status: { type: 'string', enum: ['verified', 'assumed', 'unknown'] },
evidence: { type: 'string' }, evidence: { type: 'string' },