Video keyframe OCR
IMG_1234.PNG raw OCR без синтеза.
#!/usr/bin/env node import { promises as fs } from 'node:fs' import { existsSync, readFileSync } from 'node:fs' import path from 'node:path' import os from 'node:os' import crypto from 'node:crypto' import { spawn } from 'node:child_process' import { SPEC_TYPES } from './mnemazine-note-spec.mjs' import { listTreeFiles } from './mnemazine-tracked-files.mjs' const ROOT = path.resolve(process.cwd()) function run(command, args, options = {}) { return new Promise(resolve => { const child = spawn(command, args, { cwd: options.cwd || ROOT, env: { ...process.env, ...(options.env || {}) }, stdio: ['ignore', 'pipe', 'pipe'] }) let stdout = '' let stderr = '' child.stdout.on('data', chunk => { stdout += String(chunk) }) child.stderr.on('data', chunk => { stderr += String(chunk) }) child.on('close', code => resolve({ code: code ?? 1, stdout, stderr })) child.on('error', error => resolve({ code: 1, stdout, stderr: `${stderr}\n${error.message}` })) }) } function runWithStdin(command, args, input, env = {}) { return new Promise(resolve => { const child = spawn(command, args, { cwd: ROOT, env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'] }) let stdout = '' let stderr = '' child.stdout.on('data', chunk => { stdout += String(chunk) }) child.stderr.on('data', chunk => { stderr += String(chunk) }) child.on('close', code => resolve({ code: code ?? 1, stdout, stderr })) child.on('error', error => resolve({ code: 1, stdout, stderr: `${stderr}\n${error.message}` })) child.stdin.write(input) child.stdin.end() }) } async function must(label, command, args, options = {}) { const result = await run(command, args, options) if (result.code !== 0) { throw new Error(`${label} failed\n$ ${command} ${args.join(' ')}\n${result.stdout}\n${result.stderr}`.trim()) } return result } async function readJson(file) { return JSON.parse(await fs.readFile(file, 'utf8')) } function sha256Text(text) { return crypto.createHash('sha256').update(text).digest('hex') } async function listFiles(dir) { const out = [] for (const entry of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) { const file = path.join(dir, entry.name) if (entry.isDirectory()) out.push(...await listFiles(file)) else out.push(file) } return out } function noteType(text) { const match = String(text || '').match(/^type:\s*["']?([^"'\n#]+)["']?\s*(?:#.*)?$/m) return match ? match[1].trim() : '' } // Источник правды синтаксиса — git ls-files (CI и локальная машина видят одно и то же), // пересеченный с наличием на диске. Ручной список из 30 путей (план П11) убран: он не // проверял десять отслеживаемых .mjs (в т.ч. kb-lint.mjs и normalize-old-frontmatter.mjs — // оба правят живой vault), ни один .sh и почти все .py. async function gitLsFiles() { // Распакованный релиз не является репозиторием: там правду говорит диск. // Подмену отслеживаемого файла это уже не ловит, но в архиве и сравнивать // не с чем - именно на этой среде падал изолированный прогон гейта выкладки. return listTreeFiles(ROOT).files } function syntaxTargetsFrom(tracked) { const mjs = tracked.filter(file => /\.mjs$/.test(file) && (file.startsWith('scripts/') || file.startsWith('tests/'))) const workflows = tracked.filter(file => file === 'workflows/mnemazina-pipeline.js') const py = tracked.filter(file => /^scripts\/[^/]+\.py$/.test(file)) const sh = tracked.filter(file => /\.sh$/.test(file) && file.split('/').length <= 2 && file !== '.mnemazine/config.local.sh') return { mjs, workflows, py, sh, all: [...mjs, ...workflows, ...py, ...sh].sort() } } async function checkSyntax() { const targets = syntaxTargetsFrom(await gitLsFiles()) // Отсутствие файла из списка git ls-files — провал, а не молчаливый пропуск // (тот шов, через который проба «спрячь прибор» проходила зеленой). const missing = targets.all.filter(file => !existsSync(path.join(ROOT, file))) if (missing.length) throw new Error(`syntax: отслеживаемые файлы отсутствуют на диске: ${missing.join(', ')}`) for (const file of targets.mjs) await must(`syntax:${file}`, process.execPath, ['--check', file]) for (const file of targets.workflows) await must(`workflow-syntax:${file}`, process.execPath, ['scripts/check-workflow-syntax.mjs', file]) for (const file of targets.py) await must(`syntax:${file}`, 'python3', ['-m', 'py_compile', file]) for (const file of targets.sh) await must(`syntax:${file}`, 'bash', ['-n', file]) } 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() { const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-release-')) const inbox = path.join(temp, 'inbox') const vault = path.join(temp, 'vault') const scripts = path.join(temp, 'scripts') const config = path.join(temp, 'config') await fs.mkdir(inbox, { recursive: true }) await fs.mkdir(vault, { recursive: true }) await fs.mkdir(scripts, { recursive: true }) await fs.mkdir(config, { recursive: true }) await fs.copyFile(path.join(ROOT, 'demo/inbox/example-guide.md'), path.join(inbox, 'example-guide.md')) await fs.writeFile(path.join(inbox, 'empty-source.bin'), '') await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-paths.mjs'), path.join(scripts, 'mnemazine-paths.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-note-spec.mjs'), path.join(scripts, 'mnemazine-note-spec.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-project-categories.mjs'), path.join(scripts, 'mnemazine-project-categories.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs'), path.join(scripts, 'mnemazine-vault-quality-gate.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-synthesize.mjs'), path.join(scripts, 'mnemazine-synthesize.mjs')) // synthesize импортирует metiz: без него песочница падает ERR_MODULE_NOT_FOUND ещё до первой проверки. // Список копирования ручной, и врезка Метиды его не пополнила - гейт краснел на исправном коде. await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-metiz.mjs'), path.join(scripts, 'mnemazine-metiz.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-llm.mjs'), path.join(scripts, 'mnemazine-llm.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-runtime.mjs'), path.join(scripts, 'mnemazine-cli-runtime.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-router.mjs'), path.join(scripts, 'mnemazine-cli-router.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-probe.mjs'), path.join(scripts, 'mnemazine-cli-probe.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-codex.mjs'), path.join(scripts, 'mnemazine-codex.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-verify.mjs'), path.join(scripts, 'mnemazine-verify.mjs')) await fs.copyFile(path.join(ROOT, 'config/cli-registry.json'), path.join(config, 'cli-registry.json')) await fs.copyFile(path.join(ROOT, 'config/project-categories.json'), path.join(config, 'project-categories.json')) await fs.writeFile(path.join(config, 'cli-registry.local.json'), '{}\n', 'utf8') const mixedRun = await run(process.execPath, ['scripts/mnemazine-run.mjs'], { env: { MNEMAZINE_ROOT: temp, MNEMAZINE_INBOX: inbox, MNEMAZINE_VAULT: vault, // finishRun не входит в контракт этого смоука (он про intake→synth→archive), // а его обязательные скрипты сюда не копируются — runLocalNodeScript теперь // fail-closed на пропаже обязательного. Гасим finish, как уже делает // strictArchiveGateSmoke ниже. MNEMAZINE_FINISH: '0' } }) if (mixedRun.code === 0) throw new Error('demo smoke failed: mixed batch with unextractable input passed') if (!existsSync(path.join(inbox, 'example-guide.md')) || !existsSync(path.join(inbox, 'empty-source.bin'))) throw new Error('demo smoke failed: failed batch archived an input') if ((await listFiles(path.join(temp, '.mnemazine/archive'))).length) throw new Error('demo smoke failed: failed batch must archive nothing') // Isolate the rejected fixture; only the now-complete batch may archive. await fs.rename(path.join(inbox, 'empty-source.bin'), path.join(temp, 'empty-source.bin')) await must('demo validated-source archive smoke', process.execPath, ['scripts/mnemazine-run.mjs'], { env: { MNEMAZINE_ROOT: temp, MNEMAZINE_INBOX: inbox, MNEMAZINE_VAULT: vault, MNEMAZINE_FINISH: '0' } }) const inboxFiles = await fs.readdir(inbox) if (inboxFiles.length !== 0) { throw new Error(`demo smoke failed: expected validated inbox to be empty (${inboxFiles.join(', ')})`) } const notes = (await listFiles(vault)) .filter(file => file.endsWith('.md')) .filter(file => !file.split(path.sep).includes('graphify-out')) if (notes.length < 1) throw new Error(`demo smoke failed: expected synthesized notes, got ${notes.length}`) const forbidden = [/intake-draft/i, /draft-local/i, /\btemp_image/i, /\bIMG_\d+/, /\.(WEBP|PNG|JPE?G|HEIC|TIFF)\b/, /status:\s*"candidate"/i, /local extraction only/i] for (const noteFile of notes) { const note = await fs.readFile(noteFile, 'utf8') const hit = forbidden.find(re => re.test(note)) if (hit) throw new Error(`demo smoke failed: raw marker in ${path.basename(noteFile)} (${hit})`) const type = noteType(note) if (!SPEC_TYPES.has(type)) throw new Error(`demo smoke failed: ${path.basename(noteFile)} type is outside NOTE-SPEC enum: ${type || 'empty'}`) if (!/source_ref:\s*"session:/.test(note) || !/local-media:/.test(note)) throw new Error(`demo smoke failed: ${path.basename(noteFile)} synthesis provenance missing`) } const archived = await listFiles(path.join(temp, '.mnemazine/archive')) 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')) if (extractRecords.length !== 2) throw new Error(`demo smoke failed: expected 2 extract records, got ${extractRecords.length}`) const cache = await readJson(path.join(temp, '.mnemazine/cache/processed-hashes.json')) const cacheOnly = Object.values(cache).filter(value => value && typeof value === 'object' && value.status === 'needs_manual_context') if (cacheOnly.length !== 1) throw new Error(`demo smoke failed: expected 1 cache-only source, got ${cacheOnly.length}`) await fs.copyFile(path.join(ROOT, 'demo/inbox/example-guide.md'), path.join(inbox, 'cached-guide.md')) await must('demo cached-source archive smoke', process.execPath, ['scripts/mnemazine-run.mjs'], { env: { MNEMAZINE_ROOT: temp, MNEMAZINE_INBOX: inbox, MNEMAZINE_VAULT: vault, MNEMAZINE_FINISH: '0' } }) const cachedInboxFiles = await fs.readdir(inbox) if (cachedInboxFiles.length !== 0) { throw new Error(`demo cached smoke failed: expected validated inbox to be empty (${cachedInboxFiles.join(', ')})`) } const archivedAfterCachedRun = await listFiles(path.join(temp, '.mnemazine/archive')) 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 config = path.join(temp, 'config') 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(config, { recursive: true }) await fs.mkdir(extracts, { recursive: true }) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-paths.mjs'), path.join(scripts, 'mnemazine-paths.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-note-spec.mjs'), path.join(scripts, 'mnemazine-note-spec.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-project-categories.mjs'), path.join(scripts, 'mnemazine-project-categories.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs'), path.join(scripts, 'mnemazine-vault-quality-gate.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-digest.mjs'), path.join(scripts, 'mnemazine-digest.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-humanize-gate.mjs'), path.join(scripts, 'mnemazine-humanize-gate.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-human-layer-gate.mjs'), path.join(scripts, 'mnemazine-human-layer-gate.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-llm.mjs'), path.join(scripts, 'mnemazine-llm.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-runtime.mjs'), path.join(scripts, 'mnemazine-cli-runtime.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-router.mjs'), path.join(scripts, 'mnemazine-cli-router.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-probe.mjs'), path.join(scripts, 'mnemazine-cli-probe.mjs')) await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-codex.mjs'), path.join(scripts, 'mnemazine-codex.mjs')) await fs.copyFile(path.join(ROOT, 'config/cli-registry.json'), path.join(config, 'cli-registry.json')) await fs.copyFile(path.join(ROOT, 'config/project-categories.json'), path.join(config, 'project-categories.json')) await fs.writeFile(path.join(config, 'cli-registry.local.json'), '{}\n', 'utf8') 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: "concept" 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: "concept" verified: true verification_status: "verified" status: "final" enrichment: "external-research" --- # Проверенная cached note ## Что это MarkItDown здесь зафиксирован как проверенное переиспользуемое знание, а не голый распознанный текст. ## Как использовать - Держать source refs как доказательство происхождения. - Проверять публичный репозиторий перед рекомендацией. - Архивировать исходник только после verified final note. ## Источники Local source refs: - ${ref} Публичные источники: - Microsoft MarkItDown: https://github.com/microsoft/markitdown ## Расширение знания Факты, добавленные до атомизации: - Microsoft maintains MarkItDown as an open-source file-to-Markdown converter. - The public repository documents optional extras for additional input formats. ## Проверка - Статус: verified. - Источник сверяется с публичным GitHub URL. ## Следующее действие - Держать эту ноту как smoke fixture для strict archive gate. `) const noCompletion = await run(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 (noCompletion.code === 0 || !existsSync(good.sourceFile)) throw new Error('strict archive gate smoke failed: cached knowledge without completion must retain source') if (!`${noCompletion.stdout}\n${noCompletion.stderr}`.includes('completion failed before archive')) throw new Error('strict archive gate smoke failed: expected explicit missing-completion rejection') // Strict cached intake still requires real completion gates with FINISH=0. // Supply measured fixture baseline and truthful fixture reports, never a PASS shim. for (const name of ['complete-check', 'coverage-check', 'spec-ceiling', 'report-quality-gate']) { await fs.copyFile(path.join(ROOT, `scripts/mnemazine-${name}.mjs`), path.join(goodTemp, `scripts/mnemazine-${name}.mjs`)) } const goodState = path.join(goodTemp, '.mnemazine/state') const goodReports = path.join(goodTemp, 'reports') await fs.mkdir(goodState, { recursive: true }) await fs.mkdir(goodReports, { recursive: true }) await fs.mkdir(path.join(good.vault, '99 Система'), { recursive: true }) await fs.writeFile(path.join(good.vault, '99 Система/_ПРОЕКТЫ.md'), '# Проекты тестовой базы\n\n## Мнемозина\n\nЛокальная проверка конвейера.\n', 'utf8') await must('strict fixture measured baseline', process.execPath, [path.join(goodTemp, 'scripts/mnemazine-spec-ceiling.mjs'), '--update', '--vault', good.vault], { env: { MNEMAZINE_ROOT: goodTemp, MNEMAZINE_VAULT: good.vault } }) await fs.writeFile(path.join(goodReports, 'visual-knowledge-report.html'), `
Синтез: тестовый материал описывает преобразование документов в текст и сохраняет ссылки на происхождение. Эта фикстура проверяет порядок завершения локального конвейера и не представляет результат нового внешнего исследования.
Проверить сохранность источника до успешного завершения всех обязательных проверок.
Используется заранее подготовленная локальная тестовая запись. Сетевые запросы и обращения к модели в этой проверке не выполняются.
После успешной проверки перенести только покрытый тестовый источник в архив.
`, 'utf8') await fs.writeFile(path.join(goodState, 'last-action-brief.md'), '# Короткий отчет Mnemazine\n\n## Статус\n\nПодготовлена локальная фикстура проверки очередности архивирования.\n\n## Следующие действия\n\nЗавершить проверки и сохранить источник при любом отказе.\n', 'utf8') await must('strict archive gate smoke:real-completion', 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() { 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('live status selftest', process.execPath, ['scripts/mnemazine-live-status.mjs', '--selftest']) await must('doctor selftest', process.execPath, ['scripts/mnemazine-doctor.mjs', '--selftest']) await must('semantic graph task selftest', process.execPath, ['scripts/mnemazine-semantic-graph-task.mjs', '--selftest']) // Явный корпус, а не дефолтный vault/: он не публикуется, а установщик в песочнице // гейта идет сухим и каталога не создает. Смоук не должен требовать живой корпус. await must('semantic monitor dry-run smoke', process.execPath, ['scripts/mnemazine-semantic-graph-task.mjs', '--monitor', '--dry-run', '--stale-hours', '1', '--vault', 'demo/vault']) await semanticShardResumeSmoke() await must('agent-os mirror selftest', process.execPath, ['scripts/mnemazine-athena-mirror.mjs', '--selftest']) await must('agent-os mirror manifest check', process.execPath, ['scripts/mnemazine-athena-mirror.mjs', '--check', '--repo-only']) await must('wiki link cleanup selftest', process.execPath, ['scripts/mnemazine-wiki-link-cleanup.mjs', '--selftest']) await must('demo vault quality', 'npm', ['run', 'quality', '--', '--vault', 'demo/vault']) await vaultFinalAuditSmoke() await toolDecisionQueueSmoke() await reportQualityGateSmoke() await digestAliasSmoke() await humanLayerGateSmoke() await completeGateSmoke() } async function semanticShardResumeSmoke() { const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-semantic-resume-')) const vault = path.join(temp, 'vault') const shards = path.join(temp, 'shards') const graph = path.join(vault, 'graphify-out', 'graph.json') await fs.mkdir(path.join(vault, 'graphify-out'), { recursive: true }) await fs.mkdir(shards, { recursive: true }) await fs.writeFile(path.join(vault, 'note.md'), '# Resume smoke\n\nCached shard should skip worker.\n', 'utf8') await fs.writeFile(graph, '{"nodes":[],"links":[]}\n', 'utf8') const shardGraph = path.join(shards, '00000-00000.json') const signature = JSON.stringify({ start: 0, limit: 1, batchSize: 1, excerptChars: 600, maxTokens: 360, backend: 'resume-smoke', model: 'resume-smoke', cache: true }) await fs.writeFile(shardGraph, '{"nodes":[],"links":[]}\n', 'utf8') await fs.writeFile(path.join(shards, 'manifest.json'), '{}\n', 'utf8') await fs.writeFile(path.join(shards, '00000-00000.done.json'), `${JSON.stringify({ signature, graph: shardGraph }, null, 2)}\n`, 'utf8') const result = await must('semantic shard resume smoke', process.execPath, [ 'scripts/mnemazine-semantic-swarm.mjs', '--vault', vault, '--graph', graph, '--shards-dir', shards, '--limit', '1', '--chunk-size', '1', '--batch-size', '1', '--backend', 'resume-smoke', '--model', 'resume-smoke', '--concurrency', '1' ]) const parsed = JSON.parse(result.stdout) if (parsed.skipped !== 1 || !parsed.resumed) throw new Error('semantic shard resume smoke failed: completed shard was not resumed') const progress = await readJson(path.join(shards, 'progress.json')) if (progress.remaining_jobs !== 0 || progress.skipped_completed_jobs !== 1) throw new Error('semantic shard resume smoke failed: progress counters wrong') } async function vaultFinalAuditSmoke() { const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-vault-final-audit-')) const vault = path.join(temp, 'vault') const concepts = path.join(vault, '01 Concepts') const system = path.join(vault, '99 Система') await fs.mkdir(concepts, { recursive: true }) await fs.mkdir(system, { recursive: true }) await fs.mkdir(path.join(vault, 'graphify-out'), { recursive: true }) await fs.writeFile(path.join(vault, 'graphify-out', 'graph.json'), '{}\n', 'utf8') await fs.writeFile(path.join(concepts, 'good.md'), `--- title: "Проверенная заметка" type: "concept" aliases: ["Рабочая заметка"] --- # Проверенная заметка ## Что это Русская финальная заметка без raw-маркеров и приватных имен файлов. ## Как использовать Использовать как smoke fixture для full-vault audit. ## Источники - local-media:vaultfinalaudit ## Проверка Статус: assumed. ## Следующее действие Оставить final-audit в release-check. `, 'utf8') await fs.writeFile(path.join(system, 'Протокол_Мнемозина.md'), `# Протокол ## Что это Системная smoke-заметка со ссылкой на [[Рабочая заметка]]. `, 'utf8') await must('vault final audit smoke:good', process.execPath, ['scripts/mnemazine-vault-final-audit.mjs', '--vault', vault]) await fs.mkdir(path.join(concepts, 'skills', 'graphify-out'), { recursive: true }) await fs.writeFile(path.join(concepts, 'private path leaked temp_image.md'), '# Bad\n\n## What This Is\n\nIMG_1234.PNG raw OCR\n', 'utf8') const bad = await run(process.execPath, ['scripts/mnemazine-vault-final-audit.mjs', '--vault', vault]) if (bad.code === 0) throw new Error('vault final audit smoke failed: bad vault passed') } async function digestAliasSmoke() { const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-digest-alias-')) const vault = path.join(temp, 'vault') const concepts = path.join(vault, '01 Concepts') await fs.mkdir(concepts, { recursive: true }) const started = new Date(Date.now() - 1000).toISOString() await fs.writeFile(path.join(concepts, 'source-a.md'), `--- title: "Looper: проектирование цикла агента" type: "concept" cluster_id: "alias-smoke" --- # Looper: проектирование цикла агента ## Что это Заметка объясняет, зачем сначала описывать цель, проверки и лимиты цикла, а уже потом запускать агента. ## Зачем это нужно Так меньше риск сжечь токены на плохо поставленную задачу. ## Как использовать - Сначала собрать короткий loop.yaml. - Потом отдать цикл исполнителю. ## Источники - https://github.com/ksimback/looper ## Проверка Источник требует отдельной проверки перед установкой. ## Следующее действие - Проверить навык и поставить только после scan. `, 'utf8') await fs.writeFile(path.join(concepts, 'source-b.md'), `--- title: "Проверки цикла агента" type: "concept" cluster_id: "alias-smoke" --- # Проверки цикла агента ## Что это Заметка фиксирует роль reviewer, команды проверки и стоп-условий для агентного цикла. ## Зачем это нужно Проверки делают цикл наблюдаемым и не дают ему крутиться без прогресса. ## Как использовать - Задать критерий готовности. - Задать лимит итераций. ## Источники - local-media:alias-smoke ## Проверка Локальная smoke-заметка для release-check. ## Следующее действие - Проверить формат ссылок в digest. `, 'utf8') await must('digest alias smoke:run', process.execPath, ['scripts/mnemazine-digest.mjs', '--vault', vault, '--session', 'alias-smoke', '--deterministic', '--changed-since', started]) const digest = await fs.readFile(path.join(vault, '_digest', 'Сводка-alias-smoke.md'), 'utf8') if (/\[\[[^\]|]+\]\]/.test(digest)) throw new Error('digest alias smoke failed: bare wikilink found') if (!digest.includes('[[01 Concepts/source-a|Looper: проектирование цикла агента]]')) throw new Error('digest alias smoke failed: note alias missing') if (!digest.includes('[[01 Concepts/source-b|Проверки цикла агента]]')) throw new Error('digest alias smoke failed: connection alias missing') } async function toolDecisionQueueSmoke() { const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-tool-queue-')) const vault = path.join(temp, 'vault') const concepts = path.join(vault, '01 Concepts') await fs.mkdir(concepts, { recursive: true }) const started = new Date(Date.now() - 1000).toISOString() await fs.writeFile(path.join(concepts, 'aider.md'), `--- title: "Aider-AI/aider: решение для Mnemazine" type: "concept" verified: true verification_status: "verified" status: "final" --- # Aider-AI/aider: решение для Mnemazine ## Что это CLI-инструмент для разработки с LLM внутри локального git-репозитория. ## Решение Хранить как кандидата в рабочие возможности, не устанавливать автоматически. ## Что добавила Mnemazine - Метаданные GitHub: 1 звезда, 1 форк, 1 issue, MIT, основной язык Python. - Свежесть репозитория: основная ветка main, последний push 2026-06-24, последний release v1. ## Источники - https://github.com/Aider-AI/aider ## Проверка - Статус: verified. ## Следующее действие - Добавить в очередь разбора возможностей. `, 'utf8') await must('tool decision queue smoke', process.execPath, ['scripts/mnemazine-tool-decision-queue.mjs', '--vault', vault, '--changed-since', started]) const out = path.join(vault, '08 AI и Инструменты/Tools/Очередь разбора инструментов.md') const body = await fs.readFile(out, 'utf8') for (const token of ['# Очередь разбора инструментов', 'Aider', 'Пробный запуск', 'берем, откладываем, забываем']) { if (!body.includes(token)) throw new Error(`tool queue smoke failed: missing ${token}`) } } async function completeGateSmoke() { const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-complete-gate-')) const inbox = path.join(temp, 'inbox') const reports = path.join(temp, 'reports') const state = path.join(temp, 'state') await fs.mkdir(inbox, { recursive: true }) await fs.mkdir(reports, { recursive: true }) await fs.mkdir(state, { recursive: true }) await fs.writeFile(path.join(reports, 'complete-smoke.html'), [ '', 'Свежий слой знаний на русском языке: понятно, что обработано, что проверено и какой следующий шаг нужен человеку.
Проверенная идея после обработки превращена в короткий вывод, а не оставлена как сырой захват.
В пайплайне.
Проверить источники.
Запустить gate.
IMG_1234.PNG raw OCR без синтеза.
Проверенная идея после обработки.
В пайплайне.
Проверить источники.
Добавить тест.
Понятная сводка объясняет, что появилось, зачем это нужно, где источник и какое действие взять следующим шагом.
Сырой HTML исключен из пользовательского текста, а непроверенные утверждения остаются помеченными до ручной проверки.
Запустить gate и убедиться, что отчет читается человеком без знания внутреннего пайплайна.