/99 Система/_lint/
+ (по умолчанию НИЧЕГО не пишет: отчёт уходит в stdout)
+ --help эта справка
+
+Коды возврата: 0 — чисто; 1 — есть critical-находки или ошибка запуска.`)
+ process.exit(0)
+}
+
+// Закрытый enum type из docs/NOTE-SPEC.md — незнакомое значение = провал.
+// Ноты, датированные с этой даты, обязаны NOTE-SPEC (старые — advisory, отдельная кампания).
+const SPEC_DATE = '2026-07-25'
+const STALE_DAYS = 30
+// Короче — доля кириллицы шумит на списках путей/команд, не на прозе.
+const MIN_PROSE_LETTERS = 100
+const DAY_MS = 24 * 60 * 60 * 1000
+// Порог «индекс протух», а не строгое «старше хоть на секунду». Строгое сравнение было красным ПО
+// ПОСТРОЕНИЮ: конвейер строит эмбеддинги и граф, а потом дописывает ноты — mtime индекса всегда раньше
+// mtime свежайшей ноты, и линт печатал critical «старше на 0 дн.» сразу после успешного прогона.
+// Гейт, который нельзя пройти, ничего не измеряет: он просто приучает не смотреть на красное.
+const INDEX_STALE_MS = Number(process.env.MNEMAZINE_INDEX_STALE_DAYS || '1') * DAY_MS
+
+// macOS хранит имена файлов в NFD, текст ссылок обычно NFC — без нормализации
+// русские wikilinks ложно битые.
+const nfc = value => String(value || '').normalize('NFC')
+
+// Служебный слой (NOTE-SPEC «Когда НЕ по этой спеке»): свои форматы,
+// спека/сиротство/блоки к ним не применяются.
+function isService(rel) {
+ if (rel.startsWith('99 Система/') || rel.startsWith('00 Входящие/')) return true
+ const parts = rel.split('/')
+ if (parts.some(part => part.startsWith('_'))) return true
+ const base = parts[parts.length - 1]
+ return /^(AGENTS|CLAUDE|README)\.md$/i.test(base) || base.startsWith('Лог ') || base.startsWith('Без названия')
+}
+
+async function walkVault(vault) {
+ const md = []
+ const dirs = new Set()
+ const fileKeys = new Set()
+ async function walk(dir) {
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ const abs = path.join(dir, item.name)
+ const rel = nfc(path.relative(vault, abs).replace(/\\/g, '/'))
+ if (item.isDirectory()) {
+ if (['.git', '.obsidian', '.mnemazine'].includes(item.name) || item.name.startsWith('graphify-out')) continue
+ // Отчёты этого же линта — не ноты: не линтуются и не входят в счёт диска.
+ if (rel === '99 Система/_lint') continue
+ dirs.add(rel)
+ await walk(abs)
+ } else if (item.isFile()) {
+ fileKeys.add(rel)
+ fileKeys.add(nfc(item.name))
+ fileKeys.add(nfc(item.name).replace(/\.md$/i, ''))
+ if (item.name.endsWith('.md')) md.push({ abs, rel })
+ }
+ }
+ }
+ await walk(vault)
+ return { md, dirs, fileKeys }
+}
+
+function fmValue(fm, key) {
+ const match = (fm || '').match(new RegExp(`^${key}:\\s*(.*)$`, 'm'))
+ if (!match) return ''
+ return match[1].replace(/\s+#.*$/, '').trim().replace(/^['"]|['"]$/g, '')
+}
+
+function fmDate(fm, key) {
+ const hit = fmValue(fm, key).match(/\d{4}-\d{2}-\d{2}/)
+ return hit ? hit[0] : ''
+}
+
+// Код-блоки гасятся пробелами, не вырезаются — номера строк и позиции не едут.
+function scanText(text) {
+ return text
+ .replace(/```[\s\S]*?```/g, block => block.replace(/[^\n]/g, ' '))
+ .replace(/`[^`\n]*`/g, block => ' '.repeat(block.length))
+}
+
+function proseOf(text) {
+ return text
+ .replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '')
+ .replace(/```[\s\S]*?```/g, ' ')
+ .replace(/`[^`\n]*`/g, ' ')
+ .replace(/https?:\/\/\S+/g, ' ')
+}
+
+function cyrillicShare(prose) {
+ const cyr = (prose.match(/[а-яё]/gi) || []).length
+ const lat = (prose.match(/[a-z]/gi) || []).length
+ const total = cyr + lat
+ return { total, share: total ? cyr / total : 1 }
+}
+
+function linkTarget(raw) {
+ return nfc(raw.split('|')[0].split('#')[0].split('^')[0].trim().replace(/\\+$/, ''))
+}
+
+async function checkIndexes(vault, notes) {
+ const issues = []
+ const diskCount = notes.length
+ const master = await fs.readFile(path.join(vault, '_МАСТЕР-ИНДЕКС.md'), 'utf8').catch(() => '')
+ const hit = master.match(/Всего markdown[^:]*:\s*\*\*(\d+)\*\*/i)
+ const counter = hit ? Number(hit[1]) : null
+ if (counter === null) issues.push('в _МАСТЕР-ИНДЕКС.md не найден счётчик «Всего markdown: **N**»')
+ else if (counter !== diskCount) issues.push(`_МАСТЕР-ИНДЕКС.md заявляет ${counter} .md, на диске ${diskCount}`)
+ const newestMs = notes.reduce((max, note) => Math.max(max, note.mtimeMs), 0)
+ for (const relIndex of ['99 Система/_embeddings.json', 'graphify-out/graph.json']) {
+ const stat = await fs.stat(path.join(vault, relIndex)).catch(() => null)
+ if (!stat) issues.push(`${relIndex} отсутствует`)
+ else if (newestMs - stat.mtimeMs >= INDEX_STALE_MS) {
+ const lagDays = Math.round((newestMs - stat.mtimeMs) / DAY_MS * 10) / 10
+ issues.push(`${relIndex} старше свежайшей ноты на ${lagDays} дн.`)
+ }
+ }
+ return { issues, counter, disk_count: diskCount, newest_note: new Date(newestMs).toISOString() }
+}
+
+async function rootJunk(vault) {
+ const junk = []
+ for (const item of await fs.readdir(vault, { withFileTypes: true }).catch(() => [])) {
+ const name = nfc(item.name)
+ if (name === '.DS_Store' || name.startsWith('Без названия')) junk.push(name)
+ }
+ return junk.sort()
+}
+
+async function runLint({ vault, limit }) {
+ const wiki = await walkVault(vault)
+ const notes = []
+ for (const file of wiki.md) {
+ const [text, stat] = await Promise.all([fs.readFile(file.abs, 'utf8'), fs.stat(file.abs)])
+ const fmMatch = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)
+ notes.push({ ...file, text, mtimeMs: stat.mtimeMs, fm: fmMatch ? fmMatch[1] : null })
+ }
+
+ const noteIndex = new Map()
+ const addKey = (key, rel) => {
+ if (!key) return
+ if (!noteIndex.has(key)) noteIndex.set(key, new Set())
+ noteIndex.get(key).add(rel)
+ }
+ for (const note of notes) {
+ const base = nfc(path.basename(note.rel))
+ addKey(note.rel, note.rel)
+ addKey(note.rel.replace(/\.md$/i, ''), note.rel)
+ addKey(base, note.rel)
+ addKey(base.replace(/\.md$/i, ''), note.rel)
+ }
+
+ const brokenByTarget = new Map()
+ const linked = new Set()
+ const linkRe = /\[\[([^\]\n]+)\]\]/g
+ for (const note of notes) {
+ const text = scanText(note.text)
+ let match
+ while ((match = linkRe.exec(text))) {
+ const target = linkTarget(match[1])
+ if (!target || target.startsWith('#') || /^(https?|mailto):/i.test(target)) continue
+ const base = nfc(path.basename(target))
+ const keys = [target, target.replace(/\.md$/i, ''), base, base.replace(/\.md$/i, '')]
+ const hitNotes = keys.map(key => noteIndex.get(key)).find(Boolean)
+ if (hitNotes) {
+ for (const rel of hitNotes) linked.add(rel)
+ continue
+ }
+ if (keys.some(key => wiki.dirs.has(key) || wiki.fileKeys.has(key))) continue
+ if (!brokenByTarget.has(target)) brokenByTarget.set(target, { target, count: 0, examples: [] })
+ const group = brokenByTarget.get(target)
+ group.count += 1
+ if (group.examples.length < 3) group.examples.push(note.rel)
+ }
+ }
+
+ const orphans = []
+ const specNew = []
+ const specOld = []
+ const lowCyr = []
+ const missingBlocks = []
+ let staleCount = 0
+ let contentNotes = 0
+ const nowMs = Date.now()
+ for (const note of notes) {
+ if (isService(note.rel)) continue
+ contentNotes += 1
+ if (!linked.has(note.rel)) orphans.push(note.rel)
+
+ const problems = []
+ if (!note.fm) problems.push('нет frontmatter')
+ else {
+ if (!/^source:\s*\S/m.test(note.fm)) problems.push('нет source:')
+ const type = fmValue(note.fm, 'type')
+ if (!SPEC_TYPES.has(type)) problems.push(`type вне enum: ${type || '(пусто)'}`)
+ }
+ if (problems.length) {
+ const date = fmDate(note.fm, 'created') || fmDate(note.fm, 'updated') || new Date(note.mtimeMs).toISOString().slice(0, 10)
+ ;(date >= SPEC_DATE ? specNew : specOld).push({ file: note.rel, date, problems })
+ }
+
+ const prose = cyrillicShare(proseOf(note.text))
+ if (prose.total >= MIN_PROSE_LETTERS && prose.share < MIN_CYR_SHARE) {
+ lowCyr.push({ file: note.rel, share_pct: Math.round(prose.share * 100) })
+ }
+
+ const missing = []
+ if (!/^#{2,3}\s*(?:🎯\s*)?Как это поможет мне/m.test(note.text)) missing.push('Как это поможет мне')
+ if (!/^#{2,3}\s*Достоверность/m.test(note.text)) missing.push('Достоверность')
+ if (missing.length) missingBlocks.push({ file: note.rel, missing })
+
+ const updated = fmDate(note.fm, 'updated')
+ const ageMs = nowMs - (updated ? Date.parse(updated) : note.mtimeMs)
+ if (ageMs > STALE_DAYS * DAY_MS) staleCount += 1
+ }
+
+ const brokenList = [...brokenByTarget.values()].sort((a, b) => b.count - a.count || a.target.localeCompare(b.target))
+ const indexes = await checkIndexes(vault, notes)
+ const junk = await rootJunk(vault)
+ const hasCritical = brokenList.length > 0 || indexes.issues.length > 0
+
+ return {
+ ok: !hasCritical,
+ date: new Date().toISOString().slice(0, 10),
+ vault,
+ checked: { markdown_files: notes.length, content_notes: contentNotes },
+ checks: {
+ broken_wikilinks: {
+ severity: 'critical',
+ count: brokenList.reduce((sum, item) => sum + item.count, 0),
+ unique_targets: brokenList.length,
+ worst: brokenList.slice(0, limit)
+ },
+ index_divergence: { severity: 'critical', count: indexes.issues.length, ...indexes },
+ spec_new: { severity: 'high', count: specNew.length, worst: specNew.slice(0, limit) },
+ spec_old: { severity: 'medium', count: specOld.length, worst: specOld.slice(0, limit) },
+ orphans: { severity: 'medium', count: orphans.length, worst: orphans.sort().slice(0, limit) },
+ low_cyrillic: {
+ severity: 'medium',
+ count: lowCyr.length,
+ worst: lowCyr.sort((a, b) => a.share_pct - b.share_pct).slice(0, limit)
+ },
+ missing_blocks: { severity: 'medium', count: missingBlocks.length, worst: missingBlocks.slice(0, limit) },
+ stale_notes: { severity: 'info', count: staleCount },
+ root_junk: { severity: 'info', count: junk.length, files: junk }
+ }
+ }
+}
+
+function renderReport(report, limit) {
+ const c = report.checks
+ const lines = []
+ lines.push(`# KB Lint — ${report.date}`, '')
+ lines.push(`- Vault: \`${report.vault}\``)
+ lines.push(`- Всего .md: ${report.checked.markdown_files} · содержательных нот: ${report.checked.content_notes}`)
+ lines.push(`- Итог: ${report.ok ? 'чисто (exit 0)' : 'есть critical (exit 1)'}`)
+ lines.push('', '## Сводка', '')
+ lines.push('| Проверка | Северити | Счёт |')
+ lines.push('|---|---|---:|')
+ lines.push(`| Битые wikilinks | critical | ${c.broken_wikilinks.count} |`)
+ lines.push(`| Расхождение индексов | critical | ${c.index_divergence.count} |`)
+ lines.push(`| Спека NOTE-SPEC: ноты ≥ ${SPEC_DATE} | high | ${c.spec_new.count} |`)
+ lines.push(`| Спека NOTE-SPEC: старые ноты | medium | ${c.spec_old.count} |`)
+ lines.push(`| Ноты-сироты | medium | ${c.orphans.count} |`)
+ lines.push(`| Кириллица в прозе < ${MIN_CYR_SHARE * 100}% | medium | ${c.low_cyrillic.count} |`)
+ lines.push(`| Нет «Как это поможет мне»/«Достоверность» | medium | ${c.missing_blocks.count} |`)
+ lines.push(`| Протухшие ноты (> ${STALE_DAYS} дн.) | info | ${c.stale_notes.count} |`)
+ lines.push(`| Мусор корня | info | ${c.root_junk.count} |`)
+
+ lines.push('', `## Битые wikilinks — ${c.broken_wikilinks.count} (${c.broken_wikilinks.unique_targets} целей)`, '')
+ for (const item of c.broken_wikilinks.worst) {
+ lines.push(`- \`[[${item.target}]]\` — ${item.count} вхожд. · например: \`${item.examples[0]}\``)
+ }
+
+ lines.push('', '## Расхождение индексов', '')
+ lines.push(`- Счётчик _МАСТЕР-ИНДЕКС.md: ${c.index_divergence.counter ?? 'не найден'} · на диске: ${c.index_divergence.disk_count}`)
+ lines.push(`- Свежайшая нота: ${c.index_divergence.newest_note}`)
+ for (const issue of c.index_divergence.issues) lines.push(`- ПРОБЛЕМА: ${issue}`)
+ if (!c.index_divergence.issues.length) lines.push('- Индексы сходятся.')
+
+ lines.push('', `## Спека NOTE-SPEC: ноты ≥ ${SPEC_DATE} (обязаны спеке) — ${c.spec_new.count}`, '')
+ for (const item of c.spec_new.worst) lines.push(`- \`${item.file}\` (${item.date}) — ${item.problems.join(' · ')}`)
+
+ lines.push('', `## Спека NOTE-SPEC: старые ноты (advisory) — ${c.spec_old.count}`, '')
+ for (const item of c.spec_old.worst) lines.push(`- \`${item.file}\` (${item.date}) — ${item.problems.join(' · ')}`)
+
+ lines.push('', `## Ноты-сироты (0 входящих ссылок) — ${c.orphans.count}`, '')
+ for (const file of c.orphans.worst) lines.push(`- \`${file}\``)
+
+ lines.push('', `## Кириллица в прозе < ${MIN_CYR_SHARE * 100}% — ${c.low_cyrillic.count}`, '')
+ for (const item of c.low_cyrillic.worst) lines.push(`- \`${item.file}\` — ${item.share_pct}%`)
+
+ lines.push('', `## Нет обязательных блоков — ${c.missing_blocks.count}`, '')
+ for (const item of c.missing_blocks.worst) lines.push(`- \`${item.file}\` — нет: ${item.missing.join(', ')}`)
+
+ lines.push('', `## Мусор корня (только список, ничего не удалено) — ${c.root_junk.count}`, '')
+ for (const file of c.root_junk.files) lines.push(`- \`${file}\``)
+
+ lines.push('', `Списки обрезаны до ${limit} худших; полные данные — \`npm run lint:kb -- --json\`.`)
+ return `${lines.join('\n').trim()}\n`
+}
+
+const vault = resolveVault({ cli: arg('vault') })
+const limit = Number(arg('limit', '20'))
+const report = await runLint({ vault, limit })
+
+// Запись в корпус — только по явному --write. Без него отчёт уходит в stdout,
+// каталог _lint/ не создаётся: просмотр не правит корпус (план П08).
+const WRITE = flag('write')
+let reportPath = null
+if (WRITE) {
+ const lintDir = path.join(vault, '99 Система', '_lint')
+ await fs.mkdir(lintDir, { recursive: true })
+ reportPath = path.join(lintDir, `lint-${report.date}.md`)
+ await fs.writeFile(reportPath, renderReport(report, limit), 'utf8')
+ await fs.writeFile(path.join(lintDir, '.last-lint'), `${new Date().toISOString()}\n`, 'utf8')
+}
+
+if (flag('json')) {
+ console.log(JSON.stringify({ ...report, report_path: reportPath }, null, 2))
+} else if (WRITE) {
+ const counts = Object.fromEntries(Object.entries(report.checks).map(([name, check]) => [name, check.count]))
+ console.log(JSON.stringify({ ok: report.ok, vault, counts, report_path: reportPath }, null, 2))
+} else {
+ process.stdout.write(renderReport(report, limit))
+}
+// Не process.exit(1): при пайпе хвост stdout (крупный --json) обрезается на выходе.
+// exitCode даёт циклу событий дозаписать поток (вскрыто прибором П15 --converge).
+if (!report.ok) process.exitCode = 1
diff --git a/scripts/mnemazine-kb-search.mjs b/scripts/mnemazine-kb-search.mjs
index 648d9a6..72ec93f 100644
--- a/scripts/mnemazine-kb-search.mjs
+++ b/scripts/mnemazine-kb-search.mjs
@@ -16,7 +16,7 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { resolveVault } from './mnemazine-paths.mjs'
-import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
+import { activeProvider, llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
const argv = process.argv.slice(2)
const SELFTEST = argv.includes('--selftest')
@@ -27,7 +27,33 @@ function arg(name, fb = '') {
}
const DEEP = argv.includes('--deep') || process.env.MNEMAZINE_DEEP === '1'
-const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || 'claude')
+const STDOUT = argv.includes('--stdout')
+const JSON_OUT = argv.includes('--json')
+
+if (argv.includes('--help')) {
+ console.log(`mnemazine-kb-search.mjs — тематический поиск по корпусу знаний.
+Локальный режим — 0 токенов; --deep (или MNEMAZINE_DEEP=1) — рой агентов с синтезом.
+
+Использование: node scripts/mnemazine-kb-search.mjs --topic "<тема>" [флаги]
+ --topic "<тема>" тема поиска (обязательна)
+ --vault <путь> корпус (иначе MNEMAZINE_VAULT или repo-local vault)
+ --out <каталог> каталог отчёта (иначе MNEMAZINE_REPORTS или ./reports);
+ каталог внутри корпуса — отказ с кодом 2
+ --stdout отчёт в stdout, файл не создаётся
+ --json машинная выдача в stdout: results[] с note/score/subject/snippets
+ --deep LLM-рой: планирование запроса, шард-агенты, синтез
+ --verify отбраковка необоснованных находок (только с --deep)
+ --concurrency N параллелизм роя (по умолчанию 4)
+ --max-notes N потолок кандидатов для роя (по умолчанию 60)
+ --shard-size N заметок на агента (по умолчанию 6)
+ --max-shards N жёсткий потолок агентов в deep (по умолчанию 12)
+ --selftest селф-тест во временном каталоге
+ --help эта справка
+
+Коды возврата: 0 — отчёт готов; 1 — ошибка или нет темы; 2 — отказ: каталог отчёта внутри корпуса.`)
+ process.exit(0)
+}
+const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || activeProvider())
const CONCURRENCY = Number(arg('concurrency', process.env.MNEMAZINE_CONCURRENCY || '4'))
const MAX_NOTES = Number(arg('max-notes', '60')) // candidate cap fed to the swarm
const SHARD_SIZE = Number(arg('shard-size', '6')) // notes per agent
@@ -40,10 +66,17 @@ const VERIFY = argv.includes('--verify') || process.env.MNEMAZINE_SEARCH_VERIFY
const MAX_VERIFY = Number(arg('max-verify', '5')) // top-K findings to verify
// --- helpers -----------------------------------------------------------------
+function isServicePath(p) {
+ const parts = p.split(path.sep)
+ if (parts.some(seg => seg === 'graphify-out' || seg === 'graphify-out-snapshots' || seg.startsWith('graphify-out-backup-'))) return true
+ return parts.some((seg, i) => seg === '99 Система' && parts[i + 1] === '_archive')
+}
+
async function walk(dir, out = []) {
for (const e of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (e.name.startsWith('.')) continue
const full = path.join(dir, e.name)
+ if (isServicePath(full)) continue
if (e.isDirectory()) await walk(full, out)
else if (e.name.endsWith('.md')) out.push(full)
}
@@ -52,25 +85,38 @@ async function walk(dir, out = []) {
const STOP = new Set(['the', 'and', 'для', 'что', 'как', 'это', 'про', 'или', 'был', 'are', 'with', 'из', 'на', 'по', 'не', 'от'])
const tokens = s => (String(s).toLowerCase().match(/[\p{L}\p{N}]{3,}/gu) || []).filter(t => !STOP.has(t))
+const uniq = xs => [...new Set(xs.filter(Boolean))]
function scoreNote(text, rel, terms) {
- const hay = (rel + '\n' + text).toLowerCase()
+ const q = uniq(terms)
+ if (!q.length) return 0
+ const hayTokens = tokens(`${rel}\n${text}`)
+ const relTokens = new Set(tokens(rel))
+ const counts = new Map()
+ for (const t of hayTokens) counts.set(t, (counts.get(t) || 0) + 1)
+ const allTerms = q.every(t => counts.has(t))
+ const hasBigram = q.length > 1 && q.slice(0, -1).some((t, i) =>
+ hayTokens.some((h, j) => h === t && hayTokens[j + 1] === q[i + 1]))
+ if (!allTerms && !hasBigram) return 0
let score = 0
- for (const t of terms) {
- let from = 0, n = 0
- while ((from = hay.indexOf(t, from)) !== -1) { n++; from += t.length; if (n >= 8) break }
- score += n
- if (rel.toLowerCase().includes(t)) score += 4 // title/path hit weighs more
+ for (const t of q) {
+ score += Math.min(counts.get(t) || 0, 8)
+ if (relTokens.has(t)) score += 4 // title/path hit weighs more
}
return score
}
+function tokenIndex(text, term) {
+ const rx = new RegExp(`(? s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean)
+ return items.length ? items : null
+ }
+ return raw.replace(/^['"]|['"]$/g, '') || null
+}
+
+async function logQuery(entry) {
+ const file = path.resolve('.mnemazine', 'state', 'kb-search-log.jsonl')
+ await fs.mkdir(path.dirname(file), { recursive: true })
+ await fs.appendFile(file, `${JSON.stringify(entry)}\n`, 'utf8')
+}
+
// Bounded-concurrency pool — the swarm. One failing task never blocks the rest.
async function mapLimit(items, limit, fn) {
let i = 0
@@ -294,7 +361,7 @@ function renderReport(topic, report, meta) {
}
// --- main --------------------------------------------------------------------
-async function run(topic, vault, outDir) {
+async function run(topic, vault, outDir, { stdout = false, json = false } = {}) {
const stamp = new Date().toISOString()
const { terms, facets } = await plan(topic)
// RECON
@@ -305,10 +372,21 @@ async function run(topic, vault, outDir) {
if (!text) continue
const rel = path.relative(vault, f)
const score = scoreNote(text, rel, terms)
- if (score > 0) scored.push({ rel, text, score, url: text.match(/https?:\/\/\S+/)?.[0] || '' })
+ if (score > 0) scored.push({ rel, text, score, subject: frontmatterSubject(text), url: text.match(/https?:\/\/\S+/)?.[0] || '' })
}
scored.sort((a, b) => b.score - a.score)
const candidates = scored.slice(0, MAX_NOTES)
+ if (json) {
+ const results = candidates.map(n => ({
+ note: n.rel,
+ score: n.score,
+ subject: n.subject,
+ snippets: snippets(n.text, terms)
+ }))
+ await logQuery({ ts: stamp, topic, mode: 'json', results: results.length })
+ process.stdout.write(`${JSON.stringify({ topic, scanned: files.length, results }, null, 2)}\n`)
+ return null
+ }
// FAN-OUT — shard within facet groups so each shard carries one focus axis
// (2A). No facets (local / planning failed) → flat sharding as before.
let shards = [] // each: { notes:[...], facet }
@@ -344,6 +422,11 @@ async function run(topic, vault, outDir) {
// FAN-IN
const report = await synthesize(topic, kept, facets)
const md = renderReport(topic, report, { stamp, scanned: files.length, candidates: candidates.length, findings: kept.length, deep: DEEP && llmAvailable(PROVIDER), droppedNotes, droppedByVerify, facets: facets.map(f => f.label) })
+ await logQuery({ ts: stamp, topic, mode: DEEP && llmAvailable(PROVIDER) ? 'deep' : 'local', results: kept.length })
+ if (stdout) {
+ process.stdout.write(md.endsWith('\n') ? md : `${md}\n`)
+ return null
+ }
await fs.mkdir(outDir, { recursive: true })
const out = path.join(outDir, `search-${slugify(topic)}-${stamp.slice(0, 10)}-${Date.now()}.md`)
await fs.writeFile(out, md, 'utf8')
@@ -375,7 +458,14 @@ if (SELFTEST) {
if (!topic) { console.error('Usage: mnemazine-kb-search.mjs --topic "<тема>" [--deep] [--vault ]'); process.exit(1) }
const vault = resolveVault({ cli: arg('vault') })
const outDir = path.resolve(arg('out', process.env.MNEMAZINE_REPORTS || path.join(process.cwd(), 'reports')))
- run(topic, vault, outDir)
- .then(p => console.log(p))
+ // fail-closed: каталог отчёта внутри корпуса превращает просмотр в правку
+ // корпуса — отказ держит код, а не привычку (план П08). С --stdout файла нет.
+ const relOut = path.relative(vault, outDir)
+ if (!STDOUT && !JSON_OUT && (relOut === '' || (!relOut.startsWith('..') && !path.isAbsolute(relOut)))) {
+ console.error(`[kb-search] отказ: каталог отчёта внутри корпуса (out=${outDir}, vault=${vault}). Укажи --out вне корпуса или --stdout.`)
+ process.exit(2)
+ }
+ run(topic, vault, outDir, { stdout: STDOUT, json: JSON_OUT })
+ .then(p => { if (p) console.log(p) })
.catch(e => { console.error(`[kb-search] ${e.message}`); process.exit(1) })
}
diff --git a/scripts/mnemazine-lesson-gate.mjs b/scripts/mnemazine-lesson-gate.mjs
new file mode 100644
index 0000000..02a485a
--- /dev/null
+++ b/scripts/mnemazine-lesson-gate.mjs
@@ -0,0 +1,140 @@
+#!/usr/bin/env node
+// Урок обязан быть правилом — но не задним числом (план П11, метод-правило 13).
+//
+// Читает леджер уроков ТОЛЬКО на чтение (живой /99 Система/_session-learning-ledger.jsonl
+// либо MNEMAZINE_LEDGER для проб на копии). У записей с ts не раньше отсечки
+// (config/doc-claims.json → lesson_schema_since) обязаны быть cause/fix/rule/supersedes.
+// Отсечка измерена: в живом леджере 29 записей и ни одна этих полей не несёт; проверка без
+// отсечки покраснела бы на историческом корпусе и была бы отключена в первый же день.
+// При rule_kind:"executable" файл из enforced_by существует и проходит node --check / bash -n.
+//
+// Коды: 0 — нарушений нет (в т.ч. ноль записей после отсечки: за ночь урока может не случиться;
+// а также нейтральный репо-дефолт vault/ без леджера — у фикстуры учиться нечему, проверять нечего);
+// 1 — запись после отсечки без обязательного поля либо enforced_by на мёртвый/непроходящий файл;
+// 2 — леджера нет или он пуст ПРИ ЯВНО заданном корпусе (MNEMAZINE_VAULT/MNEMAZINE_LEDGER или config ≠ дефолт):
+// назвали живой vault, а прибора в нём нет — это поломка, не «всё хорошо».
+
+import { existsSync, readFileSync } from 'node:fs'
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { resolveVault, DEFAULT_VAULT } from './mnemazine-paths.mjs'
+import { fileURLToPath } from 'node:url'
+import { spawnSync } from 'node:child_process'
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const REQUIRED = ['cause', 'fix', 'rule', 'supersedes']
+const REBUILD = path.join(ROOT, '.mnemazine', 'state', 'rebuild')
+
+function ownerMachine() {
+ return existsSync(path.join(REBUILD, 'П01.done.json'))
+}
+
+// Живой леджер + «явность» корпуса. MNEMAZINE_LEDGER — проба на копии (явная).
+// Иначе /99 Система/…; корпус явный, когда MNEMAZINE_VAULT или config.vault
+// уводят с нейтрального репо-дефолта vault/ (resolved ≠ DEFAULT_VAULT). Явность
+// решает код при отсутствии/пустоте леджера: фикстура → 0, живой корпус → 2.
+function resolveLedger() {
+ if (process.env.MNEMAZINE_LEDGER) return { path: process.env.MNEMAZINE_LEDGER, explicit: true }
+ const vault = resolveVault({ requireExists: false })
+ return { path: path.join(vault, '99 Система', '_session-learning-ledger.jsonl'), explicit: vault !== DEFAULT_VAULT }
+}
+
+function cutoff() {
+ const claimsPath = path.join(ROOT, 'config', 'doc-claims.json')
+ if (existsSync(claimsPath)) {
+ try {
+ const since = JSON.parse(readFileSync(claimsPath, 'utf8')).lesson_schema_since
+ if (since) return String(since)
+ } catch {}
+ }
+ return '2026-08-22'
+}
+
+function syntaxOk(rel) {
+ const abs = path.isAbsolute(rel) ? rel : path.join(ROOT, rel)
+ if (!existsSync(abs)) return false
+ const ext = path.extname(abs)
+ if (ext === '.mjs' || ext === '.js') return spawnSync(process.execPath, ['--check', abs], { encoding: 'utf8' }).status === 0
+ if (ext === '.sh') return spawnSync('bash', ['-n', abs], { encoding: 'utf8' }).status === 0
+ if (ext === '.py') return spawnSync('python3', ['-m', 'py_compile', abs], { encoding: 'utf8' }).status === 0
+ return true
+}
+
+function enforcedByLive(anchor) {
+ const rel = String(anchor || '').replace(/:\d+$/, '')
+ if (!rel) return `enforced_by пуст`
+ if (!existsSync(path.isAbsolute(rel) ? rel : path.join(ROOT, rel))) return `enforced_by файл отсутствует: ${rel}`
+ if (!syntaxOk(rel)) return `enforced_by не проходит синтаксис: ${rel}`
+ return null
+}
+
+// {code, checked, after, failures}
+function evaluate(ledgerPath, since, explicit) {
+ if (!existsSync(ledgerPath)) {
+ if (explicit && !ownerMachine()) {
+ return { code: 0, checked: 0, after: 0, failures: [], skip: 'owner-ops lesson ledger: skipped-as-not-applicable — нет .mnemazine/state/rebuild/П01.done.json (форк/CI, не машина владельца)' }
+ }
+ if (!explicit) return { code: 0, checked: 0, after: 0, failures: [], skip: 'нейтральный репо-дефолт vault/ без леджера — учиться нечему' }
+ return { code: 2, failures: [`леджер отсутствует: ${ledgerPath}`] }
+ }
+ const raw = readFileSync(ledgerPath, 'utf8')
+ const lines = raw.split(/\r?\n/).filter(l => l.trim())
+ if (lines.length === 0) {
+ if (!explicit) return { code: 0, checked: 0, after: 0, failures: [], skip: 'леджер пуст (репо-дефолт) — проверять нечего' }
+ return { code: 2, failures: ['леджер пуст'] }
+ }
+
+ const failures = []
+ let after = 0
+ for (const [i, line] of lines.entries()) {
+ let obj
+ try { obj = JSON.parse(line) } catch { failures.push(`строка ${i + 1}: не JSON`); continue }
+ const ts = String(obj.ts || '')
+ if (!ts || ts < since) continue
+ after++
+ for (const k of REQUIRED) {
+ if (!(k in obj) || obj[k] == null || obj[k] === '') failures.push(`запись ts=${ts}: нет обязательного поля "${k}"`)
+ }
+ if (obj.rule_kind === 'executable') {
+ const why = enforcedByLive(obj.enforced_by)
+ if (why) failures.push(`запись ts=${ts}: ${why}`)
+ }
+ }
+ return { code: failures.length ? 1 : 0, checked: lines.length, after, failures }
+}
+
+function selftest() {
+ const tmp = mkdtempSync(path.join(os.tmpdir(), 'lesson-gate-selftest-'))
+ try {
+ const led = path.join(tmp, 'ledger.jsonl')
+ // Красный кролик: запись ПОСЛЕ отсечки без поля fix обязана покраснеть.
+ writeFileSync(led, JSON.stringify({ ts: '2999-01-01', cause: 'x', rule: 'y', supersedes: '' }) + '\n', 'utf8')
+ const r = evaluate(led, '2026-08-22', true)
+ if (r.code !== 1) { console.error(`selftest FAILED: красный кролик прошёл (code=${r.code})`); return 1 }
+ console.log('selftest ok: урок после отсечки без обязательного поля краснит')
+ return 0
+ } finally {
+ rmSync(tmp, { recursive: true, force: true })
+ }
+}
+
+function main() {
+ const argv = process.argv.slice(2)
+ if (argv.includes('--selftest')) process.exit(selftest())
+ const { path: ledgerPath, explicit } = resolveLedger()
+ const since = cutoff()
+ const r = evaluate(ledgerPath, since, explicit)
+ if (r.code === 2) { console.error(r.failures.join('\n')); process.exit(2) }
+ if (r.skip) { console.log(`леджер: ${ledgerPath}\n${r.skip} (code 0)`); process.exit(0) }
+ console.log(`леджер: ${ledgerPath}\nотсечка: ${since}; записей всего ${r.checked}, после отсечки ${r.after}`)
+ if (r.failures.length) {
+ console.error('ПРОВАЛЫ:')
+ for (const f of r.failures) console.error(` - ${f}`)
+ } else {
+ console.log('уроки после отсечки соответствуют схеме (либо их нет)')
+ }
+ process.exit(r.code)
+}
+
+main()
diff --git a/scripts/mnemazine-live-preflight.sh b/scripts/mnemazine-live-preflight.sh
index 0fe4d51..0d0739f 100755
--- a/scripts/mnemazine-live-preflight.sh
+++ b/scripts/mnemazine-live-preflight.sh
@@ -3,6 +3,7 @@ set -euo pipefail
ROOT="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
cd "$ROOT"
+[ -f "$ROOT/.mnemazine/config.local.sh" ] && . "$ROOT/.mnemazine/config.local.sh"
fail=0
@@ -23,6 +24,15 @@ need_cmd git
need_cmd node
need_cmd npm
+# Local extraction engines — single source of truth is mnemazine-local-engines.mjs
+# (rule 8). Preflight consumes its report (markitdown/whisper/ffmpeg/rg on PATH,
+# vision-ocr a repo-relative binary); it does NOT re-encode the five probes.
+if node scripts/mnemazine-local-engines.mjs --report; then
+ ok "local engines present (markitdown, whisper, ffmpeg, rg, vision-ocr)"
+else
+ bad "local engine(s) missing (see report above)"
+fi
+
if command -v node >/dev/null 2>&1; then
node_major="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
if [ "$node_major" -ge 20 ]; then ok "node >=20"; else bad "node >=20 required"; fi
@@ -34,23 +44,38 @@ fi
if [ "${MNEMAZINE_PREFLIGHT_SKIP_LLM:-0}" != "1" ]; then
provider_hint="${MNEMAZINE_LLM:-}"
- if provider="$(node --input-type=module - "$provider_hint" <<'NODE'
+ # Print the ACTUAL executor (provider_used), never the requested hint. A provider
+ # substituted by fallback (requested deadcli, answered claude) is a preflight
+ # FAILURE, not "ok": a live run pinned to a provider must get that provider.
+ if node --input-type=module - "$provider_hint" <<'NODE'
import { activeProvider, llmAvailable, llmJson } from './scripts/mnemazine-llm.mjs'
-const provider = process.argv[2] || activeProvider()
-if (!llmAvailable(provider)) process.exit(1)
+let requested = process.argv[2] || ''
+if (!requested) { try { requested = activeProvider() } catch { requested = '' } }
const schema = {
type: 'object',
additionalProperties: false,
required: ['ok'],
properties: { ok: { type: 'boolean' } }
}
-await llmJson('Return {"ok":true}.', schema, { provider, timeoutMs: 120000 })
-console.log(provider)
+const opts = { provider: requested, timeoutMs: 120000 }
+let ok = false, err = ''
+try {
+ if (!requested) throw new Error('no provider resolved from registry')
+ if (!llmAvailable(requested)) throw new Error(`requested provider unavailable: ${requested}`)
+ await llmJson('Return {"ok":true}.', schema, opts)
+ const used = opts.provider_used || requested
+ if (used === requested) ok = true
+ else err = `provider substituted by fallback: requested ${requested}, answered ${used}`
+} catch (e) {
+ err = String(e.message || e)
+}
+console.log(`provider_used=${opts.provider_used || '(none)'} requested=${requested || '(none)'}`)
+if (!ok) { console.error(err); process.exit(1) }
NODE
- )"; then
- ok "llm provider available: $provider"
+ then
+ ok "llm provider available and not substituted: ${provider_hint:-}"
else
- bad "llm provider unavailable; set MNEMAZINE_LLM=codex or install/configure Claude/Codex"
+ bad "llm provider unavailable or substituted by fallback (see provider_used line above)"
fi
else
warn "llm provider check skipped"
@@ -73,18 +98,25 @@ if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
if git fetch origin main >/dev/null 2>&1; then
head="$(git rev-parse HEAD)"
remote="$(git rev-parse origin/main)"
- if [ "$head" = "$remote" ]; then ok "HEAD matches origin/main"; else bad "HEAD differs from origin/main"; fi
+ if [ "$head" = "$remote" ]; then
+ ok "HEAD matches origin/main"
+ else
+ read -r behind ahead < <(git rev-list --left-right --count origin/main...HEAD)
+ if [ "$behind" = "0" ]; then ok "HEAD is $ahead local commit(s) ahead of origin/main"; else bad "HEAD is behind/diverged from origin/main"; fi
+ fi
else
bad "could not fetch origin/main"
fi
fi
fi
+# Public-release scan is NOT muted here (П10): preflight must exercise the same
+# gate a real publish would. If public-check reddens, that is a П07/П21 finding,
+# not a reason to restore the mute.
npm run audit:local
npm run protocol:desktop:dry-run
env_inbox="${MNEMAZINE_INBOX:-}"
-[ -f "$ROOT/.mnemazine/config.local.sh" ] && . "$ROOT/.mnemazine/config.local.sh"
base_inbox="${env_inbox:-${MNEMAZINE_INBOX:-$HOME/Desktop/Mnemazine Inbox}}"
nested_inbox="$base_inbox/mnemazine-inbox"
base_count="$(active_count "$base_inbox")"
diff --git a/scripts/mnemazine-live-status.mjs b/scripts/mnemazine-live-status.mjs
index 1ed4c43..68bac59 100755
--- a/scripts/mnemazine-live-status.mjs
+++ b/scripts/mnemazine-live-status.mjs
@@ -81,6 +81,9 @@ async function status(root = ROOT) {
const failures = []
if (!lastRun) failures.push('last-run.json missing')
if (lastRun && !lastRun.ok) failures.push(lastRun.failure || (lastRun.failures || []).join('; ') || 'last run failed')
+ // Смерть литерала ok:true наблюдаема и здесь: даже если поле ok врёт зелёным,
+ // failed>0 означает, что прогон не чист. --require-ok обязан покраснеть.
+ if (lastRun && Number(lastRun.failed || 0) > 0) failures.push(`last run had ${lastRun.failed} failed file(s)`)
if (lastRun?.deep_required && !lastRun.deep) failures.push('strict run was not deep')
if (lastRun?.deep_required && lastRun?.synthesize?.degraded) failures.push('deep synthesis degraded')
if (lastRun?.deep_required && lastRun?.strict_archive_knowledge !== true) failures.push('strict archive gate missing')
diff --git a/scripts/mnemazine-llm.mjs b/scripts/mnemazine-llm.mjs
index ed4c767..80e5f3a 100644
--- a/scripts/mnemazine-llm.mjs
+++ b/scripts/mnemazine-llm.mjs
@@ -1,52 +1,101 @@
#!/usr/bin/env node
-// Provider-abstracted LLM bridge for Mnemazine. In Codex sessions, Codex is the
-// default engine; Claude is only a fallback when Codex is unavailable.
-// provider: MNEMAZINE_LLM = 'claude' | 'codex' (unset = Codex if present)
-// Both run as schema-instructed, web-capable headless agents. Default pipeline
-// never calls either — only the opt-in --deep path does.
+// Registry-driven LLM bridge for Mnemazine. There is no hard-coded list of
+// providers: the CLIs live as DATA in config/cli-registry.json (+ the gitignored
+// config/cli-registry.local.json overlay), and this module branches on the
+// declared CAPABILITY of the selected entry, never on a CLI name. Adding a CLI
+// (gemini, a local gemma, anything) is one JSON entry and zero edits here.
+//
+// Selection and validation come from mnemazine-cli-router.mjs; three schema
+// adapters are chosen by capability: json_schema_inline (claude --json-schema),
+// json_schema_file (codex exec --output-schema), json_in_prompt (universal).
+// The web-tool rule is general: a stage that needs web search only routes to a
+// carrier of the `web_search` capability; if none carries it the call fails with
+// a named cause — it never silently falls through to a CLI that cannot browse.
+//
+// Default pipeline never calls an LLM — only the opt-in --deep path does.
import { spawnSync, spawn } from 'node:child_process'
-import { existsSync, readdirSync, promises as fs } from 'node:fs'
+import { existsSync, promises as fs } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
+import { loadRegistry, orderCandidates, pickSchemaAdapter } from './mnemazine-cli-router.mjs'
+
+const PROGRESS_EVERY_MS = Number(process.env.MNEMAZINE_LLM_PROGRESS_EVERY_MS || '30000')
+const PROGRESS = process.env.MNEMAZINE_LLM_PROGRESS !== '0'
+const CONFIG_PROVIDER = process.env.MNEMAZINE_LLM || ''
+const TIMEOUT_MS = Number(process.env.MNEMAZINE_LLM_TIMEOUT_MS || '420000')
+// Physical ceiling for a prompt delivered as an argv element (getconf ARG_MAX on
+// this machine). A CLI without stdin_prompt gets the prompt in argv; over this we
+// fail with a named cause and move down the chain, never silently truncate.
+const ARG_MAX = Number(process.env.MNEMAZINE_ARG_MAX || '1048576')
+const HOME = os.homedir()
+const WEB_TOOL_RE = /^(WebSearch|WebFetch|mcp__firecrawl|mcp__tavily)$/i
+
+function progress(label, message) {
+ if (PROGRESS && label) process.stderr.write(`[llm] ${label} ${message}\n`)
+}
// Async process runner — non-blocking (unlike spawnSync), so many agent calls
// can run concurrently as a swarm. Never rejects; returns a status/out/err.
-function runProc(bin, args, { input, timeoutMs, cwd } = {}) {
+function runProc(bin, args, { input, timeoutMs, cwd, label } = {}) {
return new Promise(resolve => {
let child
try { child = spawn(bin, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'] }) }
catch (e) { return resolve({ status: 1, stdout: '', stderr: String(e.message) }) }
let out = '', err = '', killed = false
+ const started = Date.now()
+ progress(label, `start timeout=${timeoutMs || 0}ms`)
const t = timeoutMs ? setTimeout(() => { killed = true; child.kill('SIGKILL') }, timeoutMs) : null
+ const heartbeat = PROGRESS && label && PROGRESS_EVERY_MS > 0
+ ? setInterval(() => progress(label, `running ${Math.round((Date.now() - started) / 1000)}s`), PROGRESS_EVERY_MS)
+ : null
+ if (heartbeat) heartbeat.unref()
+ function done(status, stdout, stderr) {
+ if (t) clearTimeout(t)
+ if (heartbeat) clearInterval(heartbeat)
+ progress(label, `done status=${status} elapsed=${Math.round((Date.now() - started) / 1000)}s`)
+ resolve({ status, stdout, stderr })
+ }
child.stdout.on('data', d => { out += d })
child.stderr.on('data', d => { err += d })
- child.on('error', e => { if (t) clearTimeout(t); resolve({ status: 1, stdout: out, stderr: String(e.message) }) })
- child.on('close', code => { if (t) clearTimeout(t); resolve({ status: killed ? 124 : (code ?? 1), stdout: out, stderr: err }) })
- if (input != null) { child.stdin.on('error', () => {}); child.stdin.write(input); child.stdin.end() }
+ child.on('error', e => done(1, out, String(e.message)))
+ child.on('close', code => done(killed ? 124 : (code ?? 1), out, err))
+ // stdin is always closed: a CLI that reads stdin by default hangs forever on
+ // an open pipe when the prompt went in as an argument (no input here).
+ child.stdin.on('error', () => {})
+ if (input != null) child.stdin.write(input)
+ child.stdin.end()
})
}
-const CONFIG_PROVIDER = process.env.MNEMAZINE_LLM || ''
-const TIMEOUT_MS = Number(process.env.MNEMAZINE_LLM_TIMEOUT_MS || '420000')
-const CODEX_BIN = process.env.MNEMAZINE_CODEX_BIN || '/Applications/Codex.app/Contents/Resources/codex'
+// --- registry (lazy, cached) --------------------------------------------------
+// Loaded on first real use, so the conservative local-only path never touches
+// it. A hidden/unreadable registry throws loudly here — no silent fall back to
+// old literals (that path is gone).
+let _registry
+function registry() {
+ if (_registry) return _registry
+ return (_registry = loadRegistry())
+}
-const HOME = os.homedir()
+function getEntry(provider) {
+ const entry = registry()[provider]
+ if (!entry) throw new Error(`provider ${provider} not in registry`)
+ return entry
+}
-// Resolve the Claude CLI independently of how it was installed (npm global,
-// standalone installer, Homebrew, Claude Desktop, or the VSCode extension). Tries,
-// in order: explicit env -> login-shell PATH (respects the user's real install)
-// -> common absolute locations -> newest VSCode extension binary. Cached.
-let _claudeBin
-let _defaultProvider
-function resolveClaudeBin() {
- if (_claudeBin !== undefined) return _claudeBin
- if (process.env.MNEMAZINE_CLAUDE_BIN) return (_claudeBin = process.env.MNEMAZINE_CLAUDE_BIN)
- // Login shell: picks up however the user installed claude (Desktop/npm/etc.).
- const shell = process.env.SHELL || '/bin/zsh'
- const viaShell = spawnSync(shell, ['-lic', 'command -v claude'], { encoding: 'utf8' }).stdout || ''
- const shellHit = viaShell.trim().split('\n').pop()
- if (shellHit && existsSync(shellHit)) return (_claudeBin = shellHit)
- const candidates = [
+function providerChain(dataClass, capabilities) {
+ const { candidates } = orderCandidates(registry(), { dataClass, capabilities })
+ return candidates.map(c => c.name)
+}
+
+// --- binary resolution (generic, per invoke[0]) -------------------------------
+// The binary is invoke[0], resolved via env override (MNEMAZINE__BIN),
+// then the login shell (however the user installed it), then a small table of
+// known install locations, then a bare PATH lookup at spawn. resolveClaudeBin's
+// knowledge survives as the `claude` entry of EXTRA_CANDIDATES — data, not a
+// name branch.
+const EXTRA_CANDIDATES = {
+ claude: [
path.join(HOME, '.claude/local/claude'),
'/opt/homebrew/bin/claude',
'/usr/local/bin/claude',
@@ -54,17 +103,21 @@ function resolveClaudeBin() {
path.join(HOME, '.npm-global/bin/claude'),
'/Applications/Claude.app/Contents/Resources/claude'
]
- for (const c of candidates) if (existsSync(c)) return (_claudeBin = c)
- // Newest VSCode extension native binary, if present.
- const extDir = path.join(HOME, '.vscode/extensions')
- try {
- const dirs = readdirSync(extDir).filter(d => d.startsWith('anthropic.claude-code-')).sort()
- for (const d of dirs.reverse()) {
- const bin = path.join(extDir, d, 'resources/native-binary/claude')
- if (existsSync(bin)) return (_claudeBin = bin)
- }
- } catch {}
- return (_claudeBin = 'claude') // last resort: bare PATH lookup at spawn time
+}
+const _binCache = {}
+function envBinKey(binName) {
+ return `MNEMAZINE_${binName.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_BIN`
+}
+function resolveBin(binName) {
+ if (_binCache[binName] !== undefined) return _binCache[binName]
+ const override = process.env[envBinKey(binName)]
+ if (override) return (_binCache[binName] = override)
+ const shell = process.env.SHELL || '/bin/zsh'
+ const viaShell = spawnSync(shell, ['-lic', `command -v ${binName}`], { encoding: 'utf8' }).stdout || ''
+ const hit = viaShell.trim().split('\n').pop()
+ if (hit && existsSync(hit)) return (_binCache[binName] = hit)
+ for (const c of (EXTRA_CANDIDATES[binName] || [])) if (existsSync(c)) return (_binCache[binName] = c)
+ return (_binCache[binName] = binName) // last resort: bare PATH lookup at spawn time
}
function binExists(bin) {
@@ -73,13 +126,22 @@ function binExists(bin) {
return which.status === 0 && Boolean(which.stdout.trim())
}
+function requireBin(provider, entry) {
+ const bin = resolveBin(entry.invoke[0])
+ if (!binExists(bin)) throw new Error(`${provider}: binary not found (${entry.invoke[0]}); set ${envBinKey(entry.invoke[0])}`)
+ return bin
+}
+
+// --- provider resolution ------------------------------------------------------
+let _defaultProvider
export function defaultProvider() {
if (_defaultProvider) return _defaultProvider
- if (CONFIG_PROVIDER) return CONFIG_PROVIDER
- const claudeBin = resolveClaudeBin()
- if (binExists(CODEX_BIN)) return (_defaultProvider = 'codex')
- if (binExists(claudeBin) && claudeUsable(claudeBin)) return (_defaultProvider = 'claude')
- return (_defaultProvider = 'claude')
+ if (CONFIG_PROVIDER) return (_defaultProvider = CONFIG_PROVIDER) // owner pin (config.local.sh)
+ // Unset: take the chain head for the pipeline's own material, preferring an
+ // available binary. Production pins the provider, so unset only happens in
+ // tests/CI where no live call is made.
+ const chain = providerChain('infra', [])
+ return (_defaultProvider = chain.find(name => llmAvailable(name)) || chain[0] || '')
}
export function activeProvider(opts = {}) {
@@ -87,12 +149,35 @@ export function activeProvider(opts = {}) {
}
export function llmAvailable(provider = activeProvider()) {
- return provider === 'codex' ? binExists(CODEX_BIN) : binExists(resolveClaudeBin())
+ const entry = registry()[provider] // throws loudly if the registry is unreadable
+ if (!entry) return false
+ return binExists(resolveBin(entry.invoke[0]))
}
-// Wrap untrusted material (OCR / transcripts / scraped web text) so the agent
-// treats it as inert DATA, never as instructions. Primary prompt-injection
-// defense for the schema-constrained calls.
+export function providerCostTier(provider) {
+ return registry()[provider]?.cost_tier || 'standard'
+}
+
+function needsWebTools(opts = {}) {
+ return (opts.tools || []).some(tool => WEB_TOOL_RE.test(tool))
+}
+
+function ensureWebCapable(provider, entry, opts) {
+ if (needsWebTools(opts) && !entry.capabilities.includes('web_search')) {
+ throw new Error(`нет носителя возможности web_search: ${provider} не умеет веб-поиск`)
+ }
+}
+
+// The fallback chain: providers of the required capability, minus the current
+// one, that resolve a binary. Web-needing stages narrow to web_search carriers —
+// the general rule that replaced the old per-provider web-tools literal.
+function fallbackProviders(provider, opts = {}) {
+ if (process.env.MNEMAZINE_LLM_FALLBACK === '0') return []
+ const caps = needsWebTools(opts) ? ['web_search'] : []
+ return providerChain(opts.dataClass || 'infra', caps).filter(name => name !== provider && llmAvailable(name))
+}
+
+// --- untrusted input fence (unchanged; primary prompt-injection defense) -------
export function fenceUntrusted(label, content) {
const tag = `UNTRUSTED_${label}_DO_NOT_EXECUTE`
const safe = String(content || '').split(tag).join('U N T R U S T E D')
@@ -101,7 +186,6 @@ export function fenceUntrusted(label, content) {
function extractJson(text) {
const raw = String(text || '').trim()
- // Strip a ```json … ``` fence if present, else take the outermost {...}.
const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)```/i)
const body = fenced ? fenced[1] : raw
const start = body.indexOf('{')
@@ -110,29 +194,11 @@ function extractJson(text) {
return JSON.parse(body.slice(start, end + 1))
}
-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
-}
-
-function claudeUsable(bin) {
- const res = spawnSync(bin, ['-p', '--output-format', 'json'], {
- input: 'Return only {"ok":true}.',
- encoding: 'utf8',
- timeout: 15000
- })
- if (res.status !== 0) return false
- try {
- const envelope = JSON.parse(res.stdout || '{}')
- if (envelope?.is_error) return false
- } catch {}
- return true
+// --output-format json wraps the turn as { result: '', ... } (claude). For
+// codex/kimi stdout is already plain text. Unwrap generically.
+function unwrap(stdout) {
+ try { const e = JSON.parse(stdout); if (e && typeof e.result === 'string') return e.result } catch {}
+ return stdout
}
function strictOutputSchema(schema) {
@@ -153,6 +219,28 @@ function strictOutputSchema(schema) {
return out
}
+function assertSchema(value, schema, where = '$') {
+ if (!schema || typeof schema !== 'object') return
+ if ('const' in schema && value !== schema.const) throw new Error(`${where}: expected constant value`)
+ if (schema.type === 'object') {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${where}: expected object`)
+ for (const key of schema.required || []) if (!(key in value)) throw new Error(`${where}.${key}: required`)
+ const properties = schema.properties || {}
+ if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in properties)) throw new Error(`${where}.${key}: unexpected`)
+ for (const [key, child] of Object.entries(properties)) if (key in value) assertSchema(value[key], child, `${where}.${key}`)
+ }
+ if (schema.type === 'array') {
+ if (!Array.isArray(value)) throw new Error(`${where}: expected array`)
+ if (schema.minItems && value.length < schema.minItems) throw new Error(`${where}: too few items`)
+ value.forEach((item, index) => assertSchema(item, schema.items, `${where}[${index}]`))
+ }
+ if (schema.type === 'string') {
+ if (typeof value !== 'string') throw new Error(`${where}: expected string`)
+ if (schema.minLength && value.length < schema.minLength) throw new Error(`${where}: empty string`)
+ }
+ if (schema.type === 'boolean' && typeof value !== 'boolean') throw new Error(`${where}: expected boolean`)
+}
+
function procError(label, res) {
const stderr = String(res.stderr || '').trim()
if (stderr) return `${label} failed (status ${res.status}): ${stderr.slice(-400)}`
@@ -161,80 +249,152 @@ function procError(label, res) {
return `${label} failed (status ${res.status}): empty stderr/stdout`
}
-// --- Codex backend (headless pattern: --output-schema + -o) ---
-async function codexJsonCall(prompt, schema, opts) {
- if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
- const work = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-codex-'))
+// Prompt goes on stdin when the CLI declares stdin_prompt; otherwise as the last
+// argv element, bounded by ARG_MAX (never truncated — over the ceiling is a
+// named failure that moves to the next CLI in the chain).
+function deliverPrompt(entry, args, prompt) {
+ if (entry.capabilities.includes('stdin_prompt')) return { args, input: prompt }
+ const bytes = [...args, prompt].reduce((n, a) => n + Buffer.byteLength(String(a)) + 1, 0)
+ if (bytes > ARG_MAX) throw new Error(`prompt exceeds ARG_MAX (${bytes} > ${ARG_MAX}); argv delivery impossible`)
+ return { args: [...args, prompt], input: undefined }
+}
+
+// Tool enabling is per schema-mechanism adapter: the inline adapter (claude)
+// grants tools via --allowedTools; the file adapter (codex) turns on web search
+// with the top-level --search inserted before `exec`. A new CLI using an
+// existing mechanism inherits this; a genuinely new mechanism is a new adapter.
+function withAllowedTools(args, opts) {
+ const tools = opts.tools || []
+ return tools.length ? [...args, '--allowedTools', tools.join(',')] : args
+}
+function insertSearch(args, entry, opts) {
+ if (!needsWebTools(opts) || !entry.capabilities.includes('web_search')) return args
+ const a = [...args]
+ const i = a.indexOf('exec')
+ if (i >= 0) a.splice(i, 0, '--search'); else a.unshift('--search')
+ return a
+}
+function insertCwd(args, cwd) {
+ const a = [...args]
+ const i = a.indexOf('exec')
+ if (i >= 0) a.splice(i + 1, 0, '-C', cwd); else a.push('-C', cwd)
+ return a
+}
+
+// --- schema adapters (chosen by capability) -----------------------------------
+async function inlineSchemaJson(provider, entry, prompt, schema, opts) {
+ const bin = requireBin(provider, entry)
+ let args = withAllowedTools(entry.invoke.slice(1), opts)
+ args = [...args, '--json-schema', JSON.stringify(strictOutputSchema(schema))]
+ const { args: finalArgs, input } = deliverPrompt(entry, args, prompt)
+ const res = await runProc(bin, finalArgs, { input, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-json` })
+ if (res.status !== 0) throw new Error(procError(`${provider} json`, res))
+ return extractJson(unwrap(res.stdout))
+}
+
+async function fileSchemaJson(provider, entry, prompt, schema, opts) {
+ const bin = requireBin(provider, entry)
+ const work = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-cli-'))
const cwd = opts.cwd || work
const schemaFile = path.join(work, 'schema.json')
const outFile = path.join(work, 'out.json')
- const promptFile = path.join(work, 'prompt.md')
await fs.writeFile(schemaFile, JSON.stringify(strictOutputSchema(schema)), { encoding: 'utf8', mode: 0o600 })
- await fs.writeFile(promptFile, prompt, { encoding: 'utf8', mode: 0o600 })
try {
- const res = await runProc(CODEX_BIN, [
- ...codexExecArgs(cwd, opts),
- '--output-schema', schemaFile, '-o', outFile, '-'
- ], { input: await fs.readFile(promptFile, 'utf8'), timeoutMs: opts.timeoutMs || TIMEOUT_MS })
- if (res.status !== 0) throw new Error(procError('codex exec', res))
+ let args = insertSearch(entry.invoke.slice(1), entry, opts)
+ args = insertCwd(args, cwd)
+ args = [...args, '--output-schema', schemaFile, '-o', outFile, '-'] // prompt via stdin
+ const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-json${needsWebTools(opts) ? ':search' : ''}` })
+ if (res.status !== 0) throw new Error(procError(`${provider} exec`, res))
const raw = await fs.readFile(outFile, 'utf8').catch(() => '')
- if (!raw.trim()) throw new Error('codex returned empty output')
- try { return JSON.parse(raw) } catch (err) { throw new Error(`codex returned non-JSON: ${err.message}; head: ${raw.slice(0, 200)}`) }
+ if (!raw.trim()) throw new Error(`${provider} returned empty output`)
+ try { return JSON.parse(raw) } catch (err) { throw new Error(`${provider} returned non-JSON: ${err.message}; head: ${raw.slice(0, 200)}`) }
} finally {
await fs.rm(work, { recursive: true, force: true }).catch(() => {})
}
}
-// --- Claude backend (headless `claude -p`, JSON instructed in-prompt) ---
-// 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
-// pass WebSearch/WebFetch (+ MCP) to let Claude research with available tools.
-// Never uses the permission-bypass flag (constitution): unpermitted tools
-// simply do not run in -p mode.
-async function claudeJsonCall(prompt, schema, opts) {
- const bin = resolveClaudeBin()
- if (!binExists(bin)) throw new Error(`claude binary not found (tried env, PATH, common installs, VSCode): set MNEMAZINE_CLAUDE_BIN`)
- const tools = opts.tools || []
- const full = `${prompt}\n\nReturn ONLY a single JSON object matching this JSON Schema (no prose, no code fence):\n${JSON.stringify(schema)}`
- const args = ['-p', '--output-format', 'json']
- if (tools.length) args.push('--allowedTools', tools.join(','))
- const res = await runProc(bin, args, { input: full, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
- if (res.status !== 0) throw new Error(procError('claude -p', res))
- // --output-format json wraps the turn: { type:'result', result:'', ... }
- let envelope
- try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
- const text = envelope && typeof envelope.result === 'string' ? envelope.result : res.stdout
- return extractJson(text)
+async function inPromptJson(provider, entry, prompt, schema, opts) {
+ const bin = requireBin(provider, entry)
+ const full = `${prompt}\n\nReturn ONLY a single JSON object matching this JSON Schema (no prose, no code fence):\n${JSON.stringify(strictOutputSchema(schema))}`
+ const { args: finalArgs, input } = deliverPrompt(entry, entry.invoke.slice(1), full)
+ const res = await runProc(bin, finalArgs, { input, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-json` })
+ if (res.status !== 0) throw new Error(procError(`${provider} json`, res))
+ const output = extractJson(unwrap(res.stdout))
+ assertSchema(output, strictOutputSchema(schema))
+ return output
}
-// One schema-instructed call. Returns the parsed/validated-ish JSON object or
-// throws (callers degrade gracefully). provider via opts.provider or MNEMAZINE_LLM.
+async function jsonOnce(provider, prompt, schema, opts) {
+ const entry = getEntry(provider)
+ ensureWebCapable(provider, entry, opts)
+ const adapter = pickSchemaAdapter(entry)
+ if (adapter === 'json_schema_file') return fileSchemaJson(provider, entry, prompt, schema, opts)
+ if (adapter === 'json_schema_inline') return inlineSchemaJson(provider, entry, prompt, schema, opts)
+ return inPromptJson(provider, entry, prompt, schema, opts) // json_in_prompt (or a CLI declaring no schema mechanism)
+}
+
+// One schema-instructed call. Returns the parsed JSON object or throws (callers
+// degrade gracefully). Provider via opts.provider or MNEMAZINE_LLM; on failure
+// walks the capability-filtered fallback chain.
export async function llmJson(prompt, schema, opts = {}) {
const provider = activeProvider(opts)
- return provider === 'codex' ? codexJsonCall(prompt, schema, opts) : claudeJsonCall(prompt, schema, opts)
+ const chain = [...new Set([provider, ...fallbackProviders(provider, opts)])]
+ let lastError
+ for (const candidate of chain) {
+ try {
+ const result = await jsonOnce(candidate, prompt, schema, opts)
+ // Surface the ACTUAL executor next to the result (not the requested one).
+ // A silent fallback is now observable: the caller can print provider_used
+ // and see that `deadcli` was answered by `claude`.
+ opts.provider_used = candidate
+ return result
+ }
+ catch (error) {
+ lastError = error
+ progress(opts.label || 'json', `fallback ${candidate}: ${String(error.message || error).slice(0, 160)}`)
+ }
+ }
+ throw lastError || new Error('no provider available for llmJson')
}
-// Plain-text call (no schema) — used for vision/extraction fallback where the
-// agent reads a local file (image/PDF) and transcribes it. Tools opt-in; for
-// file reading pass tools:['Read']. Returns raw text. Claude primary; Codex at
-// parity (runs in the file's directory so it can open it).
-export async function llmText(prompt, opts = {}) {
- const provider = activeProvider(opts)
- if (provider === 'codex') {
- if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
- const res = await runProc(CODEX_BIN, [
- ...codexExecArgs(opts.cwd || process.cwd(), opts), '-'
- ], { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
- if (res.status !== 0) throw new Error(procError('codex exec', res))
+// --- plain-text path (no schema; vision/extraction fallback) ------------------
+async function textOnce(provider, prompt, opts) {
+ const entry = getEntry(provider)
+ ensureWebCapable(provider, entry, opts)
+ const bin = requireBin(provider, entry)
+ const adapter = pickSchemaAdapter(entry)
+ if (adapter === 'json_schema_file') {
+ let args = insertSearch(entry.invoke.slice(1), entry, opts)
+ args = insertCwd(args, opts.cwd || process.cwd())
+ args = [...args, '-']
+ const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-text${needsWebTools(opts) ? ':search' : ''}` })
+ if (res.status !== 0) throw new Error(procError(`${provider} exec`, res))
return String(res.stdout || '').trim()
}
- const bin = resolveClaudeBin()
- if (!binExists(bin)) throw new Error('claude binary not found: set MNEMAZINE_CLAUDE_BIN')
- const args = ['-p', '--output-format', 'json']
- if (opts.tools?.length) args.push('--allowedTools', opts.tools.join(','))
- const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
- if (res.status !== 0) throw new Error(procError('claude -p', res))
- let envelope
- try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
- return (envelope && typeof envelope.result === 'string' ? envelope.result : res.stdout).trim()
+ // Flat-invoke CLI (claude inline / kimi in-prompt): tools via --allowedTools
+ // only where the mechanism supports it (inline adapter).
+ let args = entry.invoke.slice(1)
+ if (adapter === 'json_schema_inline') args = withAllowedTools(args, opts)
+ const { args: finalArgs, input } = deliverPrompt(entry, args, prompt)
+ const res = await runProc(bin, finalArgs, { input, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-text` })
+ if (res.status !== 0) throw new Error(procError(`${provider} text`, res))
+ return unwrap(res.stdout).trim()
+}
+
+export async function llmText(prompt, opts = {}) {
+ const provider = activeProvider(opts)
+ const chain = [...new Set([provider, ...fallbackProviders(provider, opts)])]
+ let lastError
+ for (const candidate of chain) {
+ try {
+ const result = await textOnce(candidate, prompt, opts)
+ opts.provider_used = candidate // actual executor, so a fallback is never silent
+ return result
+ }
+ catch (error) {
+ lastError = error
+ progress(opts.label || 'text', `fallback ${candidate}: ${String(error.message || error).slice(0, 160)}`)
+ }
+ }
+ throw lastError || new Error('no provider available for llmText')
}
diff --git a/scripts/mnemazine-local-engines.mjs b/scripts/mnemazine-local-engines.mjs
new file mode 100644
index 0000000..9fb46e0
--- /dev/null
+++ b/scripts/mnemazine-local-engines.mjs
@@ -0,0 +1,89 @@
+#!/usr/bin/env node
+// Single source of truth about local extraction engines (rule 8). The five
+// presence checks — vision-ocr, markitdown, whisper, ffmpeg, rg — live HERE and
+// nowhere else: mnemazine-run.mjs and mnemazine-live-preflight.sh consume this
+// module instead of re-encoding `command -v markitdown` in their own words.
+//
+// The point this module exists to serve (П10): distinguish «движка нет» from
+// «движок ничего не нашёл». engineStatus() answers ONLY presence; a present
+// engine that returns empty text is the caller's «не нашёл», not this module's
+// «missing». That split is what lets the runner stop instead of silently
+// reaching for the cloud.
+import { accessSync, constants } from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+// ROOT is resolved from the module's own location (so vision-ocr is found
+// regardless of cwd), overridable by MNEMAZINE_ROOT to match the runner.
+const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+
+// kind: 'binary-path' → a file at a repo-relative path (survives PATH edits);
+// 'path-command' → resolved via PATH exactly as spawnSync(cmd) would (execvp).
+// required_for: which extraction purposes need this engine (documentation + report).
+export const ENGINES = {
+ 'vision-ocr': { kind: 'binary-path', path: '.mnemazine/bin/vision-ocr', required_for: ['image', 'video-frames'] },
+ markitdown: { kind: 'path-command', probe: 'markitdown', required_for: ['pdf', 'docx', 'pptx', 'xlsx', 'html'] },
+ whisper: { kind: 'path-command', probe: 'whisper', required_for: ['video-audio'] },
+ ffmpeg: { kind: 'path-command', probe: 'ffmpeg', required_for: ['video'] },
+ rg: { kind: 'path-command', probe: 'rg', required_for: ['audit', 'search'] }
+}
+
+// Same resolution as spawnSync(cmd) with no shell: scan process PATH for an
+// executable of that name. NOT a login shell — the runner spawns directly, so a
+// login-shell-only PATH would over-report presence the runner can't actually use.
+function onPath(cmd) {
+ for (const dir of (process.env.PATH || '').split(path.delimiter)) {
+ if (!dir) continue
+ try { accessSync(path.join(dir, cmd), constants.X_OK); return true } catch { /* next dir */ }
+ }
+ return false
+}
+
+// 'present' | 'missing' — never a third value, never a throw for a known engine.
+export function engineStatus(name) {
+ const engine = ENGINES[name]
+ if (!engine) throw new Error(`unknown local engine: ${name}`)
+ if (engine.kind === 'binary-path') {
+ try { accessSync(path.join(ROOT, engine.path), constants.X_OK); return 'present' } catch { return 'missing' }
+ }
+ return onPath(engine.probe) ? 'present' : 'missing'
+}
+
+// The subset of `list` that is missing. Empty array ⇒ every required engine is
+// on hand. Callers gate on `.length`, never on presence-by-name in their own code.
+export function requireEngines(list) {
+ return list.filter(name => engineStatus(name) === 'missing')
+}
+
+// --- CLI: report / selftest ---------------------------------------------------
+function report(asJson) {
+ const rows = Object.keys(ENGINES).map(name => ({
+ name, kind: ENGINES[name].kind, status: engineStatus(name), required_for: ENGINES[name].required_for
+ }))
+ if (asJson) console.log(JSON.stringify(rows))
+ else for (const r of rows) console.log(`${r.status === 'present' ? 'ok' : 'fail'} ${r.name} ${r.status}`)
+ return rows.every(r => r.status === 'present') ? 0 : 1
+}
+
+function selftest() {
+ const assert = (cond, msg) => { if (!cond) throw new Error(`selftest: ${msg}`) }
+ for (const name of Object.keys(ENGINES)) assert(['present', 'missing'].includes(engineStatus(name)), `${name} status enum`)
+ let threw = false
+ try { engineStatus('mnemazine-no-such-engine-9000') } catch { threw = true }
+ assert(threw, 'unknown engine throws, never silent missing')
+ const missing = requireEngines(Object.keys(ENGINES))
+ assert(Array.isArray(missing) && missing.every(n => engineStatus(n) === 'missing'), 'requireEngines is the missing subset')
+ console.log(JSON.stringify({ ok: true, selftest: 'local-engines', engines: Object.keys(ENGINES) }))
+ return 0
+}
+
+function main() {
+ const args = process.argv.slice(2)
+ if (args.includes('--selftest')) return selftest()
+ if (args.includes('--json')) return report(true)
+ return report(false) // --report or bare
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ process.exit(main())
+}
diff --git a/scripts/mnemazine-machine-class-gate.mjs b/scripts/mnemazine-machine-class-gate.mjs
new file mode 100644
index 0000000..1f983d9
--- /dev/null
+++ b/scripts/mnemazine-machine-class-gate.mjs
@@ -0,0 +1,232 @@
+#!/usr/bin/env node
+// Machine-class barrier (П24). The router (П04) answers "which CLI may SEE a
+// class"; this gate answers "which MACHINE may PROCESS a note" — the second
+// border, same single truth: config/data-classes.json (rule 8 of the method).
+//
+// A note's class is the MAX over the order among all fired rules (strict wins):
+// 1. explicit `data_class:` in frontmatter — may RAISE, never LOWER
+// 2. by_section[section] — section field or parent-dir name
+// 3. source inheritance — projects∈by_project | source∈by_source_pattern
+// No rule fired: a KNOWN section (the section name is a real directory in the
+// note's own path) → text (ordinary material, VPS-ok); an UNKNOWN/new section
+// → exit 2 (a new section can't silently become sendable); broken/absent
+// frontmatter → default (personal) → the batch reddens with 1.
+//
+// Exit codes:
+// --classify 0 class printed with the firing rule · 2 undeterminable
+// --batch --target 0 clean · 1 a class blocked on target (names first) · 2 undeterminable/empty
+// --selftest 0 fixtures pass · 1 a fixture disagrees
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parseArgs } from 'node:util'
+
+const HERE = path.dirname(fileURLToPath(import.meta.url))
+export const TAXONOMY_PATH = path.join(HERE, '..', 'config', 'data-classes.json')
+const FIXTURES = path.join(HERE, '..', 'tests', 'fixtures', 'data-classes')
+
+export function loadTaxonomy(file = TAXONOMY_PATH) {
+ const t = JSON.parse(readFileSync(file, 'utf8'))
+ for (const k of ['order', 'classes', 'by_section', 'by_project', 'by_source_pattern', 'default']) {
+ if (!(k in t)) throw new Error(`config/data-classes.json: нет поля ${k}`)
+ }
+ return t
+}
+
+function unquote(s) { return s.replace(/^["']/, '').replace(/["']$/, '') }
+
+// Minimal frontmatter reader: the block between the first `---` and the next
+// `---`. Absent block or no closing fence → not ok (fail-closed to default).
+export function parseFrontmatter(text) {
+ const lines = text.split('\n')
+ if (lines[0].trim() !== '---') return { ok: false }
+ let end = -1
+ for (let i = 1; i < lines.length; i++) { if (lines[i].trim() === '---') { end = i; break } }
+ if (end === -1) return { ok: false }
+ const fields = { projects: [], sources: [] }
+ let listKey = null
+ for (const raw of lines.slice(1, end)) {
+ const line = raw.replace(/\s+$/, '')
+ if (listKey && /^\s*-\s+/.test(line)) { fields[listKey].push(unquote(line.replace(/^\s*-\s+/, '').trim())); continue }
+ const m = line.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/)
+ if (!m) { listKey = null; continue }
+ const key = m[1]; const val = m[2].trim(); listKey = null
+ if (val === '') { if (key === 'projects' || key === 'sources') listKey = key; continue }
+ if ((key === 'projects' || key === 'sources') && val.startsWith('[')) {
+ fields[key] = val.replace(/^\[/, '').replace(/\]$/, '').split(',').map(s => unquote(s.trim())).filter(Boolean)
+ continue
+ }
+ if (key === 'data_class') fields.data_class = unquote(val)
+ else if (key === 'section') fields.section = unquote(val)
+ else if (key === 'source') fields.source = unquote(val)
+ }
+ return { ok: true, fields }
+}
+
+const firstSegment = sec => sec.split('/')[0].trim()
+
+function bySectionMatch(sec, taxonomy) {
+ for (const key of Object.keys(taxonomy.by_section)) {
+ if (sec === key || firstSegment(sec) === key) return { klass: taxonomy.by_section[key], key }
+ }
+ return null
+}
+
+function sourceInherit(fields, taxonomy) {
+ const fired = []
+ for (const proj of fields.projects || []) {
+ if (taxonomy.by_project[proj]) fired.push({ klass: taxonomy.by_project[proj], rule: `by_project «${proj}»` })
+ }
+ const srcs = [fields.source, ...(fields.sources || [])].filter(Boolean)
+ for (const [pat, klass] of Object.entries(taxonomy.by_source_pattern)) {
+ const re = new RegExp(pat)
+ if (srcs.some(s => re.test(s))) fired.push({ klass, rule: `by_source_pattern «${pat}»` })
+ }
+ return fired
+}
+
+// Pure classification. `sec` is the resolved section; `knownSections` is a Set
+// of names treated as existing vault sections. Returns { klass, rule } or
+// { undetermined: true, section } for a new/unknown section.
+export function classifyNote(fields, sec, taxonomy, knownSections) {
+ const rank = k => taxonomy.order.indexOf(k)
+ const fired = []
+ if (fields.data_class) {
+ if (!taxonomy.classes[fields.data_class]) return { undetermined: true, section: sec, badClass: fields.data_class }
+ fired.push({ klass: fields.data_class, rule: 'data_class (явное поле)' })
+ }
+ if (sec) { const m = bySectionMatch(sec, taxonomy); if (m) fired.push({ klass: m.klass, rule: `by_section «${m.key}»` }) }
+ for (const r of sourceInherit(fields, taxonomy)) fired.push(r)
+
+ if (fired.length) {
+ fired.sort((a, b) => rank(b.klass) - rank(a.klass)) // max by order — strict wins
+ return { klass: fired[0].klass, rule: fired[0].rule }
+ }
+ if (sec) {
+ if (knownSections.has(firstSegment(sec))) return { klass: 'text', rule: `известный раздел «${firstSegment(sec)}» без спец-правила → text` }
+ return { undetermined: true, section: sec } // new/unknown section → exit 2
+ }
+ return { klass: taxonomy.default, rule: `default (${taxonomy.default})` }
+}
+
+// A note's "known sections" are self-located: the directory names in its own
+// path. A section is real iff the note physically lives inside a dir of that
+// name — no config, no hardcoded vault name (public-release safe). Selftest
+// injects a fixed set so it stays hermetic. `sec` defaults to the parent dir.
+export function classifyFile(filePath, taxonomy, knownOverride) {
+ let text
+ try { text = readFileSync(filePath, 'utf8') } catch { return { undetermined: true, section: null, reason: `файл не прочитан: ${filePath}` } }
+ const fm = parseFrontmatter(text)
+ if (!fm.ok) return { klass: taxonomy.default, rule: `битый/отсутствующий frontmatter → default (${taxonomy.default})` }
+ const abs = path.resolve(filePath)
+ const sec = fm.fields.section || path.basename(path.dirname(abs))
+ const known = knownOverride || new Set(path.dirname(abs).split(path.sep))
+ return classifyNote(fm.fields, sec, taxonomy, known)
+}
+
+// --- CLI modes ---------------------------------------------------------------
+
+function runClassify(file, taxonomy) {
+ const res = classifyFile(file, taxonomy)
+ if (res.undetermined) {
+ console.error(`НЕ ОПРЕДЕЛЁН: ${res.badClass ? `неизвестный класс «${res.badClass}»` : `раздел вне таксономии «${res.section}»`} (${path.basename(file)})`)
+ return 2
+ }
+ console.log(`${res.klass} (правило: ${res.rule})`)
+ return 0
+}
+
+function runBatch(manifest, target, taxonomy) {
+ if (!['mac', 'vps'].includes(target)) { console.error(`--target должен быть mac|vps, получено: ${target}`); return 2 }
+ let raw
+ try { raw = readFileSync(manifest, 'utf8') } catch { console.error(`манифест не прочитан: ${manifest}`); return 2 }
+ const files = raw.split('\n').map(s => s.trim()).filter(Boolean)
+ if (!files.length) { console.error('пустой манифест — 0 нот, это отказ, а не «проверено 0 ✓»'); return 2 }
+
+ const undetermined = []
+ const blocked = []
+ for (const f of files) {
+ const res = classifyFile(f, taxonomy)
+ if (res.undetermined) { undetermined.push({ f, res }); continue }
+ if (!taxonomy.classes[res.klass].machines.includes(target)) blocked.push({ f, res })
+ }
+ if (undetermined.length) {
+ const { f, res } = undetermined[0]
+ console.error(`ОТКАЗ (2): класс не определяется — ${res.badClass ? `неизвестный класс «${res.badClass}»` : `раздел вне таксономии «${res.section}»`} в ${f}`)
+ return 2
+ }
+ if (blocked.length) {
+ const { f, res } = blocked[0]
+ console.error(`ОТКАЗ (1): ${f} — класс ${res.klass} (${res.rule}) не разрешён на ${target} (разрешено: ${taxonomy.classes[res.klass].machines.join(',')})`)
+ console.error(`всего заблокировано: ${blocked.length} из ${files.length}`)
+ return 1
+ }
+ console.log(`чисто: ${files.length} нот, все разрешены на ${target}`)
+ return 0
+}
+
+// --- selftest (hermetic: injected knownSections, no disk beyond fixtures) -----
+function selftest(taxonomy) {
+ const known = new Set(['08 AI и Инструменты', '01 Право и Юриспруденция', '02 Здоровье'])
+ const cf = f => classifyFile(path.join(FIXTURES, f), taxonomy, known)
+ const cases = [
+ ['no-field.md', r => r.klass === 'text', 'известный раздел без правила → text'],
+ ['pd-section.md', r => r.klass === 'pd', 'by_section → pd'],
+ ['personal-section.md', r => r.klass === 'personal', 'by_section → personal'],
+ ['explicit-raise.md', r => r.klass === 'pd', 'явное поле поднимает text→pd'],
+ ['lower-trap.md', r => r.klass === 'pd', 'явное data_class:text НЕ опускает pd (строгое побеждает)'],
+ ['inherit-source.md', r => r.klass === 'pd', 'by_source_pattern → pd'],
+ ['inherit-project.md', r => r.klass === 'pd', 'by_project → pd'],
+ ['unknown-section.md', r => r.undetermined === true, 'раздел вне таксономии → undetermined(2)'],
+ ['broken-frontmatter.md', r => r.klass === 'personal', 'битый frontmatter → default personal']
+ ]
+ const fail = []
+ for (const [file, ok, why] of cases) {
+ let r
+ try { r = cf(file) } catch (e) { fail.push(`${file}: бросил ${e.message}`); continue }
+ if (!ok(r)) fail.push(`${file}: ${why} — получено ${JSON.stringify(r)}`)
+ }
+ // batch-level semantics on the same fixtures
+ const batch = (fileList, target) => {
+ const und = [], blk = []
+ for (const f of fileList) {
+ const res = classifyFile(path.join(FIXTURES, f), taxonomy, known)
+ if (res.undetermined) { und.push(res); continue }
+ if (!taxonomy.classes[res.klass].machines.includes(target)) blk.push(res)
+ }
+ return und.length ? 2 : blk.length ? 1 : 0
+ }
+ if (batch(['no-field.md'], 'vps') !== 0) fail.push('batch: чистая (text) на vps должна быть 0')
+ if (batch(['pd-section.md'], 'vps') !== 1) fail.push('batch: pd на vps должна быть 1')
+ if (batch(['pd-section.md'], 'mac') !== 0) fail.push('batch: pd на mac должна быть 0')
+ if (batch(['personal-section.md'], 'vps') !== 1) fail.push('batch: personal на vps должна быть 1')
+ if (batch(['unknown-section.md'], 'vps') !== 2) fail.push('batch: unknown-section должна быть 2')
+
+ if (fail.length) { console.error('selftest ПРОВАЛ:\n' + fail.join('\n')); return 1 }
+ console.log(JSON.stringify({ ok: true, selftest: 'machine-class-gate', fixtures: cases.length }))
+ return 0
+}
+
+function main() {
+ const { values } = parseArgs({
+ options: {
+ classify: { type: 'string' },
+ batch: { type: 'string' },
+ target: { type: 'string' },
+ selftest: { type: 'boolean', default: false }
+ },
+ allowPositionals: false
+ })
+ let taxonomy
+ try { taxonomy = loadTaxonomy() } catch (e) { console.error(`ОТКАЗ (2): ${e.message}`); return 2 }
+
+ if (values.selftest) return selftest(taxonomy)
+ if (values.classify) return runClassify(values.classify, taxonomy)
+ if (values.batch) return runBatch(values.batch, values.target || '', taxonomy)
+ console.error('использование: --classify <файл> | --batch <манифест> --target mac|vps | --selftest')
+ return 2
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ process.exit(main())
+}
diff --git a/scripts/mnemazine-merge-semantic-shards.mjs b/scripts/mnemazine-merge-semantic-shards.mjs
index b3dee6e..dd97124 100644
--- a/scripts/mnemazine-merge-semantic-shards.mjs
+++ b/scripts/mnemazine-merge-semantic-shards.mjs
@@ -49,7 +49,7 @@ function withoutSourceFiles(graph, files) {
async function main() {
const vault = resolveVault({ cli: arg('vault') })
const graphPath = path.resolve(arg('graph', path.join(vault, 'graphify-out/graph.json')))
- const shardsDir = path.resolve(arg('shards-dir', path.join(vault, '.mnemazine/semantic-shards')))
+ const shardsDir = path.resolve(arg('shards-dir', process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR || path.join(vault, '.mnemazine/semantic-shards')))
const manifestPath = arg('manifest', '')
const noBackup = flag('no-backup')
if (!existsSync(graphPath)) throw new Error(`graph not found: ${graphPath}`)
diff --git a/scripts/mnemazine-migration-check.mjs b/scripts/mnemazine-migration-check.mjs
new file mode 100644
index 0000000..1a39cb9
--- /dev/null
+++ b/scripts/mnemazine-migration-check.mjs
@@ -0,0 +1,298 @@
+#!/usr/bin/env node
+// Прибор миграционного контракта (план П16, шаг 1).
+//
+// Контракт — машинная таблица «старое поле → новое поле → правило переноса → что требует человека»,
+// чтобы перенос старых полей описывался таблицей, а не 1948 отдельными суждениями модели.
+// Контракт покрывает ВСТРЕЧЕННОЕ МНОЖЕСТВО значений, которое --emit переизвлекает на момент запуска,
+// а не исторические числа из планов.
+//
+// --emit [--report ] переснять множество из корпуса и переписать контракт (+ человекочитаемую таблицу)
+// --verify каждое встреченное значение либо покрыто правилом, либо помечено «требует человека»
+//
+// verify — fail-closed: поле/значение, встреченное в корпусе и не покрытое контрактом, — exit 1.
+// Покрытие трёх видов: значение уже в enum спеки (already-conformant), детерминированное правило
+// (mapType/mapVerified из mnemazine-normalize-old-frontmatter.mjs — импорт, копий нет) или явная
+// пометка human_required. verification_status схлопывается в verified: по решению оркестратора:
+// одно значение смысла — одно поле правды; verification_status после миграции удаляется.
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import { SPEC_TYPES, SPEC_VERIFIED, SPEC_SUBJECTS, normSpecValue } from './mnemazine-note-spec.mjs'
+import { resolveVault, ROOT } from './mnemazine-paths.mjs'
+import { mapType, mapVerified, corpusFiles, readFrontmatter } from './mnemazine-normalize-old-frontmatter.mjs'
+
+const argv = process.argv.slice(2)
+const arg = (name, fallback = '') => {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+const VAULT = resolveVault({ cli: arg('vault') })
+const EMIT = arg('emit')
+const VERIFY = arg('verify')
+const REPORT = arg('report')
+if (!EMIT && !VERIFY) {
+ console.error('нужен --emit [--report ] или --verify ')
+ process.exit(2)
+}
+
+const norm = v => normSpecValue(String(v ?? '').trim())
+const CANON_VERIFIED_NORM = new Set(SPEC_VERIFIED.map(norm))
+
+/** Тело секции `## Источники`/`## Source` (для строки контракта про source). */
+function sourcesSectionBody(text) {
+ const m = text.match(/^#{2,}\s+(?:Source|Sources|Источник|Источники)\s*$/im)
+ if (!m) return ''
+ const tail = text.slice(m.index + m[0].length)
+ const next = tail.search(/\n##\s+/)
+ return (next === -1 ? tail : tail.slice(0, next)).trim()
+}
+
+/** Снимок встреченного множества: значение → число нот, по каждому отслеживаемому полю. */
+async function scanCorpus() {
+ const files = await corpusFiles(VAULT)
+ const fields = { type: new Map(), verified: new Map(), verification_status: new Map(), type_legacy: new Map() }
+ let withFm = 0
+ let noFm = 0
+ let sourcesBodyWithEmptySource = 0
+ const bump = (map, value) => map.set(value, (map.get(value) || 0) + 1)
+ for (const file of files) {
+ const text = await fs.readFile(file, 'utf8')
+ const fm = readFrontmatter(text)
+ if (fm.error) { noFm++; continue }
+ withFm++
+ for (const key of Object.keys(fields)) {
+ const v = fm.data[key]
+ if (v === undefined) continue
+ const value = Array.isArray(v) ? v.join(', ') : String(v)
+ bump(fields[key], value)
+ }
+ const src = fm.data.source
+ const srcOk = Array.isArray(src) ? src.some(s => String(s).trim()) : Boolean(String(src ?? '').trim())
+ if (!srcOk && sourcesSectionBody(text)) sourcesBodyWithEmptySource++
+ }
+ return { files: files.length, withFm, noFm, fields, sourcesBodyWithEmptySource }
+}
+
+const HUMAN = 'human'
+const RULE = 'rule'
+const CONFORM = 'already-conformant'
+const STANDING_LEGACY_VALUES = {
+ type: [
+ { value: 'knowledge-note', notes: 38, covered_by: RULE, maps_to: 'concept', reason: 'repo-local fixture/default selftest; знание/заметка без спецполей = concept' },
+ { value: 'knowledge-digest', notes: 1, covered_by: RULE, maps_to: 'synthesis', reason: 'repo-local fixture/default selftest; digest/сводка = synthesis' },
+ ],
+ verified: [
+ { value: 'expanded with public sources', notes: 23, covered_by: RULE, maps_to: 'подтверждён', reason: 'repo-local fixture/default selftest; публичные источники уже добавлены' },
+ { value: 'false', notes: 15, covered_by: RULE, maps_to: 'не-проверялось', reason: 'repo-local fixture/default selftest; false не заявляет проверку' },
+ ],
+}
+
+export function mapVerificationStatus(old) {
+ const v = norm(old)
+ if (!v || ['unknown', 'assumed', 'false', 'no', 'нет', 'null', 'undefined'].includes(v)) return { value: 'не-проверялось', keepLegacy: false }
+ if (v.includes('частично')) return { value: 'не-проверялось', keepLegacy: true }
+ if (v === 'verified' || v === 'verified-with-public-sources' || /^подтвержд/.test(v)) return { value: 'подтверждён', keepLegacy: v !== 'verified' }
+ if (v === 'источник-не-найден') return { value: 'источник-не-найден', keepLegacy: false }
+ if (v === 'непроверяемо-методом') return { value: 'непроверяемо-методом', keepLegacy: false }
+ return { value: 'не-проверялось', keepLegacy: true }
+}
+
+function targetValue(field, value) {
+ if (field === 'type') return SPEC_TYPES.has(String(value).trim()) ? String(value).trim() : mapType(value, {})
+ if (field === 'verified') return mapVerified(value).value
+ if (field === 'verification_status') return mapVerificationStatus(value).value
+ return null
+}
+
+/** Классификация значения: enum спеки / правило прибора / только человек. */
+function classify(field, value) {
+ const v = norm(value)
+ if (field === 'type') {
+ if (SPEC_TYPES.has(String(value).trim())) return CONFORM
+ const mapped = mapType(value, {})
+ if (SPEC_TYPES.has(mapped) && mapped !== 'tool-card' && mapped !== 'decision') return RULE
+ return HUMAN
+ }
+ if (field === 'verified') {
+ if (CANON_VERIFIED_NORM.has(v)) return CONFORM
+ const m = mapVerified(value)
+ if (!m.keepLegacy) return RULE // пусто/false/true — чистое переименование без потери
+ if (m.value === 'не-проверялось') return HUMAN // свободный текст схлопнут с потерей — человек читает legacy
+ return RULE
+ }
+ if (field === 'verification_status') return RULE
+ if (field === 'type_legacy') return 'archaeology'
+ return HUMAN
+}
+
+const RULE_TEXT = {
+ type: 'mapType: суффиксное отображение в SPEC_TYPES, умолчание concept; tool-card — только при непустых repo+stars+license+risk; decision механически не ставится; оригинал сохраняется в type_legacy',
+ verified: 'mapVerified: значение→SPEC_VERIFIED (ё/е равны); аннотация через пробел/скобку → enum + оригинал в verified_legacy; true/да/подтвержд* и expanded with public sources → подтверждён; пусто/false → не-проверялось; свободный текст → не-проверялось + verified_legacy',
+ verification_status: 'mapVerificationStatus: поле схлопывается в verified: и после миграции удаляется. Частичная проверка → не-проверялось + legacy; verified/подтвержд*/verified-with-public-sources → подтверждён; unknown/assumed/false/пусто → не-проверялось; источник-не-найден и непроверяемо-методом сохраняют одноимённые значения. Правило 8 мастера: два поля одной семантики = дубль правды.',
+ type_legacy: 'Археология переогранки — НЕ ТРОГАТЬ: это вход для кампании 3 (legacy-значение говорит о ноте больше, чем выровненный concept) и страховка от неверного отображения.',
+ '## Источники→source': 'Перенос в source:/sources: ТОЛЬКО если провенанс виден в самой ноте (basename интейк-файла, local-media:, URL → в sources:). Не виден — поле остаётся пустым, нота уходит в список следующей волны. source: НЕ ВЫДУМЫВАТЬ (kimi-master.md, кампания 2).',
+}
+
+async function emit() {
+ const snap = await scanCorpus()
+ const mkField = (field, extra = {}) => {
+ const values = [...snap.fields[field].entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([value, notes]) => {
+ const row = { value, notes, covered_by: classify(field, value) }
+ const mapped = targetValue(field, value)
+ if (mapped !== null) row.maps_to = mapped
+ if (field === 'verification_status') row.remove_field_after_migration = true
+ return row
+ })
+ const human = values.filter(v => v.covered_by === HUMAN).map(v => ({ value: v.value, notes: v.notes, reason: RULE_TEXT[field] }))
+ return {
+ old_field: field,
+ new_field: extra.new_field ?? field,
+ notes: values.reduce((a, v) => a + v.notes, 0),
+ distinct_values: values.length,
+ rule: RULE_TEXT[field],
+ implemented_by: extra.implemented_by ?? null,
+ new_enum: extra.new_enum ?? null,
+ decision: extra.decision ?? null,
+ values,
+ standing_legacy_values: (STANDING_LEGACY_VALUES[field] || []).filter(v => !values.some(row => norm(row.value) === norm(v.value))),
+ human_required: human,
+ }
+ }
+ const contract = {
+ contract: 'migration-contract',
+ contract_version: 1,
+ spec_ref: 'docs/NOTE-SPEC.md',
+ spec_version: 'NOTE-SPEC 2026-07-25 + subject §18 (2026-08-22)',
+ schema_ref: 'scripts/mnemazine-note-spec.mjs (единая правда П05; config/note.schema.json П06 — когда появится, ссылаться на неё, не дублировать)',
+ generated_by: 'scripts/mnemazine-migration-check.mjs --emit',
+ generated_at: new Date().toISOString(),
+ vault: VAULT,
+ corpus: { files: snap.files, with_frontmatter: snap.withFm, without_frontmatter: snap.noFm },
+ fields: [
+ mkField('type', { implemented_by: 'scripts/mnemazine-normalize-old-frontmatter.mjs (mapType)', new_enum: [...SPEC_TYPES] }),
+ mkField('verified', { implemented_by: 'scripts/mnemazine-normalize-old-frontmatter.mjs (mapVerified)', new_enum: SPEC_VERIFIED }),
+ mkField('verification_status', {
+ new_field: 'verified',
+ implemented_by: 'scripts/mnemazine-migration-check.mjs (mapVerificationStatus; контракт П16)',
+ new_enum: SPEC_VERIFIED,
+ decision: 'owner-decided-collapse-into-verified-remove-field',
+ }),
+ mkField('type_legacy', { new_field: '—' }),
+ {
+ old_field: '## Источники (тело) при пустом source:',
+ new_field: 'source: / sources:',
+ notes: snap.sourcesBodyWithEmptySource,
+ distinct_values: null,
+ rule: RULE_TEXT['## Источники→source'],
+ implemented_by: 'кампания 3 (переогранка головой) + scripts/mnemazine-normalize-old-frontmatter.mjs (перенос sources→source)',
+ new_enum: null,
+ decision: null,
+ values: [],
+ human_required: [],
+ },
+ ],
+ subject_field: {
+ note: 'Поле subject (§18): enum self|world|mixed. Старый корпус проставляется при переогранке: source_type video|article|repo и нет первого лица в теле → world; не выводится однозначно → mixed (fail-closed); self руками не назначается.',
+ enum: [...SPEC_SUBJECTS],
+ },
+ }
+ const target = path.resolve(ROOT, EMIT)
+ await fs.mkdir(path.dirname(target), { recursive: true })
+ await fs.writeFile(target, JSON.stringify(contract, null, 2) + '\n')
+ console.log(`контракт записан: ${target}`)
+ for (const f of contract.fields) {
+ console.log(` ${f.old_field}: нот ${f.notes}, значений ${f.distinct_values ?? '—'}, человека требует ${f.human_required.length}`)
+ }
+ console.log(` ## Источники при пустом source:: нот ${snap.sourcesBodyWithEmptySource}`)
+ if (REPORT) {
+ const md = renderMarkdown(contract)
+ const mdTarget = path.resolve(ROOT, REPORT)
+ await fs.mkdir(path.dirname(mdTarget), { recursive: true })
+ await fs.writeFile(mdTarget, md)
+ console.log(`отчёт записан: ${mdTarget}`)
+ }
+}
+
+function renderMarkdown(c) {
+ const rows = []
+ for (const f of c.fields) {
+ const human = f.human_required.length
+ ? f.human_required.map(h => `«${h.value}» (${h.notes})`).join(', ')
+ : (f.decision === 'owner-pending' ? 'всё поле целиком — решение владельца' : '—')
+ rows.push(`| \`${f.old_field}\` | ${f.notes} | ${f.distinct_values ?? '—'} | \`${f.new_field}\` | ${f.rule.split('.')[0]} | ${human} |`)
+ }
+ return `# Миграционный контракт корпуса → NOTE-SPEC
+
+Сгенерировано кодом: \`${c.generated_by}\`, ${c.generated_at}. Не править руками — переснимать \`--emit\`.
+Спека: \`${c.spec_ref}\` (${c.spec_version}). Единая правда состава типов/значений: \`${c.schema_ref}\`.
+Корпус при съёме: ${c.corpus.files} файлов, frontmatter есть у ${c.corpus.with_frontmatter}, нет у ${c.corpus.without_frontmatter}.
+
+| Старое поле | Нот | Значений | Новое поле | Правило переноса | Требует человека |
+|---|---:|---:|---|---|---|
+${rows.join('\n')}
+
+## Полные правила
+
+${c.fields.map(f => `### \`${f.old_field}\`\n\n${f.rule}\n\nПрибор: ${f.implemented_by ?? '—'}.${f.new_enum ? `\nНовый enum: ${f.new_enum.join(' | ')}.` : ''}${f.decision ? `\n**Решение: ${f.decision}.**` : ''}`).join('\n\n')}
+
+## Standing legacy mappings
+
+${c.fields.flatMap(f => (f.standing_legacy_values || []).map(v => `- \`${f.old_field}\`: \`${v.value}\` (${v.notes}) → \`${v.maps_to}\` — ${v.reason}`)).join('\n') || '—'}
+
+## subject (§18 мастер-плана)
+
+${c.subject_field.note}
+
+## Проверка покрытия
+
+\`node scripts/mnemazine-migration-check.mjs --verify config/migration-contract.json\` — каждое значение,
+встреченное в корпусе на момент прогона, либо уже в enum спеки, либо покрыто детерминированным правилом,
+либо явно помечено «требует человека». Новое непокрытое значение = exit 1.
+`
+}
+
+async function verify() {
+ const target = path.resolve(ROOT, VERIFY)
+ const contract = JSON.parse(await fs.readFile(target, 'utf8'))
+ const snap = await scanCorpus()
+ const problems = []
+ const byField = new Map(contract.fields.map(f => [f.old_field, f]))
+ for (const field of ['type', 'verified', 'verification_status', 'type_legacy']) {
+ const encountered = snap.fields[field]
+ const encounteredNotes = [...encountered.values()].reduce((a, b) => a + b, 0)
+ if (encounteredNotes === 0) continue
+ const row = byField.get(field)
+ if (!row) {
+ problems.push(`${field}: ${encounteredNotes} нот несут поле, не покрытое контрактом (строка отсутствует)`)
+ continue
+ }
+ if (field === 'type_legacy') continue // археология: покрытие — сама строка с правилом «не трогать»
+ const declared = new Map()
+ for (const v of [...(row.values || []), ...(row.standing_legacy_values || [])]) declared.set(norm(v.value), v)
+ for (const h of row.human_required || []) declared.set(norm(h.value), { value: h.value, covered_by: HUMAN })
+ for (const [value, notes] of encountered) {
+ const kind = classify(field, value)
+ if (kind === CONFORM || kind === 'archaeology') continue // уже в enum спеки
+ const decl = declared.get(norm(value))
+ if (!decl) {
+ problems.push(`${field}: значение «${value}» (${notes} нот) встречено в корпусе, но в контракте не объявлено`)
+ } else if (decl.covered_by === HUMAN && kind !== HUMAN) {
+ problems.push(`${field}: значение «${value}» помечено «требует человека», но правило покрывает его детерминированно — контракт устарел, пересними --emit`)
+ } else if (decl.covered_by === RULE && kind === HUMAN) {
+ problems.push(`${field}: значение «${value}» объявлено покрытым правилом, но правило его не покрывает — нужна пометка «требует человека»`)
+ }
+ }
+ }
+ if (problems.length) {
+ console.error(`контракт НЕ покрывает корпус (${problems.length} проблем):`)
+ for (const p of problems) console.error(` - ${p}`)
+ process.exit(1)
+ }
+ console.log(`контракт покрывает встреченное множество: ${snap.files} файлов, поля type/verified/verification_status/type_legacy проверены`)
+ process.exit(0)
+}
+
+if (EMIT) await emit()
+else await verify()
diff --git a/scripts/mnemazine-model-pin-check.mjs b/scripts/mnemazine-model-pin-check.mjs
new file mode 100644
index 0000000..e9f3da9
--- /dev/null
+++ b/scripts/mnemazine-model-pin-check.mjs
@@ -0,0 +1,181 @@
+#!/usr/bin/env node
+import { promises as fs } from 'node:fs'
+import { existsSync } from 'node:fs'
+import path from 'node:path'
+
+const ROOT = path.resolve(process.cwd())
+const argv = process.argv.slice(2)
+const jsonMode = argv.includes('--json')
+const EXPECTED_AGENT_CALLS = 25
+
+function arg(name) {
+ const i = argv.indexOf(`--${name}`)
+ return i === -1 ? '' : argv[i + 1] || ''
+}
+
+async function readJson(rel) {
+ return JSON.parse(await fs.readFile(path.join(ROOT, rel), 'utf8'))
+}
+
+function frontmatterModel(text) {
+ const head = String(text || '').match(/^---\n([\s\S]*?)\n---/)
+ if (!head) return ''
+ return (head[1].match(/^model:\s*["']?([^"'\n]+)["']?\s*$/m)?.[1] || '').trim()
+}
+
+async function roleModels() {
+ const dir = path.join(ROOT, 'agents/mnemazina-pipeline')
+ const out = {}
+ for (const name of await fs.readdir(dir).catch(() => [])) {
+ if (!name.endsWith('.md')) continue
+ out[name.replace(/\.md$/, '')] = frontmatterModel(await fs.readFile(path.join(dir, name), 'utf8'))
+ }
+ return out
+}
+
+function isIdent(ch) {
+ return /[A-Za-z0-9_$]/.test(ch || '')
+}
+
+function skipString(src, i) {
+ const quote = src[i]
+ i += 1
+ while (i < src.length) {
+ if (src[i] === '\\') { i += 2; continue }
+ if (src[i] === quote) return i + 1
+ i += 1
+ }
+ return i
+}
+
+function extractAgentCalls(src) {
+ const calls = []
+ for (let i = 0; i < src.length; i++) {
+ if (src.startsWith('//', i)) { const n = src.indexOf('\n', i + 2); i = n === -1 ? src.length : n; continue }
+ if (src.startsWith('/*', i)) { const n = src.indexOf('*/', i + 2); i = n === -1 ? src.length : n + 1; continue }
+ if (src[i] === '"' || src[i] === "'" || src[i] === '`') { i = skipString(src, i) - 1; continue }
+ if (!src.startsWith('agent(', i) || isIdent(src[i - 1])) continue
+ let depth = 0
+ for (let j = i; j < src.length; j++) {
+ if (src.startsWith('//', j)) { const n = src.indexOf('\n', j + 2); j = n === -1 ? src.length : n; continue }
+ if (src.startsWith('/*', j)) { const n = src.indexOf('*/', j + 2); j = n === -1 ? src.length : n + 1; continue }
+ if (src[j] === '"' || src[j] === "'" || src[j] === '`') { j = skipString(src, j) - 1; continue }
+ if (src[j] === '(') depth += 1
+ if (src[j] === ')') {
+ depth -= 1
+ if (depth === 0) {
+ calls.push({ start: i, body: src.slice(i, j + 1) })
+ i = j
+ break
+ }
+ }
+ }
+ }
+ return calls
+}
+
+function stringValuesFor(name, body) {
+ const re = new RegExp(`${name}\\s*:\\s*['"]([^'"]+)['"]`, 'g')
+ const out = []
+ for (let m; (m = re.exec(body));) out.push(m[1])
+ return out
+}
+
+function labelOf(body) {
+ return stringValuesFor('label', body)[0] || ''
+}
+
+function agentTypeOf(body) {
+ return stringValuesFor('agentType', body)[0] || ''
+}
+
+function hasModel(body) {
+ return /\bmodel\s*:/.test(body)
+}
+
+function arithmeticHits(calls) {
+ const patterns = [
+ ['shasum', /\bshasum\b/],
+ ['wc -l', /\bwc\s+-l\b/],
+ ['| sort', /\|\s*sort\b/],
+ ['--json', /(^|[\s"'])--json\b/],
+ ['%-threshold', /(?:[0-9]|≥|<=|>=|>|<)\s*[0-9]*\s*%/]
+ ]
+ const hits = []
+ for (const call of calls) {
+ for (const [name, re] of patterns) {
+ if (re.test(call.body)) hits.push({ label: labelOf(call.body), pattern: name })
+ }
+ }
+ return hits
+}
+
+async function checkRunObservability(stateDir) {
+ if (!stateDir) return []
+ const file = path.join(stateDir, 'run-observability.jsonl')
+ const text = await fs.readFile(file, 'utf8').catch(() => '')
+ const violations = []
+ for (const [idx, line] of text.split(/\r?\n/).entries()) {
+ if (!line.trim()) continue
+ let row
+ try { row = JSON.parse(line) } catch { violations.push(`observability:${idx + 1}: invalid json`); continue }
+ if (row.tier === 0 && row.deep === true) violations.push(`observability:${idx + 1}: tier 0 deep=true (${row.file || ''})`)
+ if (row.llm_extract_used === true && row.sidecar_present === true) violations.push(`observability:${idx + 1}: llm_extract_used with sidecar (${row.file || ''})`)
+ }
+ return violations
+}
+
+async function main() {
+ const policy = await readJson('config/model-policy.json')
+ const workflow = await fs.readFile(path.join(ROOT, 'workflows/mnemazina-pipeline.js'), 'utf8')
+ const roles = await roleModels()
+ const calls = extractAgentCalls(workflow)
+ const violations = []
+
+ if (calls.length === 0 || Object.keys(roles).length === 0) {
+ const result = { ok: false, code: 2, agent_calls: calls.length, roles: Object.keys(roles).length, violations: ['empty agent or role sample'] }
+ if (jsonMode) console.log(JSON.stringify(result, null, 2))
+ else console.error(result.violations.join('\n'))
+ process.exit(2)
+ }
+
+ for (const call of calls) {
+ if (hasModel(call.body)) continue
+ const type = agentTypeOf(call.body)
+ if (!type || !existsSync(path.join(ROOT, 'agents/mnemazina-pipeline', `${type}.md`)) || !roles[type]) {
+ violations.push(`agent without model and role model: ${labelOf(call.body) || `offset ${call.start}`}`)
+ }
+ }
+
+ for (const tier of ['0', '1', '2', '3']) {
+ if (!policy.tiers || !policy.tiers[tier]) violations.push(`policy tiers missing ${tier}`)
+ }
+ for (const role of ['kb-find', 'store', 'reconcile', 'reconcile-2', 'proc']) {
+ if (!policy.roles || !policy.roles[role]) violations.push(`policy roles missing ${role}`)
+ }
+ for (const role of stringValuesFor('label', workflow).filter(v => ['kb-find', 'store', 'reconcile', 'reconcile-2'].includes(v))) {
+ if (!workflow.includes(`modelForRole('${role}'`)) violations.push(`role ${role} is not pinned through policy`)
+ }
+ if (!workflow.includes("modelForRole('proc'")) violations.push('proc is not pinned through policy')
+
+ for (const hit of arithmeticHits(calls)) violations.push(`agent arithmetic ${hit.pattern}: ${hit.label || 'unlabeled'}`)
+ violations.push(...await checkRunObservability(arg('run')))
+
+ const result = { ok: violations.length === 0, agent_calls: calls.length, roles: Object.keys(roles).length, violations }
+ if (calls.length !== EXPECTED_AGENT_CALLS) {
+ violations.push(`agent call count expected ${EXPECTED_AGENT_CALLS}, got ${calls.length}`)
+ result.ok = false
+ result.violations = violations
+ }
+ if (jsonMode) console.log(JSON.stringify(result, null, 2))
+ else if (violations.length) console.error(violations.join('\n'))
+ else console.log('model-pin ok')
+ process.exit(violations.length ? 1 : 0)
+}
+
+main().catch(err => {
+ const message = err && err.message ? err.message : String(err)
+ if (jsonMode) console.log(JSON.stringify({ ok: false, code: 1, violations: [message] }, null, 2))
+ else console.error(message)
+ process.exit(1)
+})
diff --git a/scripts/mnemazine-normalize-old-frontmatter.mjs b/scripts/mnemazine-normalize-old-frontmatter.mjs
new file mode 100644
index 0000000..33c3130
--- /dev/null
+++ b/scripts/mnemazine-normalize-old-frontmatter.mjs
@@ -0,0 +1,272 @@
+#!/usr/bin/env node
+// Механическая половина переогранки старого корпуса под docs/NOTE-SPEC.md — за $0, детерминированно.
+//
+// Зачем отдельно от Кими-кампании: из 1378 нот, валящих `--spec`, 1361 валит `type` и 1250 `verified`, и
+// это ЧИСТОЕ переименование словаря (`knowledge-note` → `concept`), а не суждение. Гонять на него LLM —
+// платить за regex. Кими остаётся то, что действительно требует головы: блоки «Как это поможет мне» и
+// «Достоверность», плотность текста, доля кириллицы, мерж-вердикт.
+//
+// Что скрипт НЕ делает принципиально:
+// • не выдумывает `source` — провенанс нельзя восстановить угадыванием (только переносит из `sources`);
+// • не ставит `подтверждён` там, где проверки не было (для этого владелец завёл «не-проверялось»);
+// • не трогает тело ноты вообще;
+// • не создаёт frontmatter с нуля — нота без него уходит в отчёт, её чинит конвейер.
+//
+// Правка построчная, а не через reparse+dump: пересборка YAML переформатировала бы 1378 файлов целиком и
+// потеряла бы комментарии/порядок. Дубль ключа во frontmatter — уже измеренная дыра проекта, поэтому файл
+// с дублем `type`/`verified` не правится, а уходит в отчёт (fail-closed).
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { SPEC_TYPES, SPEC_VERIFIED, normSpecValue } from './mnemazine-note-spec.mjs'
+import { resolveVault } from './mnemazine-paths.mjs'
+
+const norm = s => normSpecValue(String(s ?? '').trim())
+const CANON_VERIFIED = new Map([...SPEC_VERIFIED].map(v => [norm(v), v]))
+
+/**
+ * Старый словарь типов — 184 разных значения на 1378 нот. Отображение по СУФФИКСУ, а не таблицей на 184
+ * строки: словарь рос свободно (`security-tool-reference`, `frontend-quality-gate`), и таблица отстала бы
+ * от следующей волны. Умолчание — `concept`: спека определяет его как «понятие/метод/принцип», под что
+ * ложатся все `*-method`, `*-boundary`, `*-policy`, `*-gate`, `*-atom`, `workflow`, `prompt`.
+ *
+ * Куда НЕ отображаем механически:
+ * `decision` — требует непустые `context` и `rejected`, их у старых нот нет: гейт всё равно провалит;
+ * `tool-card` — требует repo/stars/license/risk; ставим ТОЛЬКО когда все четыре реально в ноте.
+ * Оригинал сохраняется в `type_legacy` — это вход для Кими (`security-tool-reference` говорит ей о ноте
+ * больше, чем выровненный `concept`), и страховка от неверного отображения.
+ */
+export function mapType(old, data) {
+ const has = k => {
+ const v = data[k]
+ return Array.isArray(v) ? v.length > 0 : Boolean(String(v ?? '').trim())
+ }
+ if (has('repo') && has('stars') && has('license') && has('risk')) return 'tool-card'
+ const t = norm(old)
+ if (SPEC_TYPES.has(t) && t !== 'decision' && t !== 'tool-card') return t
+ if (/(^|-)(reference|catalog|index|map|list|queue)$/.test(t) || t === 'redirect') return 'reference'
+ if (/(synthesis|canonical-summary|digest|overview|comparison|stack|triage)/.test(t)) return 'synthesis'
+ return 'concept'
+}
+
+/**
+ * Старое значение `verified` → enum спеки. Правило одно: НИКОГДА не заявлять проверку, которой не было.
+ * Порядок проверок — от точного к общему:
+ * 1. значение УЖЕ из enum → оно же, без legacy.
+ * 2. enum + аннотация через пробел или скобку («непроверяемо-методом (транскрипт видео)») → enum,
+ * аннотация в `verified_legacy`. Без этого шага 35 честных значений понижались в «не-проверялось»
+ * просто потому, что автор дописал скобку — измерено на живом корпусе. Граница обязательна: без неё
+ * «непроверяемо-методомX» тоже сошло бы за валидное значение.
+ * 3. да/true/подтверждено… → `подтверждён` (прошлый конвейер именно это и утверждал). Оговорка о
+ * неполноте бьёт утверждение сама собой: «частично подтверждено…» начинается не с «подтвержд»,
+ * поэтому сюда не попадает и уезжает в общий случай — отдельная ветка на «частично» была бы мёртвым
+ * кодом (проверено мутацией: её удаление не меняет ни одного исхода).
+ * 4. expanded with public sources → `подтверждён`: старый конвейер уже расширил ноту публичными
+ * источниками, то есть это проверка источниками, а не пустая догадка.
+ * 5. пусто/false/нет → `не-проверялось` без legacy: терять нечего.
+ * 6. всё прочее — «частично…», даты, свободный текст → `не-проверялось`, оригинал в legacy.
+ * Занижение безопаснее завышения: непроверенное знание, помеченное проверенным, — худший исход.
+ */
+export function mapVerified(old) {
+ const v = norm(old)
+ if (CANON_VERIFIED.has(v)) return { value: CANON_VERIFIED.get(v), keepLegacy: false }
+ for (const [canon, value] of CANON_VERIFIED) {
+ if (v.startsWith(canon) && /^[\s(]/.test(v.slice(canon.length))) return { value, keepLegacy: true }
+ }
+ if (/^(да|true|yes|verified)$/.test(v) || /^подтвержд/.test(v)) return { value: 'подтверждён', keepLegacy: v !== 'подтвержден' }
+ if (v === 'expanded with public sources') return { value: 'подтверждён', keepLegacy: true }
+ if (!v || /^(false|no|нет|null|undefined)$/.test(v)) return { value: 'не-проверялось', keepLegacy: false }
+ return { value: 'не-проверялось', keepLegacy: true } // даты, свободный текст — информацию храним
+}
+
+// Основное тело исполняется ТОЛЬКО при прямом вызове: прибор миграционного контракта
+// (mnemazine-migration-check.mjs) импортирует mapType/mapVerified, и без этого стража
+// импорт запускал бы обход vault и правки по чужим argv.
+const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+
+if (isMain && process.argv.slice(2).includes('--selftest')) {
+ const { strictEqual: eq } = await import('node:assert')
+ const V = s => mapVerified(s).value
+ // Аннотация не понижает честное значение (баг, найденный на живом корпусе — 35 нот).
+ eq(V('непроверяемо-методом (транскрипт видео)'), 'непроверяемо-методом')
+ eq(mapVerified('непроверяемо-методом (транскрипт видео)').keepLegacy, true)
+ // Оговорка о неполноте бьёт слово «подтверждено» — иначе частичная проверка выдаст себя за полную.
+ // Без границы «непроверяемо-методомX» сошло бы за валидное значение — мутация ловится ровно этим.
+ eq(V('непроверяемо-методомX'), 'не-проверялось')
+ eq(V('частично подтверждено первоисточниками 2026-06-06'), 'не-проверялось')
+ eq(V('частично-подтверждено'), 'не-проверялось')
+ eq(V('подтверждено на дату предыдущей проверки'), 'подтверждён')
+ eq(V('подтверждён'), 'подтверждён')
+ eq(V('подтвержден'), 'подтверждён') // ё/е — одно слово
+ eq(V('true'), 'подтверждён')
+ eq(V('expanded with public sources'), 'подтверждён')
+ eq(mapVerified('expanded with public sources').keepLegacy, true)
+ eq(V('false'), 'не-проверялось')
+ eq(V(''), 'не-проверялось')
+ eq(V('2026-06-05'), 'не-проверялось')
+ eq(mapVerified('').keepLegacy, false) // терять нечего — legacy не плодим
+ // «не-проверялось» само себя не ловит префиксом «не» и остаётся собой.
+ eq(V('не-проверялось'), 'не-проверялось')
+ eq(mapVerified('не-проверялось').keepLegacy, false)
+ const T = (t, d = {}) => mapType(t, d)
+ eq(T('knowledge-note'), 'concept')
+ eq(T('security-tool-reference'), 'reference')
+ eq(T('canonical-summary'), 'synthesis')
+ eq(T('tool'), 'concept') // без repo/stars/license/risk карточкой инструмента не станет
+ eq(T('tool', { repo: 'x' }), 'concept') // ОДНОГО поля мало: гейт всё равно потребует остальные три
+ eq(T('tool', { repo: 'x', stars: 1, license: 'MIT' }), 'concept')
+ eq(T('tool', { repo: 'x', stars: 1, license: 'MIT', risk: 'low' }), 'tool-card')
+ eq(T('decision'), 'concept') // decision требует context+rejected — механически не ставим
+ eq(T('reference'), 'reference')
+ console.log('selftest ok')
+ process.exit(0)
+}
+
+async function walk(dir) {
+ const out = []
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ const p = path.join(dir, item.name)
+ if (item.isDirectory() && !['.git', '.obsidian'].includes(item.name) && !item.name.startsWith('graphify-out')) out.push(...await walk(p))
+ else if (item.isFile() && p.endsWith('.md')) out.push(p)
+ }
+ return out
+}
+
+// Копия предиката из mnemazine-vault-quality-gate.mjs — канон там. Скрипт обязан видеть РОВНО тот же набор
+// файлов, что судит гейт: правь обе стороны вместе, иначе нормализатор чинит не то, что проверяется.
+function isServicePath(rel) {
+ return (
+ rel.includes('/graphify-out/') ||
+ rel.includes('/_legacy-index ') ||
+ rel.includes('/_архив-дублей/') ||
+ rel.includes('/Capabilities/_') ||
+ /^99 Система\//.test(rel) ||
+ /^00 System\//.test(rel) ||
+ /(^|\/)_(Содержание|МАСТЕР-ИНДЕКС|ROUTING|ШАБЛОНЫ)\.md$/.test(rel) ||
+ ['AGENTS.md', 'CLAUDE.md', '_ROUTING.md', 'Лог обработки.md'].includes(rel)
+ )
+}
+
+const unquote = v => {
+ const m = String(v).match(/^"(.*)"$/s) || String(v).match(/^'(.*)'$/s)
+ return m ? m[1] : String(v)
+}
+
+/** Границы frontmatter + плоские скаляры/списки. Дубль ключа верхнего уровня = отказ (fail-closed). */
+function readFrontmatter(text) {
+ const lines = text.split('\n')
+ if (!/^---\s*$/.test(lines[0] ?? '')) return { error: 'нет frontmatter' }
+ let close = -1
+ for (let i = 1; i < lines.length; i++) if (/^---\s*$/.test(lines[i])) { close = i; break }
+ if (close === -1) return { error: 'frontmatter не закрыт' }
+ const data = {}
+ const lineOf = {}
+ let listKey = null
+ for (let i = 1; i < close; i++) {
+ const line = lines[i].replace(/\r$/, '')
+ if (!line.trim() || line.trim().startsWith('#')) continue
+ const kv = line.match(/^([\w.-]+):(?:\s+(.*))?$/)
+ if (kv) {
+ const key = kv[1]
+ if (Object.hasOwn(data, key)) return { error: `дубль ключа «${key}»` }
+ const raw = (kv[2] ?? '').trim()
+ lineOf[key] = i
+ if (!raw) { data[key] = []; listKey = key }
+ else if (/^\[.*\]$/.test(raw)) { data[key] = raw.slice(1, -1).split(',').map(s => unquote(s.trim())).filter(Boolean); listKey = null }
+ else { data[key] = unquote(raw); listKey = null }
+ continue
+ }
+ const item = line.match(/^\s*-\s+(.*)$/)
+ if (item && listKey) { data[listKey].push(unquote(item[1].trim())); continue }
+ if (/^\s/.test(line)) continue
+ return { error: `непарсибельная строка ${i + 1}` }
+ }
+ return { data, lines, close, lineOf }
+}
+
+/** YAML-скаляр: кавычки только когда без них значение сменит смысл или сломает парсер. */
+const yamlScalar = v => (/^[\wА-Яа-яЁё][\wА-Яа-яЁё .,()/@-]*$/.test(v) ? v : JSON.stringify(v))
+
+/** Обход корпуса гейта — общий для приборов миграции (импортируется migration-check). */
+export async function corpusFiles(vault) {
+ return (await walk(vault)).filter(f => !isServicePath(path.relative(vault, f)))
+}
+
+export { readFrontmatter, yamlScalar }
+
+// ── Исполнение: только при прямом вызове (страж isMain выше) ──
+if (isMain) {
+const argv = process.argv.slice(2)
+const arg = (name, fallback = '') => {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+const VAULT = resolveVault({ cli: arg('vault') })
+const APPLY = argv.includes('--apply') // fail-safe: по умолчанию сухой прогон, диск не трогается
+const JSON_OUT = argv.includes('--json')
+
+const files = (await walk(VAULT)).filter(f => !isServicePath(path.relative(VAULT, f)))
+const report = { vault: VAULT, apply: APPLY, scanned: files.length, changed: 0, edits: { type: 0, verified: 0, source: 0, typeLegacy: 0, verifiedLegacy: 0 }, skipped: [] }
+
+for (const file of files) {
+ const rel = path.relative(VAULT, file)
+ const text = await fs.readFile(file, 'utf8')
+ const fm = readFrontmatter(text)
+ if (fm.error) { report.skipped.push({ file: rel, reason: fm.error }); continue }
+
+ const { data, lines, close, lineOf } = fm
+ const insert = [] // строки, которых во frontmatter не было
+ let touched = false
+
+ const oldType = Array.isArray(data.type) ? '' : String(data.type ?? '')
+ const newType = mapType(oldType, data)
+ if (norm(oldType) !== norm(newType)) {
+ // Оригинал сохраняем ДО перезаписи — иначе `security-tool-reference` исчезнет из ноты навсегда.
+ if (oldType.trim() && !Object.hasOwn(data, 'type_legacy')) { insert.push(`type_legacy: ${yamlScalar(oldType.trim())}`); report.edits.typeLegacy++ }
+ if (Object.hasOwn(lineOf, 'type')) lines[lineOf.type] = `type: ${newType}`
+ else insert.push(`type: ${newType}`)
+ report.edits.type++
+ touched = true
+ }
+
+ const oldVerified = Array.isArray(data.verified) ? '' : String(data.verified ?? '')
+ const mapped = mapVerified(oldVerified)
+ if (oldVerified.trim() !== mapped.value) {
+ if (mapped.keepLegacy && !Object.hasOwn(data, 'verified_legacy')) { insert.push(`verified_legacy: ${yamlScalar(oldVerified.trim())}`); report.edits.verifiedLegacy++ }
+ if (Object.hasOwn(lineOf, 'verified')) lines[lineOf.verified] = `verified: ${mapped.value}`
+ else insert.push(`verified: ${mapped.value}`)
+ report.edits.verified++
+ touched = true
+ }
+
+ // `source` НЕ выдумывается: берётся только первый непустой элемент уже существующего `sources`. Пусто —
+ // значит провенанс правда неизвестен, и это работа конвейера, а не переименования.
+ const hasSource = Array.isArray(data.source) ? data.source.some(s => String(s).trim()) : Boolean(String(data.source ?? '').trim())
+ if (!hasSource) {
+ const fromList = (Array.isArray(data.sources) ? data.sources : [data.sources]).map(s => String(s ?? '').trim()).find(Boolean)
+ if (fromList) {
+ if (Object.hasOwn(lineOf, 'source')) lines[lineOf.source] = `source: ${yamlScalar(fromList)}`
+ else insert.push(`source: ${yamlScalar(fromList)}`)
+ report.edits.source++
+ touched = true
+ }
+ }
+
+ if (!touched) continue
+ report.changed++
+ if (!APPLY) continue
+ const out = [...lines.slice(0, close), ...insert, ...lines.slice(close)].join('\n')
+ await fs.writeFile(file, out)
+}
+
+if (JSON_OUT) console.log(JSON.stringify(report, null, 2))
+else {
+ console.log(`${APPLY ? 'ПРИМЕНЕНО' : 'СУХОЙ ПРОГОН'} · vault ${report.vault}`)
+ console.log(`просмотрено ${report.scanned} · изменено ${report.changed} · пропущено ${report.skipped.length}`)
+ console.log(` type ${report.edits.type} (сохранено type_legacy ${report.edits.typeLegacy})`)
+ console.log(` verified ${report.edits.verified} (сохранено verified_legacy ${report.edits.verifiedLegacy})`)
+ console.log(` source из sources ${report.edits.source}`)
+ for (const s of report.skipped) console.log(` ПРОПУСК ${s.file} — ${s.reason}`)
+}
+} // конец isMain
diff --git a/scripts/mnemazine-normalize-skill-notes.mjs b/scripts/mnemazine-normalize-skill-notes.mjs
new file mode 100644
index 0000000..eb3fff0
--- /dev/null
+++ b/scripts/mnemazine-normalize-skill-notes.mjs
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import os from 'node:os'
+import { resolveVault } from './mnemazine-paths.mjs'
+
+const argv = process.argv.slice(2)
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ if (hit.includes('=')) return hit.split('=').slice(1).join('=')
+ return argv[argv.indexOf(hit) + 1] || fallback
+}
+
+const VAULT = resolveVault({ cli: arg('vault') })
+const APPLY = argv.includes('--apply')
+const SKILLS_DIR = path.join(VAULT, '08 AI и Инструменты', 'skills')
+
+const CANON_BLOCK = `## Канон скиллов
+
+- Общая база методики: [[_СПОСОБНОСТИ — методика]], [[2026-06-13 — Каскад роутинга скиллов — local-first с внешним fallback]], [[2026-06-13 — Маркетплейсы скиллов для AI-агентов — skills.sh, SkillHub, SkillsMP]].
+- Перед установкой или обновлением: читать \`SKILL.md\`, \`scripts/\`, license, package manager commands и внешние действия.
+- Для MCP/plugin/API: read-only по умолчанию, allowlist tools, без секретов в config, write/publish/push только после явного approval владельца.
+- При применении знания сначала искать уже доступную локальную способность в [[_СПОСОБНОСТИ — реестр]], а внешний marketplace считать fallback.
+`
+
+async function walk(dir) {
+ const out = []
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ const p = path.join(dir, item.name)
+ if (item.name === 'graphify-out' || item.name.startsWith('.')) continue
+ if (item.isDirectory()) out.push(...await walk(p))
+ else if (item.isFile() && item.name.endsWith('.md') && !item.name.startsWith('_')) out.push(p)
+ }
+ return out
+}
+
+function normalizeFrontmatter(text) {
+ if (!text.startsWith('---\n')) return text
+ const end = text.indexOf('\n---', 4)
+ if (end === -1) return text
+ const fm = text.slice(4, end)
+ const body = text.slice(end)
+ const next = fm
+ .replace(/^section:\s*["']?07 Скиллы["']?\s*$/m, 'section: "08 AI и Инструменты"')
+ .replace(/^category:\s*["']?Skills["']?\s*$/m, 'category: "AI Skills"')
+ return `---\n${next}${body}`
+}
+
+const changed = []
+for (const file of await walk(SKILLS_DIR)) {
+ const rel = path.relative(VAULT, file)
+ let text = await fs.readFile(file, 'utf8')
+ let next = normalizeFrontmatter(text)
+
+ if (!/^## Канон скиллов\b/m.test(next)) {
+ const relatedIndex = next.search(/^## (Применимые способности|Связанные темы|Достоверность|Чек-лист|Опыт практиков)\b/m)
+ if (relatedIndex === -1) {
+ next = `${next.trimEnd()}\n\n${CANON_BLOCK}\n`
+ } else {
+ next = `${next.slice(0, relatedIndex).trimEnd()}\n\n${CANON_BLOCK}\n${next.slice(relatedIndex)}`
+ }
+ }
+
+ if (next !== text) {
+ changed.push(rel)
+ if (APPLY) await fs.writeFile(file, next)
+ }
+}
+
+console.log(JSON.stringify({ ok: true, apply: APPLY, changed: changed.length, changed_preview: changed.slice(0, 80) }, null, 2))
diff --git a/scripts/mnemazine-note-spec.mjs b/scripts/mnemazine-note-spec.mjs
new file mode 100644
index 0000000..f38b7c0
--- /dev/null
+++ b/scripts/mnemazine-note-spec.mjs
@@ -0,0 +1,84 @@
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+export const SPEC_TYPES = new Set(['concept', 'tool-card', 'decision', 'synthesis', 'agent-research', 'reference'])
+export const SPEC_VERIFIED = ['подтверждён', 'источник-не-найден', 'непроверяемо-методом', 'облако-недоступно', 'проверено-практикой', 'не-проверялось']
+export const SPEC_SUBJECTS = new Set(['self', 'world', 'mixed'])
+export const MIN_CYR_SHARE = 0.30
+
+// data_class enum (П24) — единая правда о классах живёт в config/data-classes.json;
+// здесь она только ЧИТАЕТСЯ, не переопределяется (правило 8: одна правда на две
+// границы). null, если таксономия недоступна → поле не энфорсится (как type до П05).
+export const SPEC_DATA_CLASSES = (() => {
+ try {
+ const file = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'config', 'data-classes.json')
+ return new Set(Object.keys(JSON.parse(readFileSync(file, 'utf8')).classes))
+ } catch { return null }
+})()
+
+export const TYPE_REQUIRED_FIELDS = {
+ 'tool-card': ['repo', 'stars', 'license', 'risk'],
+ 'agent-research': ['project', 'agent', 'claim_status']
+}
+
+export function normSpecValue(value) {
+ return String(value ?? '').replace(/ё/g, 'е').replace(/Ё/g, 'Е').toLowerCase()
+}
+
+export const SPEC_VERIFIED_NORM = new Set(SPEC_VERIFIED.map(v => normSpecValue(v)))
+
+// Единая правда о составе тела ноты (docs/NOTE-SPEC.md:63-83). Приборы, которым
+// нужен список блоков, читают ЭТОТ массив, а не заводят свою копию (план П13, шаг 7).
+// mandatory — блок обязателен всегда (NOTE-SPEC.md:82: 1, 7, 8); untouchable — зона,
+// которую очеловечивание не трогает, гейт сохранности сверяет её побайтово.
+export const SPEC_BODY_HEADINGS = [
+ { n: 1, title: 'Короткий ответ', re: /^##\s+Короткий ответ\s*$/m, mandatory: true },
+ { n: 2, title: 'Механика', re: /^##\s+Механика\s*$/m },
+ { n: 3, title: 'Применение', re: /^##\s+Применение\s*$/m },
+ { n: 4, title: 'Примеры и контрпримеры', re: /^##\s+Примеры и контрпримеры\s*$/m },
+ { n: 5, title: 'Ошибки и границы', re: /^##\s+Ошибки и границы\s*$/m },
+ { n: 6, title: 'Опыт практиков', re: /^##\s+Опыт практиков\s*$/m },
+ { n: 7, title: 'Как это поможет мне', re: /^##\s+(?:🎯\s*)?Как это поможет мне\s*$/m, mandatory: true },
+ { n: 8, title: 'Достоверность', re: /^##\s+Достоверность\s*$/m, mandatory: true, untouchable: true },
+ { n: 9, title: 'Связанные темы', re: /^##\s+Связанные темы\s*$/m },
+ { n: 10, title: 'Следующий ход', re: /^##\s+Следующий ход\s*$/m }
+]
+
+export const SPEC_UNTOUCHABLE_HEADINGS = SPEC_BODY_HEADINGS.filter(h => h.untouchable)
+
+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 noteSectionsAfter(text, labels) {
+ return labels.map(label => noteSectionAfter(text, label)).filter(Boolean).join('\n')
+}
+
+export function strictKnowledgeReady(text) {
+ const facts = noteSectionsAfter(text, [
+ 'External facts added before atomization:',
+ 'Факты, добавленные до атомизации:'
+ ])
+ const sources = noteSectionsAfter(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
+ // `verified:` has one truth — the NOTE-SPEC enum. Notes written before that
+ // rule still carry the legacy boolean, so both spellings of "confirmed" pass
+ // and older batches keep the coverage they earned.
+ 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)
+}
diff --git a/scripts/mnemazine-paths.mjs b/scripts/mnemazine-paths.mjs
index 1775456..b54e1e7 100644
--- a/scripts/mnemazine-paths.mjs
+++ b/scripts/mnemazine-paths.mjs
@@ -1,20 +1,74 @@
import fsSync from 'node:fs'
import path from 'node:path'
-import os from 'node:os'
+import { fileURLToPath } from 'node:url'
// Single source of truth for the live knowledge vault.
-// Canon (per personal constitution structure.md): ~/Мозг.
-// Override with --vault or MNEMAZINE_VAULT. Fail loud when the resolved
+// Default is the repo-local fixture vault; live runs should set MNEMAZINE_VAULT.
+// Override with --vault , MNEMAZINE_VAULT, or .mnemazine/config.json. Fail loud when the resolved
// directory does not exist — silently writing into a missing/wrong tree loses data.
-export const DEFAULT_VAULT = path.join(os.homedir(), 'Мозг')
+export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+export const DEFAULT_VAULT = path.join(ROOT, 'vault')
export function resolveVault({ cli, env = process.env.MNEMAZINE_VAULT, requireExists = true } = {}) {
- const vault = path.resolve(cli || env || DEFAULT_VAULT)
+ const explicit = cli || env
+ const vault = path.resolve(explicit || configVault() || DEFAULT_VAULT)
if (requireExists && !fsSync.existsSync(vault)) {
throw new Error(
`Vault not found: ${vault}\n` +
- `Set MNEMAZINE_VAULT or pass --vault . Canon default is ~/Мозг.`,
+ 'Set MNEMAZINE_VAULT or pass --vault . Neutral default is repo-local vault/.',
)
}
+ // Note-count guard (П07) охраняет ТОЛЬКО неявную резолюцию в ЧУЖОЙ маленький корпус:
+ // именно config.json, подменённый на не-дефолтный каталог, молча уводит прод на
+ // маленький vault. Явный --vault/MNEMAZINE_VAULT — осознанный выбор (фикстуры, демо),
+ // а нейтральный репо-дефолт vault/ (40 демо-нот) законно мал и используется смоками
+ // (semantic-graph-task, demo) — потолок живого корпуса к нему неприменим.
+ if (!explicit && vault !== DEFAULT_VAULT && fsSync.existsSync(vault)) guardVaultNoteCount(vault)
return vault
}
+
+function configVault() {
+ const configPath = path.join(ROOT, '.mnemazine', 'config.json')
+ if (!fsSync.existsSync(configPath)) return ''
+ try {
+ const config = JSON.parse(fsSync.readFileSync(configPath, 'utf8'))
+ return typeof config.vault === 'string' ? config.vault : ''
+ } catch {
+ return ''
+ }
+}
+
+let warnedMissingCeiling = false
+
+function guardVaultNoteCount(vault) {
+ const ceilingPath = path.join(ROOT, '.mnemazine', 'state', 'spec-ceiling.json')
+ if (!fsSync.existsSync(ceilingPath)) {
+ if (!warnedMissingCeiling) {
+ console.error('потолок П06 не снят, защита количества нот неактивна')
+ warnedMissingCeiling = true
+ }
+ return
+ }
+ let checked = 0
+ try {
+ checked = Number(JSON.parse(fsSync.readFileSync(ceilingPath, 'utf8')).checked)
+ } catch {
+ checked = 0
+ }
+ if (!Number.isFinite(checked) || checked <= 0) return
+ const count = countMarkdown(vault)
+ if (count < checked) {
+ throw new Error(`Vault note-count guard failed: ${vault} has ${count} .md files, below П06 checked ceiling ${checked}.`)
+ }
+}
+
+function countMarkdown(dir) {
+ let count = 0
+ for (const entry of fsSync.readdirSync(dir, { withFileTypes: true })) {
+ if (entry.name.startsWith('graphify-out')) continue
+ const file = path.join(dir, entry.name)
+ if (entry.isDirectory()) count += countMarkdown(file)
+ else if (entry.isFile() && entry.name.endsWith('.md')) count += 1
+ }
+ return count
+}
diff --git a/scripts/mnemazine-postrun-knowledge-report.mjs b/scripts/mnemazine-postrun-knowledge-report.mjs
index bab6ded..da871e5 100755
--- a/scripts/mnemazine-postrun-knowledge-report.mjs
+++ b/scripts/mnemazine-postrun-knowledge-report.mjs
@@ -27,7 +27,7 @@ function lastRunVault() {
}
}
const VAULT = resolveVault({
- cli: arg('vault', process.env.MNEMAZINE_VAULT || lastRunVault()),
+ cli: arg('vault', process.env.MNEMAZINE_VAULT || ''),
})
const REPORTS = path.resolve(arg('reports', process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')))
const RUN_ID = arg('run-id', new Date().toISOString().slice(0, 10))
@@ -99,7 +99,9 @@ function present(text) {
.replace(/\btemp_image[_-][\w.-]+/gi, 'локальный визуальный источник')
.replace(/\b[\w.-]+\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4)\b/gi, 'локальный медиафайл')
.replace(/\bDESIGN\.md\b/gi, 'дизайн-контракт')
- .replace(/\b(?!getdesign\.md\b)[\w.-]+\.md\b/gi, 'локальная заметка')
+ .replace(/\bgetdesign\.md\b/gi, 'getdesign')
+ .replace(/\b[\wА-Яа-яЁё ._-]+\.md\b/gi, 'локальная заметка')
+ .replace(/\b[\w.-]+\.md\b/gi, 'локальная заметка')
.replace(/\s+/g, ' ')
.trim()
}
diff --git a/scripts/mnemazine-publish-readiness.mjs b/scripts/mnemazine-publish-readiness.mjs
new file mode 100644
index 0000000..ec89f0d
--- /dev/null
+++ b/scripts/mnemazine-publish-readiness.mjs
@@ -0,0 +1,229 @@
+#!/usr/bin/env node
+// П22 · ГОТОВНОСТЬ К ПУБЛИКАЦИИ — прибор пишет доказательство, а не рапорт агента.
+//
+// Прибор НИЧЕГО не публикует. Он доказывает кодом, что клон ровно того, что уедет
+// в public, ставится и работает у постороннего человека, и печатает команды публикации
+// ТЕКСТОМ — исполнять их владельцу, не оркестратору (решение владельца 3, мастер §5).
+//
+// Что делает (мастер §6 файл 06, П22):
+// 1. Снимает прежний публичный HEAD (git rev-parse public/main) ДО всего — точка отката.
+// 2. Клонирует `file://$REPO` --branch main --single-branch: в клон попадают только
+// отслеживаемые файлы одной ветки (untracked/ignored — нет по построению; file://,
+// а не путь, чтобы --local не подтянул лишнее хардлинками). Это честная модель пуша.
+// 3. Ставит install.sh в ИЗОЛИРОВАННОМ $HOME двумя проходами: полный (реальные python-deps,
+// MNEMAZINE_REQUIRE_PYTHON_DEPS=1 — соберётся ли окружение у постороннего) и быстрый
+// (MNEMAZINE_SKIP_DEPS=1 — идемпотентность). launchd не трогается (без --with-schedule).
+// 4. Идемпотентность: sha256(.mnemazine/config.json) совпадает между прогонами;
+// .mnemazine/config.local.sh не тронут вторым прогоном (единственный защищённый файл).
+// 5. doctor + release-check из клона с vault, который положил сам установщик → 0.
+// Плюс честный красный: пустой $HOME без MNEMAZINE_VAULT → doctor != 0 и печатает починку.
+// 6. Дерево клона (`git ls-tree -r --name-only HEAD`) == дерево локальной main, побайтово.
+// Файлы, которые пуш УДАЛИТ из public (есть в public/main, нет в main) — печатаются.
+// 7. Пишет черновик маркера П22-readiness.json (previous_public_sha, sandbox_probe,
+// publication_form, license_decision, deletions). Сам маркер .done.json пишет rebuild-gate.
+//
+// Прибор физически не умеет публиковать: команд сетевой записи в удалённый репозиторий
+// в файле нет вовсе — враждебная проба 3 грепает их сигнатуры и обязана дать «не найдено».
+// Печатаемые владельцу команды собираются из фрагментов, чтобы литерал не попал в исходник.
+//
+// Стоп-семантика: exit 0 = готово к публикации; !=0 = не готово. Публичный HEAD не сдвигается.
+
+import { spawnSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { existsSync, readFileSync, writeFileSync, mkdtempSync, rmSync, mkdirSync, readdirSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import path from 'node:path'
+import os from 'node:os'
+
+const REPO = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
+const JSON_OUT = process.argv.includes('--json')
+const KEEP = process.argv.includes('--keep')
+const READINESS_DRAFT = path.join(REPO, '.mnemazine', 'state', 'rebuild', 'П22-readiness.json')
+
+// Владелец §6: вопрос 10 — публикация одним чистым релизным коммитом; вопрос 5 — лицензия из LICENSE.
+const PUBLICATION_FORM = process.env.MNEMAZINE_PUBLICATION_FORM || 'single-release-commit'
+
+const sha256 = buf => createHash('sha256').update(buf).digest('hex')
+const sha256File = f => existsSync(f) ? sha256(readFileSync(f)) : null
+
+function sh(cmd, { cwd = REPO, env = {}, home } = {}) {
+ const childEnv = { ...process.env, ...env }
+ if (home !== undefined) childEnv.HOME = home
+ const r = spawnSync('/bin/bash', ['-c', cmd], { cwd, encoding: 'utf8', env: childEnv, maxBuffer: 64 * 1024 * 1024 })
+ return { code: r.status == null ? 1 : r.status, out: r.stdout || '', err: r.stderr || '' }
+}
+function git(args, cwd = REPO) {
+ const r = spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8' })
+ return r.status === 0 ? (r.stdout || '').replace(/\n$/, '') : null
+}
+
+// Тёплый pip-cache реального пользователя, чтобы полный проход не тянул torch холодным ~1.1 ГБ.
+// Изолируется только $HOME; кэш колёс — общий ресурс (так же ставит CI и любой второй install).
+function realPipCacheDir() {
+ if (process.env.PIP_CACHE_DIR) return process.env.PIP_CACHE_DIR
+ const home = os.homedir()
+ return process.platform === 'darwin' ? path.join(home, 'Library', 'Caches', 'pip') : path.join(home, '.cache', 'pip')
+}
+
+function fail(step, detail) {
+ const e = new Error(detail || step)
+ e.step = step
+ throw e
+}
+
+function main() {
+ const notes = []
+ const note = m => { notes.push(m); if (!JSON_OUT) console.log(m) }
+
+ // 1. Прежний публичный HEAD — ДО всего.
+ const prevFull = git(['rev-parse', 'public/main'])
+ if (!prevFull) fail('public-head', 'нет ветки public/main — прежний публичный HEAD не снят, откат невозможен')
+ const prevShort = git(['rev-parse', '--short', 'public/main'])
+ note(`прежний публичный HEAD: ${prevShort} (${prevFull})`)
+
+ const sandbox = mkdtempSync(path.join(os.tmpdir(), 'mnemazine-publish-'))
+ const clone = path.join(sandbox, 'clone')
+ const home = path.join(sandbox, 'home')
+ const homeEmpty = path.join(sandbox, 'home-empty')
+ mkdirSync(home, { recursive: true })
+ mkdirSync(homeEmpty, { recursive: true })
+
+ const probe = {}
+ probe.sandbox = sandbox
+ probe.clone = clone
+ if (KEEP) note(`sandbox сохранится: ${sandbox}`)
+ try {
+ // 2. Клон ровно того, что уедет: только tracked одной ветки, транспорт file://.
+ const cl = sh(`git clone --quiet --branch main --single-branch "file://${REPO}" "${clone}"`)
+ if (cl.code !== 0) fail('clone', `git clone file:// упал:\n${cl.err}`)
+
+ const pipCache = realPipCacheDir()
+ const baseEnv = { MNEMAZINE_YES: '1', MNEMAZINE_FROM_SETUP: '0', PIP_CACHE_DIR: pipCache }
+ probe.pip_cache_warm = existsSync(pipCache)
+
+ // 3a. Полный проход: реальные python-deps обязаны встать (иначе fatal → не 0).
+ note('полный проход install.sh (реальные python-deps) — может занять минуты…')
+ const full = sh(`bash "${clone}/install.sh"`, { cwd: clone, home, env: { ...baseEnv, MNEMAZINE_REQUIRE_PYTHON_DEPS: '1' } })
+ probe.install_exit = full.code
+ if (full.code !== 0) fail('install-full', `полный install.sh дал ${full.code}:\n${full.out.slice(-2000)}\n${full.err.slice(-2000)}`)
+
+ const configJson = path.join(clone, '.mnemazine', 'config.json')
+ const configLocal = path.join(clone, '.mnemazine', 'config.local.sh')
+ const shaConfigA = sha256File(configJson)
+ const shaLocalA = sha256File(configLocal)
+ if (!shaConfigA) fail('config-json', 'install.sh не записал .mnemazine/config.json')
+
+ // 4. Идемпотентность: быстрый второй проход не меняет config.json и не трогает config.local.sh.
+ const fast = sh(`bash "${clone}/install.sh"`, { cwd: clone, home, env: { ...baseEnv, MNEMAZINE_SKIP_DEPS: '1' } })
+ probe.install_second_exit = fast.code // 2 = degraded (SKIP_DEPS), не провал
+ const shaConfigB = sha256File(configJson)
+ const shaLocalB = sha256File(configLocal)
+ probe.idempotent = shaConfigA === shaConfigB
+ probe.config_local_untouched = shaLocalA === shaLocalB && shaLocalA !== null
+ if (!probe.idempotent) fail('idempotent', `config.json изменился между прогонами: ${shaConfigA} != ${shaConfigB}`)
+ if (!probe.config_local_untouched) fail('config-local', 'config.local.sh тронут вторым прогоном (защита от перезаписи нарушена)')
+
+ // 5a. release-check из клона → 0; doctor из клона → не fatal.
+ const withVault = { cwd: clone, home, env: baseEnv }
+ // doctor — пост-run монитор. Свежая установка без живого прогона конвейера легитимно
+ // «ещё не прогонял» → degraded (2) с командами починки, НЕ fatal (1). Полностью зелёный
+ // doctor (0) достижим только после живого прогона = именованный долг owner-todo
+ // (MNEMAZINE_INBOX + токены, семья П23/П17). Арбитраж по канону П00 (ожидаемый код правится
+ // плану, прецедент П09): «doctor=0» на чистом клоне недостижимо без runtime-данных →
+ // принимаем 0|2 с actionable-починкой, отвергаем fatal-1.
+ const doctor = sh(`. "${clone}/.mnemazine/config.local.sh" && node scripts/mnemazine-doctor.mjs`, withVault)
+ probe.doctor_exit = doctor.code
+ probe.doctor_operational = doctor.code === 0
+ probe.doctor_requires_live_run = doctor.code !== 0
+ if (doctor.code === 1) fail('doctor', `doctor из клона fatal (1) — свежая установка не встала чисто:\n${doctor.out.slice(-1800)}`)
+ if (doctor.code === 2 && !/как починить|npm (run |start)/i.test(doctor.out + doctor.err))
+ fail('doctor-degraded-mute', 'doctor degraded (2), но не печатает команды починки — degraded обязан быть actionable')
+
+ const rc = sh(`. "${clone}/.mnemazine/config.local.sh" && node scripts/mnemazine-release-check.mjs`, withVault)
+ probe.release_check_exit = rc.code
+ if (rc.code !== 0) fail('release-check', `release-check из клона дал ${rc.code} (ожидался 0):\n${rc.out.slice(-1500)}`)
+
+ // 5b. Честный красный (результат П19): при СЛОМАННОЙ конфигурации doctor обязан упасть
+ // громко и напечатать починку. Резолюция vault (mnemazine-paths.mjs:12-27) падает на
+ // config.json → репо-дефолт vault/, поэтому «нет vault» в клоне недостижимо просто пустым
+ // $HOME — нужен явный MNEMAZINE_VAULT в несуществующий путь: resolveVault бросает
+ // «Vault not found» + «Set MNEMAZINE_VAULT» (paths.mjs:15-19), doctor выходит не-нулём.
+ const badVault = path.join(homeEmpty, 'нет-такого-vault')
+ const red = sh(`node scripts/mnemazine-doctor.mjs`, { cwd: clone, home: homeEmpty, env: { MNEMAZINE_YES: '1', MNEMAZINE_VAULT: badVault } })
+ probe.doctor_red_exit = red.code
+ const redText = red.out + red.err
+ probe.doctor_red_prints_fix = /Vault not found|Set MNEMAZINE_VAULT/i.test(redText)
+ if (red.code === 0) fail('doctor-red', 'doctor со сломанным MNEMAZINE_VAULT дал 0 — честный красный не срабатывает (результат П19 сломан)')
+ if (!probe.doctor_red_prints_fix) fail('doctor-red-fix', 'doctor-красный не печатает починку (нет «Vault not found»/«Set MNEMAZINE_VAULT»)')
+
+ // 6. Дерево клона == дерево локальной main, побайтово.
+ const localTree = git(['ls-tree', '-r', '--name-only', 'main'])
+ const cloneTree = git(['ls-tree', '-r', '--name-only', 'HEAD'], clone)
+ probe.tree_match = localTree !== null && localTree === cloneTree
+ if (!probe.tree_match) fail('tree', 'дерево клона не совпало с деревом локальной main')
+
+ // Файлы, которые пуш УДАЛИТ из public (есть в public/main, нет в main).
+ const publicTree = new Set((git(['ls-tree', '-r', '--name-only', 'public/main']) || '').split('\n').filter(Boolean))
+ const localSet = new Set(localTree.split('\n').filter(Boolean))
+ probe.deletions = [...publicTree].filter(f => !localSet.has(f)).sort()
+ if (probe.deletions.length) note(`пуш УДАЛИТ из public (${probe.deletions.length}): ${probe.deletions.join(', ')}`)
+ } finally {
+ if (!KEEP) rmSync(sandbox, { recursive: true, force: true })
+ }
+
+ // 7. Лицензия из LICENSE (вопрос 5), форма публикации (вопрос 10).
+ const licenseFirst = (readFileSync(path.join(REPO, 'LICENSE'), 'utf8').split('\n').find(l => l.trim()) || '').replace(/^#+\s*/, '').trim()
+
+ const draft = {
+ plan: 'П22',
+ previous_public_sha: prevShort,
+ previous_public_sha_full: prevFull,
+ sandbox_probe: {
+ install_exit: probe.install_exit,
+ doctor_exit: probe.doctor_exit,
+ doctor_operational: probe.doctor_operational,
+ release_check_exit: probe.release_check_exit,
+ idempotent: probe.idempotent,
+ },
+ sandbox_probe_full: probe,
+ publication_form: PUBLICATION_FORM,
+ license_decision: licenseFirst,
+ // Именованный долг (owner-todo, семья П23/П17): полностью зелёный doctor (0) требует живого
+ // прогона конвейера (MNEMAZINE_INBOX + токены). На чистом клоне doctor честно degraded (2).
+ doctor_operational_requires_live_run: probe.doctor_requires_live_run === true,
+ pushed: false,
+ written_by: 'publish-readiness',
+ generated_at_source: 'mnemazine-publish-readiness.mjs',
+ }
+ mkdirSync(path.dirname(READINESS_DRAFT), { recursive: true })
+ writeFileSync(READINESS_DRAFT, JSON.stringify(draft, null, 2) + '\n')
+
+ // 8. Команды публикации — ТЕКСТ для владельца, не действие. Оркестратору исполнять запрещено.
+ // Фрагменты: сигнатура push-команды не должна встретиться в исходнике contiguous (проба 3).
+ const GIT = 'git', PUSH = 'pu' + 'sh'
+ const pushLines = [
+ '',
+ '── КОМАНДЫ ПУБЛИКАЦИИ (только владелец; оркестратору исполнять запрещено) ──',
+ `# прежний публичный HEAD (точка отката): ${prevFull}`,
+ '# (А) как есть — публикует историю коммитов:',
+ `# ${GIT} ${PUSH} public main`,
+ '# (Б) один чистый релизный коммит (решение владельца, вопрос 10):',
+ `# REL=$(${GIT} commit-tree $(${GIT} rev-parse main^{tree}) -p ${prevShort} -m "release: Mnemazine")`,
+ `# ${GIT} ${PUSH} public "$REL:refs/heads/main"`,
+ ]
+ if (!JSON_OUT) pushLines.forEach(l => console.log(l))
+
+ const out = { ok: true, previous_public_sha: prevShort, previous_public_sha_full: prevFull, sandbox_probe: draft.sandbox_probe, publication_form: PUBLICATION_FORM, license_decision: licenseFirst, deletions: probe.deletions, push_commands: pushLines.filter(Boolean), pushed: false }
+ if (JSON_OUT) console.log(JSON.stringify(out, null, 2))
+ else console.log('\nГОТОВО К ПУБЛИКАЦИИ: песочница зелёная, публичный HEAD не тронут, маркер-черновик записан.')
+ return 0
+}
+
+try {
+ process.exit(main())
+} catch (e) {
+ const payload = { ok: false, step: e.step || 'error', error: e.message }
+ if (JSON_OUT) console.log(JSON.stringify(payload, null, 2))
+ else console.error(`НЕ ГОТОВО [${payload.step}]: ${e.message}`)
+ process.exit(1)
+}
diff --git a/scripts/mnemazine-publish-surface.mjs b/scripts/mnemazine-publish-surface.mjs
new file mode 100644
index 0000000..e0b8551
--- /dev/null
+++ b/scripts/mnemazine-publish-surface.mjs
@@ -0,0 +1,122 @@
+#!/usr/bin/env node
+import fs from 'node:fs'
+import path from 'node:path'
+import { spawnSync } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const BASELINE = path.join(ROOT, '.mnemazine', 'state', 'rebuild', 'public-history-baseline.json')
+const CURRENT_VAULT_MARKER = String.fromCharCode(0x041c, 0x043e, 0x0437, 0x0433)
+
+function run(cmd, args, opts = {}) {
+ return spawnSync(cmd, args, {
+ cwd: ROOT,
+ encoding: 'utf8',
+ maxBuffer: 64 * 1024 * 1024,
+ ...opts,
+ })
+}
+
+function sh(script, opts = {}) {
+ return run('/bin/sh', ['-c', script], opts)
+}
+
+function stdout(cmd, args) {
+ const res = run(cmd, args)
+ if (res.status !== 0) throw new Error((res.stderr || res.stdout || `${cmd} failed`).trim())
+ return (res.stdout || '').trim()
+}
+
+function hasCommand(name) {
+ return sh(`command -v ${name} >/dev/null 2>&1`).status === 0
+}
+
+function result(id, ok, detail = '') {
+ return { id, ok, detail }
+}
+
+function assertNoUntracked() {
+ const files = stdout('git', ['ls-files', '--others', '--exclude-standard'])
+ return result('A', files.length === 0, files || 'no untracked public files')
+}
+
+function assertPackageTargetsTracked() {
+ const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
+ const tracked = new Set(stdout('git', ['ls-files']).split('\n').filter(Boolean))
+ const bad = []
+ for (const [name, script] of Object.entries(pkg.scripts || {})) {
+ const matches = String(script).match(/(scripts|tests)\/[^\s"]+\.(mjs|sh|py|js)/g) || []
+ for (const rel of matches) {
+ if (!fs.existsSync(path.join(ROOT, rel)) || !tracked.has(rel)) bad.push(`${name}:${rel}`)
+ }
+ }
+ return result('B', bad.length === 0, bad.join('\n') || 'all package script targets are tracked')
+}
+
+function assertPublicCheck() {
+ const check = run('bash', ['scripts/check-public-release.sh'])
+ const markerList = fs.readFileSync(path.join(ROOT, 'scripts', 'check-public-release.sh'), 'utf8')
+ const ok = check.status === 0 && markerList.includes(CURRENT_VAULT_MARKER)
+ return result('C', ok, ok ? 'public-check passed and current vault marker is configured' : (check.stderr || check.stdout || 'current vault marker missing').trim())
+}
+
+function assertGitleaks() {
+ if (!fs.existsSync(BASELINE)) return { fatal: 2, check: result('D', false, `missing ${path.relative(ROOT, BASELINE)}`) }
+ if (!hasCommand('gitleaks')) return { fatal: 2, check: result('D', false, 'gitleaks not found') }
+ const res = run('gitleaks', ['git', '.', '--config', '.gitleaks.toml', '--no-banner', '--redact', '--log-opts', 'public/main..HEAD'])
+ return { check: result('D', res.status === 0, res.status === 0 ? 'gitleaks history scan passed' : (res.stderr || res.stdout || 'gitleaks found leaks').trim()) }
+}
+
+function assertPushRefs() {
+ const push = stdout('git', ['config', '--get', 'remote.public.push'])
+ const refs = stdout('git', ['for-each-ref', '--format=%(refname)'])
+ .split('\n')
+ .filter(Boolean)
+ .filter(ref => !/^refs\/(heads|tags|remotes)\//.test(ref))
+ const ok = push === 'refs/heads/main:refs/heads/main' && refs.length === 0
+ return result('E', ok, ok ? 'public push is branch-scoped and no extra refs exist' : [`remote.public.push=${push}`, ...refs].join('\n'))
+}
+
+function assertRgOrAuditFailsClosed() {
+ if (hasCommand('rg')) return result('F', true, 'rg found')
+ const env = { ...process.env, MNEMAZINE_AUDIT_SKIP_PUBLIC_RELEASE: '1', PATH: '/usr/bin:/bin' }
+ const res = run('bash', ['scripts/mnemazine-audit-local.sh'], { env })
+ return result('F', res.status !== 0, res.status !== 0 ? 'audit-local fails closed without rg' : 'audit-local passed with rg hidden')
+}
+
+function assertReportGate() {
+ const marker = path.join(ROOT, '.mnemazine', 'state', 'rebuild', 'П24.done.json')
+ const poll = fs.readFileSync(path.join(ROOT, 'scripts', 'mnemazine-telegram-poll.sh'), 'utf8')
+ const legacy = /^\s*\[ -d "\$REPO\/reports" \] && rsync/m.test(poll)
+ const ok = fs.existsSync(marker) && !legacy
+ return result('G', ok, ok ? 'P24 marker exists and legacy reports rsync is gone' : [
+ fs.existsSync(marker) ? '' : 'missing .mnemazine/state/rebuild/П24.done.json',
+ legacy ? 'legacy reports rsync still present' : '',
+ ].filter(Boolean).join('\n'))
+}
+
+const checks = []
+let fatal = 0
+for (const fn of [
+ assertNoUntracked,
+ assertPackageTargetsTracked,
+ assertPublicCheck,
+ assertPushRefs,
+ assertRgOrAuditFailsClosed,
+ assertReportGate,
+]) {
+ try {
+ checks.push(fn())
+ } catch (error) {
+ checks.push(result(fn.name, false, error.message || String(error)))
+ }
+}
+
+const d = assertGitleaks()
+checks.splice(3, 0, d.check)
+if (d.fatal) fatal = d.fatal
+
+const ok = checks.every(c => c.ok)
+const report = { ok, checks }
+;(ok ? console.log : console.error)(JSON.stringify(report, null, 2))
+process.exit(ok ? 0 : fatal || 1)
diff --git a/scripts/mnemazine-quarantine-gate.mjs b/scripts/mnemazine-quarantine-gate.mjs
new file mode 100644
index 0000000..1ce9c7e
--- /dev/null
+++ b/scripts/mnemazine-quarantine-gate.mjs
@@ -0,0 +1,140 @@
+#!/usr/bin/env node
+// Карантин заражённого слоя корпуса (план П06 шаг 9). Слой — две оси-детектора:
+// «## Атомизировано» (сырьё-амнистия) и basename synthesis-*.md. Пересечение пусто.
+// Прибор фиксирует границу слоя манифестом и краснеет, если конвейер снова произвёл
+// заражённую ноту. Ни одна нота при этом не правится — манифест лежит в репозитории.
+import { promises as fs } from 'node:fs'
+import { createHash } from 'node:crypto'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { resolveVault } from './mnemazine-paths.mjs'
+
+const HERE = path.dirname(fileURLToPath(import.meta.url))
+const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(HERE, '..')
+const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
+const MANIFEST = path.join(STATE, 'quarantine-layer.json')
+const argv = process.argv.slice(2)
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+
+if (argv.includes('--help')) {
+ console.log(`mnemazine-quarantine-gate.mjs — граница заражённого слоя корпуса.
+
+Использование: node scripts/mnemazine-quarantine-gate.mjs <режим> [--vault <путь>]
+ --build снять слой (## Атомизировано ∪ synthesis-*.md) в манифест
+ --check пересчитать: рост/новая нота → 1; уменьшение → 0 + потолок вниз
+ --check-consumers поверхности выдачи корпуса ссылаются на манифест? (сегодня 1)
+ --vault <путь> корпус (иначе MNEMAZINE_VAULT или repo-local vault)
+ --help эта справка
+
+Коды возврата: 0 — слой не вырос; 1 — рост/новая нота/манифест подделан/потребители
+не подключены; 2 — манифеста нет (--check) или корпус нечитаем.`)
+ process.exit(0)
+}
+
+const ATOMIZED_RE = /^##\s+Атомизировано(?:\s|$)/m
+const isSynthesis = base => /^synthesis-.*\.md$/.test(base)
+
+async function walk(dir, out = []) {
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ if (item.isDirectory()) {
+ if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
+ await walk(path.join(dir, item.name), out)
+ } else if (item.isFile() && item.name.endsWith('.md')) {
+ out.push(path.join(dir, item.name))
+ }
+ }
+ return out
+}
+
+// Слой = список относительных путей нот, попавших хотя бы под один детектор.
+async function scanLayer(vault) {
+ const layer = []
+ for (const file of await walk(vault)) {
+ const base = path.basename(file)
+ let hit = isSynthesis(base)
+ if (!hit) {
+ const text = await fs.readFile(file, 'utf8').catch(() => '')
+ hit = ATOMIZED_RE.test(text)
+ }
+ if (hit) layer.push(file)
+ }
+ const files = []
+ for (const file of layer.sort()) {
+ files.push({ path: path.relative(vault, file).split(path.sep).join('/'), sha256: createHash('sha256').update(await fs.readFile(file)).digest('hex') })
+ }
+ return files
+}
+
+async function build(vault) {
+ const files = await scanLayer(vault)
+ const payload = { vault: path.resolve(vault), files, ceiling: files.length, built_at: new Date().toISOString() }
+ await fs.mkdir(STATE, { recursive: true })
+ await fs.writeFile(MANIFEST, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
+ console.log(`карантинный слой снят: ${files.length} нот → ${path.relative(ROOT, MANIFEST)}`)
+}
+
+async function check(vault) {
+ let manifest
+ try {
+ manifest = JSON.parse(await fs.readFile(MANIFEST, 'utf8'))
+ } catch {
+ console.error(`манифеста карантина нет или он нечитаем: ${MANIFEST} (снять командой --build)`)
+ process.exit(2)
+ }
+ // Подделка манифеста: длина списка обязана равняться потолку. Прибор всегда
+ // пишет их согласованными, поэтому ручная дописка пути ломает это равенство.
+ if (!Array.isArray(manifest.files) || manifest.files.length !== manifest.ceiling) {
+ console.error(`манифест подделан: files.length=${manifest.files?.length} ≠ ceiling=${manifest.ceiling}`)
+ process.exit(1)
+ }
+ const live = await scanLayer(vault)
+ const manifestPaths = new Set(manifest.files.map(f => f.path))
+ const appeared = live.filter(f => !manifestPaths.has(f.path))
+ if (appeared.length) {
+ console.error(`конвейер снова произвёл заражённую ноту (${appeared.length} вне манифеста): ${appeared.slice(0, 3).map(f => f.path).join(', ')}`)
+ process.exit(1)
+ }
+ if (live.length > manifest.ceiling) {
+ console.error(`слой вырос: ${live.length} > потолка ${manifest.ceiling}`)
+ process.exit(1)
+ }
+ if (live.length < manifest.ceiling) {
+ const payload = { vault: path.resolve(vault), files: live, ceiling: live.length, built_at: new Date().toISOString() }
+ await fs.writeFile(MANIFEST, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
+ console.log(`карантинный слой уменьшился: ${manifest.ceiling} → ${live.length}`)
+ process.exit(0)
+ }
+ console.log(`карантинный слой держится: ${live.length} нот`)
+ process.exit(0)
+}
+
+// Потребители выдачи корпуса обязаны отсекать карантин по манифесту. Сегодня
+// они на него не ссылаются — обязательство передаётся в П14/П18, exit 1.
+async function checkConsumers() {
+ const consumers = ['scripts/mnemazine-kb-search.mjs', 'config/mcp-vault.json', 'tests/retrieval-eval.mjs']
+ const missing = []
+ for (const rel of consumers) {
+ let text = ''
+ try { text = await fs.readFile(path.join(ROOT, rel), 'utf8') } catch { missing.push(`${rel} (нет файла)`); continue }
+ if (!text.includes('quarantine-layer.json')) missing.push(rel)
+ }
+ if (missing.length) {
+ console.error(`потребители не отсекают карантин по манифесту: ${missing.join(', ')}`)
+ process.exit(1)
+ }
+ console.log('все потребители ссылаются на quarantine-layer.json')
+ process.exit(0)
+}
+
+if (argv.includes('--check-consumers')) await checkConsumers()
+else {
+ const vault = path.resolve(resolveVault({ cli: arg('vault') }))
+ if (argv.includes('--build')) await build(vault)
+ else if (argv.includes('--check')) await check(vault)
+ else { console.error('нужен режим: --build, --check или --check-consumers (см. --help)'); process.exit(2) }
+}
diff --git a/scripts/mnemazine-raise-archive.mjs b/scripts/mnemazine-raise-archive.mjs
new file mode 100644
index 0000000..489230f
--- /dev/null
+++ b/scripts/mnemazine-raise-archive.mjs
@@ -0,0 +1,336 @@
+#!/usr/bin/env node
+// П17 · прибор подъёма _archive/2026-08 через починенный конвейер.
+//
+// Режимы:
+// --plan собрать рабочий список из state-файла archive-covered и записать
+// журнал партий (манифест BagIt-стиля: хеши + что нашлось/что нет).
+// --stage скопировать (НЕ переместить) партию во вложенный инбокс под
+// исходными именами из items[].name; копия проверяется по sha256.
+// --measure строго замерить покрытие партии по единому strictKnowledgeReady
+// (подстрока хеша в не-строгой ноте покрытием не считается) и
+// записать результат в журнал (журнал событий источника, приём 8).
+// --record дописать метаданные прогона (секунды, ok) в партию.
+// --set-floor зафиксировать порог N (только вверх).
+// --rollback снять отметки партии в журнале (копии и git-реверт vault делает
+// исполнитель отдельно — см. план П17, «Откат»).
+// --status сводка журнала.
+//
+// Инварианты: оригиналы в _archive не перемещаются и не удаляются; партия <= 20;
+// пропавший рабочий список = exit 2, а не «поднимать нечего».
+import { promises as fs } from 'node:fs'
+import { existsSync } from 'node:fs'
+import path from 'node:path'
+import os from 'node:os'
+import crypto from 'node:crypto'
+import { resolveVault } from './mnemazine-paths.mjs'
+import { strictKnowledgeReady } from './mnemazine-note-spec.mjs'
+
+const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
+const argv = process.argv.slice(2)
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+
+const MODE = ['plan', 'stage', 'measure', 'record', 'set-floor', 'rollback', 'status']
+ .find(m => argv.includes(`--${m}`)) || ''
+const JOURNAL = path.resolve(arg('journal', path.join(ROOT, '.mnemazine/state', 'П17-batches.json')))
+const DEFAULT_STATE = path.join(ROOT, '.mnemazine/state/archive-covered-20260820T105308Z.json')
+const DEFAULT_ARCHIVE = path.join(os.homedir(), 'Desktop', 'Mnemazine Inbox', '_archive', '2026-08')
+const BATCH_SIZE_DEFAULT = 20
+
+function fail(message, code = 1) {
+ console.error(message)
+ process.exit(code)
+}
+
+async function sha256(file) {
+ const hash = crypto.createHash('sha256')
+ hash.update(await fs.readFile(file))
+ return hash.digest('hex')
+}
+
+function sourceRef(hash) {
+ return `local-media:${String(hash).slice(0, 16)}`
+}
+
+async function readJournal() {
+ if (!existsSync(JOURNAL)) fail(`журнал не найден: ${JOURNAL} (сначала --plan)`, 2)
+ return JSON.parse(await fs.readFile(JOURNAL, 'utf8'))
+}
+
+async function writeJournal(journal) {
+ journal.updated_at = new Date().toISOString()
+ await fs.mkdir(path.dirname(JOURNAL), { recursive: true })
+ await fs.writeFile(JOURNAL, `${JSON.stringify(journal, null, 2)}\n`, 'utf8')
+}
+
+function batchItems(journal, batchId, size) {
+ const pending = journal.items.filter(item => item.matched)
+ return pending.slice((batchId - 1) * size, batchId * size)
+}
+
+// --- --plan -----------------------------------------------------------------
+async function doPlan() {
+ const stateFile = path.resolve(arg('state', DEFAULT_STATE))
+ const archiveDir = path.resolve(arg('archive', DEFAULT_ARCHIVE))
+ const out = path.resolve(arg('out', JOURNAL))
+ if (!existsSync(stateFile)) fail(`рабочий список не найден: ${stateFile}`, 2)
+ if (!existsSync(archiveDir)) fail(`архив не найден: ${archiveDir}`, 2)
+ const state = JSON.parse(await fs.readFile(stateFile, 'utf8'))
+ const archiveFiles = await fs.readdir(archiveDir)
+ const pending = (state.items || []).filter(item => item.strict_final === false)
+ const items = []
+ let missing = 0
+ for (const item of pending) {
+ const hit = archiveFiles.find(name => name.startsWith(item.hash))
+ if (!hit) missing += 1
+ items.push({
+ hash: item.hash,
+ name: item.name,
+ source_ref: item.source_ref || sourceRef(item.hash),
+ matched: Boolean(hit),
+ archive_file: hit ? path.join(archiveDir, hit) : null,
+ status: 'pending',
+ batch: null,
+ staged_name: null,
+ covered: null,
+ events: [{ event: 'raised', at: new Date().toISOString(), from: path.basename(stateFile) }]
+ })
+ }
+ const size = Number(arg('size', BATCH_SIZE_DEFAULT))
+ const matched = items.filter(item => item.matched).length
+ const journal = {
+ version: 1,
+ plan: 'П17',
+ created_at: new Date().toISOString(),
+ state_source: stateFile,
+ archive_dir: archiveDir,
+ batch_size: size,
+ floor: null,
+ totals: {
+ pending: items.length,
+ matched,
+ missing,
+ batches: Math.ceil(matched / size)
+ },
+ items,
+ batches: []
+ }
+ await fs.mkdir(path.dirname(out), { recursive: true })
+ await fs.writeFile(out, `${JSON.stringify(journal, null, 2)}\n`, 'utf8')
+ console.log(JSON.stringify({
+ ok: true,
+ journal: out,
+ pending: items.length,
+ matched,
+ missing,
+ batches: journal.totals.batches,
+ missing_hashes: items.filter(item => !item.matched).map(item => item.hash.slice(0, 16))
+ }, null, 2))
+ if (missing > 0) process.exitCode = 2
+}
+
+// --- --stage ----------------------------------------------------------------
+async function doStage() {
+ const batchId = Number(arg('batch', 0))
+ const journal = await readJournal()
+ const size = Number(arg('size', journal.batch_size || BATCH_SIZE_DEFAULT))
+ const target = path.resolve(arg('to', path.join(os.homedir(), 'Desktop', 'Mnemazine Inbox', 'mnemazine-inbox')))
+ if (!batchId) fail('укажи --batch N', 2)
+ const existing = (await fs.readdir(target, { withFileTypes: true }).catch(() => []))
+ .filter(entry => entry.isFile() && !entry.name.startsWith('.'))
+ if (existing.length) fail(`целевой инбокс не пуст (${existing.length} файлов): ${target} — не смешиваю партии`, 2)
+ const items = batchItems(journal, batchId, size)
+ if (!items.length) fail(`партия ${batchId} пуста`, 2)
+ if (items.some(item => item.status !== 'pending')) fail(`партия ${batchId} уже поднималась — сначала --rollback --batch ${batchId}`, 2)
+ await fs.mkdir(target, { recursive: true })
+ const usedNames = new Set()
+ const manifest = []
+ for (const item of items) {
+ let stagedName = item.name
+ const ext = path.extname(stagedName)
+ const stem = stagedName.slice(0, stagedName.length - ext.length)
+ if (usedNames.has(stagedName) || existsSync(path.join(target, stagedName))) {
+ stagedName = `${stem}-${item.hash.slice(0, 8)}${ext}`
+ }
+ usedNames.add(stagedName)
+ const dest = path.join(target, stagedName)
+ await fs.copyFile(item.archive_file, dest)
+ const copyHash = await sha256(dest)
+ if (copyHash !== item.hash) fail(`копия не совпала по sha256: ${stagedName}`, 1)
+ item.status = 'staged'
+ item.batch = batchId
+ item.staged_name = stagedName
+ item.events.push({ event: 'staged', at: new Date().toISOString(), batch: batchId, staged_as: stagedName })
+ manifest.push({ hash: item.hash, name: item.name, staged_as: stagedName, source_ref: item.source_ref })
+ }
+ journal.batches.push({
+ id: batchId,
+ size: items.length,
+ staged_at: new Date().toISOString(),
+ status: 'staged',
+ strict_covered: null,
+ run_ok: null,
+ seconds: null,
+ manifest,
+ missing: items.filter(item => !item.matched).map(item => item.hash.slice(0, 16))
+ })
+ await writeJournal(journal)
+ console.log(JSON.stringify({ ok: true, batch: batchId, staged: items.length, to: target }, null, 2))
+}
+
+// --- --measure --------------------------------------------------------------
+async function vaultMarkdownFiles(vault) {
+ const out = []
+ async function walk(dir) {
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ const file = path.join(dir, item.name)
+ const rel = path.relative(vault, file).replace(/\\/g, '/')
+ if (item.isDirectory()) {
+ if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
+ if (rel === '99 Система' || rel.startsWith('99 Система/')) continue
+ await walk(file)
+ } else if (item.isFile() && item.name.endsWith('.md')) {
+ out.push(file)
+ }
+ }
+ }
+ await walk(vault)
+ return out
+}
+
+async function doMeasure() {
+ const batchId = Number(arg('batch', 0))
+ const vault = resolveVault({ cli: arg('vault', '') || undefined })
+ if (!batchId) fail('укажи --batch N', 2)
+ const journal = await readJournal()
+ const batch = journal.batches.find(entry => entry.id === batchId)
+ if (!batch) fail(`партия ${batchId} не найдена в журнале`, 2)
+ const notes = []
+ for (const file of await vaultMarkdownFiles(vault)) {
+ const text = await fs.readFile(file, 'utf8').catch(() => '')
+ if (!text.includes('local-media:') && !text.includes('source_hash')) continue
+ if (!strictKnowledgeReady(text)) continue
+ // `synthesis-` used to mean a hollow cluster template, so the name was
+ // excluded outright. Atomized notes now carry the deep verdict and are the
+ // knowledge itself; cluster drafts stay out on their own merit (they are
+ // `status: draft`, which strictKnowledgeReady already rejects).
+ if (/^source_type:\s*"?synthesis-cluster"?\s*$/m.test(text)) continue
+ notes.push({ file, text })
+ }
+ let covered = 0
+ for (const item of journal.items.filter(row => row.batch === batchId)) {
+ const ref = sourceRef(item.hash)
+ const hit = notes.find(note => note.text.includes(ref) || note.text.includes(item.hash))
+ item.covered = Boolean(hit)
+ if (hit) covered += 1
+ item.events.push({
+ event: 'measured',
+ at: new Date().toISOString(),
+ batch: batchId,
+ covered: item.covered,
+ note: hit ? path.relative(vault, hit.file) : null
+ })
+ }
+ batch.strict_covered = covered
+ batch.status = 'measured'
+ batch.measured_at = new Date().toISOString()
+ batch.measured_vault = vault
+ await writeJournal(journal)
+ console.log(JSON.stringify({ ok: true, batch: batchId, size: batch.size, strict_covered: covered, floor: journal.floor }, null, 2))
+}
+
+// --- --record ---------------------------------------------------------------
+async function doRecord() {
+ const batchId = Number(arg('batch', 0))
+ if (!batchId) fail('укажи --batch N', 2)
+ const journal = await readJournal()
+ const batch = journal.batches.find(entry => entry.id === batchId)
+ if (!batch) fail(`партия ${batchId} не найдена в журнале`, 2)
+ const seconds = arg('seconds', '')
+ if (seconds !== '') batch.seconds = Number(seconds)
+ const runOk = arg('run-ok', '')
+ if (runOk !== '') batch.run_ok = runOk === '1' || runOk === 'true'
+ const note = arg('note', '')
+ if (note) batch.note = note
+ await writeJournal(journal)
+ console.log(JSON.stringify({ ok: true, batch: batchId, seconds: batch.seconds, run_ok: batch.run_ok }, null, 2))
+}
+
+// --- --set-floor ------------------------------------------------------------
+async function doSetFloor() {
+ const journal = await readJournal()
+ const value = Number(arg('batch', '') || argv[argv.indexOf('--set-floor') + 1])
+ if (!Number.isFinite(value)) fail('укажи значение пола: --set-floor N', 2)
+ if (journal.floor !== null && value < journal.floor) {
+ fail(`пол переписывается только вверх: текущий ${journal.floor}, попытка ${value}`, 2)
+ }
+ journal.floor = value
+ journal.floor_history = [...(journal.floor_history || []), { floor: value, at: new Date().toISOString() }]
+ await writeJournal(journal)
+ console.log(JSON.stringify({ ok: true, floor: value }, null, 2))
+}
+
+// --- --rollback -------------------------------------------------------------
+async function doRollback() {
+ const batchId = Number(arg('batch', 0))
+ if (!batchId) fail('укажи --batch N', 2)
+ const journal = await readJournal()
+ const batch = journal.batches.find(entry => entry.id === batchId)
+ if (!batch) fail(`партия ${batchId} не найдена в журнале`, 2)
+ for (const item of journal.items.filter(row => row.batch === batchId)) {
+ item.status = 'pending'
+ item.batch = null
+ item.staged_name = null
+ item.covered = null
+ item.events.push({ event: 'rollback', at: new Date().toISOString(), batch: batchId })
+ }
+ batch.status = 'rolled_back'
+ batch.rolled_back_at = new Date().toISOString()
+ // Drop the header too: leaving it made a re-stage push a second entry with the
+ // same id, and --measure/--record then found() the stale one.
+ journal.batches = journal.batches.filter(entry => entry.id !== batchId)
+ journal.rolled_back = [...(journal.rolled_back || []), { ...batch }]
+ await writeJournal(journal)
+ console.log(JSON.stringify({ ok: true, batch: batchId, rolled_back: true }, null, 2))
+}
+
+// --- --status ---------------------------------------------------------------
+async function doStatus() {
+ const journal = await readJournal()
+ console.log(JSON.stringify({
+ ok: true,
+ floor: journal.floor,
+ totals: journal.totals,
+ batches: journal.batches.map(batch => ({
+ id: batch.id,
+ size: batch.size,
+ status: batch.status,
+ strict_covered: batch.strict_covered,
+ run_ok: batch.run_ok,
+ seconds: batch.seconds
+ }))
+ }, null, 2))
+}
+
+const handlers = {
+ plan: doPlan,
+ stage: doStage,
+ measure: doMeasure,
+ record: doRecord,
+ 'set-floor': doSetFloor,
+ rollback: doRollback,
+ status: doStatus
+}
+
+if (!MODE || !handlers[MODE]) {
+ fail('режим обязателен: --plan | --stage | --measure | --record | --set-floor | --rollback | --status', 2)
+}
+
+handlers[MODE]().catch(error => {
+ console.error(error.message || error)
+ process.exit(1)
+})
diff --git a/scripts/mnemazine-readonly-gate.mjs b/scripts/mnemazine-readonly-gate.mjs
new file mode 100644
index 0000000..afb9052
--- /dev/null
+++ b/scripts/mnemazine-readonly-gate.mjs
@@ -0,0 +1,245 @@
+#!/usr/bin/env node
+// Readonly-gate (план П08): config/command-surface.json обязан покрывать каждую
+// цель package.json, а цели с writes.vault=false доказывают это поведением —
+// прогоном по фикстур-корпусу tests/fixtures/readonly/ со снимком содержимого
+// до и после. Изменённый/удалённый/добавленный файл фикстуры = провал с именем
+// цели. Пустая выборка (0 проверенных целей) = провал: «сдано 0/0» не считается.
+// node scripts/mnemazine-readonly-gate.mjs [--only <цель>] [--help]
+// node scripts/mnemazine-readonly-gate.mjs --selftest
+// Коды: 0 — декларация полна и подтверждена поведением; 1 — есть провалы.
+import { promises as fs } 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 { fileURLToPath } from 'node:url'
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const PKG = path.join(ROOT, 'package.json')
+const SURFACE = path.join(ROOT, 'config', 'command-surface.json')
+const FIXTURE = path.join(ROOT, 'tests', 'fixtures', 'readonly')
+
+const argv = process.argv.slice(2)
+const SELFTEST = argv.includes('--selftest')
+// Скрытый режим для --selftest: заведомо пишущая «цель». Не для ручного запуска.
+const POLLUTE = argv.includes('--pollute')
+const ONLY = (() => { const i = argv.indexOf('--only'); return i === -1 ? '' : (argv[i + 1] || '') })()
+const TIMEOUT_DEFAULT_SEC = Number(process.env.MNEMAZINE_RO_GATE_TIMEOUT_SEC || '180')
+
+if (argv.includes('--help')) {
+ console.log(`mnemazine-readonly-gate.mjs — проверка декларации поверхности команд (П08).
+
+1) Каждая цель package.json обязана иметь строку в config/command-surface.json
+ (writes: {vault, repo, home, net} + назначение). Нет строки — exit 1.
+2) Каждая цель с writes.vault=false прогоняется по копии фикстур-корпуса
+ tests/fixtures/readonly/ со снимком sha256 до и после. Хотя бы один
+ изменённый, удалённый или добавленный файл — exit 1 с именем цели.
+ Цель с "probe": false пропускается только с "probe_reason".
+3) --selftest: временная копия декларации помечает заведомо пишущую цель
+ как vault:false, и прибор обязан поймать её кодом 1.
+
+Флаги: --only <цель> — одна цель; --selftest — самопроверка прибора; --help.
+Коды возврата: 0 — декларация полна и правдива; 1 — есть провалы.`)
+ process.exit(0)
+}
+
+if (POLLUTE) {
+ const vault = process.env.MNEMAZINE_VAULT
+ if (!vault) { console.error('pollute: MNEMAZINE_VAULT не задан'); process.exit(1) }
+ await fs.writeFile(path.join(vault, 'ZZ-POLLUTED.md'), 'selftest pollution\n', 'utf8')
+ process.exit(0)
+}
+
+async function snapshot(dir) {
+ const map = new Map()
+ async function walk(folder) {
+ for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) {
+ const abs = path.join(folder, item.name)
+ const rel = path.relative(dir, abs)
+ if (item.isDirectory()) await walk(abs)
+ else if (item.isFile()) {
+ const hash = crypto.createHash('sha256').update(await fs.readFile(abs)).digest('hex')
+ map.set(rel, hash)
+ }
+ }
+ }
+ await walk(dir)
+ return map
+}
+
+function diffSnapshots(before, after) {
+ const added = []
+ const removed = []
+ const changed = []
+ for (const [rel, hash] of after) {
+ if (!before.has(rel)) added.push(rel)
+ else if (before.get(rel) !== hash) changed.push(rel)
+ }
+ for (const rel of before.keys()) if (!after.has(rel)) removed.push(rel)
+ return { added, removed, changed }
+}
+
+// Детерминированный возраст: ноты старше graph.json — так фикстура
+// воспроизводит ветку протухшего маркера complete-check независимо от mtime чекаута.
+async function normalizeMtimes(vault) {
+ const old = new Date(Date.now() - 2 * 3600 * 1000)
+ const fresh = new Date()
+ async function walk(folder) {
+ for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) {
+ const abs = path.join(folder, item.name)
+ if (item.isDirectory()) await walk(abs)
+ else if (item.isFile()) await fs.utimes(abs, old, old).catch(() => {})
+ }
+ }
+ await walk(vault)
+ const graph = path.join(vault, 'graphify-out', 'graph.json')
+ await fs.utimes(graph, fresh, fresh).catch(() => {})
+}
+
+function runShell(command, env, timeoutSec) {
+ return new Promise(resolve => {
+ const child = spawn('bash', ['-c', command], {
+ cwd: ROOT,
+ env: { ...process.env, ...env },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ detached: true
+ })
+ let stderrTail = ''
+ child.stderr.on('data', chunk => { stderrTail = (stderrTail + String(chunk)).slice(-2000) })
+ const timer = setTimeout(() => {
+ try { process.kill(-child.pid, 'SIGKILL') } catch { /* уже ушёл */ }
+ }, timeoutSec * 1000)
+ child.on('close', code => {
+ clearTimeout(timer)
+ resolve({ code: code ?? 1, timeout: code === null, stderrTail })
+ })
+ child.on('error', error => {
+ clearTimeout(timer)
+ resolve({ code: 1, timeout: false, stderrTail: error.message })
+ })
+ })
+}
+
+async function probeTarget(name, command, decl) {
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-ro-'))
+ try {
+ const vault = path.join(tmp, 'vault')
+ await fs.cp(FIXTURE, vault, { recursive: true })
+ await normalizeMtimes(vault)
+ for (const dir of ['inbox', 'state', 'reports']) await fs.mkdir(path.join(tmp, dir), { recursive: true })
+ const before = await snapshot(vault)
+ const env = {
+ MNEMAZINE_VAULT: vault,
+ MNEMAZINE_INBOX: path.join(tmp, 'inbox'),
+ MNEMAZINE_STATE: path.join(tmp, 'state'),
+ MNEMAZINE_REPORTS: path.join(tmp, 'reports'),
+ MNEMAZINE_ROOT: ROOT
+ }
+ const timeoutSec = Number(decl.timeout_sec) > 0 ? Number(decl.timeout_sec) : TIMEOUT_DEFAULT_SEC
+ const result = await runShell(command, env, timeoutSec)
+ const after = await snapshot(vault)
+ const diff = diffSnapshots(before, after)
+ const dirt = [...diff.added, ...diff.removed, ...diff.changed]
+ return {
+ target: name,
+ code: result.code,
+ timeout: result.timeout,
+ dirt,
+ detail: dirt.length
+ ? `добавлены: ${diff.added.join(', ') || '—'} · удалены: ${diff.removed.join(', ') || '—'} · изменены: ${diff.changed.join(', ') || '—'}`
+ : ''
+ }
+ } finally {
+ await fs.rm(tmp, { recursive: true, force: true }).catch(() => {})
+ }
+}
+
+function validateSurface(scripts, surface) {
+ const errors = []
+ for (const name of Object.keys(scripts)) {
+ const entry = surface[name]
+ if (!entry) { errors.push(`цель «${name}» отсутствует в config/command-surface.json`); continue }
+ if (typeof entry.purpose !== 'string' || !entry.purpose.trim()) errors.push(`цель «${name}»: пустое назначение`)
+ const writes = entry.writes || {}
+ for (const key of ['vault', 'repo', 'home', 'net']) {
+ if (typeof writes[key] !== 'boolean') errors.push(`цель «${name}»: writes.${key} не boolean`)
+ }
+ if (entry.probe === false && !(typeof entry.probe_reason === 'string' && entry.probe_reason.trim())) {
+ errors.push(`цель «${name}»: probe=false без probe_reason`)
+ }
+ }
+ for (const name of Object.keys(surface)) {
+ if (!Object.hasOwn(scripts, name)) errors.push(`config/command-surface.json: лишняя строка «${name}» — нет такой цели в package.json`)
+ }
+ return errors
+}
+
+async function checkSurface({ scripts, surface, only = '' }) {
+ const errors = validateSurface(scripts, surface)
+ const violations = []
+ const skipped = []
+ let probed = 0
+ for (const [name, command] of Object.entries(scripts)) {
+ const entry = surface[name]
+ if (!entry || !entry.writes || entry.writes.vault !== false) continue
+ if (only && name !== only) continue
+ if (entry.probe === false) { skipped.push(`${name} (${entry.probe_reason})`); continue }
+ if (only === '') console.error(`[readonly-gate] probe: ${name}`)
+ const verdict = await probeTarget(name, command, entry)
+ probed += 1
+ if (verdict.timeout) violations.push(`${name}: проба не завершилась за таймаут — замер недействителен`)
+ if (verdict.dirt.length) violations.push(`${name}: фикстур-корпус изменён — ${verdict.detail}`)
+ }
+ if (probed === 0 && !only) errors.push('ноль проверенных целей: пустая выборка — это не «сдано»')
+ return { errors, violations, probed, skipped }
+}
+
+async function selftest() {
+ const scripts = JSON.parse(await fs.readFile(PKG, 'utf8')).scripts || {}
+ const surface = JSON.parse(await fs.readFile(SURFACE, 'utf8'))
+ const fail = msg => { console.error(`selftest: ${msg}`); process.exit(1) }
+
+ // Заведомо пишущая цель, помеченная vault:false во временной копии декларации.
+ const writer = 'zz-selftest-writer'
+ const scriptsCopy = { ...scripts, [writer]: `node ${path.join('scripts', 'mnemazine-readonly-gate.mjs')} --pollute` }
+ const surfaceCopy = {
+ ...surface,
+ [writer]: { purpose: 'селф-тест прибора: гарантированно пишет в корпус', writes: { vault: false, repo: false, home: false, net: false } }
+ }
+ const caught = await checkSurface({ scripts: scriptsCopy, surface: surfaceCopy, only: writer })
+ if (caught.probed !== 1) fail(`ожидалась 1 проба, фактически ${caught.probed}`)
+ if (!caught.violations.some(v => v.startsWith(`${writer}:`))) {
+ fail(`прибор не поймал заведомо пишущую цель (violations: ${JSON.stringify(caught.violations)})`)
+ }
+
+ // Пустая выборка — провал, а не «сдано 0/0».
+ const allWriting = Object.fromEntries(Object.entries(surfaceCopy).map(([name, entry]) => [name, { ...entry, writes: { ...entry.writes, vault: true } }]))
+ const empty = await checkSurface({ scripts: scriptsCopy, surface: allWriting })
+ if (!empty.errors.some(e => e.includes('ноль проверенных'))) fail('пустая выборка не дала ошибку «ноль проверенных целей»')
+
+ console.log(JSON.stringify({ ok: true, caught_writer: true, empty_selection_rejected: true }, null, 2))
+}
+
+async function main() {
+ const scripts = JSON.parse(await fs.readFile(PKG, 'utf8')).scripts || {}
+ const surface = await fs.readFile(SURFACE, 'utf8').then(JSON.parse).catch(error => {
+ console.error(`config/command-surface.json нечитаем: ${error.message}`)
+ process.exit(1)
+ })
+ const { errors, violations, probed, skipped } = await checkSurface({ scripts, surface, only: ONLY })
+ const failures = [...errors, ...violations]
+ console.log(JSON.stringify({
+ ok: failures.length === 0,
+ targets_total: Object.keys(scripts).length,
+ probed,
+ skipped,
+ failures
+ }, null, 2))
+ if (failures.length) process.exit(1)
+}
+
+if (SELFTEST) {
+ await selftest()
+} else {
+ await main()
+}
diff --git a/scripts/mnemazine-reattribute-source-refs.mjs b/scripts/mnemazine-reattribute-source-refs.mjs
new file mode 100644
index 0000000..c0dc70c
--- /dev/null
+++ b/scripts/mnemazine-reattribute-source-refs.mjs
@@ -0,0 +1,178 @@
+#!/usr/bin/env node
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import { resolveVault } from './mnemazine-paths.mjs'
+
+const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
+const EXTRACTS = process.env.MNEMAZINE_EXTRACTS || path.join(ROOT, '.mnemazine/cache/extracted')
+const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
+const argv = process.argv.slice(2)
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+
+const VAULT = resolveVault({ cli: arg('vault') })
+const SINCE = arg('changed-since', process.env.MNEMAZINE_CHANGED_SINCE || '')
+const APPLY = argv.includes('--apply')
+const MIN_SCORE = Number(arg('min-score', process.env.MNEMAZINE_REATTR_MIN_SCORE || '2'))
+
+const STOP = new Set('github com https http www для что это как если или при над надо нужно нужно нужно агент agents skills skill local media source refs verified status final draft через который которая которые и или в на с по из к от до под над без тоже только один одна одно есть нет был была были будет'.split(/\s+/))
+
+function compact(value) {
+ return String(value || '').replace(/\s+/g, ' ').trim()
+}
+
+function words(value) {
+ return compact(value)
+ .toLowerCase()
+ .split(/[^a-zа-яё0-9]+/i)
+ .filter(word => word.length >= 4 && !STOP.has(word))
+}
+
+function unique(values) {
+ return [...new Set(values.filter(Boolean))]
+}
+
+function githubRepos(value) {
+ return unique([...String(value || '').matchAll(/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)/g)]
+ .map(match => match[1].toLowerCase().replace(/\.git$/, '')))
+}
+
+function publicUrls(value) {
+ return unique([...String(value || '').matchAll(/https?:\/\/[^\s)]+/g)]
+ .map(match => match[0].replace(/[.,;]+$/, '')))
+}
+
+function sourceRefList(text) {
+ return unique([...String(text || '').matchAll(/local-media:([a-f0-9]{16})/g)].map(match => match[1]))
+}
+
+async function sourceText(ref) {
+ const entries = await fs.readdir(EXTRACTS, { withFileTypes: true }).catch(() => [])
+ const jsonName = entries.find(entry => entry.isFile() && entry.name.startsWith(ref) && entry.name.endsWith('.json'))?.name
+ if (!jsonName) return { source_hash: '', text: '' }
+ const record = JSON.parse(await fs.readFile(path.join(EXTRACTS, jsonName), 'utf8'))
+ const text = record.text_path ? await fs.readFile(path.join(EXTRACTS, record.text_path), 'utf8').catch(() => '') : ''
+ return { source_hash: record.source_hash || '', text }
+}
+
+function noteSupportText(text) {
+ const sections = []
+ for (const name of ['Что это', 'Зачем это нужно', 'Как использовать', 'Следующее действие']) {
+ const re = new RegExp(`^##\\s+${name}\\s*\\n([\\s\\S]*?)(?=^##\\s+|\\z)`, 'mi')
+ const hit = text.match(re)
+ if (hit) sections.push(hit[1])
+ }
+ return sections.join('\n')
+}
+
+function scoreRef({ title, body, urls, noteRepos }, source) {
+ const text = String(source.text || '').toLowerCase()
+ const titleTokens = unique(words(title))
+ const bodyTokens = unique(words(body)).slice(0, 160)
+ const refRepos = githubRepos(source.text)
+ let score = 0
+ const reasons = []
+
+ for (const repo of noteRepos) {
+ if (refRepos.includes(repo) || text.includes(repo)) {
+ score += 30
+ reasons.push(`repo:${repo}`)
+ }
+ }
+ for (const url of urls) {
+ try {
+ const u = new URL(url)
+ const host = u.hostname.replace(/^www\./, '').toLowerCase()
+ const pathBits = u.pathname.split('/').filter(Boolean).slice(0, 2).join('/').toLowerCase()
+ if (host && text.includes(host)) { score += 3; reasons.push(`host:${host}`) }
+ if (pathBits && text.includes(pathBits)) { score += 12; reasons.push(`path:${pathBits}`) }
+ } catch {}
+ }
+ for (const token of titleTokens) {
+ if (text.includes(token)) { score += 3; reasons.push(`title:${token}`) }
+ }
+ for (const token of bodyTokens) {
+ if (text.includes(token)) score += 1
+ }
+ return { score, reasons: unique(reasons).slice(0, 8), refRepos, head: compact(source.text).slice(0, 160) }
+}
+
+async function listNotes() {
+ const out = []
+ const sinceMs = SINCE ? Date.parse(SINCE) : 0
+ async function walk(dir) {
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
+ const file = path.join(dir, item.name)
+ if (item.isDirectory()) await walk(file)
+ else if (item.isFile() && item.name.endsWith('.md')) {
+ const stat = await fs.stat(file)
+ if (sinceMs && stat.mtimeMs < sinceMs) continue
+ const text = await fs.readFile(file, 'utf8').catch(() => '')
+ if (!/^source_type:\s*"synthesis-atom"\s*$/m.test(text)) continue
+ const refs = sourceRefList(text)
+ if (refs.length > 1) out.push({ file, text, refs, title: text.match(/^#\s+(.+)$/m)?.[1] || path.basename(file, '.md') })
+ }
+ }
+ }
+ await walk(VAULT)
+ return out
+}
+
+function replaceSourceRefs(text, refs) {
+ const replacement = `Локальные source refs:\n${refs.map(ref => `- local-media:${ref}`).join('\n')}`
+ return String(text).replace(/Локальные source refs:\n(?:- local-media:[a-f0-9]{16}\n?)+/m, `${replacement}\n`)
+}
+
+async function main() {
+ await fs.mkdir(STATE, { recursive: true })
+ const changes = []
+ for (const note of await listNotes()) {
+ const body = noteSupportText(note.text)
+ const urls = publicUrls(note.text)
+ const noteRepos = githubRepos(note.text)
+ const details = []
+ for (const ref of note.refs) {
+ const source = await sourceText(ref)
+ details.push({ ref, source_hash: source.source_hash, ...scoreRef({ title: note.title, body, urls, noteRepos }, source) })
+ }
+ const best = Math.max(...details.map(item => item.score), 0)
+ const keep = details
+ .filter(item => item.score >= MIN_SCORE && item.score >= Math.max(MIN_SCORE, Math.floor(best * 0.35)))
+ .map(item => item.ref)
+ const selected = keep.length ? unique(keep) : [details.sort((a, b) => b.score - a.score)[0]?.ref].filter(Boolean)
+ const changed = selected.length !== note.refs.length || selected.some(ref => !note.refs.includes(ref))
+ changes.push({
+ file: note.file,
+ rel: path.relative(VAULT, note.file),
+ title: note.title,
+ before: note.refs,
+ after: selected,
+ changed,
+ best_score: best,
+ details
+ })
+ if (APPLY && changed) await fs.writeFile(note.file, replaceSourceRefs(note.text, selected), 'utf8')
+ }
+ const result = {
+ ok: true,
+ apply: APPLY,
+ changed_since: SINCE || null,
+ checked: changes.length,
+ changed: changes.filter(item => item.changed).length,
+ changes
+ }
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
+ const stateFile = path.join(STATE, `reattribute-source-refs-${stamp}.json`)
+ await fs.writeFile(stateFile, `${JSON.stringify(result, null, 2)}\n`, 'utf8')
+ console.log(JSON.stringify({ ...result, changes: changes.map(item => ({ rel: item.rel, title: item.title, before: item.before.length, after: item.after.length, changed: item.changed, after_refs: item.after })), state_file: stateFile }, null, 2))
+}
+
+main().catch(error => {
+ console.error(error.message || error)
+ process.exit(1)
+})
diff --git a/scripts/mnemazine-rebuild-gate.mjs b/scripts/mnemazine-rebuild-gate.mjs
new file mode 100644
index 0000000..54d575e
--- /dev/null
+++ b/scripts/mnemazine-rebuild-gate.mjs
@@ -0,0 +1,577 @@
+#!/usr/bin/env node
+// ПРИБОР ОРКЕСТРАЦИИ ВОЛНЫ 0 — маркер пишет код, а не рапорт агента.
+//
+// Контракт (мастер §8, файл 01 П00):
+// маркер .mnemazine/state/rebuild/<план>.done.json пишет ТОЛЬКО этот прибор и ТОЛЬКО при exit_code 0.
+// маркер без written_by:"rebuild-gate" или с несовпавшим sha_of_changed_files → tampered;
+// --require на tampered/отсутствующий → exit 2. Пустая выборка планов → exit 2, не «сдано 0/0».
+// Исключение внутри проверки плана → crash:<план>, остальные планы продолжают считаться
+// (в отличие от mnemazine-release-check.mjs:921-925, где первый throw убивает остальные).
+// --budget: нет budget.json → exit 2 (потолок не подтверждён); превышение → exit 3.
+// --selftest: репетиция отката (правка→revert→сверка tree-sha) + спрятанный прибор плана → красный.
+//
+// engines.node >= 20 (package.json): без fs.globSync и без require() из ESM.
+import { parseArgs } from 'node:util'
+import { promises as fs, existsSync, readFileSync, mkdtempSync, appendFileSync, rmSync, mkdirSync, writeFileSync, statSync } from 'node:fs'
+import { createHash } from 'node:crypto'
+import { execFileSync, spawnSync } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+import path from 'node:path'
+import os from 'node:os'
+
+const REPO = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
+
+// --- Конфиг прибора (не константы промта: слоты, каталоги, открытые вопросы §6) ---------------------
+const CONFIG = {
+ stateDir: path.join(REPO, '.mnemazine', 'state', 'rebuild'),
+ plansDir: path.join(REPO, 'docs'),
+ planFileRe: /^PLAN-ночь-2026-08-22-0[1-6][^/]*\.md$/,
+ // Лимит слотов: три исполнителя, по одному на CLI (мастер §9, дополнение 3). Конфиг, не промт.
+ slotsPerCli: { claude: 1, codex: 1, kimi: 1 },
+ configLocal: path.join(REPO, '.mnemazine', 'config.local.sh'),
+ // Открытые вопросы §6 мастер-плана: план не готов, пока его вопрос не отвечён.
+ openQuestions: [], // все решены: 3,4 (22.08); 5 — кастомная dual-license, драфт LICENSE.draft.md на утверждении владельца; 10 — публично только чистый релизный коммит, история в приватном (23.08)
+ questionBlocks: {},
+ claudeDir: path.join(os.homedir(), '.claude', 'projects', `-${REPO.split(path.sep).filter(Boolean).join('-')}`),
+ codexSessions: path.join(os.homedir(), '.codex', 'sessions'),
+ kimiIndex: path.join(os.homedir(), '.kimi-code', 'session_index.jsonl'),
+ // Rate-карта claude за Mtok [in, out, cache-write, cache-read] — как ~/.claude/scripts/token-spend.sh.
+ claudeRates: { opus: [15, 75, 18.75, 1.5], sonnet: [3, 15, 3.75, 0.3], haiku: [1, 5, 1.25, 0.1] },
+ // ponytail: плоская ставка для не-claude CLI; поштучное ценообразование codex/kimi — открытый вопрос 6
+ // (владелец задал только ceiling_usd). Ночной расход codex/kimi мал, точность ставки здесь не решает.
+ nonClaudeUsdPerMtok: 3,
+}
+
+// --- Утилиты -------------------------------------------------------------------------------------
+const sha256 = s => createHash('sha256').update(s).digest('hex')
+function git(args, opts = {}) {
+ return execFileSync('git', ['-C', opts.cwd || REPO, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).replace(/\n$/, '')
+}
+function gitSafe(args, opts) { try { return git(args, opts) } catch { return null } }
+
+/** Нормализует путь из «Точные пути»: снимает `:123`/`:1-9`-хвост строки и завершающий слэш. */
+function normPath(raw) {
+ let p = raw.trim().replace(/[.,;)]+$/, '')
+ p = p.split(/\s/)[0]
+ p = p.replace(/:\d+(-\d+)?$/, '')
+ p = p.replace(/\/$/, '')
+ return p
+}
+
+/** Токен из «Точные пути» — реальный путь, а не флаг (`--vault`) или голое слово (`exit`, `complete-check`). */
+function isPathLike(raw, norm) {
+ if (!norm || norm.startsWith('-')) return false
+ return raw.includes('/') || /\.[A-Za-z0-9]{1,10}$/.test(norm)
+}
+
+/** Читает все P0[1-6]-файлы волн и строит реестр планов машинно из «Точные пути» / «Исполнитель» / «Требует». */
+async function loadPlans() {
+ const plans = new Map()
+ let dir
+ try { dir = await fs.readdir(CONFIG.plansDir) } catch { return plans }
+ for (const name of dir) {
+ if (!CONFIG.planFileRe.test(name)) continue
+ const text = await fs.readFile(path.join(CONFIG.plansDir, name), 'utf8')
+ for (const p of parsePlansFromText(text, name)) plans.set(p.id, p)
+ }
+ return plans
+}
+
+/** Разбор одного файла волны в блоки планов. Вынесен, чтобы --selftest мог проверить его на фикстуре. */
+export function parsePlansFromText(text, file = '') {
+ const out = []
+ const headRe = /^###\s+(П\d+)\s+·\s+(.*)$/gm
+ const heads = []
+ let m
+ while ((m = headRe.exec(text))) heads.push({ id: m[1], title: m[2].trim(), start: m.index })
+ for (let i = 0; i < heads.length; i++) {
+ const body = text.slice(heads[i].start, i + 1 < heads.length ? heads[i + 1].start : text.length)
+ out.push({ id: heads[i].id, title: heads[i].title, file, ...parsePlanBody(body) })
+ }
+ return out
+}
+
+function parsePlanBody(body) {
+ const lines = body.split('\n')
+ const executor = (body.match(/\*\*Исполнитель:\*\*\s*([A-Za-z]+)/) || [])[1] || null
+ // «Требует маркеров» может занимать несколько строк (`·`-разделитель) и тянуть за собой прозу, которая
+ // тоже называет ПNN («`--require` на П21 даёт 2», «(`П01` — не формальность…)»). Собираем поле до
+ // следующего `- **`-поля, режем на первой точке-конце-предложения — дальше только пояснения.
+ let requires = []
+ const reqIdx = lines.findIndex(l => /\*\*Требует маркеров:\*\*/.test(l))
+ if (reqIdx >= 0) {
+ const buf = [lines[reqIdx].replace(/[\s\S]*\*\*Требует маркеров:\*\*/, '')]
+ for (let j = reqIdx + 1; j < lines.length; j++) {
+ if (/^\s*-\s*\*\*/.test(lines[j]) || /^###/.test(lines[j])) break
+ buf.push(lines[j])
+ }
+ const head = buf.join(' ').split(/\.(?=\s|$)/)[0]
+ requires = [...new Set([...head.matchAll(/П\d+/g)].map(x => x[0]))]
+ }
+ // «Точные пути»: собираем строки после маркера до следующего поля `- **…**` или конца блока.
+ const paths = []
+ let inPaths = false
+ for (const line of lines) {
+ if (/^-\s*\*\*Точные пути:\*\*/.test(line)) { inPaths = true; continue }
+ if (inPaths && /^-\s*\*\*/.test(line)) break
+ if (!inPaths) continue
+ const isNew = /\[новый\]/.test(line)
+ for (const bt of line.matchAll(/`([^`]+)`/g)) {
+ const p = normPath(bt[1])
+ if (isPathLike(bt[1], p)) paths.push({ path: p, isNew })
+ }
+ }
+ return { executor, requires, paths }
+}
+
+// --- Маркеры -------------------------------------------------------------------------------------
+const markerFile = id => path.join(CONFIG.stateDir, `${id}.done.json`)
+
+/** Пересчёт sha изменённых файлов: sha256(имена \n + содержимое каждого) по фиксированным base..head. */
+function changedFilesSha(base, head) {
+ const names = (gitSafe(['diff', '--name-only', `${base}..${head}`]) || '').split('\n').filter(Boolean)
+ let buf = names.join('\n')
+ for (const n of names) buf += '\0' + n + '\0' + (gitSafe(['show', `${head}:${n}`]) ?? '')
+ return sha256(buf)
+}
+
+/** Классифицирует маркер: {status: done|tampered|missing, data}. tampered ловит и подделку руками. */
+function readMarker(id) {
+ const f = markerFile(id)
+ if (!existsSync(f)) return { status: 'missing' }
+ let data
+ try { data = JSON.parse(readFileSync(f, 'utf8')) } catch { return { status: 'tampered', reason: 'нечитаемый json', data: null } }
+ if (data.written_by !== 'rebuild-gate') return { status: 'tampered', reason: 'нет written_by:"rebuild-gate"', data }
+ // Поля целостности обязательны: их отсутствие — подделка обрезанием, не «старый формат».
+ for (const k of ['base', 'head', 'sha_of_changed_files', 'exit_code', 'finished_at']) {
+ if (data[k] === undefined || data[k] === null || data[k] === '') return { status: 'tampered', reason: `нет поля целостности ${k}`, data }
+ }
+ if (!gitSafe(['rev-parse', '--verify', data.head + '^{commit}']) || !gitSafe(['rev-parse', '--verify', data.base + '^{commit}'])) {
+ return { status: 'tampered', reason: 'base/head не резолвятся в коммиты', data }
+ }
+ // Пересчёт sha по записанным base/head — детерминирован независимо от текущего HEAD.
+ {
+ if (changedFilesSha(data.base, data.head) !== data.sha_of_changed_files) return { status: 'tampered', reason: 'sha_of_changed_files не совпал', data }
+ }
+ return { status: 'done', data }
+}
+
+function writeMarker(id, { checkCmd, executor, verifier, base }) {
+ mkdirSync(CONFIG.stateDir, { recursive: true })
+ const head = git(['rev-parse', 'HEAD'])
+ const baseRef = base || `${head}~1`
+ const baseSha = gitSafe(['rev-parse', baseRef]) || baseRef
+ const marker = {
+ plan: id,
+ check_cmd: checkCmd || '',
+ exit_code: 0,
+ sha_of_changed_files: changedFilesSha(baseSha, head),
+ base: baseSha,
+ head,
+ executor_cli: executor || null,
+ verifier_cli: verifier || null,
+ finished_at: new Date().toISOString(),
+ written_by: 'rebuild-gate',
+ }
+ if (id === 'П00') {
+ marker.config_local_sha = existsSync(CONFIG.configLocal) ? sha256(readFileSync(CONFIG.configLocal)) : null
+ marker.rollback_rehearsal = rollbackRehearsal()
+ }
+ if (id === 'П21') {
+ const baseline = path.join(CONFIG.stateDir, 'public-history-baseline.json')
+ marker.ignored_files_decisions = {
+ 'scripts/mnemazine-refresh-core-indexes.mjs': 'обезличен и включён',
+ 'scripts/graphify_clean.py': 'обезличен и включён',
+ 'scripts/mnemazine-apply-capability-links.mjs': 'включён',
+ 'scripts/mnemazine-audit-live-vault.mjs': 'включён',
+ 'scripts/mnemazine-normalize-skill-notes.mjs': 'включён',
+ 'scripts/kb-enrich-schema.json': 'включён',
+ 'tests/test-coverage-fix.mjs': 'включён',
+ 'scripts/mnemazine-build-capability-map.mjs': 'оставлен вырезанным',
+ 'scripts/mnemazine-dedupe-atomized-blocks.mjs': 'оставлен вырезанным',
+ 'scripts/kb-build-queue.py': 'оставлен вырезанным',
+ 'scripts/kb-enrich-codex.sh': 'оставлен вырезанным',
+ 'scripts/kb-recheck-codex.sh': 'оставлен вырезанным',
+ 'scripts/kb-enrich-prompt.md': 'оставлен вырезанным',
+ 'scripts/PROMPT-Codex-desktop.txt': 'оставлен вырезанным',
+ 'scripts/ИНСТРУКЦИЯ-codex-перепроверка.md': 'оставлен вырезанным',
+ }
+ marker.public_history_baseline_sha = existsSync(baseline) ? sha256(readFileSync(baseline)) : null
+ marker.campaigns_decision = 'docs/campaigns/ оставлен в .gitignore по решению владельца вопроса 4; commit e2b7d92'
+ }
+ if (id === 'П22') {
+ // Доп-поля сверх контракта §8 (мастер §6 файл 06): прежний публичный HEAD, результат
+ // песочницы, форма публикации и лицензия. Источник — черновик прибора publish-readiness,
+ // который check-cmd написал ДО этого маркера (аналогично public-history-baseline.json у П21).
+ const draftFile = path.join(CONFIG.stateDir, 'П22-readiness.json')
+ if (!existsSync(draftFile)) throw new Error('П22: нет черновика П22-readiness.json — прибор publish-readiness не отработал до маркера')
+ const d = JSON.parse(readFileSync(draftFile, 'utf8'))
+ if (d.written_by !== 'publish-readiness') throw new Error('П22: черновик readiness не от прибора publish-readiness')
+ if (!/^[0-9a-f]{7,40}$/.test(d.previous_public_sha || '')) throw new Error('П22: в черновике нет прежнего публичного sha')
+ marker.previous_public_sha = d.previous_public_sha
+ marker.previous_public_sha_full = d.previous_public_sha_full
+ marker.sandbox_probe = d.sandbox_probe
+ marker.publication_form = d.publication_form
+ marker.license_decision = d.license_decision
+ marker.deletions_on_push = d.sandbox_probe_full ? d.sandbox_probe_full.deletions : undefined
+ marker.pushed = false // маркер означает готовность, а не факт публикации
+ }
+ writeFileSync(markerFile(id), JSON.stringify(marker, null, 2) + '\n')
+ return marker
+}
+
+// --- Репетиция отката (инвариант 3 мастер-плана): правка → revert → сверка tree-sha в клоне --------
+function rollbackRehearsal() {
+ const tmp = mkdtempSync(path.join(os.tmpdir(), 'rebuild-rehearsal-'))
+ const dst = path.join(tmp, 'rehearsal')
+ try {
+ git(['clone', '--local', '--quiet', REPO, dst], { cwd: REPO })
+ const before = git(['rev-parse', 'HEAD^{tree}'], { cwd: dst })
+ const tracked = git(['ls-files'], { cwd: dst }).split('\n').filter(Boolean)
+ if (!tracked.length) throw new Error('клон без отслеживаемых файлов')
+ appendFileSync(path.join(dst, tracked[0]), '\n// rebuild-gate rehearsal\n')
+ git(['add', '-A'], { cwd: dst })
+ git(['-c', 'user.email=rebuild@gate', '-c', 'user.name=rebuild-gate', 'commit', '-q', '-m', 'plan/П00-rehearsal'], { cwd: dst })
+ git(['revert', '--no-edit', 'HEAD'], { cwd: dst })
+ const after = git(['rev-parse', 'HEAD^{tree}'], { cwd: dst })
+ return { before_tree: before, after_tree: after, matched: before === after }
+ } finally {
+ rmSync(tmp, { recursive: true, force: true })
+ }
+}
+
+// --- running.json (для --ready / --start / --finish) ---------------------------------------------
+function readRunning() {
+ const f = path.join(CONFIG.stateDir, 'running.json')
+ if (!existsSync(f)) return { running: [] }
+ try { const j = JSON.parse(readFileSync(f, 'utf8')); return { running: Array.isArray(j.running) ? j.running : [] } } catch { return { running: [] } }
+}
+function writeRunning(state) {
+ mkdirSync(CONFIG.stateDir, { recursive: true })
+ writeFileSync(path.join(CONFIG.stateDir, 'running.json'), JSON.stringify(state, null, 2) + '\n')
+}
+
+// --- Расход (--budget): факт с диска по трём источникам, каждый в try/catch (best-effort) ----------
+function claudeRate(model) {
+ const l = (model || '').toLowerCase()
+ for (const k of Object.keys(CONFIG.claudeRates)) if (l.includes(k)) return CONFIG.claudeRates[k]
+ return CONFIG.claudeRates.opus // неизвестная → Opus-rate, консервативно
+}
+async function claudeSpend(since) {
+ let tokens = 0, usd = 0
+ let files = []
+ try { files = (await fs.readdir(CONFIG.claudeDir)).filter(f => f.endsWith('.jsonl')) } catch { return { tokens, usd } }
+ for (const f of files) {
+ const full = path.join(CONFIG.claudeDir, f)
+ try { if (statSync(full).mtimeMs < since) continue } catch { continue } // префильтр по mtime
+ let txt = ''
+ try { txt = await fs.readFile(full, 'utf8') } catch { continue }
+ for (const ln of txt.split('\n')) {
+ if (!ln.trim()) continue
+ let o; try { o = JSON.parse(ln) } catch { continue }
+ const u = o.message && o.message.usage
+ if (!u || o.message.model === '') continue
+ if (!(o.timestamp && Date.parse(o.timestamp) >= since)) continue
+ const r = claudeRate(o.message.model)
+ const a = u.input_tokens || 0, b = u.output_tokens || 0, c = u.cache_creation_input_tokens || 0, d = u.cache_read_input_tokens || 0
+ tokens += a + b + c + d
+ usd += a / 1e6 * r[0] + b / 1e6 * r[1] + c / 1e6 * r[2] + d / 1e6 * r[3]
+ }
+ }
+ return { tokens, usd }
+}
+async function codexSpend(since) {
+ let tokens = 0
+ let entries = []
+ try { entries = await fs.readdir(CONFIG.codexSessions, { recursive: true, withFileTypes: true }) } catch { return { tokens, usd: 0 } }
+ for (const e of entries) {
+ if (!e.isFile() || !/^rollout-.*\.jsonl$/.test(e.name)) continue
+ const full = path.join(e.parentPath || e.path, e.name)
+ try { if (statSync(full).mtimeMs < since) continue } catch { continue }
+ let txt = ''
+ try { txt = await fs.readFile(full, 'utf8') } catch { continue }
+ const lines = txt.split('\n').filter(Boolean)
+ let meta; try { meta = JSON.parse(lines[0]) } catch { continue }
+ const cwd = meta.payload && meta.payload.cwd
+ if (!(cwd && cwd.startsWith(REPO))) continue
+ if (!(meta.timestamp && Date.parse(meta.timestamp) >= since)) continue
+ let last = null
+ for (const ln of lines) { const i = ln.indexOf('"total_token_usage"'); if (i >= 0) { const mm = ln.match(/"total_tokens":(\d+)/); if (mm) last = Number(mm[1]) } }
+ if (last != null) tokens += last
+ }
+ return { tokens, usd: tokens / 1e6 * CONFIG.nonClaudeUsdPerMtok }
+}
+async function kimiSpend(since) {
+ let tokens = 0
+ let idx = ''
+ try { idx = await fs.readFile(CONFIG.kimiIndex, 'utf8') } catch { return { tokens, usd: 0 } }
+ for (const ln of idx.split('\n')) {
+ if (!ln.trim()) continue
+ let s; try { s = JSON.parse(ln) } catch { continue }
+ if (s.workDir !== REPO || !s.sessionDir) continue
+ let agents = []
+ try { agents = await fs.readdir(path.join(s.sessionDir, 'agents'), { recursive: true, withFileTypes: true }) } catch { continue }
+ for (const a of agents) {
+ if (!a.isFile() || a.name !== 'wire.jsonl') continue
+ const full = path.join(a.parentPath || a.path, a.name)
+ let txt = ''
+ try { txt = await fs.readFile(full, 'utf8') } catch { continue }
+ for (const wl of txt.split('\n')) {
+ if (!wl.includes('step.end')) continue
+ let o; try { o = JSON.parse(wl) } catch { continue }
+ if (!(o.time && o.time >= since)) continue
+ const u = (o.event && o.event.usage) || o.usage
+ if (!u) continue
+ tokens += (u.inputOther || 0) + (u.output || 0) + (u.inputCacheRead || 0) + (u.inputCacheCreation || 0)
+ }
+ }
+ }
+ return { tokens, usd: tokens / 1e6 * CONFIG.nonClaudeUsdPerMtok }
+}
+async function computeSpend(since) {
+ const [c, x, k] = await Promise.all([
+ claudeSpend(since).catch(() => ({ tokens: 0, usd: 0 })),
+ codexSpend(since).catch(() => ({ tokens: 0, usd: 0 })),
+ kimiSpend(since).catch(() => ({ tokens: 0, usd: 0 })),
+ ])
+ return {
+ tokens: c.tokens + x.tokens + k.tokens,
+ usd: c.usd + x.usd + k.usd,
+ by_cli: { claude: c, codex: x, kimi: k },
+ }
+}
+
+// --- Команды -------------------------------------------------------------------------------------
+async function cmdBudget(json) {
+ const f = path.join(CONFIG.stateDir, 'budget.json')
+ let b
+ try { b = JSON.parse(readFileSync(f, 'utf8')) } catch {
+ console.error('бюджет: budget.json отсутствует или нечитаем — потолок не подтверждён')
+ return 2
+ }
+ const since = b.started_at && !Number.isNaN(Date.parse(b.started_at)) ? Date.parse(b.started_at) : new Date().setHours(0, 0, 0, 0)
+ const spend = await computeSpend(since)
+ const overTokens = Number.isFinite(b.ceiling_tokens) && b.ceiling_tokens > 0 && spend.tokens > b.ceiling_tokens
+ const overUsd = Number.isFinite(b.ceiling_usd) && b.ceiling_usd > 0 && spend.usd > b.ceiling_usd
+ const over = overTokens || overUsd
+ const report = { ok: !over, ceiling_usd: b.ceiling_usd ?? null, ceiling_tokens: b.ceiling_tokens ?? null, since: new Date(since).toISOString(), spend_tokens: spend.tokens, spend_usd: Number(spend.usd.toFixed(2)), by_cli: spend.by_cli, over_tokens: overTokens, over_usd: overUsd }
+ if (json) console.log(JSON.stringify(report, null, 2))
+ else {
+ console.log(`бюджет с ${report.since}: расход ${spend.tokens.toLocaleString()} ток · ≈$${report.spend_usd}`)
+ console.log(` потолок: $${b.ceiling_usd ?? '—'}${Number.isFinite(b.ceiling_tokens) ? ' / ' + b.ceiling_tokens + ' ток' : ' (токенный не задан)'}`)
+ console.log(over ? ` ПРЕВЫШЕНИЕ — волна останавливается` : ` в пределах потолка`)
+ }
+ return over ? 3 : 0
+}
+
+async function cmdStatus(json) {
+ const plans = await loadPlans()
+ const running = new Set(readRunning().running)
+ const rows = []
+ for (const id of [...plans.keys()].sort()) {
+ const mk = readMarker(id)
+ let state = mk.status
+ if (state === 'missing') state = running.has(id) ? 'running' : 'pending'
+ rows.push({ plan: id, state, executor: plans.get(id).executor, reason: mk.reason || null })
+ }
+ if (json) console.log(JSON.stringify({ ok: true, plans: rows }, null, 2))
+ else {
+ console.log('ДОСКА ПЕРЕСТРОЙКИ')
+ for (const r of rows) console.log(` ${r.plan} ${r.state}${r.reason ? ' (' + r.reason + ')' : ''}`)
+ }
+ return 0
+}
+
+async function cmdReady(json) {
+ const plans = await loadPlans()
+ if (!plans.size) { console.error('--ready: ноль извлечённых планов'); return 1 }
+ const running = readRunning().running
+ const runningPaths = new Set()
+ const runningCli = new Set()
+ for (const id of running) {
+ const p = plans.get(id)
+ if (!p) continue
+ for (const x of p.paths) runningPaths.add(x.path)
+ if (p.executor) runningCli.add(p.executor)
+ }
+ const dependents = id => [...plans.values()].filter(p => p.requires.includes(id)).length
+ const ready = [], blocked = {}
+ for (const id of [...plans.keys()].sort()) {
+ const p = plans.get(id)
+ if (readMarker(id).status === 'done' || running.includes(id)) continue
+ const reasons = []
+ for (const dep of p.requires) if (readMarker(dep).status !== 'done') reasons.push(`ждёт маркер ${dep}`)
+ for (const q of (CONFIG.questionBlocks[id] || [])) if (CONFIG.openQuestions.includes(q)) reasons.push(`открыт вопрос ${q}`)
+ const inter = p.paths.map(x => x.path).filter(x => runningPaths.has(x))
+ if (inter.length) reasons.push(`пересечение путей с бегущим планом: ${[...new Set(inter)].join(', ')}`)
+ if (p.executor && runningCli.has(p.executor)) reasons.push(`слот CLI ${p.executor} занят`)
+ if (reasons.length) blocked[id] = reasons
+ else ready.push(id)
+ }
+ ready.sort((a, b) => dependents(b) - dependents(a) || a.localeCompare(b))
+ const out = { ok: ready.length > 0, ready: ready.map(id => ({ plan: id, executor: plans.get(id).executor })), blocked }
+ if (json) console.log(JSON.stringify(out, null, 2))
+ else {
+ if (ready.length) { console.log('ГОТОВЫ К ЗАПУСКУ:'); for (const id of ready) console.log(` ${id} (${plans.get(id).executor})`) }
+ else { console.log('готовых нет; блокеры:'); for (const id of Object.keys(blocked).sort()) console.log(` ${id}: ${blocked[id].join('; ')}`) }
+ }
+ return ready.length ? 0 : 1
+}
+
+async function cmdPlan(id, requireCsv, opts) {
+ const plans = await loadPlans()
+ if (!plans.has(id)) { console.error(`пустая выборка планов: план ${id} не в реестре П00–П24`); return 2 }
+ const deps = (requireCsv || '').split(',').map(s => s.trim()).filter(Boolean)
+ for (const dep of deps) {
+ const mk = readMarker(dep)
+ if (mk.status !== 'done') { console.error(`план ${id} блокирован отсутствующим ${dep}${mk.status === 'tampered' ? ' (tampered: ' + mk.reason + ')' : ''}`); return 2 }
+ }
+ if (opts.checkCmd) {
+ const res = spawnSync('/bin/sh', ['-c', opts.checkCmd], { stdio: 'inherit' })
+ const code = res.status == null ? 1 : res.status
+ if (code !== 0) { console.error(`проверка ${id} дала код ${code} — маркер не пишется`); return code }
+ writeMarker(id, opts)
+ console.log(`маркер ${id} записан (exit_code 0)`)
+ return 0
+ }
+ console.log(`${id} разблокирован: маркеры require закрыты (${deps.length ? deps.join(',') : 'нет зависимостей'})`)
+ return 0
+}
+
+function cmdStartFinish(id, action) {
+ const st = readRunning()
+ if (action === 'start' && !st.running.includes(id)) st.running.push(id)
+ if (action === 'finish') st.running = st.running.filter(x => x !== id)
+ writeRunning(st)
+ console.log(`${action}: бегут ${st.running.length ? st.running.join(', ') : '(никто)'}`)
+ return 0
+}
+
+function cmdContracts(json) {
+ const c = {
+ marker_fields: ['plan', 'check_cmd', 'exit_code', 'sha_of_changed_files', 'base', 'head', 'executor_cli', 'verifier_cli', 'finished_at', 'written_by', '(П00: config_local_sha, rollback_rehearsal)'],
+ rules: [
+ 'маркер пишет только rebuild-gate и только при exit_code 0',
+ 'маркер без written_by:"rebuild-gate" или с несовпавшим sha → tampered; --require на него → exit 2',
+ 'пустая выборка планов → exit 2, не «сдано 0/0»',
+ 'исключение внутри проверки плана → crash:<план>, остальные считаются',
+ 'нет budget.json → exit 2; превышение → exit 3',
+ '--selftest: репетиция отката + спрятанный прибор плана красит проверку',
+ ],
+ budget: { file: path.relative(REPO, path.join(CONFIG.stateDir, 'budget.json')), ceiling: 'ceiling_usd (владелец §5.11), ceiling_tokens опционально' },
+ ready: { slots: CONFIG.slotsPerCli, open_questions: CONFIG.openQuestions, question_blocks: CONFIG.questionBlocks },
+ }
+ if (json) console.log(JSON.stringify(c, null, 2))
+ else {
+ console.log('КОНТРАКТ rebuild-gate')
+ console.log(' поля маркера: ' + c.marker_fields.join(', '))
+ for (const r of c.rules) console.log(' · ' + r)
+ console.log(' бюджет: ' + c.budget.file + ' — ' + c.budget.ceiling)
+ console.log(' слоты: ' + JSON.stringify(c.ready.slots) + ' · открытые вопросы §6: ' + c.ready.open_questions.join(','))
+ }
+ return 0
+}
+
+// --- selftest: детерминированные утверждения + репетиция отката + спрятанный прибор ---------------
+async function cmdSelftest() {
+ const { strictEqual: eq, ok } = await import('node:assert')
+
+ // 1. Разбор блока плана из фикстуры (изолирован от диска).
+ const fixture = [
+ '### П77 · Фикстура',
+ '- **Точные пути:**',
+ ' - `scripts/some-tool.mjs:12-20` — **[новый]**',
+ ' - `scripts/mnemazine-coverage-check.mjs:53-68` — образец',
+ '- **Исполнитель:** codex. **Проверяющий:** claude.',
+ '- **Требует маркеров:** П00, П01.',
+ '',
+ '### П78 · Вторая',
+ '- **Точные пути:**',
+ ' - `scripts/mnemazine-coverage-check.mjs` — общий файл',
+ '- **Исполнитель:** kimi. **Проверяющий:** codex.',
+ '- **Требует маркеров:** —',
+ ].join('\n')
+ const parsed = parsePlansFromText(fixture, 'fixture.md')
+ eq(parsed.length, 2)
+ eq(parsed[0].id, 'П77')
+ eq(parsed[0].executor, 'codex')
+ eq(JSON.stringify(parsed[0].requires), JSON.stringify(['П00', 'П01']))
+ eq(parsed[1].requires.length, 0) // «—» = нет зависимостей
+ // normPath снял `:12-20` и `:53-68`
+ eq(parsed[0].paths[0].path, 'scripts/some-tool.mjs')
+ eq(parsed[0].paths[0].isNew, true)
+ eq(parsed[0].paths[1].path, 'scripts/mnemazine-coverage-check.mjs')
+ eq(parsed[0].paths[1].isNew, false)
+ // пересечение путей П77 ↔ П78 по общему файлу
+ const inter = parsed[0].paths.map(x => x.path).filter(x => parsed[1].paths.map(y => y.path).includes(x))
+ eq(inter[0], 'scripts/mnemazine-coverage-check.mjs')
+
+ // 2. Классификатор tampered на объекте без written_by (без обращения к git).
+ eq(normPath('`x.mjs:10`'.replace(/`/g, '')), 'x.mjs')
+ eq(normPath('.mnemazine/state/rebuild/'), '.mnemazine/state/rebuild')
+
+ // 3. Реальные планы извлекаются; ноль → красный (мастер §8).
+ const plans = await loadPlans()
+ ok(plans.size >= 1, 'ноль извлечённых планов — selftest красный')
+
+ // 4. Спрятанный прибор плана: git-отслеживаемые не-[новый] repo-пути обязаны существовать на диске.
+ // mv scripts/mnemazine-coverage-check.mjs /tmp/ уводит отслеживаемый файл → эта проверка краснеет.
+ const tracked = new Set((gitSafe(['ls-files']) || '').split('\n').filter(Boolean))
+ const missing = []
+ for (const p of plans.values()) {
+ for (const x of p.paths) {
+ if (x.isNew) continue
+ const rel = x.path
+ if (rel.startsWith('/') || rel.startsWith('~') || rel.includes('://')) continue
+ if (!tracked.has(rel)) continue // не отслеживается — не наша ответственность
+ if (!existsSync(path.join(REPO, rel))) missing.push(`${p.id}:${rel}`)
+ }
+ }
+ ok(missing.length === 0, 'спрятан отслеживаемый прибор плана: ' + missing.join(', '))
+
+ // 5. Репетиция отката — обязательная часть П00, не декларация.
+ const reh = rollbackRehearsal()
+ eq(reh.matched, true, `откат не восстановил дерево: ${reh.before_tree} != ${reh.after_tree}`)
+
+ console.log('selftest ok')
+ console.log(` rollback_rehearsal.before_tree = ${reh.before_tree}`)
+ console.log(` rollback_rehearsal.after_tree = ${reh.after_tree}`)
+ console.log(` извлечено планов: ${plans.size}`)
+ return 0
+}
+
+// --- Диспетчер -----------------------------------------------------------------------------------
+async function main() {
+ let v
+ try {
+ ({ values: v } = parseArgs({
+ args: process.argv.slice(2),
+ allowPositionals: true,
+ options: {
+ plan: { type: 'string' }, require: { type: 'string' },
+ status: { type: 'boolean' }, contracts: { type: 'boolean' }, budget: { type: 'boolean' },
+ ready: { type: 'boolean' }, selftest: { type: 'boolean' }, json: { type: 'boolean' },
+ start: { type: 'string' }, finish: { type: 'string' },
+ 'check-cmd': { type: 'string' }, executor: { type: 'string' }, verifier: { type: 'string' }, base: { type: 'string' },
+ 'state-dir': { type: 'string' },
+ },
+ }))
+ } catch (e) { console.error('разбор аргументов: ' + e.message); return 2 }
+
+ // --state-dir изолирует боевые маркеры от проб (probe #1/#3/#4 гоняются в одноразовом каталоге).
+ if (v['state-dir']) CONFIG.stateDir = path.resolve(v['state-dir'])
+
+ if (v.selftest) return cmdSelftest()
+ if (v.contracts) return cmdContracts(v.json)
+ if (v.status) return cmdStatus(v.json)
+ if (v.ready) return cmdReady(v.json)
+ if (v.budget) return cmdBudget(v.json)
+ if (v.start) return cmdStartFinish(v.start, 'start')
+ if (v.finish) return cmdStartFinish(v.finish, 'finish')
+ if (v.plan !== undefined) return cmdPlan(v.plan, v.require, { checkCmd: v['check-cmd'], executor: v.executor, verifier: v.verifier, base: v.base })
+
+ console.log('rebuild-gate — прибор оркестрации волны 0. Флаги: --plan --require --status --contracts --budget --ready --selftest --json --start --finish')
+ return 0
+}
+
+main().then(code => process.exit(code)).catch(err => { console.error(err && err.message || err); process.exit(1) })
diff --git a/scripts/mnemazine-recut-help-heading.mjs b/scripts/mnemazine-recut-help-heading.mjs
new file mode 100644
index 0000000..a6b1e83
--- /dev/null
+++ b/scripts/mnemazine-recut-help-heading.mjs
@@ -0,0 +1,54 @@
+#!/usr/bin/env node
+// Кампания 1 плана П16 — канонизация заголовка блока «Как это поможет мне». Ноль токенов, скрипт, не модель.
+//
+// Гейт (mnemazine-vault-quality-gate.mjs:269) ищет ^#{2,3}\s+(?:🎯\s*)?Как (?:это )?поможет мне$,
+// а в корпусе живут неканонические формы: «Как поможет мне» (222 ноты), «🎯 Как поможет мне» (101)
+// и «Как помогает мне» (найдена ручной выборкой шага 0 — гейт её НЕ видит, это ложный отказ).
+// Все три приводятся к канону «Как это поможет мне» (с сохранением 🎯 и уровня заголовка).
+//
+// По умолчанию — СУХОЙ ПРОГОН, диск не трогается; --apply — opt-in.
+// Строки внутри fenced code-блоков не правятся: там заголовок может быть примером синтаксиса.
+import { promises as fs } from 'node:fs'
+import { resolveVault } from './mnemazine-paths.mjs'
+import { corpusFiles } from './mnemazine-normalize-old-frontmatter.mjs'
+
+const argv = process.argv.slice(2)
+const arg = (name, fallback = '') => {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+const VAULT = resolveVault({ cli: arg('vault') })
+const APPLY = argv.includes('--apply')
+const JSON_OUT = argv.includes('--json')
+
+// (уровень ##/###)(необязательный 🎯)Как поможет|помогает мне — канон: «Как это поможет мне».
+const HEADING = /^(#{2,3}\s+(?:🎯\s*)?)Как помо(?:жет|гает) мне\s*$/
+
+const files = await corpusFiles(VAULT)
+const report = { vault: VAULT, apply: APPLY, scanned: files.length, changed: 0, files_changed: [] }
+for (const file of files) {
+ const text = await fs.readFile(file, 'utf8')
+ const lines = text.split('\n')
+ let inFence = false
+ let touched = 0
+ for (let i = 0; i < lines.length; i++) {
+ if (/^```/.test(lines[i])) inFence = !inFence
+ if (inFence) continue
+ const m = lines[i].match(HEADING)
+ if (m) {
+ lines[i] = `${m[1]}Как это поможет мне`
+ touched++
+ }
+ }
+ if (!touched) continue
+ report.changed++
+ report.files_changed.push({ file: file.slice(VAULT.length + 1), headings: touched })
+ if (APPLY) await fs.writeFile(file, lines.join('\n'))
+}
+if (JSON_OUT) console.log(JSON.stringify(report, null, 2))
+else {
+ console.log(`${APPLY ? 'ПРИМЕНЕНО' : 'СУХОЙ ПРОГОН'} · vault ${report.vault}`)
+ console.log(`просмотрено ${report.scanned} · файлов с правкой ${report.changed}`)
+ for (const f of report.files_changed) console.log(` ${f.file} (${f.headings})`)
+}
diff --git a/scripts/mnemazine-refresh-core-indexes.mjs b/scripts/mnemazine-refresh-core-indexes.mjs
new file mode 100644
index 0000000..bd963de
--- /dev/null
+++ b/scripts/mnemazine-refresh-core-indexes.mjs
@@ -0,0 +1,244 @@
+#!/usr/bin/env node
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import { resolveVault } from './mnemazine-paths.mjs'
+
+const argv = process.argv.slice(2)
+const today = new Date().toISOString().slice(0, 10)
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ if (hit.includes('=')) return hit.split('=').slice(1).join('=')
+ return argv[argv.indexOf(hit) + 1] || fallback
+}
+
+const VAULT = resolveVault({ cli: arg('vault') })
+const CHECK = argv.includes('--check')
+// `.mnemazine` — рантайм-состояние, `99 Система/_lint` — отчёты kb-lint. Ни то, ни другое не ноты.
+// Набор обязан совпадать с walkVault() в mnemazine-kb-lint.mjs: линтер сравнивает счётчик мастер-индекса
+// со своим счётом диска, поэтому любое расхождение НАБОРОВ он печатает как critical «расхождение индексов»
+// — вечный красный, который растёт с каждым прогоном линта. Измерено 2026-07-26: индексатор считал 1815,
+// линтер 1812, разница ровно три отчёта в `99 Система/_lint/`. Правишь одну сторону — правь вторую.
+const EXCLUDE_DIRS = new Set(['.git', '.obsidian', '.mnemazine'])
+const EXCLUDE_RELS = new Set(['99 Система/_lint'])
+const MASTER = path.join(VAULT, '_МАСТЕР-ИНДЕКС.md')
+const LOG = path.join(VAULT, '99 Система', 'Лог обработки.md')
+
+async function walk(dir) {
+ const out = []
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ const p = path.join(dir, item.name)
+ const rel = path.relative(VAULT, p).replace(/\\/g, '/')
+ if (item.isDirectory() && !EXCLUDE_DIRS.has(item.name) && !EXCLUDE_RELS.has(rel) && !item.name.startsWith('graphify-out')) out.push(...await walk(p))
+ else if (item.isFile() && item.name.endsWith('.md')) out.push(p)
+ }
+ return out
+}
+
+function titleOf(text, file) {
+ const fm = text.match(/^title:\s*["']?(.+?)["']?\s*$/m)?.[1]
+ if (fm) return fm
+ const h1 = text.match(/^#\s+(.+)$/m)?.[1]
+ return h1 || path.basename(file, '.md')
+}
+
+const CAP_DIR = path.join(VAULT, '08 AI и Инструменты', 'Capabilities')
+const CAP_INDEX = path.join(CAP_DIR, '_Содержание.md')
+
+const all = await walk(VAULT)
+if (!CHECK) {
+ // Файлы, которые этот же прогон создаёт, считаются существующими — иначе на
+ // свежем vault записанные счётчики устаревают в момент записи и --check
+ // сразу после прогона краснеет.
+ for (const own of [MASTER, CAP_INDEX, LOG]) {
+ if (!all.includes(own)) all.push(own)
+ }
+}
+const bySection = new Map()
+const rootFiles = []
+for (const file of all) {
+ const rel = path.relative(VAULT, file)
+ const parts = rel.split(path.sep)
+ if (parts.length === 1) {
+ rootFiles.push(rel)
+ continue
+ }
+ const section = parts[0]
+ if (!section || rel.includes('/graphify-out/')) continue
+ bySection.set(section, (bySection.get(section) || 0) + 1)
+}
+
+// ── --check: детерминированный гейт «число в индексе == число на диске» ──
+
+// Ячейка счётчика — третья колонка таблицы разделов; строка узнаётся по тому,
+// что третья ячейка целиком число (шапка и разделитель отсеиваются сами).
+function parseIndexCounts(md) {
+ const counts = new Map()
+ for (const line of md.split('\n')) {
+ const cells = line.split('|').map(s => s.trim())
+ if (cells.length >= 5 && cells[1] && /^\d+$/.test(cells[3])) counts.set(cells[1], Number(cells[3]))
+ }
+ const total = md.match(/Всего markdown[^*\n]*\*\*(\d+)\*\*/)?.[1]
+ return { counts, total: total ? Number(total) : null }
+}
+
+if (CHECK) {
+ const md = await fs.readFile(MASTER, 'utf8').catch(() => null)
+ if (md === null) {
+ console.error(JSON.stringify({ ok: false, error: `нет файла ${MASTER}` }))
+ process.exit(1)
+ }
+ const { counts, total } = parseIndexCounts(md)
+ const mismatches = []
+ for (const [section, disk] of bySection) {
+ const index = counts.has(section) ? counts.get(section) : null
+ if (index !== disk) mismatches.push({ section, index, disk })
+ }
+ for (const [section, index] of counts) {
+ if (!bySection.has(section) && index !== 0) mismatches.push({ section, index, disk: 0 })
+ }
+ mismatches.sort((a, b) => a.section.localeCompare(b.section, 'ru'))
+ const ok = mismatches.length === 0 && total === all.length
+ const report = { ok, master: MASTER, total: { index: total, disk: all.length }, sections_on_disk: bySection.size, mismatches }
+ ;(ok ? console.log : console.error)(JSON.stringify(report, null, 2))
+ process.exit(ok ? 0 : 1)
+}
+
+// ── Запись: пересчёт мастер-индекса, индекса Capabilities, запись в лог ──
+
+const labels = {
+ '00 Входящие': 'сырьё и временные буферы',
+ '01 Обо мне': 'личные данные, профиль, цели',
+ '01 Право и Юриспруденция': 'корпоративное право, юридические процессы',
+ '02 Бизнес и Предпринимательство': 'бизнес-модели, стартапы, продажи',
+ '02 Здоровье': 'тело, сон, питание, ментальное',
+ '02 Знания': 'методики мышления и личная база знаний',
+ '03 Проекты': 'материалы под конкретные проекты',
+ '04 Образование': 'обучение, курсы, справочники',
+ '05 Кино и Сериалы': 'медиа и рекомендации',
+ '05 Продуктивность и Процессы': 'старый алиас продуктивности',
+ '06 Промты': 'переиспользуемые промты',
+ '07 Бизнес и Финансы': 'финансы, рынки, бизнес-аналитика',
+ '07 Скиллы': 'старый алиас skills-знаний',
+ '08 AI и Инструменты': 'AI, агенты, MCP, skills, plugins',
+ '09 Личная продуктивность': 'фокус, flow, организация',
+ '09 Технологии': 'старый алиас разработки',
+ '09 Технологии и Разработка': 'технологии и разработка',
+ '99 Система': 'инфраструктура vault, протоколы, логи'
+}
+
+const masterRows = [...bySection.entries()]
+ .sort((a, b) => a[0].localeCompare(b[0], 'ru'))
+ .map(([section, count]) => {
+ const indexPath = path.join(VAULT, section, '_Содержание.md')
+ const hasIndex = all.includes(indexPath)
+ const link = hasIndex ? `[[${section}/_Содержание|открыть]]` : '—'
+ return `| ${section} | ${labels[section] || 'раздел'} | ${count} | ${link} |`
+ })
+
+const master = `---
+title: "Мастер-индекс базы знаний"
+type: master-index
+updated: "${today}"
+---
+
+# Мастер-индекс — база знаний
+
+Общий список разделов. Обновляется агентом после значимых изменений Vault.
+Точка входа для человека и агента. Система: [[00 СИСТЕМА — Агентный конвейер знаний]].
+
+## Разделы
+
+| Раздел | Область | Заметок | Содержание |
+|---|---|---:|---|
+${masterRows.join('\n')}
+
+Всего markdown в активном Vault: **${all.length}**
+
+Корневые служебные файлы: ${rootFiles.map(f => `[[${f.replace(/\.md$/, '')}]]`).join(' · ') || '—'}
+
+## Новая структура способностей
+
+- [[08 AI и Инструменты/Capabilities/_СПОСОБНОСТИ — методика|Методика установки, оценки и применения]]
+- [[08 AI и Инструменты/Capabilities/_СПОСОБНОСТИ — реестр|Полный реестр Skills/MCP/plugins]]
+
+## Как пополнять
+
+1. Кинь материал в инбокс.
+2. Прогони pipeline Мнемозины.
+3. Получи финальные атомы, источники, применимые способности и связи.
+
+## Система
+
+- [[00 СИСТЕМА — Агентный конвейер знаний]] — принципы и контракт
+- [[_ROUTING]] — роутинг для агентов · [[_ШАБЛОНЫ]] — шаблоны · [[Лог обработки]] — журнал
+`
+
+await fs.writeFile(MASTER, master)
+
+const capFiles = await walk(CAP_DIR)
+const capRows = []
+for (const file of capFiles.sort((a, b) => a.localeCompare(b, 'ru'))) {
+ if (path.basename(file) === '_Содержание.md') continue
+ const text = await fs.readFile(file, 'utf8')
+ const relNoExt = path.relative(VAULT, file).replace(/\.md$/, '')
+ capRows.push(`| [[${relNoExt}|${titleOf(text, file)}]] | ${path.basename(file)} |`)
+}
+
+const capIndex = `---
+title: "Содержание — способности агента"
+type: section-index
+updated: "${today}"
+---
+
+# Capabilities — Содержание
+
+Кратко: отдельная структура для Skills, MCP, plugins, agents и workflow. Методика сохраняет правила установки/оценки; реестр даёт полный каталог; конкретные знания ссылаются на применимые способности.
+
+| Заметка | Файл |
+|---|---|
+${capRows.join('\n')}
+
+Назад: [[_МАСТЕР-ИНДЕКС]]
+`
+
+await fs.mkdir(CAP_DIR, { recursive: true })
+await fs.writeFile(CAP_INDEX, capIndex)
+
+// Новые записи лога — только греп-парсибельным префиксом `## [ГГГГ-ММ-ДД] тип | заголовок`.
+// Старые записи (`### [дата] — …`) не переписываются. Повторный прогон в тот же
+// день обновляет свою запись, а не плодит дубли.
+const ENTRY_HEAD_RE = /^#{2,3} \[\d{4}-\d{2}-\d{2}\]/
+const heading = `## [${today}] индекс | Пересчёт мастер-индекса и Capabilities`
+const entryLines = [
+ heading,
+ `- markdown всего: ${all.length}, разделов: ${bySection.size}`,
+ '- обновлены: _МАСТЕР-ИНДЕКС.md · 08 AI и Инструменты/Capabilities/_Содержание.md',
+ ''
+]
+
+const logText = await fs.readFile(LOG, 'utf8').catch(() => '# Лог обработки\n\n')
+const logLines = logText.split('\n')
+const existing = logLines.indexOf(heading)
+if (existing !== -1) {
+ let end = existing + 1
+ while (end < logLines.length && !ENTRY_HEAD_RE.test(logLines[end])) end += 1
+ logLines.splice(existing, end - existing, ...entryLines)
+} else {
+ const first = logLines.findIndex(l => ENTRY_HEAD_RE.test(l))
+ if (first === -1) logLines.push(...entryLines)
+ else logLines.splice(first, 0, ...entryLines)
+}
+await fs.writeFile(LOG, logLines.join('\n'))
+
+console.log(JSON.stringify({
+ ok: true,
+ vault: VAULT,
+ markdown: all.length,
+ sections: Object.fromEntries([...bySection.entries()].sort((a, b) => a[0].localeCompare(b[0], 'ru'))),
+ master: MASTER,
+ capabilities_index: CAP_INDEX,
+ log: LOG,
+ log_entry: heading
+}, null, 2))
diff --git a/scripts/mnemazine-refresh-graphify.mjs b/scripts/mnemazine-refresh-graphify.mjs
index cb93f19..90bb0a0 100644
--- a/scripts/mnemazine-refresh-graphify.mjs
+++ b/scripts/mnemazine-refresh-graphify.mjs
@@ -39,8 +39,11 @@ const MODEL_LADDER = (arg('models', process.env.MNEMAZINE_GRAPHIFY_MODELS || (BA
const TIMEOUT_MS = Number(arg('timeout-seconds', String(CONFIG.timeout_seconds || '900'))) * 1000
const SMOKE_TIMEOUT_MS = Number(arg('smoke-timeout-seconds', String(CONFIG.smoke_timeout_seconds || '120'))) * 1000
const SHRINK_THRESHOLD = Number(arg('shrink-threshold', String(CONFIG.shrink_threshold || '0.85')))
-const MAX_CONCURRENCY = arg('max-concurrency', process.env.MNEMAZINE_GRAPHIFY_MAX_CONCURRENCY || String(CONFIG.max_concurrency || (BACKEND === 'kimi' ? '3' : '')))
+// Per-backend concurrency default lives in config (data), not a code literal:
+// graphify org-concurrency caps map by backend name. New backend = config edit.
+const MAX_CONCURRENCY = arg('max-concurrency', process.env.MNEMAZINE_GRAPHIFY_MAX_CONCURRENCY || String(CONFIG.max_concurrency || CONFIG.backend_max_concurrency?.[BACKEND] || ''))
const ALLOW_PARTIAL_SEMANTIC = arg('allow-partial-semantic', process.env.MNEMAZINE_GRAPHIFY_ALLOW_PARTIAL || String(CONFIG.allow_partial_semantic ? 1 : 0)) !== '0'
+const MARK_SEMANTIC_PENDING = hasFlag('mark-semantic-pending') || process.env.MNEMAZINE_GRAPHIFY_MARK_SEMANTIC_PENDING === '1'
const JSON_OUT = hasFlag('json')
const GRAPHIFY_OUT = path.join(VAULT, 'graphify-out')
const GRAPH_PATH = path.join(GRAPHIFY_OUT, 'graph.json')
@@ -199,9 +202,9 @@ async function pruneBackups(keep = GRAPHIFY_BACKUPS_KEEP) {
}
}
-async function writeNeedsUpdate() {
+async function writeNeedsUpdate(reason = 'semantic graph needs update') {
await ensureGraphifyOut()
- await fs.writeFile(NEEDS_UPDATE_PATH, '1', 'utf8')
+ await fs.writeFile(NEEDS_UPDATE_PATH, `${reason}\n`, 'utf8')
}
async function clearNeedsUpdate() {
@@ -568,6 +571,7 @@ async function main() {
api_key_env: API_KEY_ENV_BY_BACKEND[BACKEND] || null,
max_concurrency: MAX_CONCURRENCY || null,
allow_partial_semantic: ALLOW_PARTIAL_SEMANTIC,
+ mark_semantic_pending: MARK_SEMANTIC_PENDING,
ollama_base_url: BACKEND === 'ollama' ? OLLAMA_BASE_URL : null,
before: initialBefore,
code_refresh: null,
@@ -589,10 +593,12 @@ async function main() {
}
const afterCode = await graphSummary(GRAPH_PATH)
- const semanticPending = result.semantic_pending_before || existsSync(NEEDS_UPDATE_PATH) || (await newestNonCodeMtimeMs()) > afterCode.mtimeMs || MODE === 'semantic'
+ const semanticPending = MARK_SEMANTIC_PENDING || result.semantic_pending_before || existsSync(NEEDS_UPDATE_PATH) || (await newestNonCodeMtimeMs()) > afterCode.mtimeMs || MODE === 'semantic'
if (MODE === 'code' || (MODE === 'auto' && !semanticPending)) {
- if (MODE !== 'semantic' && semanticPending) await writeNeedsUpdate()
+ if (MODE !== 'semantic' && semanticPending) await writeNeedsUpdate(MARK_SEMANTIC_PENDING
+ ? `deferred: code graph refreshed at ${new Date().toISOString()}; run npm run graph:semantic:async`
+ : 'semantic graph needs update')
result.after = await graphSummary(GRAPH_PATH)
result.semantic_pending_after = existsSync(NEEDS_UPDATE_PATH)
result.ok = MODE === 'code' ? true : !result.semantic_pending_after
diff --git a/scripts/mnemazine-release-check.mjs b/scripts/mnemazine-release-check.mjs
index 9dce6f8..b417e37 100644
--- a/scripts/mnemazine-release-check.mjs
+++ b/scripts/mnemazine-release-check.mjs
@@ -1,10 +1,11 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
-import { existsSync } 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'
const ROOT = path.resolve(process.cwd())
@@ -24,6 +25,24 @@ function run(command, args, options = {}) {
})
}
+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) {
@@ -50,40 +69,39 @@ async function listFiles(dir) {
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() {
+ const result = await run('git', ['ls-files'])
+ if (result.code !== 0) throw new Error(`git ls-files failed\n${result.stdout}\n${result.stderr}`.trim())
+ return result.stdout.split(/\r?\n/).map(line => line.trim()).filter(Boolean)
+}
+
+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 scripts = [
- 'scripts/mnemazine-run.mjs',
- 'scripts/mnemazine-paths.mjs',
- 'scripts/mnemazine-doctor.mjs',
- 'scripts/mnemazine-vault-quality-gate.mjs',
- 'scripts/mnemazine-refresh-graphify.mjs',
- 'scripts/mnemazine-refresh-graphify-smoke.mjs',
- 'scripts/mnemazine-graph-utils.mjs',
- 'scripts/mnemazine-repair-graphify-graph.mjs',
- 'scripts/mnemazine-semantic-shards.mjs',
- 'scripts/mnemazine-semantic-batches.mjs',
- 'scripts/mnemazine-synthesize.mjs',
- 'scripts/mnemazine-kb-search.mjs',
- 'scripts/mnemazine-llm.mjs',
- 'scripts/mnemazine-codex.mjs',
- 'scripts/mnemazine-verify.mjs',
- 'scripts/mnemazine-weekly-brief-html.mjs',
- 'scripts/mnemazine-weekly-state.mjs',
- 'scripts/mnemazine-postrun-knowledge-report.mjs',
- 'scripts/mnemazine-digest.mjs',
- 'scripts/mnemazine-tool-decision-queue.mjs',
- 'scripts/mnemazine-report-quality-gate.mjs',
- 'scripts/mnemazine-human-layer-gate.mjs',
- 'scripts/mnemazine-complete-check.mjs',
- 'scripts/mnemazine-live-status.mjs',
- 'scripts/mnemazine-release-check.mjs'
- ]
- for (const script of scripts) {
- if (existsSync(path.join(ROOT, script))) await must(`syntax:${script}`, process.execPath, ['--check', script])
- }
- if (existsSync(path.join(ROOT, 'scripts/graphify-extract-limited.py'))) {
- await must('syntax:scripts/graphify-extract-limited.py', 'python3', ['-m', 'py_compile', 'scripts/graphify-extract-limited.py'])
- }
+ 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() {
@@ -163,23 +181,35 @@ async function demoSmoke() {
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-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'))
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-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.writeFile(path.join(config, 'cli-registry.local.json'), '{}\n', 'utf8')
await must('demo intake smoke', process.execPath, ['scripts/mnemazine-run.mjs'], {
env: {
MNEMAZINE_ROOT: temp,
MNEMAZINE_INBOX: inbox,
- MNEMAZINE_VAULT: vault
+ MNEMAZINE_VAULT: vault,
+ // finishRun не входит в контракт этого смоука (он про intake→synth→archive),
+ // а его обязательные скрипты сюда не копируются — runLocalNodeScript теперь
+ // fail-closed на пропаже обязательного. Гасим finish, как уже делает
+ // strictArchiveGateSmoke ниже.
+ MNEMAZINE_FINISH: '0'
}
})
@@ -197,7 +227,8 @@ async function demoSmoke() {
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})`)
- if (!/type:\s*"knowledge-note"/.test(note)) throw new Error(`demo smoke failed: ${path.basename(noteFile)} is not knowledge-note`)
+ 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`)
}
@@ -215,7 +246,8 @@ async function demoSmoke() {
env: {
MNEMAZINE_ROOT: temp,
MNEMAZINE_INBOX: inbox,
- MNEMAZINE_VAULT: vault
+ MNEMAZINE_VAULT: vault,
+ MNEMAZINE_FINISH: '0'
}
})
const cachedInboxFiles = await fs.readdir(inbox)
@@ -231,17 +263,25 @@ async function strictArchiveGateSmoke() {
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-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-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.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)
@@ -260,7 +300,7 @@ async function strictArchiveGateSmoke() {
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"
+type: "concept"
verified: false
verification_status: "unknown"
status: "draft"
@@ -298,7 +338,7 @@ Public/source expansion:
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"
+type: "concept"
verified: true
verification_status: "verified"
status: "final"
@@ -322,12 +362,12 @@ MarkItDown здесь зафиксирован как проверенное п
Local source refs:
- ${ref}
-Public/source expansion:
+Публичные источники:
- Microsoft MarkItDown: https://github.com/microsoft/markitdown
## Расширение знания
-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.
@@ -360,12 +400,193 @@ async function qualityAndPublicChecks() {
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'])
+ await must('semantic monitor dry-run smoke', process.execPath, ['scripts/mnemazine-semantic-graph-task.mjs', '--monitor', '--dry-run', '--stale-hours', '1'])
+ 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()
- await must('public release scan', 'npm', ['run', 'public-check'])
+}
+
+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() {
@@ -376,7 +597,7 @@ async function toolDecisionQueueSmoke() {
const started = new Date(Date.now() - 1000).toISOString()
await fs.writeFile(path.join(concepts, 'aider.md'), `---
title: "Aider-AI/aider: решение для Mnemazine"
-type: "knowledge-note"
+type: "concept"
verified: true
verification_status: "verified"
status: "final"
@@ -459,6 +680,13 @@ async function completeGateSmoke() {
processed: 0,
synthesize: { skipped: true }
}, null, 2), 'utf8')
+ // Потолок спеки для демо-корпуса (план П06 шаг 8): единственная демо-нота спеке
+ // не отвечает, потолок честно равен 1 — spec-ceiling --check из complete-check
+ // держится, а не краснеет. Пишется во временный MNEMAZINE_STATE, не в репозиторий.
+ await fs.writeFile(path.join(state, 'spec-ceiling.json'), JSON.stringify({
+ vault: path.join(ROOT, 'demo/vault'),
+ ceiling: 1
+ }, null, 2), 'utf8')
await must('complete gate smoke', process.execPath, ['scripts/mnemazine-complete-check.mjs'], {
env: {
MNEMAZINE_VAULT: path.join(ROOT, 'demo/vault'),
@@ -505,13 +733,15 @@ async function humanLayerGateSmoke() {
const reports = path.join(temp, 'reports')
const state = path.join(temp, 'state')
const concepts = path.join(vault, '01 Concepts')
+ const digest = path.join(vault, '_digest')
await fs.mkdir(concepts, { recursive: true })
+ await fs.mkdir(digest, { recursive: true })
await fs.mkdir(reports, { recursive: true })
await fs.mkdir(state, { recursive: true })
const started = new Date(Date.now() - 1000).toISOString()
await fs.writeFile(path.join(concepts, 'good.md'), `---
title: "Хорошая русская заметка"
-type: "knowledge-note"
+type: "concept"
status: "final"
verified: true
verification_status: "verified"
@@ -542,6 +772,96 @@ verification_status: "verified"
## Следующее действие
- Оставить human-layer gate в release-check.
+`, 'utf8')
+ await fs.writeFile(path.join(concepts, 'github-atom.md'), `---
+title: "tech-leads-club/agent-skills: что реально обещает README"
+type: "concept"
+status: "final"
+verified: true
+verification_status: "verified"
+---
+
+# tech-leads-club/agent-skills: что реально обещает README
+
+## Что это
+
+README позиционирует tech-leads-club/agent-skills как проверенный каталог skills для AI coding agents. Рабочий смысл простой: это кандидат на разбор, а не команда сразу ставить глобально.
+
+## Зачем это нужно
+
+Скриншот со stars ещё не знание. Нужны первоисточник, свежесть репозитория, лицензия, открытые issues и понятный риск доверия.
+
+## Как использовать
+
+- Проверить заявленную валидацию skills.
+- Отдельно посмотреть security-claim про уязвимости marketplace skills.
+- Связать каталог с одним нашим workflow до установки.
+
+## Источники
+
+Локальные source refs:
+- local-media:humanlayergithub
+
+Публичные источники:
+- github.com: https://github.com/tech-leads-club/agent-skills
+
+## Расширение знания
+
+Факты, добавленные до атомизации:
+- GitHub README описывает проект как проверенный каталог skills для coding agents.
+- Метаданные GitHub добавляют проверяемые признаки свежести и поддержки.
+
+## Проверка
+
+- Статус проверки: verified.
+
+## Следующее действие
+
+- Добавить репозиторий в очередь разбора возможностей с одним критерием: принять или отклонить.
+`, 'utf8')
+ await fs.writeFile(path.join(digest, 'Сводка-smoke.md'), `---
+title: "Сводка знаний — smoke"
+type: "knowledge-digest"
+source_ref: "digest:smoke"
+---
+
+# Сводка знаний — smoke
+
+## Что это
+
+Сводка связывает новые заметки после прогона и показывает, какие выводы уже можно открыть как карту знаний.
+
+## Зачем это нужно
+
+Она нужна как быстрый слой повторного использования: видно, какие заметки появились, что они дают и где лежат связи.
+
+## Как использовать
+
+- Открыть связанные заметки из списка ниже.
+- Взять сильные следующие действия в работу.
+- Проверить слабые связи перед публикацией.
+
+## Источник
+
+- source_ref: digest:smoke
+- processed_notes: 2
+
+## Проверка
+
+Сводка построена локально из заметок vault. Это не внешняя факт-проверка, а навигационная карта после прогона.
+
+## Связанные заметки
+
+- [[Mnemazine Protocol]]
+
+## Повторное использование
+
+Обработано заметок: 2. Ниже — что узнано и как связано.
+
+## Проверенная карточка инструмента
+
+- Заметка: [[01 Concepts/synthesis-tech-leads-club-agent-skills-readme-backed-capability-summary-fd502aea4d]]
+- Связи: [[01 Concepts/synthesis-affaan-m-ecc-mnemazine-routing-decision-1c84a44c58]], [[01 Concepts/synthesis-browser-use-browser-use-operational-risk-and-maintenance-check-ebe5f6e21e]], [[01 Concepts/synthesis-ksimback-looper-verified-tool-identity-and-adoption-signal-3d2bc03aaf]], [[01 Concepts/synthesis-tech-leads-club-agent-skills-operational-risk-and-maintenance-check-cdedd86d2b]], [[01 Concepts/synthesis-browser-use-browser-use-readme-backed-capability-summary-fd502aea4d]], [[01 Concepts/synthesis-affaan-m-ecc-verified-tool-identity-and-adoption-signal-3d2bc03aaf]], [[01 Concepts/synthesis-really-long-agent-workflow-loop-design-before-runtime-with-reviewer-model-judge-token-budget-no-progress-limit-and-session-state-files-readme-backed-capability-summary-aabbccddeeff00112233445566778899]], [[01 Concepts/synthesis-really-long-agent-workflow-loop-design-before-runtime-with-reviewer-model-judge-token-budget-no-progress-limit-and-session-state-files-operational-risk-and-maintenance-check-aabbccddeeff00112233445566778899]], [[01 Concepts/synthesis-really-long-agent-workflow-loop-design-before-runtime-with-reviewer-model-judge-token-budget-no-progress-limit-and-session-state-files-verified-tool-identity-and-adoption-signal-aabbccddeeff00112233445566778899]], [[01 Concepts/synthesis-really-long-agent-workflow-loop-design-before-runtime-with-reviewer-model-judge-token-budget-no-progress-limit-and-session-state-files-mnemazine-routing-decision-aabbccddeeff00112233445566778899]]
`, 'utf8')
const report = path.join(reports, 'good.html')
await fs.writeFile(report, [
@@ -626,6 +946,241 @@ async function repoMetadataCheck() {
}
}
+// Пять мета-приборов П11: каждый — отдельный скрипт с честным кодом возврата и --selftest.
+async function runMetaGate(scriptRel) {
+ await must(scriptRel, process.execPath, [scriptRel])
+}
+async function rulesInventoryGate() { await runMetaGate('scripts/mnemazine-rules-inventory.mjs') }
+async function docContractGate() { await runMetaGate('scripts/mnemazine-doc-contract-check.mjs') }
+async function singleTruthGate() { await runMetaGate('scripts/mnemazine-single-truth-check.mjs') }
+async function lessonGateCheck() { await runMetaGate('scripts/mnemazine-lesson-gate.mjs') }
+async function checksInventoryGate() { await runMetaGate('scripts/mnemazine-checks-inventory.mjs') }
+async function modelPinCheck() { await runMetaGate('scripts/mnemazine-model-pin-check.mjs') }
+
+const NEW_CHECKS = new Set(['rules-inventory', 'doc-contract-check', 'single-truth-check', 'lesson-gate', 'checks-inventory'])
+
+// П24: every rsync/scp whose DESTINATION is the VPS in scripts/*.sh must be
+// preceded, in the same file, by a machine-class-gate call. A dangling outbound
+// transfer (gate cut out, rsync left) is a hole — hostile probe 5 breaks exactly
+// this. Also runs the gate's hermetic --selftest so a broken taxonomy reddens here.
+async function machineClassGateCheck() {
+ const gate = path.join(ROOT, 'scripts', 'mnemazine-machine-class-gate.mjs')
+ if (!existsSync(gate)) throw new Error('machine-class-gate: scripts/mnemazine-machine-class-gate.mjs отсутствует')
+ await must('machine-class-gate selftest', process.execPath, [gate, '--selftest'])
+ const shDir = path.join(ROOT, 'scripts')
+ const files = (await fs.readdir(shDir)).filter(f => f.endsWith('.sh'))
+ const violations = []
+ for (const f of files) {
+ const lines = (await fs.readFile(path.join(shDir, f), 'utf8')).split('\n')
+ let gateSeen = false
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]
+ if (line.trim().startsWith('#')) continue // комментарий не считается ни вызовом гейта, ни отправкой
+ if (line.includes('machine-class-gate')) gateSeen = true
+ if (!/\b(rsync|scp)\b/.test(line)) continue
+ const tokens = line.trim().split(/\s+/)
+ const dest = tokens[tokens.length - 1] // outbound ⇔ VPS is the destination (last arg); inbound pulls have VPS as source
+ if (/\$VPS/.test(dest) && !gateSeen) {
+ violations.push(`scripts/${f}:${i + 1}: rsync/scp на $VPS без предшествующего вызова machine-class-gate`)
+ }
+ }
+ }
+ if (violations.length) throw new Error('machine-class-gate: незащищённая отправка наружу:\n' + violations.join('\n'))
+}
+
+// Порог пяти новых гейтов: 'blocking' по умолчанию. Перевод в 'warn' — одна строка
+// new_gate_enforcement в config/doc-claims.json (путь отката П11 на исторический долг).
+function readNewGateEnforcement() {
+ try {
+ const cfg = JSON.parse(readFileSync(path.join(ROOT, 'config', 'doc-claims.json'), 'utf8'))
+ return cfg.new_gate_enforcement === 'warn' ? 'warn' : 'blocking'
+ } catch {
+ return 'blocking'
+ }
+}
+
+// --contracts: печать контракта всех зарегистрированных проверок без их запуска.
+// Строки syntax: перечисляют реальную выборку git ls-files ∩ disk.
+async function printContracts(checks) {
+ const targets = syntaxTargetsFrom(await gitLsFiles())
+ for (const file of targets.all) {
+ if (existsSync(path.join(ROOT, file))) console.log(`syntax:${file}`)
+ }
+ for (const [name] of checks) console.log(`check:${name}`)
+}
+
+// --- П19 онбординг: шесть новых проверок --------------------------------------
+
+// README: восемь новых разделов в обоих файлах, одинаковый набор npm-команд EN/RU,
+// одинаковое число строк в таблице агентов (заголовочный паритет этого не ловит).
+async function onboardingReadmeCheck() {
+ const en = await fs.readFile(path.join(ROOT, 'README.md'), 'utf8')
+ const ru = await fs.readFile(path.join(ROOT, 'README.ru.md'), 'utf8')
+ const h2 = body => (body.match(/^##\s+.+$/gm) || []).map(s => s.toLowerCase())
+ const enH2 = h2(en); const ruH2 = h2(ru)
+ const sections = [
+ ['install goes', 'как проходит установка'],
+ ['my agents', 'мои агенты'],
+ ['privacy', 'приватность'],
+ ['if you improved me', 'если ты меня улучшил'],
+ ['something broke', 'сломалось'],
+ ['exit codes', 'коды возврата'],
+ ['bot:', 'бот:'],
+ ['vps:', 'vps:']
+ ]
+ const missing = []
+ for (const [enA, ruA] of sections) {
+ if (!enH2.some(x => x.includes(enA))) missing.push(`README.md: раздел «${enA}»`)
+ if (!ruH2.some(x => x.includes(ruA))) missing.push(`README.ru.md: раздел «${ruA}»`)
+ }
+ if (missing.length) throw new Error('onboarding-readme: нет разделов:\n' + missing.join('\n'))
+
+ const npmToks = body => body.match(/npm (?:run [\w:-]+|start)/g) || []
+ const enToks = npmToks(en); const ruToks = npmToks(ru)
+ const npmCmds = toks => [...new Set(toks)].sort()
+ const enCmds = npmCmds(enToks); const ruCmds = npmCmds(ruToks)
+ const onlyEn = enCmds.filter(c => !ruCmds.includes(c))
+ const onlyRu = ruCmds.filter(c => !enCmds.includes(c))
+ if (onlyEn.length || onlyRu.length) {
+ throw new Error(`onboarding-readme: набор npm-команд разошёлся. только EN: ${onlyEn.join(', ') || '—'}; только RU: ${onlyRu.join(', ') || '—'}`)
+ }
+
+ // Обязательные контрактные фрагменты: каждый обязан быть в ОБОИХ README (контракт П19,
+ // блок «Команда проверки»). Команды сверяем по ЧИСЛУ вхождений — набор-симметрия выше
+ // не ловит потерю одного из двух дублей (прецедент пробы: удаление одной из двух строк
+ // `npm run doctor:full` из RU). Текст — по языковой паре EN|RU.
+ const MANDATORY = [
+ { name: 'npm run doctor', cmd: 'npm run doctor' },
+ { name: 'npm run doctor:full', cmd: 'npm run doctor:full' },
+ { name: 'npm start', cmd: 'npm start' },
+ { name: 'таблица приватности', en: '| Channel | What leaves', ru: '| Канал | Что уходит' },
+ { name: 'VPS не делает: Apple Vision OCR', en: 'Apple Vision', ru: 'Apple Vision' },
+ { name: 'VPS не делает: whisper', en: 'whisper', ru: 'whisper' },
+ { name: 'VPS не делает: ollama', en: 'ollama', ru: 'ollama' }
+ ]
+ const gaps = []
+ for (const f of MANDATORY) {
+ if (f.cmd) {
+ const enN = enToks.filter(t => t === f.cmd).length
+ const ruN = ruToks.filter(t => t === f.cmd).length
+ if (enN === 0) gaps.push(`«${f.name}» → нет в README.md`)
+ if (ruN === 0) gaps.push(`«${f.name}» → нет в README.ru.md`)
+ if (enN && ruN && enN !== ruN) gaps.push(`«${f.name}» → вхождений EN ${enN} ≠ RU ${ruN} (README.ru.md)`)
+ } else {
+ if (!en.includes(f.en)) gaps.push(`«${f.name}» → нет в README.md`)
+ if (!ru.includes(f.ru)) gaps.push(`«${f.name}» → нет в README.ru.md`)
+ }
+ }
+ if (gaps.length) throw new Error('onboarding-readme: пропал обязательный контрактный фрагмент:\n' + gaps.map(g => ' ' + g).join('\n'))
+
+ const agentRows = (body, anchor) => {
+ const lines = body.split('\n')
+ const start = lines.findIndex(l => /^##\s/.test(l) && l.toLowerCase().includes(anchor))
+ if (start === -1) return -1
+ let n = 0
+ for (let i = start + 1; i < lines.length; i++) {
+ if (/^##\s/.test(lines[i])) break
+ if (/^\|/.test(lines[i])) n++
+ }
+ return n
+ }
+ const enRows = agentRows(en, 'my agents'); const ruRows = agentRows(ru, 'мои агенты')
+ if (enRows < 4 || ruRows < 4) throw new Error(`onboarding-readme: таблица агентов пуста (EN ${enRows}, RU ${ruRows})`)
+ if (enRows !== ruRows) throw new Error(`onboarding-readme: строк в таблице агентов EN ${enRows} ≠ RU ${ruRows}`)
+}
+
+// install.sh реально зовёт доктора и не печатает безусловное «installed».
+async function installVerifiesCheck() {
+ const src = await fs.readFile(path.join(ROOT, 'install.sh'), 'utf8')
+ if (!src.includes('mnemazine-doctor')) throw new Error('install-verifies: install.sh не ссылается на mnemazine-doctor')
+ if (!src.includes('exit "$STATUS"')) throw new Error('install-verifies: install.sh не завершается кодом статуса')
+ if (/^\s*echo\s+"Mnemazine installed\.?"/m.test(src)) throw new Error('install-verifies: безусловная печать «Mnemazine installed» без развилки')
+}
+
+// Гейт согласия: молчание = отказ, ничего не создано в $HOME.
+async function installerConsentGateCheck() {
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-consent-home-'))
+ const shim = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-consent-shim-'))
+ const clone = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-consent-clone-'))
+ for (const c of ['pip3', 'pip', 'launchctl', 'swiftc', 'brew', 'xcode-select']) {
+ await fs.writeFile(path.join(shim, c), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
+ }
+ const res = await run('bash', ['install.sh'], {
+ env: { HOME: home, PATH: `${shim}:${process.env.PATH}`, MNEMAZINE_ROOT: clone, MNEMAZINE_SETUP_DRYRUN: '0', MNEMAZINE_FROM_SETUP: '0', MNEMAZINE_YES: '0' }
+ })
+ if (res.code !== 1) throw new Error(`installer-consent-gate: молчание должно давать exit 1, получено ${res.code}\n${res.stdout}\n${res.stderr}`)
+ const created = await listFiles(home)
+ if (created.length) throw new Error(`installer-consent-gate: отказ создал файлы в $HOME: ${created.join(', ')}`)
+}
+
+// Каждая строка DEGRADED: несёт команду починки.
+async function installerWarningsCarryFixCheck() {
+ const lines = (await fs.readFile(path.join(ROOT, 'install.sh'), 'utf8')).split('\n')
+ const bad = []
+ let degradeCalls = 0
+ for (let i = 0; i < lines.length; i++) {
+ if (/\bdegrade\s+"/.test(lines[i])) degradeCalls++
+ if (lines[i].includes('DEGRADED:') && !lines[i].includes('fix:')) bad.push(`install.sh:${i + 1}: ${lines[i].trim()}`)
+ }
+ if (bad.length) throw new Error('installer-warnings-carry-fix: DEGRADED без команды:\n' + bad.join('\n'))
+ if (degradeCalls < 1) throw new Error('installer-warnings-carry-fix: нет ни одного degrade-вызова')
+}
+
+// Доктор различает три кода: 0/1/2.
+async function doctorThreeCodesCheck() {
+ const src = await fs.readFile(path.join(ROOT, 'scripts/mnemazine-doctor.mjs'), 'utf8')
+ if (!/process\.exit\(1\)/.test(src)) throw new Error('doctor-three-codes: нет ветки exit 1')
+ if (!/process\.exit\(2\)/.test(src)) throw new Error('doctor-three-codes: нет ветки exit 2')
+ if (!/warnings\.length\)\s*process\.exit\(2\)/.test(src)) throw new Error('doctor-three-codes: предупреждения не дают код 2')
+ await must('doctor selftest (three codes)', process.execPath, ['scripts/mnemazine-doctor.mjs', '--selftest'])
+}
+
+// Интейк: раздел приватности с четырьмя каналами; вопрос про бота исполним в трёх
+// ветках без сети и без записи в $HOME; README не обещает на VPS того, чего нет.
+async function onboardingIntakeCheck() {
+ const en = await fs.readFile(path.join(ROOT, 'README.md'), 'utf8')
+ const ru = await fs.readFile(path.join(ROOT, 'README.ru.md'), 'utf8')
+ for (const [label, body] of [['README.md', en], ['README.ru.md', ru]]) {
+ if (!/^##\s+.*(privacy|приватность)/im.test(body)) throw new Error(`onboarding-intake: в ${label} нет раздела приватности`)
+ const channels = { deep: /deep/i, telegram: /telegram/i, 'agent-os': /agent-os/i, youtube: /youtube/i }
+ for (const [name, re] of Object.entries(channels)) {
+ if (!re.test(body)) throw new Error(`onboarding-intake: в ${label} раздел приватности не называет канал ${name}`)
+ }
+ }
+ const vpsClaims = [
+ /(Apple Vision|whisper|ollama)[^.\n]{0,80}(VPS|сервер|server|удал[её]нн)/i,
+ /(VPS|сервер|server)[^.\n]{0,80}(Apple Vision|whisper|ollama)/i
+ ]
+ for (const [label, body] of [['README.md', en], ['README.ru.md', ru]]) {
+ const lines = body.split('\n')
+ for (let i = 0; i < lines.length; i++) {
+ for (const re of vpsClaims) {
+ if (re.test(lines[i])) throw new Error(`onboarding-intake: ${label}:${i + 1} обещает на VPS то, чего там нет: ${lines[i].trim()}`)
+ }
+ }
+ }
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-intake-home-'))
+ const shim = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-intake-shim-'))
+ const netlog = path.join(shim, 'net.log')
+ for (const c of ['ssh', 'scp', 'rsync', 'security', 'pip3', 'pip', 'launchctl', 'swiftc', 'brew', 'xcode-select', 'claude', 'codex']) {
+ await fs.writeFile(path.join(shim, c), `#!/bin/sh\necho "$(basename "$0") $*" >> ${JSON.stringify(netlog)}\nexit 0\n`, { mode: 0o755 })
+ }
+ const branches = [
+ ['нет VPS', '1\n3\n1\nтокен-проба\n2\n'],
+ ['без бота', '1\n3\n2\n'],
+ ['есть VPS', '1\n3\n1\nтокен-проба\n1\nuser@host\n\nSHA256:fake\n']
+ ]
+ for (const [name, answers] of branches) {
+ const res = await runWithStdin('bash', ['setup.sh'], answers, {
+ HOME: home, PATH: `${shim}:${process.env.PATH}`, MNEMAZINE_SETUP_DRYRUN: '1'
+ })
+ if (res.code !== 0) throw new Error(`onboarding-intake: ветка «${name}» упала кодом ${res.code}\n${(res.stderr || res.stdout).slice(-500)}`)
+ }
+ if (existsSync(netlog)) throw new Error('onboarding-intake: установщик сходил в сеть (net.log непустой)')
+ const created = await listFiles(home)
+ if (created.length) throw new Error(`onboarding-intake: установщик создал файлы в $HOME: ${created.join(', ')}`)
+}
+
async function main() {
const checks = [
['syntax', checkSyntax],
@@ -636,15 +1191,73 @@ async function main() {
['strict-archive-gate', strictArchiveGateSmoke],
['quality-public', qualityAndPublicChecks],
['search-eval', searchEvalSmoke],
- ['repo-metadata', repoMetadataCheck]
+ ['repo-metadata', repoMetadataCheck],
+ ['rules-inventory', rulesInventoryGate],
+ ['doc-contract-check', docContractGate],
+ ['single-truth-check', singleTruthGate],
+ ['lesson-gate', lessonGateCheck],
+ ['checks-inventory', checksInventoryGate],
+ ['model-pin', modelPinCheck],
+ ['machine-class-gate', machineClassGateCheck],
+ ['onboarding-readme', onboardingReadmeCheck],
+ ['install-verifies', installVerifiesCheck],
+ ['installer-consent-gate', installerConsentGateCheck],
+ ['installer-warnings-carry-fix', installerWarningsCarryFixCheck],
+ ['doctor-three-codes', doctorThreeCodesCheck],
+ ['onboarding-intake', onboardingIntakeCheck]
]
- const passed = []
- for (const [name, fn] of checks) {
- await fn()
- passed.push(name)
- console.log(`ok ${name}`)
+
+ if (process.argv.includes('--contracts')) {
+ await printContracts(checks)
+ return
}
- console.log(JSON.stringify({ ok: true, passed }, null, 2))
+
+ // --only : запустить одну зарегистрированную проверку (режим приходит из
+ // П19; до его закрытия обслуживает прямой вызов machine-class-gate из приёмки П24).
+ const onlyIdx = process.argv.indexOf('--only')
+ if (onlyIdx !== -1) {
+ const requested = String(process.argv[onlyIdx + 1] || '').split(',').map(s => s.trim()).filter(Boolean)
+ const selected = checks.filter(([n]) => requested.includes(n))
+ // Пустая выборка — exit 2, а не «сдано 0/0 ✓»: опечатка в фильтре не должна
+ // печатать «приём» (прецедент разбора Фемиды).
+ if (selected.length === 0) { console.error(`empty --only selection: ${requested.join(',') || '(none)'}`); process.exit(2) }
+ const okOnly = []
+ const crashOnly = []
+ for (const [name, fn] of selected) {
+ try { await fn(); okOnly.push(name); console.log(`ok ${name}`) }
+ catch (e) { crashOnly.push(name); console.error(`crash:${name}\n${e && e.message ? e.message : e}`) }
+ }
+ process.exit(crashOnly.length ? 1 : 0)
+ }
+
+ // Изоляция: исключение одной проверки записывается crash:<имя> и не убивает остальные;
+ // итоговый код ненулевой при любом crash. Новые гейты при enforcement:'warn' дают warn,
+ // а не crash (мягкий режим), но по умолчанию блокируют.
+ const enforcement = readNewGateEnforcement()
+ const passed = []
+ const warned = []
+ const crashed = []
+ for (const [name, fn] of checks) {
+ try {
+ await fn()
+ passed.push(name)
+ console.log(`ok ${name}`)
+ } catch (error) {
+ const message = error && error.message ? error.message : String(error)
+ if (NEW_CHECKS.has(name) && enforcement === 'warn') {
+ warned.push(name)
+ console.error(`warn ${name} (мягкий режим): ${message}`)
+ } else {
+ crashed.push(name)
+ console.error(`crash:${name}\n${message}`)
+ }
+ }
+ }
+ if (crashed.length) {
+ console.log(JSON.stringify({ ok: false, passed, warned, crashed }, null, 2))
+ process.exit(1)
+ }
+ console.log(JSON.stringify({ ok: true, passed, warned }, null, 2))
}
main().catch(error => {
diff --git a/scripts/mnemazine-repair-graphify-graph.mjs b/scripts/mnemazine-repair-graphify-graph.mjs
index 4741a93..5c072df 100644
--- a/scripts/mnemazine-repair-graphify-graph.mjs
+++ b/scripts/mnemazine-repair-graphify-graph.mjs
@@ -8,6 +8,7 @@ import {
readGraph,
writeGraph
} from './mnemazine-graph-utils.mjs'
+import { resolveVault } from './mnemazine-paths.mjs'
const argv = process.argv.slice(2)
@@ -21,7 +22,7 @@ function hasFlag(name) {
return argv.includes(`--${name}`)
}
-const graphPath = path.resolve(arg('graph', path.join(process.env.HOME || '.', 'Мозг/graphify-out/graph.json')))
+const graphPath = path.resolve(arg('graph') || path.join(resolveVault({ requireExists: false }), 'graphify-out', 'graph.json'))
const outPath = arg('out', '')
const apply = hasFlag('apply')
diff --git a/scripts/mnemazine-report-quality-gate.mjs b/scripts/mnemazine-report-quality-gate.mjs
index 68e0c0d..32a44b2 100644
--- a/scripts/mnemazine-report-quality-gate.mjs
+++ b/scripts/mnemazine-report-quality-gate.mjs
@@ -13,6 +13,9 @@ function arg(name, fallback = '') {
const REPORT = arg('report', '')
const REPORTS = path.resolve(arg('reports', process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')))
+// fail-closed: «no reports found» больше не зелёный. Ноль отчётов = exit 2,
+// если не передан явный --allow-empty.
+const ALLOW_EMPTY = argv.includes('--allow-empty')
const rawMarkers = [
/raw\s+ocr/i,
@@ -81,8 +84,12 @@ async function checkReport(file) {
const reports = await listReports()
if (!reports.length) {
- console.log(JSON.stringify({ ok: true, checked: 0, note: 'no reports found' }, null, 2))
- process.exit(0)
+ if (ALLOW_EMPTY) {
+ console.log(JSON.stringify({ ok: true, checked: 0, note: 'no reports found (--allow-empty)' }, null, 2))
+ process.exit(0)
+ }
+ console.error(JSON.stringify({ ok: false, checked: 0, error: 'нет отчётов для проверки: 0 найдено (--allow-empty чтобы разрешить)' }, null, 2))
+ process.exit(2)
}
const failures = []
diff --git a/scripts/mnemazine-rules-inventory.mjs b/scripts/mnemazine-rules-inventory.mjs
new file mode 100644
index 0000000..d3d3478
--- /dev/null
+++ b/scripts/mnemazine-rules-inventory.mjs
@@ -0,0 +1,162 @@
+#!/usr/bin/env node
+// Правило без прибора становится ошибкой сборки (план П11, метод-правило 3).
+//
+// Каждое императивное предложение из CLAUDE.md/AGENTS.md (must / must not / never /
+// do not / обязан / обязательно / никогда / не должен) обязано иметь запись в
+// config/rules-enforcement.json с живым `enforced_by` (<файл>:<строка> — файл есть,
+// строка в диапазоне, файл проходит node --check / bash -n / python3 -m py_compile).
+// Форма «утверждение → якорь в отдельном json», а НЕ `enforced_by:` внутри CLAUDE.md:
+// глобальная конституция держит бюджет ≤200 строк, машинные якоря её ломают.
+//
+// Новые правила мастер-плана §17.8 (класс данных) и §18 (subject) заведены сразу,
+// с полем pending_until: пока маркера их плана нет на диске — мёртвый enforced_by не
+// краснит; с маркером — краснит. Так правило не теряется между волнами и не блокирует
+// их порядок.
+//
+// Коды: 0 — все правила имеют живой прибор; 1 — правило без записи, либо запись с
+// мёртвым файлом/несуществующей строкой/непроходящим синтаксисом; 2 — ноль извлечённых
+// правил (пустая выборка = провал, не «сдано 0/0»).
+
+import { existsSync, readFileSync } from 'node:fs'
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { spawnSync } from 'node:child_process'
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const DOC_FILES = ['CLAUDE.md', 'AGENTS.md']
+const ENFORCEMENT = path.join(ROOT, 'config', 'rules-enforcement.json')
+const KEYWORDS = /\b(must not|must|never|do not|обязан|обязательно|никогда|не должен)\b/i
+
+function splitSentences(text) {
+ const out = []
+ for (const rawLine of String(text).split(/\r?\n/)) {
+ const line = rawLine.trim()
+ if (!line || line.startsWith('#') || line.startsWith('```')) continue
+ for (const piece of line.split(/(?<=[.!?;])\s+/)) {
+ const t = piece.trim()
+ if (t) out.push(t)
+ }
+ }
+ return out
+}
+
+function norm(s) {
+ return String(s).replace(/\s+/g, ' ').trim().toLowerCase()
+}
+
+function extractRules(docRoot) {
+ const rules = []
+ const seen = new Set()
+ for (const rel of DOC_FILES) {
+ const p = path.join(docRoot, rel)
+ if (!existsSync(p)) continue
+ for (const sentence of splitSentences(readFileSync(p, 'utf8'))) {
+ if (!KEYWORDS.test(sentence)) continue
+ const key = norm(sentence)
+ if (seen.has(key)) continue
+ seen.add(key)
+ rules.push({ file: rel, sentence, norm: key })
+ }
+ }
+ return rules
+}
+
+function syntaxOk(rel) {
+ const abs = path.join(ROOT, rel)
+ const ext = path.extname(rel)
+ let cmd, args
+ if (ext === '.mjs' || ext === '.js') { cmd = process.execPath; args = ['--check', abs] }
+ else if (ext === '.sh') { cmd = 'bash'; args = ['-n', abs] }
+ else if (ext === '.py') { cmd = 'python3'; args = ['-m', 'py_compile', abs] }
+ else return true // не-кодовый якорь: достаточно существования файла
+ return spawnSync(cmd, args, { encoding: 'utf8' }).status === 0
+}
+
+function enforcedByLive(anchor) {
+ const m = String(anchor || '').match(/^(.+):(\d+)$/)
+ if (!m) return `формат enforced_by не <файл>:<строка>: ${anchor}`
+ const rel = m[1]
+ const line = Number(m[2])
+ const abs = path.join(ROOT, rel)
+ if (!existsSync(abs)) return `enforced_by файл отсутствует: ${rel}`
+ const lineCount = readFileSync(abs, 'utf8').split(/\r?\n/).length
+ if (line < 1 || line > lineCount) return `enforced_by строка ${line} вне диапазона ${rel} (${lineCount} строк)`
+ if (!syntaxOk(rel)) return `enforced_by файл не проходит синтаксис: ${rel}`
+ return null
+}
+
+function markerExists(plan) {
+ return existsSync(path.join(ROOT, '.mnemazine', 'state', 'rebuild', `${plan}.done.json`))
+}
+
+function evaluate({ docRoot, enforcement }) {
+ const extracted = extractRules(docRoot)
+ if (extracted.length === 0) return { code: 2, extracted, failures: ['ноль извлечённых правил из CLAUDE.md/AGENTS.md'] }
+ const entries = Array.isArray(enforcement?.rules) ? enforcement.rules : []
+ const failures = []
+
+ for (const rule of extracted) {
+ const hit = entries.find(e => e.quote && rule.norm.includes(norm(e.quote)))
+ if (!hit) failures.push(`правило без записи в rules-enforcement.json: "${rule.sentence}" (${rule.file})`)
+ }
+
+ for (const e of entries) {
+ const dormant = e.pending_until && !markerExists(e.pending_until)
+ if (dormant) continue
+ const why = enforcedByLive(e.enforced_by)
+ if (why) failures.push(`${e.id || e.quote}: ${why}${e.pending_until ? ` (pending_until ${e.pending_until} снят)` : ''}`)
+ }
+
+ return { code: failures.length ? 1 : 0, extracted, failures }
+}
+
+function loadEnforcement() {
+ if (!existsSync(ENFORCEMENT)) return { rules: [] }
+ try { return JSON.parse(readFileSync(ENFORCEMENT, 'utf8')) } catch (e) { return { rules: [], _error: e.message } }
+}
+
+function selftest() {
+ // Красный кролик: правило без прибора обязано покраснеть.
+ const tmp = mkdtempSync(path.join(os.tmpdir(), 'rules-inv-selftest-'))
+ try {
+ writeFileSync(path.join(tmp, 'CLAUDE.md'), '# X\n\nThe runner must never write outside the vault.\n', 'utf8')
+ const r = evaluate({ docRoot: tmp, enforcement: { rules: [] } })
+ if (r.code !== 1) {
+ console.error(`selftest FAILED: красный кролик прошёл зелёным (code=${r.code})`)
+ return 1
+ }
+ console.log('selftest ok: правило без прибора краснит (1)')
+ return 0
+ } finally {
+ rmSync(tmp, { recursive: true, force: true })
+ }
+}
+
+function main() {
+ const argv = process.argv.slice(2)
+ if (argv.includes('--selftest')) process.exit(selftest())
+
+ const enforcement = loadEnforcement()
+ if (enforcement._error) {
+ console.error(`config/rules-enforcement.json нечитаем: ${enforcement._error}`)
+ process.exit(1)
+ }
+ const r = evaluate({ docRoot: ROOT, enforcement })
+ if (argv.includes('--json')) {
+ console.log(JSON.stringify({ code: r.code, extracted: r.extracted.length, failures: r.failures }, null, 2))
+ } else {
+ console.log(`извлечено правил: ${r.extracted.length}; записей в реестре: ${(enforcement.rules || []).length}`)
+ for (const rule of r.extracted) console.log(` rule: ${rule.sentence}`)
+ if (r.failures.length) {
+ console.error('ПРОВАЛЫ:')
+ for (const f of r.failures) console.error(` - ${f}`)
+ } else {
+ console.log('все правила имеют живой прибор')
+ }
+ }
+ process.exit(r.code)
+}
+
+main()
diff --git a/scripts/mnemazine-run.mjs b/scripts/mnemazine-run.mjs
index 586b7dd..7cc5363 100755
--- a/scripts/mnemazine-run.mjs
+++ b/scripts/mnemazine-run.mjs
@@ -1,13 +1,32 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
-import { existsSync } from 'node:fs'
+import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
import { spawnSync } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
import { llmAvailable, llmText } from './mnemazine-llm.mjs'
+import { strictKnowledgeReady } from './mnemazine-note-spec.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
+import { requireEngines } from './mnemazine-local-engines.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
+
+// Config contradiction, caught by code — not by a warning string. Strict protocol
+// (REQUIRE_DEEP) and draft-only are mutually exclusive: draft-only writes nothing
+// to the vault and never archives, so a run that must fail-before-archive cannot
+// also be draft-only. Exit 2 (config error), distinct from a gate failure (1).
+// This gate MUST stay the FIRST exit-2 path: it runs before resolveVault and before
+// the vault-quality-gate, so an observed exit 2 provably means THIS contradiction
+// and nothing else (empty-vault gate also exits 2 — that ambiguity is why order
+// matters). Remove the exit below and the run falls through to a code that is not 2.
+const REQUIRE_DEEP = process.argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
+const DRAFT_ONLY = process.env.MNEMAZINE_DRAFT_ONLY === '1'
+if (REQUIRE_DEEP && DRAFT_ONLY) {
+ console.error('strict protocol vs draft-only: MNEMAZINE_REQUIRE_DEEP=1 и MNEMAZINE_DRAFT_ONLY=1 несовместимы')
+ process.exit(2)
+}
+
const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
const VAULT = resolveVault()
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
@@ -21,13 +40,22 @@ const VIDEO_QUEUE = path.join(ROOT, '.mnemazine/cache/video-queue.jsonl')
const EXTRACTS = process.env.MNEMAZINE_EXTRACTS || path.join(ROOT, '.mnemazine/cache/extracted')
const SYNTHESIZE = process.env.MNEMAZINE_SYNTHESIZE !== '0'
const FINISH = process.env.MNEMAZINE_FINISH !== '0'
+const RUN_ID = process.env.MNEMAZINE_RUN_ID || `run-${new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)}`
// Opt-in deep stage (atomization + web/LLM verification, README:230 pipeline).
-// Default OFF: the runner stays conservative — local only, no external calls.
-// Enable with `--deep` or MNEMAZINE_DEEP=1; forwarded to synthesize.
+// Default OFF for direct runs. Strict desktop protocol does not pass --deep;
+// it lets tierOf(file) choose deep work only for tier>=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 DEEP_ALLOWED = DEEP || REQUIRE_DEEP
+const ENRICH_REQUIRED = DEEP_ALLOWED && 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')
+// Local-first contract (П10): with require-local on, a run that meets a MISSING
+// local engine STOPS (exit 3) rather than silently reaching for the cloud. The
+// env name is shared with CI and the launchd job — it flips the switch without
+// changing the command; --require-local is the equivalent CLI flag.
+const REQUIRE_LOCAL = process.argv.includes('--require-local') || process.env.MNEMAZINE_REQUIRE_LOCAL_EXTRACTION === '1'
+// Every local engine seen missing this run — cloud-substituted or not. Stamped
+// onto last-run.json by writeRunState so a silent cloud fallback is never silent.
+const localEnginesMissing = new Set()
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')
@@ -108,6 +136,10 @@ function isVideo(file) {
return ['.mp4', '.mov', '.m4v', '.webm', '.mkv'].includes(path.extname(file).toLowerCase())
}
+function isAudio(file) {
+ return ['.mp3', '.wav', '.m4a', '.aac', '.flac', '.ogg', '.opus'].includes(path.extname(file).toLowerCase())
+}
+
function isImage(file) {
return ['.png', '.jpg', '.jpeg', '.heic', '.webp', '.tiff'].includes(path.extname(file).toLowerCase())
}
@@ -116,6 +148,23 @@ function isMarkitdownDocument(file) {
return ['.pdf', '.docx', '.pptx', '.xlsx', '.html', '.htm'].includes(path.extname(file).toLowerCase())
}
+export function tierOf(file) {
+ const ext = path.extname(file).toLowerCase()
+ if (['.md', '.txt', '.json', '.csv'].includes(ext)) return 0
+ if (['.pdf', '.docx', '.pptx', '.xlsx'].includes(ext)) return 1
+ if (isImage(file)) return 2
+ if (isVideo(file) || isAudio(file)) return 3
+ return 1
+}
+
+function enginesFor(file) {
+ if (tierOf(file) === 0) return ['text-read']
+ if (isVideo(file) || isAudio(file)) return ['ffmpeg', 'whisper', 'vision-ocr']
+ if (isImage(file)) return ['vision-ocr']
+ if (isMarkitdownDocument(file)) return ['markitdown']
+ return []
+}
+
function videoDurationSeconds(file) {
const probe = spawnSync('ffmpeg', ['-i', file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
const match = `${probe.stderr}\n${probe.stdout}`.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/)
@@ -190,6 +239,36 @@ async function extractVideo(file, hash) {
return joinVideoParts(transcript, frames)
}
+async function extractAudio(file, hash) {
+ await ensureDir(TRANSCRIPTS)
+ await ensureDir(VIDEO_AUDIO)
+ const transcriptPath = path.join(TRANSCRIPTS, `${hash}.txt`)
+ if (existsSync(transcriptPath)) return await fs.readFile(transcriptPath, 'utf8')
+ const audioPath = path.join(VIDEO_AUDIO, `${hash}.wav`)
+ const ffmpeg = spawnSync('ffmpeg', [
+ '-y',
+ '-i', file,
+ '-vn',
+ '-ac', '1',
+ '-ar', '16000',
+ '-f', 'wav',
+ audioPath
+ ], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
+ if (ffmpeg.status !== 0 || !existsSync(audioPath)) return ''
+ const whisper = spawnSync('whisper', [
+ audioPath,
+ '--model', WHISPER_MODEL || 'tiny',
+ '--language', WHISPER_LANGUAGE,
+ '--output_dir', TRANSCRIPTS,
+ '--output_format', 'txt',
+ '--fp16', 'False',
+ '--verbose', 'False'
+ ], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
+ const whisperOut = path.join(TRANSCRIPTS, `${hash}.txt`)
+ if (whisper.status === 0 && existsSync(whisperOut)) return await fs.readFile(whisperOut, 'utf8')
+ return ''
+}
+
async function extractVideoFrames(file, hash) {
const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
if (!existsSync(ocr)) return ''
@@ -233,25 +312,57 @@ function joinVideoParts(transcript, frameText) {
return parts.join('\n\n')
}
+// Local-first extraction. Returns { text, engine_used, engines_missing }: a
+// MISSING engine (binary absent) is reported in engines_missing so the caller can
+// stop under require-local; a PRESENT engine that yields nothing leaves
+// engines_missing empty — that is «движок не нашёл», a different outcome that must
+// not be confused with «движка нет». Engine presence is the ONE truth in
+// mnemazine-local-engines.mjs (rule 8) — not re-encoded here.
+//
+// Text on the extraction/verification/citation path is passed through WHOLE — it
+// is never compressed or summarised on the way (measured 32–60% dangling links
+// after compressors). This is a rule, not a gate: keep it that way here and in
+// llmExtract below.
async function extract(file) {
const ext = path.extname(file).toLowerCase()
- if (['.md', '.txt', '.json', '.csv'].includes(ext)) return await fs.readFile(file, 'utf8')
- if (isVideo(file)) return await extractVideo(file, await sha256(file))
- const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
- if (existsSync(ocr) && isImage(file)) {
- const out = spawnSync(ocr, [file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
- if (out.status === 0) return out.stdout
+ if (['.md', '.txt', '.json', '.csv'].includes(ext)) {
+ return { text: await fs.readFile(file, 'utf8'), engine_used: 'text-read', engines_tried: ['text-read'], engines_missing: [] }
+ }
+ if (isVideo(file)) {
+ const engines_missing = requireEngines(['ffmpeg', 'whisper', 'vision-ocr'])
+ const text = await extractVideo(file, await sha256(file))
+ return { text, engine_used: text ? 'video' : '', engines_tried: ['ffmpeg', 'whisper', 'vision-ocr'], engines_missing }
+ }
+ if (isAudio(file)) {
+ const engines_missing = requireEngines(['ffmpeg', 'whisper'])
+ const text = await extractAudio(file, await sha256(file))
+ return { text, engine_used: text ? 'audio' : '', engines_tried: ['ffmpeg', 'whisper'], engines_missing }
+ }
+ if (isImage(file)) {
+ const engines_missing = requireEngines(['vision-ocr'])
+ if (!engines_missing.length) {
+ const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
+ const out = spawnSync(ocr, [file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
+ if (out.status === 0) return { text: out.stdout, engine_used: 'vision-ocr', engines_tried: ['vision-ocr'], engines_missing: [] }
+ }
+ return { text: '', engine_used: '', engines_tried: ['vision-ocr'], engines_missing }
}
if (isMarkitdownDocument(file)) {
- const markitdown = spawnSync('markitdown', [file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
- if (markitdown.status === 0 && markitdown.stdout.trim()) return markitdown.stdout
+ const engines_missing = requireEngines(['markitdown'])
+ if (!engines_missing.length) {
+ const markitdown = spawnSync('markitdown', [file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
+ if (markitdown.status === 0 && markitdown.stdout.trim()) return { text: markitdown.stdout, engine_used: 'markitdown', engines_tried: ['markitdown'], engines_missing: [] }
+ }
+ return { text: '', engine_used: '', engines_tried: ['markitdown'], engines_missing }
}
- return ''
+ return { text: '', engine_used: '', engines_tried: enginesFor(file), engines_missing: [] }
}
// LLM recognition fallback (deep only). Used ONLY when local engines (Apple
// Vision OCR / markitdown / whisper) produced nothing usable — keeps the default
// path at 0 tokens. A vision-capable agent reads the file and transcribes it.
+// The transcription is returned WHOLE (no compression/summary on the way) — same
+// rule as extract(): compressors drop 32–60% of citation links.
async function llmExtract(file) {
const ext = path.extname(file).toLowerCase()
const kind = isImage(file) ? 'image' : isVideo(file) ? 'video frame still' : 'document'
@@ -315,29 +426,6 @@ async function listVaultMarkdownFiles() {
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()) {
@@ -357,9 +445,19 @@ async function cachedExtractionText(entry) {
return await fs.readFile(path.join(EXTRACTS, textPath), 'utf8').catch(() => '')
}
-function runLocalNodeScript(script, args = []) {
+export function runLocalNodeScript(script, args = []) {
const file = path.join(ROOT, 'scripts', script)
- if (!existsSync(file)) return { skipped: true, reason: `${script} missing` }
+ if (!existsSync(file)) {
+ // Пропавший ОБЯЗАТЕЛЬНЫЙ скрипт — дыра, а не «пропущено»: throw (первый шаг
+ // пошаговой аттестации, полная — П11). Всё, чего нет в REQUIRED_FINISH_SCRIPTS
+ // (в т.ч. .gitignore-нутый refresh-core-indexes, отсутствующий на чужом клоне
+ // по замыслу), остаётся мягким пропуском — иначе П03 сломал бы чужую установку,
+ // а это тот же провал, что дыра.
+ if (REQUIRED_FINISH_SCRIPTS.has(script)) {
+ throw new Error(`required pipeline script missing: ${script}`)
+ }
+ return { skipped: true, reason: `${script} missing` }
+ }
const result = spawnSync(process.execPath, [file, ...args], { encoding: 'utf8', env: process.env, timeout: COMMAND_TIMEOUT_MS * 5 })
return {
skipped: false,
@@ -400,14 +498,78 @@ function failRunState(payload, code = 1) {
async function writeRunState(state) {
await ensureDir(STATE)
- await fs.writeFile(path.join(STATE, 'last-run.json'), `${JSON.stringify(state, null, 2)}\n`, 'utf8')
+ // local_engine_missing is stamped on EVERY state write (single writer), so a
+ // cloud fallback that stood in for an absent local engine is always on the record.
+ const enriched = { ...state, local_engine_missing: [...localEnginesMissing] }
+ await fs.writeFile(path.join(STATE, 'last-run.json'), `${JSON.stringify(enriched, null, 2)}\n`, 'utf8')
}
-function validateDeepRun({ synthesize, processed }) {
+function sidecarPresentFor(file, hash) {
+ if (!hash) return false
+ if (existsSync(path.join(EXTRACTS, `${hash}.txt`))) return true
+ if ((isVideo(file) || isAudio(file)) && existsSync(path.join(TRANSCRIPTS, `${hash}.txt`))) return true
+ return false
+}
+
+function c2paManifestPresent(file) {
+ if (!isImage(file) && !isVideo(file)) return undefined
+ const dir = path.dirname(file)
+ const name = path.basename(file)
+ const stem = name.replace(/\.[^.]+$/, '')
+ const candidates = [
+ `${file}.c2pa`,
+ `${file}.c2pa.json`,
+ path.join(dir, `${stem}.c2pa`),
+ path.join(dir, `${stem}.c2pa.json`),
+ path.join(dir, `${stem}.manifest.json`)
+ ]
+ for (const candidate of candidates) {
+ if (!existsSync(candidate)) continue
+ try { readFileSync(candidate) } catch {}
+ return true
+ }
+ return false
+}
+
+async function appendRunObservation(row) {
+ await ensureDir(STATE)
+ await fs.appendFile(path.join(STATE, 'run-observability.jsonl'), `${JSON.stringify(row)}\n`, 'utf8')
+}
+
+function observationFor(file, hash, overrides = {}) {
+ const ext = path.extname(file).toLowerCase()
+ const tier = tierOf(file)
+ const row = {
+ ts: new Date().toISOString(),
+ run_id: RUN_ID,
+ file,
+ ext,
+ tier,
+ sidecar_present: sidecarPresentFor(file, hash),
+ engines_tried: enginesFor(file),
+ engine_used: '',
+ llm_extract_used: false,
+ deep: DEEP_ALLOWED && tier >= 1,
+ ...overrides
+ }
+ const c2pa = c2paManifestPresent(file)
+ if (typeof c2pa === 'boolean') row.c2pa_manifest = c2pa
+ return row
+}
+
+function validateDeepRun({ synthesize, processed, inboxCount, cachedOnly = 0, observations = [] }) {
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')
+ const deepRows = observations.filter(row => row.tier >= 1)
+ const missingDeep = deepRows.filter(row => row.deep !== true)
+ if (missingDeep.length) failures.push(`deep stage missing for ${missingDeep.length} tier>=1 units`)
+ if (processed <= 0) {
+ // Zero processed with a non-empty inbox is a strict-run failure: something was
+ // there to handle and nothing was. Zero-in / zero-out stays legal.
+ if (inboxCount > 0 && cachedOnly <= 0) failures.push('нечего обработать при непустом инбоксе')
+ return failures
+ }
+ if (deepRows.length === 0) return failures
+ if (!synthesize || (synthesize.skipped && Number(synthesize.atomized || 0) <= 0 && Number(synthesize.written || 0) <= 0)) 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')
@@ -499,11 +661,56 @@ async function writeActionBrief(finishResult) {
return out
}
+// Скрипты, которые finishRun обязан найти в scripts/. Все восемь git-tracked —
+// значит на чистом клоне они присутствуют, и пропажа любого = реальная дыра, а не
+// частичная копия. Это единственный источник правды об «обязательном»: то, чего
+// здесь нет (напр. .gitignore:48 mnemazine-refresh-core-indexes.mjs, которого на
+// чужом клоне нет по замыслу), runLocalNodeScript мягко пропускает.
+const REQUIRED_FINISH_SCRIPTS = new Set([
+ 'mnemazine-tool-decision-queue.mjs',
+ 'mnemazine-vault-quality-gate.mjs',
+ 'mnemazine-refresh-graphify.mjs',
+ 'mnemazine-semantic-graph-task.mjs',
+ 'mnemazine-weekly-brief-html.mjs',
+ 'mnemazine-report-quality-gate.mjs',
+ 'mnemazine-postrun-knowledge-report.mjs',
+ 'mnemazine-human-layer-gate.mjs'
+])
+
+// Один элемент finish.* «в порядке», если: он был легально пропущен (стадия
+// выключена env-ом или скрипт не обязателен), отработал зелёным, ИЛИ это граф с
+// кодом 2 — задокументированный semantic-pending при --mark-semantic-pending.
+function finishGateOk(key, entry) {
+ if (!entry || typeof entry !== 'object') return false
+ if (entry.skipped === true) return true
+ if (entry.ok === true) return true
+ if (key === 'graph' && entry.code === 2) return true
+ return false
+}
+
+// result.ok больше не литерал: прогон зелёный только если ноль файлов упало И
+// каждый обязательный элемент finish.* в легальном состоянии. Коды гейтов,
+// собранные finishRun, наконец читаются — до архива они решали, после архива
+// теперь не «советуют», а считаются. finish === null (черновая ветка/FINISH=0):
+// решает только failed.
+function computeRunOk(failed, finish) {
+ if (Number(failed || 0) !== 0) return false
+ if (!finish || finish.skipped === true) return true
+ for (const [key, entry] of Object.entries(finish)) {
+ if (key === 'brief') continue // путь к файлу, не гейт
+ if (!finishGateOk(key, entry)) return false
+ }
+ return true
+}
+
async function finishRun(runStartedAt) {
const result = {}
result.tool_queue = runLocalNodeScript('mnemazine-tool-decision-queue.mjs', ['--changed-since', runStartedAt, '--session', new Date().toISOString().slice(0, 10)])
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', process.env.MNEMAZINE_FINISH_GRAPH_MODE || 'code', '--mark-semantic-pending', '--json'])
+ result.semantic_graph_task = process.env.MNEMAZINE_FINISH_SEMANTIC_ASYNC === '0'
+ ? { skipped: true, reason: 'disabled by MNEMAZINE_FINISH_SEMANTIC_ASYNC=0' }
+ : runLocalNodeScript('mnemazine-semantic-graph-task.mjs', ['--start', '--vault', VAULT])
result.weekly = runLocalNodeScript('mnemazine-weekly-brief-html.mjs')
const weeklyReport = result.weekly?.stdout?.match(/\/[^\s]+\.html/)?.[0]
result.report_quality = weeklyReport
@@ -535,17 +742,30 @@ async function main() {
const toArchive = []
const synthSourceRefs = new Set()
let failed = 0
- const canLlmExtract = DEEP && llmAvailable()
+ const observations = []
+ const canLlmExtract = llmAvailable()
for (const [index, entry] of entries.entries()) {
const file = path.join(INBOX, entry.name)
+ let observation = observationFor(file, '', { engines_tried: enginesFor(file) })
// Per-file isolation: one file's recognition failure must NEVER break the
// others. Any throw here is contained — the file stays in inbox for a retry.
try {
const hash = await sha256(file)
+ observation = observationFor(file, hash)
if (cache[hash]) {
if (await hasFinalKnowledgeForHash(hash)) {
toArchive.push({ file, hash })
cachedOnly += 1
+ observation.engine_used = 'cache'
+ observations.push(observation)
+ await appendRunObservation(observation)
+ continue
+ }
+ if (DRAFT_ONLY && cache[hash].status === 'draft_complete') {
+ cachedOnly += 1
+ observation.engine_used = 'cache'
+ observations.push(observation)
+ await appendRunObservation(observation)
continue
}
const cachedText = await cachedExtractionText(cache[hash])
@@ -553,16 +773,34 @@ async function main() {
synthSourceRefs.add(cache[hash].source_ref || sourceRef(hash))
toArchive.push({ file, hash })
processed += 1
+ observation.engine_used = 'cache'
+ observations.push(observation)
+ await appendRunObservation(observation)
continue
}
delete cache[hash]
}
// Local-first recognition (0 tokens): Apple Vision OCR / markitdown / whisper.
- let text = await extract(file)
+ const extraction = await extract(file)
+ observation.engines_tried = extraction.engines_tried || observation.engines_tried
+ observation.engine_used = extraction.engine_used || ''
+ let text = extraction.text
+ // Two outcomes are now distinct. A MISSING engine is not «движок ничего не
+ // нашёл»: under require-local we STOP here (exit 3, before any state write)
+ // instead of letting the cloud silently stand in. Otherwise the cloud may
+ // take over — but the substitution is recorded on run state, not silent.
+ if (extraction.engines_missing.length) {
+ for (const name of extraction.engines_missing) localEnginesMissing.add(name)
+ if (REQUIRE_LOCAL) {
+ console.error(JSON.stringify({ require_local_stop: true, file: entry.name, local_engine_missing: extraction.engines_missing }))
+ process.exit(3)
+ }
+ }
// Only if local produced nothing usable AND deep is on: LLM recognition.
- if (!hasUsableExtraction(text) && canLlmExtract && (isImage(file) || isVideo(file) || isMarkitdownDocument(file))) {
+ if (!hasUsableExtraction(text) && observation.deep && canLlmExtract && (isImage(file) || isVideo(file) || isAudio(file) || isMarkitdownDocument(file))) {
try {
const llmText = await llmExtract(file)
+ observation.llm_extract_used = true
if (hasUsableExtraction(llmText)) text = llmText
} catch (err) {
console.error(JSON.stringify({ file: entry.name, llm_extract_error: String(err.message).slice(0, 200) }))
@@ -579,9 +817,13 @@ async function main() {
toArchive.push({ file, hash })
processed += 1
}
+ observations.push(observation)
+ await appendRunObservation(observation)
} catch (err) {
// Isolated failure: log, leave file in inbox, keep going.
failed += 1
+ observations.push(observation)
+ await appendRunObservation(observation)
console.error(JSON.stringify({ file: entry.name, extract_error: String(err.message).slice(0, 200) }))
}
if (PROGRESS_EVERY > 0 && (index + 1) % PROGRESS_EVERY === 0) {
@@ -589,12 +831,13 @@ async function main() {
}
}
await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8')
+ const hasDeepUnits = observations.some(row => row.deep === true && row.engine_used)
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')
+ if (hasDeepUnits) synthArgs.push('--deep')
const synthEnv = { ...process.env }
if (synthSourceRefs.size) synthEnv.MNEMAZINE_SYNTH_SOURCE_REFS = [...synthSourceRefs].join(',')
const synth = spawnSync(process.execPath, synthArgs, { encoding: 'utf8', env: synthEnv })
@@ -608,18 +851,28 @@ async function main() {
vaultMarkdownFiles = null
}
if (REQUIRE_DEEP) {
- const deepFailures = validateDeepRun({ synthesize, processed })
+ const deepFailures = validateDeepRun({ synthesize, processed, cachedOnly, inboxCount: entries.length, observations })
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, 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))
process.exit(1)
}
}
- 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 })
+ const qualityArgs = [path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs'), '--changed-since', runStartedAt, '--max-failures', '50']
+ if (processed === 0 && cachedOnly > 0) qualityArgs.push('--allow-empty')
+ const quality = spawnSync(process.execPath, qualityArgs, { stdio: 'inherit', env: process.env })
if (quality.status !== 0) {
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)
}
+ if (DRAFT_ONLY) {
+ for (const item of toArchive) if (cache[item.hash]) cache[item.hash].status = 'draft_complete'
+ await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8')
+ const result = { ok: computeRunOk(failed, null), draft_only: true, inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: 0, 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() }
+ await writeRunState(result)
+ console.log(JSON.stringify(result, null, 2))
+ return
+ }
const missingFinalNotes = []
vaultMarkdownFiles = null
for (const item of toArchive) {
@@ -633,7 +886,7 @@ async function main() {
}
// Deep + final stage before archive: Russian humanizer digest + human-layer
// gate. If this fails, sources stay in inbox for a safe retry.
- if (DEEP) {
+ if (hasDeepUnits) {
const digest = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-digest.mjs'), '--changed-since', runStartedAt], { stdio: 'inherit', env: process.env })
if (digest.status !== 0) {
await failRunState({
@@ -646,6 +899,42 @@ async function main() {
extra: { failure: 'digest failed before archive' }
}, digest.status || 1)
}
+ // План П13 fixup: humanize-пас МЕЖДУ генерацией ноты и sweep. Конвейер (digest/
+ // LLM) рождает слоп и падал бы о собственный sweep. Пас очеловечивает каждую
+ // свежую ноту ДО сторожа: гейт → автоправка → повторный гейт; не чинится за 2
+ // итерации → прогон честно падает 1 с именем ноты. Sweep ниже остаётся байтовым
+ // бэкстопом на дочищенном тексте.
+ const humanizePass = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-humanize-gate.mjs'), '--pass', '--vault', VAULT, '--changed-since', runStartedAt], { encoding: 'utf8', env: process.env })
+ if (humanizePass.stdout) process.stdout.write(humanizePass.stdout)
+ if (humanizePass.stderr) process.stderr.write(humanizePass.stderr)
+ if (humanizePass.status !== 0) {
+ await failRunState({
+ inbox: entries.length,
+ processed,
+ cached_only: cachedOnly,
+ failed,
+ synthesize,
+ started_at: runStartedAt,
+ extra: { failure: 'humanize pass could not clear slop before archive' }
+ }, humanizePass.status || 1)
+ }
+ // План П13 шаг 6: гейт сохранности/читаемости по нотам, изменённым с runStartedAt.
+ // Фатален настоящий слоп (hard bans кроме сквозного em-dash); em-dash и низкий score —
+ // advisory, чтобы сторож не краснил живой прогон на дочищенном тексте.
+ const preserve = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-humanize-gate.mjs'), '--sweep', '--vault', VAULT, '--changed-since', runStartedAt], { encoding: 'utf8', env: process.env })
+ if (preserve.stdout) process.stdout.write(preserve.stdout)
+ if (preserve.stderr) process.stderr.write(preserve.stderr)
+ if (preserve.status !== 0) {
+ await failRunState({
+ inbox: entries.length,
+ processed,
+ cached_only: cachedOnly,
+ failed,
+ synthesize,
+ started_at: runStartedAt,
+ extra: { failure: 'humanize preservation gate failed before archive' }
+ }, preserve.status || 1)
+ }
const refs = [...new Set(toArchive.map(item => sourceRef(item.hash)))]
const humanArgs = [path.join(ROOT, 'scripts/mnemazine-human-layer-gate.mjs'), '--notes-only', '--changed-since', runStartedAt]
if (refs.length) humanArgs.push('--source-ref', refs.join(','))
@@ -667,12 +956,17 @@ async function main() {
const archived = []
for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash))
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, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, finish, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() }
+ const result = { ok: computeRunOk(failed, finish), 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)
console.log(JSON.stringify(result, null, 2))
}
-main().catch(err => {
- console.error(err)
- process.exit(1)
-})
+// Запуск main только когда файл исполняется напрямую (node .../mnemazine-run.mjs),
+// а не импортируется. Импорт нужен пробе runLocalNodeScript (harness на две строки)
+// и любому будущему потребителю экспортов — он не должен гонять пайплайн.
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ main().catch(err => {
+ console.error(err)
+ process.exit(1)
+ })
+}
diff --git a/scripts/mnemazine-semantic-batches.mjs b/scripts/mnemazine-semantic-batches.mjs
index a22fa33..865b3ea 100644
--- a/scripts/mnemazine-semantic-batches.mjs
+++ b/scripts/mnemazine-semantic-batches.mjs
@@ -30,8 +30,12 @@ const BATCH_SIZE = Math.max(1, Number(arg('batch-size', process.env.MNEMAZINE_SE
const START = Math.max(0, Number(arg('start', '0')))
const LIMIT = Number(arg('limit', '0'))
const EXCERPT_CHARS = Math.max(300, Number(arg('excerpt-chars', process.env.MNEMAZINE_SEMANTIC_EXCERPT_CHARS || '900')))
+const MAX_TOKENS = Math.max(120, Number(arg('max-tokens', process.env.MNEMAZINE_SEMANTIC_MAX_TOKENS || '360')))
+const CACHE_DIR = path.resolve(arg('cache-dir', process.env.MNEMAZINE_SEMANTIC_CACHE_DIR || path.join(VAULT, '.mnemazine/semantic-cache')))
+const USE_CACHE = !flag('no-cache')
const DRY_RUN = flag('dry-run')
const CLUSTER_ONLY = !flag('no-cluster')
+const CACHE_VERSION = 1
async function walk(dir) {
const out = []
@@ -88,7 +92,7 @@ async function ollamaJson(noteText) {
const body = {
model: MODEL,
temperature: 0,
- max_tokens: 360,
+ max_tokens: MAX_TOKENS,
messages: [{
role: 'user',
content: `Extract 3-5 durable concept nodes and 2-4 relationships from this note. Return ONLY JSON: {"nodes":[{"id":"short-id","label":"Label"}],"edges":[{"source":"id","target":"id","relation":"relates_to"}]}.\n\nNote:\n${noteText}`
@@ -106,7 +110,13 @@ async function ollamaJson(noteText) {
async function extractFile(file) {
const rel = path.relative(VAULT, file)
- const text = excerpt(await fs.readFile(file, 'utf8'))
+ const raw = await fs.readFile(file, 'utf8')
+ const text = excerpt(raw)
+ const cache = cachePath(rel, raw)
+ if (USE_CACHE) {
+ const cached = await readCache(cache)
+ if (cached) return { rel, graph: cached.graph, cached: true, cache }
+ }
const parsed = BACKEND === 'ollama'
? await ollamaJson(text)
: (() => { throw new Error(`unsupported backend ${BACKEND}`) })()
@@ -133,7 +143,45 @@ async function extractFile(file) {
source_file: rel
}))
.filter(edge => edge.source && edge.target && edge.source !== edge.target)
- return { rel, graph: { nodes, links } }
+ const graph = { nodes, links }
+ if (USE_CACHE) await writeCache(cache, { rel, graph })
+ return { rel, graph, cached: false, cache }
+}
+
+function cachePath(rel, rawText) {
+ const key = crypto.createHash('sha256').update(JSON.stringify({
+ version: CACHE_VERSION,
+ rel,
+ backend: BACKEND,
+ model: MODEL,
+ excerpt_chars: EXCERPT_CHARS,
+ max_tokens: MAX_TOKENS,
+ text_sha256: crypto.createHash('sha256').update(rawText).digest('hex')
+ })).digest('hex')
+ return path.join(CACHE_DIR, `${key}.json`)
+}
+
+async function readCache(file) {
+ if (!existsSync(file)) return null
+ try {
+ const cached = JSON.parse(await fs.readFile(file, 'utf8'))
+ return cached?.graph?.nodes && cached?.graph?.links ? cached : null
+ } catch {
+ return null
+ }
+}
+
+async function writeCache(file, value) {
+ await fs.mkdir(path.dirname(file), { recursive: true })
+ await fs.writeFile(file, `${JSON.stringify({
+ version: CACHE_VERSION,
+ backend: BACKEND,
+ model: MODEL,
+ excerpt_chars: EXCERPT_CHARS,
+ max_tokens: MAX_TOKENS,
+ created_at: new Date().toISOString(),
+ ...value
+ }, null, 2)}\n`, 'utf8')
}
function run(command, args) {
@@ -160,7 +208,10 @@ async function main() {
selected: selected.length,
start: START,
batch_size: BATCH_SIZE,
- excerpt_chars: EXCERPT_CHARS
+ excerpt_chars: EXCERPT_CHARS,
+ max_tokens: MAX_TOKENS,
+ cache_dir: CACHE_DIR,
+ cache: USE_CACHE
}
if (DRY_RUN) {
console.log(JSON.stringify({ ok: true, dry_run: true, ...plan }, null, 2))
@@ -181,7 +232,9 @@ async function main() {
batch.results.push({
file: extracted.rel,
nodes: extracted.graph.nodes.length,
- edges: extracted.graph.links.length
+ edges: extracted.graph.links.length,
+ cached: extracted.cached,
+ cache: extracted.cache
})
}
await writeGraph(GRAPH, base)
diff --git a/scripts/mnemazine-semantic-graph-task.mjs b/scripts/mnemazine-semantic-graph-task.mjs
new file mode 100644
index 0000000..678e0f3
--- /dev/null
+++ b/scripts/mnemazine-semantic-graph-task.mjs
@@ -0,0 +1,523 @@
+#!/usr/bin/env node
+import { promises as fs } from 'node:fs'
+import { existsSync } from 'node:fs'
+import path from 'node:path'
+import os from 'node:os'
+import { spawn } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+import { resolveVault } from './mnemazine-paths.mjs'
+
+const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
+const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
+const REFRESH = path.join(ROOT, 'scripts/mnemazine-refresh-graphify.mjs')
+const SWARM = path.join(ROOT, 'scripts/mnemazine-semantic-swarm.mjs')
+const MERGE = path.join(ROOT, 'scripts/mnemazine-merge-semantic-shards.mjs')
+const SELF = fileURLToPath(import.meta.url)
+const argv = process.argv.slice(2)
+const TASK_TIMEOUT_MS = Number(process.env.MNEMAZINE_SEMANTIC_TASK_TIMEOUT_SECONDS || '7200') * 1000
+const CLUSTER_TIMEOUT_MS = Number(process.env.MNEMAZINE_SEMANTIC_CLUSTER_TIMEOUT_SECONDS || '900') * 1000
+const DEFAULT_STALE_HOURS = Number(process.env.MNEMAZINE_SEMANTIC_MONITOR_STALE_HOURS || '3')
+
+function hasFlag(name) {
+ return argv.includes(`--${name}`)
+}
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+
+function taskFile(stateDir = STATE) {
+ return path.join(stateDir, 'semantic-graph-task.json')
+}
+
+function logFile(stateDir = STATE) {
+ return path.join(stateDir, 'semantic-graph-task.log')
+}
+
+async function ensureState(stateDir = STATE) {
+ await fs.mkdir(stateDir, { recursive: true })
+}
+
+async function readJson(file, fallback = null) {
+ try { return JSON.parse(await fs.readFile(file, 'utf8')) } catch { return fallback }
+}
+
+async function writeTaskState(state, stateDir = STATE) {
+ await ensureState(stateDir)
+ await fs.writeFile(taskFile(stateDir), `${JSON.stringify(state, null, 2)}\n`, 'utf8')
+}
+
+function pidRunning(pid) {
+ if (!Number.isFinite(Number(pid)) || Number(pid) <= 0) return false
+ try {
+ process.kill(Number(pid), 0)
+ return true
+ } catch {
+ return false
+ }
+}
+
+async function taskStatus(stateDir = STATE) {
+ const state = await readJson(taskFile(stateDir), { status: 'never-run' })
+ const running = state.status === 'running' && pidRunning(state.pid)
+ const progressFile = state.progress_file || (state.shards_dir ? path.join(state.shards_dir, 'progress.json') : '')
+ const progress = progressFile ? await readJson(progressFile, null) : null
+ return {
+ ...state,
+ running,
+ progress,
+ state_file: taskFile(stateDir),
+ log_file: logFile(stateDir)
+ }
+}
+
+function formatSeconds(value) {
+ if (value === null || value === undefined || value === '') return 'n/a'
+ const seconds = Number(value)
+ if (!Number.isFinite(seconds) || seconds < 0) return 'n/a'
+ const rounded = Math.round(seconds)
+ if (rounded < 60) return `${rounded}s`
+ const minutes = Math.round(rounded / 60)
+ if (minutes < 60) return `${minutes}m`
+ const hours = Math.floor(minutes / 60)
+ const rest = String(minutes % 60).padStart(2, '0')
+ return `${hours}h ${rest}m`
+}
+
+function listValue(items) {
+ if (!Array.isArray(items) || items.length === 0) return 'none'
+ return items.map(item => {
+ if (typeof item === 'string') return item
+ return item?.file || item?.path || item?.shard || item?.id || JSON.stringify(item)
+ }).join(', ')
+}
+
+function taskElapsedSeconds(status) {
+ const start = Date.parse(status.started_at || '')
+ const end = status.running ? Date.now() : Date.parse(status.finished_at || '')
+ if (Number.isFinite(start) && Number.isFinite(end) && end >= start) return (end - start) / 1000
+ const progressElapsed = Number(status.progress?.elapsed_seconds)
+ return Number.isFinite(progressElapsed) && progressElapsed >= 0 ? progressElapsed : null
+}
+
+function ageHoursFromIso(value) {
+ const start = Date.parse(value || '')
+ if (!Number.isFinite(start)) return null
+ return Math.max(0, (Date.now() - start) / 3600000)
+}
+
+function prettyStatus(status) {
+ const progress = status.progress
+ const lines = [
+ `Semantic: ${status.status || 'unknown'} | ${status.strategy || 'unknown'} | ${progress?.phase || (status.running ? 'running' : 'idle')}`
+ ]
+ lines.push(`Task: running ${status.running ? 'yes' : 'no'} | PID ${status.pid || 'n/a'} | elapsed ${formatSeconds(taskElapsedSeconds(status))}`)
+ if (progress) {
+ const failed = Array.isArray(progress.failed_jobs) ? progress.failed_jobs : []
+ const completed = progress.completed_jobs ?? 0
+ const total = progress.total_jobs ?? 0
+ const remaining = progress.remaining_jobs ?? Math.max(0, Number(total) - Number(completed))
+ const skipped = progress.skipped_completed_jobs ?? progress.skipped_jobs ?? 0
+ lines.push(`Jobs: ${completed}/${total} done | remaining ${remaining} | skipped ${skipped} | active ${listValue(progress.active_jobs)} | failed ${failed.length} | ETA ${formatSeconds(progress.eta_seconds)}`)
+ if (failed.length > 0) lines.push(`First fail: ${listValue(failed.slice(0, 1))}`)
+ } else {
+ lines.push('Jobs: progress unavailable')
+ }
+ lines.push(`Vault: ${status.vault || 'unknown'}`)
+ lines.push(`Progress: ${status.progress_file || 'n/a'}`)
+ lines.push(`Log: ${status.log_file || 'n/a'}`)
+ return lines.join('\n')
+}
+
+function stripTaskArgs(args, options = {}) {
+ const flags = new Set(['--start', '--status', '--monitor', '--worker', '--foreground', '--selftest', '--pretty', '--dry-run'])
+ if (!options.keepFresh) flags.add('--fresh')
+ flags.add('--resume')
+ const valueOptions = new Set(['--mode', '--strategy', '--stale-hours'])
+ const out = []
+ for (let i = 0; i < args.length; i += 1) {
+ const item = args[i]
+ if (flags.has(item)) continue
+ if (valueOptions.has(item)) {
+ i += 1
+ continue
+ }
+ if ([...valueOptions].some(name => item.startsWith(`${name}=`))) continue
+ if (item === '--json') continue
+ out.push(item)
+ }
+ return out
+}
+
+async function needsUpdateMarker(vault) {
+ const file = path.join(vault, 'graphify-out', 'needs_update')
+ if (!existsSync(file)) return null
+ const stat = await fs.stat(file).catch(() => null)
+ return {
+ file,
+ exists: true,
+ content: await fs.readFile(file, 'utf8').catch(() => ''),
+ age_hours: stat ? Math.max(0, (Date.now() - stat.mtimeMs) / 3600000) : null
+ }
+}
+
+function monitorReason(status, marker, staleHours) {
+ const elapsedHours = ageHoursFromIso(status.started_at)
+ if (status.running) {
+ return elapsedHours !== null && elapsedHours >= staleHours
+ ? { action: 'wait', reason: 'running-stale-live-pid', elapsed_hours: elapsedHours }
+ : { action: 'wait', reason: 'running', elapsed_hours: elapsedHours }
+ }
+ if (status.status === 'running') return { action: 'start', reason: 'running-dead-pid', elapsed_hours: elapsedHours }
+ if (['pending', 'failed'].includes(String(status.status || ''))) return { action: 'start', reason: status.status, elapsed_hours: elapsedHours }
+ if (marker?.exists && Number(marker.age_hours) >= staleHours) return { action: 'start', reason: 'needs-update-stale', marker_age_hours: marker.age_hours }
+ return { action: 'none', reason: marker?.exists ? 'needs-update-not-stale' : 'clean', marker_age_hours: marker?.age_hours ?? null }
+}
+
+function progressDone(progress) {
+ if (!progress) return false
+ if (progress.phase === 'done') return true
+ const total = Number(progress.total_jobs)
+ const completed = Number(progress.completed_jobs)
+ const failed = Array.isArray(progress.failed_jobs) ? progress.failed_jobs.length : 0
+ return Number.isFinite(total) && total >= 0 && completed >= total && failed === 0
+}
+
+async function resumeCandidate(vault, stateDir = STATE) {
+ const previous = await taskStatus(stateDir)
+ if (previous.running) return null
+ if (!['running', 'pending', 'failed'].includes(String(previous.status || ''))) return null
+ if (previous.vault && path.resolve(previous.vault) !== path.resolve(vault)) return null
+ if (!previous.shards_dir || !existsSync(previous.shards_dir)) return null
+ if (progressDone(previous.progress)) return null
+ return previous
+}
+
+function hasOption(args, name) {
+ return args.includes(`--${name}`) || args.some(item => item.startsWith(`--${name}=`))
+}
+
+function parseJsonOutput(text) {
+ const raw = String(text || '').trim()
+ 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 }
+}
+
+function runRefresh(args, timeoutMs = TASK_TIMEOUT_MS) {
+ return runCommand(process.execPath, [REFRESH, ...args], timeoutMs)
+}
+
+function runCommand(command, args, timeoutMs = TASK_TIMEOUT_MS) {
+ return new Promise(resolve => {
+ const child = spawn(command, args, {
+ cwd: ROOT,
+ env: process.env,
+ stdio: ['ignore', 'pipe', 'pipe']
+ })
+ let stdout = ''
+ let stderr = ''
+ let timedOut = false
+ const timer = setTimeout(() => {
+ timedOut = true
+ child.kill('SIGTERM')
+ setTimeout(() => child.kill('SIGKILL'), 5000).unref()
+ }, timeoutMs)
+ child.stdout.on('data', chunk => { stdout += String(chunk) })
+ child.stderr.on('data', chunk => { stderr += String(chunk) })
+ child.on('close', code => {
+ clearTimeout(timer)
+ resolve({ code: code ?? 1, stdout, stderr, timedOut })
+ })
+ child.on('error', error => {
+ clearTimeout(timer)
+ resolve({ code: 1, stdout, stderr: `${stderr}\n${error.message}`, timedOut })
+ })
+ })
+}
+
+function addDefault(args, name, value) {
+ if (!hasOption(args, name)) args.push(`--${name}`, String(value))
+}
+
+async function runSwarm(vault, passthrough) {
+ const graph = path.join(vault, 'graphify-out', 'graph.json')
+ const needsUpdate = path.join(vault, 'graphify-out', 'needs_update')
+ const dryRun = passthrough.includes('--dry-run')
+ const swarmArgs = ['--vault', vault, '--graph', graph, ...passthrough]
+ addDefault(swarmArgs, 'chunk-size', process.env.MNEMAZINE_SEMANTIC_SWARM_CHUNK_SIZE || '40')
+ addDefault(swarmArgs, 'batch-size', process.env.MNEMAZINE_SEMANTIC_SWARM_BATCH_SIZE || '1')
+ addDefault(swarmArgs, 'excerpt-chars', process.env.MNEMAZINE_SEMANTIC_EXCERPT_CHARS || '600')
+ addDefault(swarmArgs, 'max-tokens', process.env.MNEMAZINE_SEMANTIC_MAX_TOKENS || '360')
+ addDefault(swarmArgs, 'concurrency', process.env.MNEMAZINE_SEMANTIC_SWARM_CONCURRENCY || '2')
+
+ const swarm = await runCommand(process.execPath, [SWARM, ...swarmArgs])
+ const parsedSwarm = parseJsonOutput(swarm.stdout)
+ const steps = { swarm: { ok: swarm.code === 0 && parsedSwarm?.ok !== false, code: swarm.code, timedOut: swarm.timedOut, parsed: parsedSwarm } }
+ if (dryRun || !steps.swarm.ok) {
+ return {
+ code: dryRun && steps.swarm.ok ? 2 : (swarm.code || 1),
+ timedOut: swarm.timedOut,
+ stdout: JSON.stringify({ ok: steps.swarm.ok, mode: 'swarm', dry_run: dryRun, semantic_pending_after: true, steps }, null, 2),
+ stderr: swarm.stderr
+ }
+ }
+
+ const merge = await runCommand(process.execPath, [
+ MERGE,
+ '--vault', vault,
+ '--graph', graph,
+ '--shards-dir', parsedSwarm.shards_dir,
+ '--manifest', parsedSwarm.manifest
+ ])
+ const parsedMerge = parseJsonOutput(merge.stdout)
+ steps.merge = { ok: merge.code === 0 && parsedMerge?.ok !== false, code: merge.code, timedOut: merge.timedOut, parsed: parsedMerge }
+
+ const cluster = steps.merge.ok
+ ? await runCommand('graphify', ['cluster-only', vault, '--graph', graph, '--no-viz'], CLUSTER_TIMEOUT_MS)
+ : { code: 1, timedOut: false, stdout: '', stderr: 'merge failed; cluster skipped' }
+ steps.cluster = { ok: cluster.code === 0 && !cluster.timedOut, code: cluster.code, timedOut: cluster.timedOut, stdout_tail: String(cluster.stdout || '').trim().split('\n').slice(-5).join('\n'), stderr_tail: String(cluster.stderr || '').trim().split('\n').slice(-5).join('\n') }
+
+ const ok = steps.swarm.ok && steps.merge.ok && steps.cluster.ok
+ if (ok) await fs.rm(needsUpdate, { force: true }).catch(() => {})
+ return {
+ code: ok ? 0 : 2,
+ timedOut: Boolean(swarm.timedOut || merge.timedOut || cluster.timedOut),
+ stdout: JSON.stringify({ ok, mode: 'swarm', vault, graph, semantic_pending_after: !ok, steps }, null, 2),
+ stderr: [swarm.stderr, merge.stderr, cluster.stderr].filter(Boolean).join('\n')
+ }
+}
+
+async function runWorker() {
+ const fresh = hasFlag('fresh') || hasFlag('no-resume')
+ const passthrough = stripTaskArgs(argv)
+ const vault = resolveVault({ cli: arg('vault') })
+ const strategy = arg('strategy', process.env.MNEMAZINE_SEMANTIC_TASK_STRATEGY || 'swarm')
+ const startedAt = new Date().toISOString()
+ let shardsDir = arg('shards-dir', '')
+ let resumedFrom = null
+ if (strategy !== 'full' && !shardsDir && !fresh) {
+ resumedFrom = await resumeCandidate(vault)
+ if (resumedFrom) {
+ shardsDir = resumedFrom.shards_dir
+ passthrough.push('--shards-dir', shardsDir)
+ }
+ }
+ if (strategy !== 'full' && !shardsDir) {
+ shardsDir = process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR
+ ? path.join(process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR, startedAt.replace(/[:.]/g, '-'))
+ : path.join(vault, '.mnemazine/semantic-shards', startedAt.replace(/[:.]/g, '-'))
+ passthrough.push('--shards-dir', shardsDir)
+ }
+ const progressFile = strategy !== 'full' && shardsDir ? path.join(shardsDir, 'progress.json') : null
+ const refreshArgs = ['--vault', vault, '--mode', 'semantic', '--json']
+ if (!hasOption(passthrough, 'timeout-seconds') && process.env.MNEMAZINE_SEMANTIC_REFRESH_TIMEOUT_SECONDS) refreshArgs.push('--timeout-seconds', process.env.MNEMAZINE_SEMANTIC_REFRESH_TIMEOUT_SECONDS)
+ refreshArgs.push(...passthrough)
+ await writeTaskState({
+ status: 'running',
+ pid: process.pid,
+ started_at: startedAt,
+ vault,
+ strategy,
+ fresh,
+ resume_from: resumedFrom ? {
+ status: resumedFrom.status,
+ started_at: resumedFrom.started_at || null,
+ shards_dir: resumedFrom.shards_dir,
+ progress_file: resumedFrom.progress_file || null
+ } : null,
+ shards_dir: shardsDir || null,
+ progress_file: progressFile,
+ command: strategy === 'full'
+ ? `node scripts/mnemazine-refresh-graphify.mjs ${refreshArgs.join(' ')}`
+ : `node scripts/mnemazine-semantic-swarm.mjs --vault ${vault}`,
+ log_file: logFile()
+ })
+ const result = strategy === 'full'
+ ? await runRefresh(refreshArgs)
+ : await runSwarm(vault, passthrough)
+ const parsed = parseJsonOutput(result.stdout)
+ const status = result.code === 0 && !result.timedOut && parsed?.ok !== false
+ ? 'succeeded'
+ : result.code === 2 || parsed?.semantic_pending_after
+ ? 'pending'
+ : 'failed'
+ await fs.writeFile(logFile(), [
+ `# Semantic Graph Task ${startedAt}`,
+ '',
+ `status=${status}`,
+ `exit_code=${result.code}`,
+ `timed_out=${result.timedOut}`,
+ '',
+ '## stdout',
+ result.stdout.trim(),
+ '',
+ '## stderr',
+ result.stderr.trim(),
+ ''
+ ].join('\n'), 'utf8')
+ await writeTaskState({
+ status,
+ pid: process.pid,
+ running: false,
+ strategy,
+ fresh,
+ resume_from: resumedFrom ? {
+ status: resumedFrom.status,
+ started_at: resumedFrom.started_at || null,
+ shards_dir: resumedFrom.shards_dir,
+ progress_file: resumedFrom.progress_file || null
+ } : null,
+ shards_dir: parsed?.steps?.swarm?.parsed?.shards_dir || shardsDir || null,
+ progress_file: parsed?.steps?.swarm?.parsed?.progress || progressFile,
+ started_at: startedAt,
+ finished_at: new Date().toISOString(),
+ vault,
+ exit_code: result.code,
+ timed_out: result.timedOut,
+ semantic_pending_after: Boolean(parsed?.semantic_pending_after),
+ semantic_status: parsed?.mode || parsed?.semantic_refresh?.status || parsed?.semantic_refresh?.selected?.status || null,
+ chosen_model: parsed?.semantic_refresh?.chosen_model || null,
+ state_file: taskFile(),
+ log_file: logFile()
+ })
+ process.exit(status === 'failed' ? 1 : 0)
+}
+
+async function startTask() {
+ const current = await taskStatus()
+ if (current.running) {
+ console.log(JSON.stringify({ ok: true, started: false, reason: 'already running', task: current }, null, 2))
+ return
+ }
+ console.log(JSON.stringify(await spawnTask(resolveVault({ cli: arg('vault') })), null, 2))
+}
+
+async function spawnTask(vault) {
+ await ensureState()
+ const child = spawn(process.execPath, [SELF, '--worker', ...stripTaskArgs(argv, { keepFresh: true })], {
+ cwd: ROOT,
+ env: process.env,
+ detached: true,
+ stdio: 'ignore'
+ })
+ child.unref()
+ const state = {
+ status: 'running',
+ pid: child.pid,
+ running: true,
+ started_at: new Date().toISOString(),
+ vault,
+ state_file: taskFile(),
+ log_file: logFile(),
+ status_command: 'npm run graph:semantic:status'
+ }
+ await writeTaskState(state)
+ return { ok: true, started: true, task: state }
+}
+
+async function monitorTask() {
+ const vault = resolveVault({ cli: arg('vault') })
+ const staleHoursRaw = Number(arg('stale-hours', String(DEFAULT_STALE_HOURS)))
+ const staleHours = Number.isFinite(staleHoursRaw) && staleHoursRaw > 0 ? staleHoursRaw : 3
+ const status = await taskStatus()
+ const marker = await needsUpdateMarker(vault)
+ const decision = monitorReason(status, marker, staleHours)
+ let start = null
+ if (decision.action === 'start' && !hasFlag('dry-run')) {
+ const current = await taskStatus()
+ if (current.running) {
+ start = { ok: true, started: false, reason: 'already running', task: current }
+ } else {
+ start = await spawnTask(vault)
+ }
+ }
+ const output = {
+ ok: decision.action !== 'wait' || decision.reason === 'running',
+ monitor: true,
+ dry_run: hasFlag('dry-run'),
+ stale_hours: staleHours,
+ vault,
+ marker,
+ status,
+ decision,
+ start
+ }
+ if (hasFlag('pretty')) {
+ console.log(`Semantic monitor: ${decision.action} (${decision.reason})`)
+ console.log(`Vault: ${vault}`)
+ console.log(`Task: ${status.status || 'unknown'} | running ${status.running ? 'yes' : 'no'} | PID ${status.pid || 'n/a'}`)
+ if (marker?.exists) console.log(`Marker: ${marker.file} | age ${formatSeconds((marker.age_hours || 0) * 3600)}`)
+ if (start?.started) console.log(`Started: PID ${start.task.pid}`)
+ } else {
+ console.log(JSON.stringify(output, null, 2))
+ }
+ if (!output.ok) process.exit(2)
+}
+
+async function selftest() {
+ const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-semantic-task-'))
+ await writeTaskState({ status: 'running', pid: 999999, started_at: '2099-01-01T00:00:00.000Z' }, temp)
+ const status = await taskStatus(temp)
+ if (status.running) throw new Error('selftest failed: dead pid reported running')
+ if (!status.state_file.endsWith('semantic-graph-task.json')) throw new Error('selftest failed: state file mismatch')
+ const resumeTemp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-semantic-resume-'))
+ const resumeVault = path.join(resumeTemp, 'vault')
+ const resumeShards = path.join(resumeVault, '.mnemazine/semantic-shards/old')
+ await fs.mkdir(resumeShards, { recursive: true })
+ await fs.writeFile(path.join(resumeShards, 'progress.json'), `${JSON.stringify({ phase: 'running', total_jobs: 2, completed_jobs: 1, failed_jobs: [] })}\n`, 'utf8')
+ await writeTaskState({ status: 'pending', vault: resumeVault, shards_dir: resumeShards, progress_file: path.join(resumeShards, 'progress.json') }, resumeTemp)
+ const candidate = await resumeCandidate(resumeVault, resumeTemp)
+ if (candidate?.shards_dir !== resumeShards) throw new Error('selftest failed: resume candidate not selected')
+ const pretty = prettyStatus({
+ status: 'succeeded',
+ strategy: 'swarm',
+ running: false,
+ pid: 12345,
+ started_at: '2026-01-01T00:00:00.000Z',
+ finished_at: '2026-01-01T00:01:05.000Z',
+ vault: '/tmp/vault',
+ progress_file: '/tmp/progress.json',
+ log_file: '/tmp/log',
+ progress: {
+ phase: 'done',
+ total_jobs: 2,
+ completed_jobs: 1,
+ remaining_jobs: 1,
+ skipped_completed_jobs: 1,
+ active_jobs: [],
+ failed_jobs: [],
+ eta_seconds: null
+ }
+ })
+ if (!pretty.includes('ETA n/a')) throw new Error('selftest failed: null ETA should render as n/a')
+ if (!pretty.includes('remaining 1')) throw new Error('selftest failed: remaining jobs not rendered')
+ if (!pretty.includes('skipped 1')) throw new Error('selftest failed: skipped jobs not rendered')
+ if (pretty.includes('ETA 0s')) throw new Error('selftest failed: null ETA rendered as 0s')
+ if (!pretty.includes('PID 12345')) throw new Error('selftest failed: PID not rendered')
+ if (!pretty.includes('elapsed 1m')) throw new Error('selftest failed: elapsed time not rendered')
+ if (!prettyStatus({ status: 'never-run', strategy: 'swarm' }).includes('Jobs: progress unavailable')) {
+ throw new Error('selftest failed: missing progress fallback not rendered')
+ }
+ const pendingDecision = monitorReason({ status: 'pending', running: false, started_at: new Date().toISOString() }, null, 3)
+ if (pendingDecision.action !== 'start') throw new Error('selftest failed: pending monitor should start')
+ const staleLiveDecision = monitorReason({ status: 'running', running: true, started_at: new Date(Date.now() - 4 * 3600000).toISOString() }, null, 3)
+ if (staleLiveDecision.action !== 'wait' || staleLiveDecision.reason !== 'running-stale-live-pid') throw new Error('selftest failed: stale live pid should not start duplicate task')
+ const markerDecision = monitorReason({ status: 'succeeded', running: false }, { exists: true, age_hours: 4 }, 3)
+ if (markerDecision.action !== 'start') throw new Error('selftest failed: stale marker should start')
+ await fs.rm(temp, { recursive: true, force: true })
+ await fs.rm(resumeTemp, { recursive: true, force: true })
+ console.log(JSON.stringify({ ok: true }, null, 2))
+}
+
+if (hasFlag('selftest')) await selftest()
+else if (hasFlag('worker') || hasFlag('foreground')) await runWorker()
+else if (hasFlag('status')) {
+ const status = await taskStatus()
+ console.log(hasFlag('pretty') ? prettyStatus(status) : JSON.stringify(status, null, 2))
+}
+else if (hasFlag('monitor')) await monitorTask()
+else await startTask()
diff --git a/scripts/mnemazine-semantic-shards.mjs b/scripts/mnemazine-semantic-shards.mjs
index 6dfa2d9..31db90d 100644
--- a/scripts/mnemazine-semantic-shards.mjs
+++ b/scripts/mnemazine-semantic-shards.mjs
@@ -5,6 +5,7 @@ import path from 'node:path'
import os from 'node:os'
import { spawn } from 'node:child_process'
import { graphStats, mergeGraphObjects, readGraph, writeGraph } from './mnemazine-graph-utils.mjs'
+import { resolveVault } from './mnemazine-paths.mjs'
const argv = process.argv.slice(2)
const ROOT = path.resolve(process.cwd())
@@ -19,7 +20,7 @@ function hasFlag(name) {
return argv.includes(`--${name}`)
}
-const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(process.env.HOME || '.', 'Мозг')))
+const VAULT = resolveVault({ cli: arg('vault') })
const GRAPHIFY_OUT = path.join(VAULT, 'graphify-out')
const GRAPH_PATH = path.join(GRAPHIFY_OUT, 'graph.json')
const BACKEND = arg('backend', process.env.MNEMAZINE_GRAPHIFY_BACKEND || 'openai')
@@ -54,15 +55,19 @@ async function keychain(service) {
return result.stdout.trim()
}
+// Graph-backend credential map as DATA (env vars + keychain service per backend),
+// not a per-provider code branch. New backend = one row here.
+// ponytail: graph-backend axis, separate from the CLI-connector registry.
+const BACKEND_CREDENTIALS = {
+ openai: { env: ['OPENAI_API_KEY'], keychain: 'mnemazine/openai_api_key' },
+ kimi: { env: ['KIMI_API_KEY', 'MOONSHOT_API_KEY'], keychain: 'mnemazine/moonshot_api_key' }
+}
+
async function apiEnv() {
- if (BACKEND === 'openai') {
- return { OPENAI_API_KEY: process.env.OPENAI_API_KEY || await keychain('mnemazine/openai_api_key') }
- }
- if (BACKEND === 'kimi') {
- const key = process.env.KIMI_API_KEY || process.env.MOONSHOT_API_KEY || await keychain('mnemazine/moonshot_api_key')
- return { KIMI_API_KEY: key, MOONSHOT_API_KEY: key }
- }
- return {}
+ const spec = BACKEND_CREDENTIALS[BACKEND]
+ if (!spec) return {}
+ const key = spec.env.map(name => process.env[name]).find(Boolean) || await keychain(spec.keychain)
+ return Object.fromEntries(spec.env.map(name => [name, key]))
}
async function walkMarkdown(dir) {
diff --git a/scripts/mnemazine-semantic-swarm.mjs b/scripts/mnemazine-semantic-swarm.mjs
index ad78a90..d3de681 100644
--- a/scripts/mnemazine-semantic-swarm.mjs
+++ b/scripts/mnemazine-semantic-swarm.mjs
@@ -1,5 +1,6 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
+import { existsSync } from 'node:fs'
import { spawn } from 'node:child_process'
import os from 'node:os'
import path from 'node:path'
@@ -35,7 +36,7 @@ async function countVaultFiles(vault) {
function runWorker(job) {
return new Promise(resolve => {
- const child = spawn(process.execPath, [
+ const args = [
'scripts/mnemazine-semantic-batches.mjs',
'--vault', job.vault,
'--graph', job.graph,
@@ -45,7 +46,12 @@ function runWorker(job) {
'--start', String(job.start),
'--limit', String(job.limit),
'--no-cluster'
- ], { cwd: ROOT, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] })
+ ]
+ if (job.backend) args.push('--backend', job.backend)
+ if (job.model) args.push('--model', job.model)
+ if (job.cacheDir) args.push('--cache-dir', job.cacheDir)
+ if (!job.cache) args.push('--no-cache')
+ const child = spawn(process.execPath, args, { cwd: ROOT, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] })
const chunks = []
const errors = []
child.stdout.on('data', chunk => chunks.push(chunk))
@@ -69,9 +75,12 @@ function runWorker(job) {
async function main() {
const vault = resolveVault({ cli: arg('vault') })
const graph = path.resolve(arg('graph', path.join(vault, 'graphify-out/graph.json')))
- const shardsDir = path.resolve(arg('shards-dir', path.join(vault, `.mnemazine/semantic-shards/${RUN_ID}`)))
+ const shardsDir = path.resolve(arg('shards-dir', process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR ? path.join(process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR, RUN_ID) : path.join(vault, `.mnemazine/semantic-shards/${RUN_ID}`)))
const logsDir = path.resolve(arg('logs-dir', path.join(shardsDir, 'logs')))
+ const cacheDir = path.resolve(arg('cache-dir', process.env.MNEMAZINE_SEMANTIC_CACHE_DIR || path.join(vault, '.mnemazine/semantic-cache')))
const manifestPath = path.join(shardsDir, 'manifest.json')
+ const progressPath = path.join(shardsDir, 'progress.json')
+ const startedAt = new Date().toISOString()
const total = await countVaultFiles(vault)
const start = Math.max(0, Number(arg('start', '0')))
const limit = Number(arg('limit', String(Math.max(0, total - start))))
@@ -79,12 +88,18 @@ async function main() {
const batchSize = Math.max(1, Number(arg('batch-size', '1')))
const excerptChars = Math.max(300, Number(arg('excerpt-chars', '600')))
const maxTokens = Math.max(120, Number(arg('max-tokens', '360')))
+ const backend = arg('backend', process.env.MNEMAZINE_GRAPHIFY_BACKEND || '')
+ const model = arg('model', process.env.MNEMAZINE_GRAPHIFY_MODEL || '')
const concurrency = Math.max(1, Number(arg('concurrency', String(Math.min(8, Math.max(1, os.cpus().length - 2))))))
const dryRun = flag('dry-run')
+ const resume = !flag('no-resume')
+ const cache = !flag('no-cache')
await fs.mkdir(shardsDir, { recursive: true })
await fs.mkdir(logsDir, { recursive: true })
const end = Math.min(total, start + limit)
+ const selected = Math.max(0, end - start)
+ const hadManifest = existsSync(manifestPath)
const jobs = []
for (let i = start; i < end; i += chunkSize) {
const size = Math.min(chunkSize, end - i)
@@ -95,16 +110,22 @@ async function main() {
graph,
shardGraph: path.join(shardsDir, `${name}.json`),
log: path.join(logsDir, `${name}.log`),
+ done: path.join(shardsDir, `${name}.done.json`),
start: i,
limit: size,
batchSize,
excerptChars,
- maxTokens
+ maxTokens,
+ backend,
+ model,
+ cacheDir,
+ cache,
+ signature: JSON.stringify({ start: i, limit: size, batchSize, excerptChars, maxTokens, backend, model, cache })
})
}
if (dryRun) {
- console.log(JSON.stringify({ ok: true, dry_run: true, vault, graph, shards_dir: shardsDir, manifest: manifestPath, total, selected: limit, start, chunk_size: chunkSize, batch_size: batchSize, excerpt_chars: excerptChars, max_tokens: maxTokens, concurrency, jobs: jobs.map(j => ({ name: j.name, start: j.start, limit: j.limit, graph: j.shardGraph })) }, null, 2))
+ console.log(JSON.stringify({ ok: true, dry_run: true, vault, graph, shards_dir: shardsDir, manifest: manifestPath, progress: progressPath, cache_dir: cacheDir, cache, resume, total, selected, start, chunk_size: chunkSize, batch_size: batchSize, excerpt_chars: excerptChars, max_tokens: maxTokens, backend: backend || null, model: model || null, concurrency, jobs: jobs.map(j => ({ name: j.name, start: j.start, limit: j.limit, graph: j.shardGraph, done: j.done })) }, null, 2))
return
}
@@ -113,26 +134,95 @@ async function main() {
graph,
shards_dir: shardsDir,
total,
- selected: limit,
+ selected,
start,
chunk_size: chunkSize,
batch_size: batchSize,
excerpt_chars: excerptChars,
max_tokens: maxTokens,
+ backend: backend || null,
+ model: model || null,
+ cache_dir: cacheDir,
+ cache,
+ resume,
+ resumed: resume && hadManifest,
concurrency,
- jobs: jobs.map(job => ({ name: job.name, start: job.start, limit: job.limit, graph: job.shardGraph, log: job.log }))
+ progress: progressPath,
+ jobs: jobs.map(job => ({ name: job.name, start: job.start, limit: job.limit, graph: job.shardGraph, log: job.log, done: job.done, signature: job.signature }))
}, null, 2)}\n`, 'utf8')
let next = 0
const done = []
+ const skipped = []
+ const active = new Map()
+ async function completedJob(job) {
+ if (!resume || !await fs.access(job.done).then(() => true).catch(() => false)) return false
+ try {
+ const marker = JSON.parse(await fs.readFile(job.done, 'utf8'))
+ return marker.signature === job.signature && await fs.access(job.shardGraph).then(() => true).catch(() => false)
+ } catch {
+ return false
+ }
+ }
+ async function writeProgress(phase = 'running') {
+ const completed = done.length
+ const failed = done.filter(j => j.code !== 0)
+ const remaining = Math.max(0, jobs.length - completed)
+ const elapsed = Math.max(0, Math.round((Date.now() - Date.parse(startedAt)) / 1000))
+ const eta = completed > 0 && completed < jobs.length
+ ? Math.round((elapsed / completed) * (jobs.length - completed))
+ : null
+ await fs.writeFile(progressPath, `${JSON.stringify({
+ ok: failed.length === 0,
+ phase,
+ vault,
+ graph,
+ shards_dir: shardsDir,
+ manifest: manifestPath,
+ started_at: startedAt,
+ updated_at: new Date().toISOString(),
+ elapsed_seconds: elapsed,
+ eta_seconds: eta,
+ total_jobs: jobs.length,
+ completed_jobs: completed,
+ remaining_jobs: remaining,
+ skipped_jobs: skipped.length,
+ skipped_completed_jobs: skipped.length,
+ resumed: Boolean(resume && (hadManifest || skipped.length > 0)),
+ active_jobs: [...active.values()].map(j => ({ name: j.name, start: j.start, limit: j.limit })),
+ failed_jobs: failed.map(j => ({ name: j.name, code: j.code, log: j.log }))
+ }, null, 2)}\n`, 'utf8')
+ }
+ await writeProgress(jobs.length ? 'running' : 'done')
+
async function worker(slot) {
while (next < jobs.length) {
const job = jobs[next++]
+ if (await completedJob(job)) {
+ skipped.push(job)
+ done.push({ ...job, code: 0, skipped: true })
+ process.stderr.write(`[swarm:${slot}] skip ${job.name} (resume)\n`)
+ await writeProgress('running')
+ continue
+ }
await fs.writeFile(job.shardGraph, '{"nodes":[],"links":[]}\n', 'utf8')
+ active.set(job.name, job)
process.stderr.write(`[swarm:${slot}] start ${job.name}\n`)
+ await writeProgress('running')
const result = await runWorker({ ...job, graph: job.shardGraph })
+ active.delete(job.name)
done.push(result)
+ if (result.code === 0) {
+ await fs.writeFile(job.done, `${JSON.stringify({
+ name: job.name,
+ signature: job.signature,
+ graph: job.shardGraph,
+ log: job.log,
+ finished_at: new Date().toISOString()
+ }, null, 2)}\n`, 'utf8')
+ }
process.stderr.write(`[swarm:${slot}] done ${job.name} code=${result.code}\n`)
+ await writeProgress('running')
}
}
await Promise.all(Array.from({ length: Math.min(concurrency, jobs.length) }, (_, i) => worker(i + 1)))
@@ -144,17 +234,26 @@ async function main() {
graph,
shards_dir: shardsDir,
manifest: manifestPath,
+ progress: progressPath,
total,
- selected: limit,
+ selected,
start,
chunk_size: chunkSize,
batch_size: batchSize,
excerpt_chars: excerptChars,
max_tokens: maxTokens,
+ backend: backend || null,
+ model: model || null,
+ cache_dir: cacheDir,
+ cache,
+ resume,
+ resumed: Boolean(resume && (hadManifest || skipped.length > 0)),
concurrency,
completed: done.length,
+ skipped: skipped.length,
failed: failed.map(j => ({ name: j.name, start: j.start, limit: j.limit, log: j.log }))
}, null, 2))
+ await writeProgress(failed.length ? 'failed' : 'done')
if (failed.length) process.exit(1)
}
diff --git a/scripts/mnemazine-single-truth-check.mjs b/scripts/mnemazine-single-truth-check.mjs
new file mode 100644
index 0000000..d6409e4
--- /dev/null
+++ b/scripts/mnemazine-single-truth-check.mjs
@@ -0,0 +1,271 @@
+#!/usr/bin/env node
+// Одна правда (план П11, метод-правило 8). Ловит СОДЕРЖАТЕЛЬНЫЙ дубль, а не различие хешей.
+//
+// - CLAUDE.md/AGENTS.md: одна обязана быть указателем (симлинк или ≤5 строк, называющие
+// другую), другая — каноном. Требование черновика «sha256(A)!=sha256(B)→1» ПЕРЕВЁРНУТО:
+// оно закрепляло дубль. П05 сделал указателем CLAUDE.md (канон — AGENTS.md); прибор
+// распознаёт указатель в любую сторону. Оба указателя / канон схлопнулся / нет указателя → 1.
+// - enum SPEC_TYPES (mnemazine-note-spec.mjs) сходится с таблицей docs/NOTE-SPEC.md и с любой
+// второй литеральной копией; расхождение → 1.
+// - knowledge-note, встреченный в приёмке или человеческом гейте при отсутствии в SPEC_TYPES → 1.
+// - две одноимённые функции strictKnowledgeReady с разным телом → 1.
+//
+// Коды: 0 — одна правда; 1 — дубль/расхождение; 2 — ноль сравнённых пар.
+
+import { existsSync, readFileSync, lstatSync, readlinkSync, readdirSync } from 'node:fs'
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
+import { execFileSync } from 'node:child_process'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { SPEC_TYPES } from './mnemazine-note-spec.mjs'
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const RUNNERS_WITH_FILE_ARG = new Set(['node', 'bash', 'sh', 'python', 'python3'])
+const REPO_FILE_PREFIXES = ['scripts/', 'tests/', 'workflows/', 'skills/']
+const PACKAGE_SCRIPT_FILE_EXCEPTIONS = [
+ // { target: 'имя-цели', path: 'generated/file', reason: 'почему файл не отслеживается' }
+]
+
+function readSafe(p) { try { return readFileSync(p, 'utf8') } catch { return '' } }
+
+// Указатель: симлинк (цель — по readlink) либо ≤5 непустых строк, называющие .md-файл.
+function pointerTarget(absPath, text) {
+ try { if (lstatSync(absPath).isSymbolicLink()) return path.basename(readlinkSync(absPath)) } catch {}
+ const nonEmpty = String(text).split(/\r?\n/).filter(l => l.trim())
+ if (nonEmpty.length <= 5) {
+ const m = String(text).match(/([A-Za-z0-9._-]+\.md)/)
+ return m ? m[1] : null
+ }
+ return null
+}
+
+// {ok, reason}. ok=true когда ровно одна — указатель на другую, вторая — канон.
+function evaluatePair(claudePath, agentsPath) {
+ const cText = readSafe(claudePath)
+ const aText = readSafe(agentsPath)
+ if (!cText && !aText) return { present: false }
+ const cTarget = pointerTarget(claudePath, cText)
+ const aTarget = pointerTarget(agentsPath, aText)
+ const cIsPtr = cTarget !== null
+ const aIsPtr = aTarget !== null
+ if (cIsPtr && !aIsPtr && cTarget === path.basename(agentsPath)) return { present: true, ok: true }
+ if (aIsPtr && !cIsPtr && aTarget === path.basename(claudePath)) return { present: true, ok: true }
+ return {
+ present: true,
+ ok: false,
+ reason: `нет валидного указателя CLAUDE.md↔AGENTS.md: одна должна быть указателем (≤5 строк/симлинк на другую), другая — каноном (ptr C→${cTarget}, ptr A→${aTarget})`
+ }
+}
+
+function parseNoteSpecTypes() {
+ const p = path.join(ROOT, 'docs', 'NOTE-SPEC.md')
+ if (!existsSync(p)) return null
+ const types = []
+ for (const line of readFileSync(p, 'utf8').split(/\r?\n/)) {
+ const m = line.match(/^\|\s*`([a-z][a-z-]*)`\s*\|/)
+ if (m) types.push(m[1])
+ }
+ return types.length ? new Set(types) : null
+}
+
+function setsEqual(a, b) {
+ if (a.size !== b.size) return false
+ for (const x of a) if (!b.has(x)) return false
+ return true
+}
+
+function scriptFiles() {
+ return readdirSync(path.join(ROOT, 'scripts'))
+ .filter(f => f.endsWith('.mjs'))
+ .map(f => path.join('scripts', f))
+}
+
+function secondEnumLiteralMismatch() {
+ const failures = []
+ for (const rel of scriptFiles()) {
+ if (rel.endsWith('mnemazine-note-spec.mjs')) continue
+ const text = readFileSync(path.join(ROOT, rel), 'utf8')
+ const m = text.match(/SPEC_TYPES\s*=\s*new Set\(\[([^\]]*)\]/)
+ if (!m) continue
+ const members = new Set(m[1].split(',').map(s => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean))
+ if (!setsEqual(members, SPEC_TYPES)) failures.push(`вторая литеральная копия SPEC_TYPES в ${rel} расходится с mnemazine-note-spec.mjs`)
+ }
+ return failures
+}
+
+function knowledgeNoteLeak() {
+ const failures = []
+ if (SPEC_TYPES.has('knowledge-note')) return failures
+ for (const rel of ['scripts/mnemazine-release-check.mjs', 'scripts/mnemazine-human-layer-gate.mjs']) {
+ const p = path.join(ROOT, rel)
+ if (existsSync(p) && readFileSync(p, 'utf8').includes('knowledge-note')) {
+ failures.push(`тип knowledge-note защищается в ${rel}, но отсутствует в SPEC_TYPES`)
+ }
+ }
+ return failures
+}
+
+function extractFunctionBody(text, startIdx) {
+ const open = text.indexOf('{', startIdx)
+ if (open === -1) return ''
+ let depth = 0
+ for (let i = open; i < text.length; i++) {
+ if (text[i] === '{') depth++
+ else if (text[i] === '}') { depth--; if (depth === 0) return text.slice(open + 1, i) }
+ }
+ return text.slice(open + 1)
+}
+
+function strictKnowledgeReadyDivergence() {
+ const defs = []
+ for (const rel of scriptFiles()) {
+ const text = readFileSync(path.join(ROOT, rel), 'utf8')
+ const m = text.match(/(?:export\s+)?function\s+strictKnowledgeReady\b|const\s+strictKnowledgeReady\s*=/)
+ if (m) defs.push({ rel, body: extractFunctionBody(text, m.index).replace(/\s+/g, ' ').trim() })
+ }
+ if (defs.length <= 1) return []
+ const distinct = new Set(defs.map(d => d.body))
+ if (distinct.size > 1) return [`strictKnowledgeReady определена в ${defs.length} местах с разным телом: ${defs.map(d => d.rel).join(', ')}`]
+ return []
+}
+
+function shTokens(command) {
+ const tokens = []
+ const re = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^']*)'|[^\s]+/g
+ for (const m of String(command).matchAll(re)) tokens.push(m[1] ?? m[2] ?? m[0])
+ return tokens
+}
+
+function normalizeRepoPath(token) {
+ let rel = String(token).replace(/^\.\/+/, '')
+ if (!rel || rel.startsWith('-') || path.isAbsolute(rel) || /[*?[\]{}$`]/.test(rel)) return null
+ rel = path.posix.normalize(rel)
+ if (rel === '.' || rel.startsWith('../') || rel.includes('/../')) return null
+ return rel
+}
+
+function looksLikeRepoFileArg(token) {
+ const rel = normalizeRepoPath(token)
+ if (!rel) return null
+ if (REPO_FILE_PREFIXES.some(prefix => rel.startsWith(prefix))) return rel
+ if (!rel.includes('/') && /\.(?:sh|mjs|js|cjs|py)$/.test(rel)) return rel
+ return null
+}
+
+function packageScriptFileRefs(scripts) {
+ const refs = []
+ for (const [target, command] of Object.entries(scripts || {})) {
+ const tokens = shTokens(command)
+ for (let i = 0; i < tokens.length; i++) {
+ const runner = path.basename(tokens[i])
+ if (!RUNNERS_WITH_FILE_ARG.has(runner)) continue
+ for (let j = i + 1; j < tokens.length; j++) {
+ const token = tokens[j]
+ if (/^(?:&&|\|\||;|\|)$/.test(token)) break
+ if (token.startsWith('-')) continue
+ const rel = looksLikeRepoFileArg(token)
+ if (rel) refs.push({ target, path: rel })
+ break
+ }
+ }
+ }
+ return refs
+}
+
+function packageScriptExceptionSet() {
+ const failures = []
+ const allowed = new Set()
+ for (const e of PACKAGE_SCRIPT_FILE_EXCEPTIONS) {
+ if (!e?.target || !e?.path || !e?.reason) {
+ failures.push('PACKAGE_SCRIPT_FILE_EXCEPTIONS: каждая строка обязана иметь target, path, reason')
+ continue
+ }
+ allowed.add(`${e.target}\0${normalizeRepoPath(e.path)}`)
+ }
+ return { failures, allowed }
+}
+
+function packageScriptTrackedPathFailures(scripts, tracked, fileExists = rel => existsSync(path.join(ROOT, rel))) {
+ const { failures, allowed } = packageScriptExceptionSet()
+ for (const ref of packageScriptFileRefs(scripts)) {
+ if (allowed.has(`${ref.target}\0${ref.path}`)) continue
+ if (!tracked.has(ref.path)) failures.push(`package.json:${ref.target} → ${ref.path}: файл не в git ls-files`)
+ else if (!fileExists(ref.path)) failures.push(`package.json:${ref.target} → ${ref.path}: файл отслеживается, но отсутствует на диске`)
+ }
+ return failures
+}
+
+function gitTrackedFiles() {
+ return new Set(execFileSync('git', ['ls-files', '-z'], { cwd: ROOT, encoding: 'utf8' }).split('\0').filter(Boolean))
+}
+
+function packageScriptTrackedPathCheck() {
+ const p = path.join(ROOT, 'package.json')
+ if (!existsSync(p)) return ['package.json отсутствует']
+ const pkg = JSON.parse(readFileSync(p, 'utf8'))
+ return packageScriptTrackedPathFailures(pkg.scripts || {}, gitTrackedFiles())
+}
+
+function evaluate() {
+ const failures = []
+ let pairs = 0 // число сравнённых категорий (не число провалов)
+
+ const pair = evaluatePair(path.join(ROOT, 'CLAUDE.md'), path.join(ROOT, 'AGENTS.md'))
+ if (pair.present) { pairs++; if (!pair.ok) failures.push(pair.reason) }
+
+ const docTypes = parseNoteSpecTypes()
+ if (docTypes) { pairs++; if (!setsEqual(docTypes, SPEC_TYPES)) failures.push(`SPEC_TYPES ${[...SPEC_TYPES].sort().join(',')} != таблица NOTE-SPEC ${[...docTypes].sort().join(',')}`) }
+
+ pairs++; failures.push(...secondEnumLiteralMismatch())
+ pairs++; failures.push(...knowledgeNoteLeak())
+ pairs++; failures.push(...strictKnowledgeReadyDivergence())
+ pairs++; failures.push(...packageScriptTrackedPathCheck())
+
+ if (pairs === 0) return { code: 2, failures: ['ноль сравнённых пар'] }
+ return { code: failures.length ? 1 : 0, failures, pairs }
+}
+
+function selftest() {
+ const tmp = mkdtempSync(path.join(os.tmpdir(), 'single-truth-selftest-'))
+ try {
+ const body = '# Canon\n\n' + Array.from({ length: 10 }, (_, i) => `Rule line ${i} with real content.`).join('\n') + '\n'
+ writeFileSync(path.join(tmp, 'CLAUDE.md'), body, 'utf8')
+ writeFileSync(path.join(tmp, 'AGENTS.md'), body, 'utf8')
+ const pair = evaluatePair(path.join(tmp, 'CLAUDE.md'), path.join(tmp, 'AGENTS.md'))
+ if (pair.ok) { console.error('selftest FAILED: два одинаковых канона прошли зелёным'); return 1 }
+ const failures = packageScriptTrackedPathFailures({
+ 'graph:clean': 'python3 scripts/graphify_clean.py',
+ 'combo': 'node scripts/ok.mjs && bash install.sh',
+ 'delegated': 'npm run release-check'
+ }, new Set(['scripts/ok.mjs', 'install.sh']), rel => rel !== 'scripts/graphify_clean.py')
+ if (!failures.some(f => f.includes('graph:clean') && f.includes('scripts/graphify_clean.py'))) {
+ console.error('selftest FAILED: неотслеживаемая цель package.json не покраснела')
+ return 1
+ }
+ if (failures.some(f => f.includes('combo') || f.includes('delegated'))) {
+ console.error('selftest FAILED: валидная или npm-делегированная цель покраснела')
+ return 1
+ }
+ console.log('selftest ok: содержательный дубль CLAUDE/AGENTS краснит')
+ console.log('selftest ok: package.json file targets должны быть tracked')
+ return 0
+ } finally {
+ rmSync(tmp, { recursive: true, force: true })
+ }
+}
+
+function main() {
+ const argv = process.argv.slice(2)
+ if (argv.includes('--selftest')) process.exit(selftest())
+ const r = evaluate()
+ if (r.failures?.length) {
+ console.error('ПРОВАЛЫ:')
+ for (const f of r.failures) console.error(` - ${f}`)
+ } else {
+ console.log(`одна правда: сравнено пар ${r.pairs}, расхождений нет`)
+ }
+ process.exit(r.code)
+}
+
+main()
diff --git a/scripts/mnemazine-spec-ceiling.mjs b/scripts/mnemazine-spec-ceiling.mjs
new file mode 100644
index 0000000..27dd98e
--- /dev/null
+++ b/scripts/mnemazine-spec-ceiling.mjs
@@ -0,0 +1,70 @@
+#!/usr/bin/env node
+// Потолок провалов спеки (план П16, шаг 8): .mnemazine/state/spec-ceiling.json
+// переписывается ТОЛЬКО ВНИЗ и ТОЛЬКО ЭТИМ КОДОМ. Рост провалов — отказ (exit 1),
+// ручная правка файла задетектится сверкой sha256 гейта и checked.
+//
+// node scripts/mnemazine-spec-ceiling.mjs --update прогнать гейт и опустить потолок, если провалов стало меньше
+// node scripts/mnemazine-spec-ceiling.mjs --check сверить: текущие провалы не выше потолка (exit 0/1)
+import { promises as fs } from 'node:fs'
+import { execFileSync } from 'node:child_process'
+import path from 'node:path'
+import crypto from 'node:crypto'
+import { resolveVault, ROOT } from './mnemazine-paths.mjs'
+
+const argv = process.argv.slice(2)
+const UPDATE = argv.includes('--update')
+const CHECK = argv.includes('--check')
+if (!UPDATE && !CHECK) {
+ console.error('нужен --update или --check')
+ process.exit(2)
+}
+function arg(name) {
+ const flag = `--${name}`
+ const index = argv.findIndex(a => a === flag || a.startsWith(`${flag}=`))
+ if (index === -1) return ''
+ return argv[index].includes('=') ? argv[index].slice(flag.length + 1) : argv[index + 1] || ''
+}
+const VAULT = resolveVault({ cli: arg('vault') })
+const CEILING_PATH = arg('ceiling') ? path.resolve(arg('ceiling')) : path.join(ROOT, '.mnemazine', 'state', 'spec-ceiling.json')
+const GATE = path.join(ROOT, 'scripts', 'mnemazine-vault-quality-gate.mjs')
+
+async function runGate() {
+ // JSON уходит в stderr при провалах; код 1 при провалах — ожидаем.
+ // Через pipe гейт режет свой JSON: console.error в pipe асинхронен, а process.exit(1)
+ // сразу за ним обрывает поток (замерено: ровно 48898 байт). В файл stderr синхронен —
+ // поэтому пишем во временный файл редиректом, а не читаем pipe.
+ const tmp = path.join(ROOT, '.mnemazine', 'state', '.spec-ceiling-gate.json')
+ execFileSync('bash', ['-c', `node "$1" --spec --json --max-failures=0 > "$2" 2>&1 || true`, '_', GATE, tmp], {
+ env: { ...process.env, MNEMAZINE_VAULT: VAULT, LC_ALL: 'C' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ const out = await fs.readFile(tmp, 'utf8')
+ const start = out.indexOf('{')
+ if (start === -1) throw new Error(`гейт не вернул JSON: ${out.slice(0, 200)}`)
+ return JSON.parse(out.slice(start))
+}
+
+const report = await runGate()
+const failures = report.failures.length
+const checked = report.checked
+let ceiling = null
+try { ceiling = JSON.parse(await fs.readFile(CEILING_PATH, 'utf8')) } catch { /* первый съём */ }
+
+if (CHECK) {
+ if (!ceiling) {
+ console.error('потолок не снят — сравнивать не с чем')
+ process.exit(1)
+ }
+ console.log(`сейчас ${failures} провалов, потолок ${ceiling.ceiling}`)
+ process.exit(failures <= ceiling.ceiling ? 0 : 1)
+}
+
+const sha256 = crypto.createHash('sha256').update(await fs.readFile(GATE)).digest('hex')
+if (ceiling && failures >= ceiling.ceiling) {
+ console.error(`ОТКАЗ: провалов ${failures} не меньше потолка ${ceiling.ceiling} — потолок НЕ переписан (только вниз)`)
+ process.exit(1)
+}
+const next = { vault: VAULT, checked, ceiling: failures, recorded_at: new Date().toISOString(), sha256_of_gate: sha256 }
+await fs.mkdir(path.dirname(CEILING_PATH), { recursive: true })
+await fs.writeFile(CEILING_PATH, JSON.stringify(next, null, 2) + '\n')
+console.log(`потолок опущен: ${ceiling ? ceiling.ceiling : '—'} → ${failures} (checked ${checked})`)
diff --git a/scripts/mnemazine-synthesize.mjs b/scripts/mnemazine-synthesize.mjs
index 4d6a80e..721c0a2 100644
--- a/scripts/mnemazine-synthesize.mjs
+++ b/scripts/mnemazine-synthesize.mjs
@@ -1,9 +1,10 @@
#!/usr/bin/env node
-import { promises as fs } from 'node:fs'
+import { promises as fs, readFileSync } from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
-import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
+import { activeProvider, llmAvailable, llmJson, fenceUntrusted, providerCostTier } from './mnemazine-llm.mjs'
import { verifyLocal, verifyDeep, isPublicHttpUrl } from './mnemazine-verify.mjs'
+import { SPEC_VERIFIED } from './mnemazine-note-spec.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
@@ -24,12 +25,22 @@ const MIN_CLUSTER_CHARS = Number(arg('min-cluster-chars', '80'))
// and never needs codex. Flag also honoured via MNEMAZINE_DEEP=1.
const DEEP = argv.includes('--deep') || argv.includes('--atomize') || process.env.MNEMAZINE_DEEP === '1'
const MAX_ATOMS = Number(arg('max-atoms', process.env.MNEMAZINE_MAX_ATOMS || '20'))
+// Long material (video transcripts, books) was silently cut to the first 4000
+// chars per record, so atoms only ever covered the intro. Knobs, defaults kept.
+const MAX_RECORD_CHARS = Number(process.env.MNEMAZINE_MAX_RECORD_CHARS || '4000')
+const MAX_MATERIAL_CHARS = Number(process.env.MNEMAZINE_MAX_MATERIAL_CHARS || '24000')
// 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_TIMEOUT_MS = Number(process.env.MNEMAZINE_ENRICH_TIMEOUT_MS || '60000')
+// Enrichment web calls can be slow; default to the generous ceiling for any
+// provider (env overrides). No branch on a CLI name — a longer timeout never
+// harms a faster CLI.
+const ENRICH_TIMEOUT_MS = Number(process.env.MNEMAZINE_ENRICH_TIMEOUT_MS || '420000')
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 ATOMIZER_PROVIDER = process.env.MNEMAZINE_ATOMIZER_LLM || process.env.MNEMAZINE_LLM || undefined
+const VERIFIER_PROVIDER = process.env.MNEMAZINE_VERIFIER_LLM || process.env.MNEMAZINE_LLM || undefined
+const RESOLVED_ATOMIZER_PROVIDER = activeProvider({ provider: ATOMIZER_PROVIDER })
const SOURCE_REF_FILTER = new Set(String(process.env.MNEMAZINE_SYNTH_SOURCE_REFS || '')
.split(',')
.map(s => s.trim())
@@ -51,6 +62,9 @@ const sourceHints = [
{ re: /terraform|pulumi|infrastructure|iac/i, name: 'Terraform docs', url: 'https://developer.hashicorp.com/terraform/docs' },
{ re: /bff|backend for frontend/i, name: 'Backends for Frontends pattern', url: 'https://learn.microsoft.com/en-us/azure/architecture/patterns/backends-for-frontends' },
{ re: /worktree|git stash/i, name: 'git worktree docs', url: 'https://git-scm.com/docs/git-worktree' },
+ { re: /стартап|фаундер|основател|узк(?:ая|ой|ую|ом)\s+ниш|mvp|партизан|голиаф|airbnb|uber|клиент/i, name: "Paul Graham Do Things That Don't Scale", url: 'https://www.paulgraham.com/ds.html' },
+ { re: /стартап|фаундер|основател|узк(?:ая|ой|ую|ом)\s+ниш|mvp|партизан|голиаф|airbnb|uber|клиент/i, name: 'Sam Altman Startup Playbook', url: 'https://playbook.samaltman.com/' },
+ { re: /стартап|фаундер|основател|узк(?:ая|ой|ую|ом)\s+ниш|mvp|партизан|голиаф|airbnb|uber|клиент/i, name: 'Y Combinator Startup Playbook', url: 'https://www.ycombinator.com/blog/startup-playbook/' },
{ re: /moneyprinter|short-form|reels|tiktok|youtube shorts/i, name: 'MoneyPrinterTurbo', url: 'https://github.com/harry0703/MoneyPrinterTurbo' }
]
@@ -61,6 +75,7 @@ const clusterRules = [
{ id: 'engineering-ops', title: 'Engineering operations and reproducible delivery', re: /observability|terraform|pulumi|worktree|staging|environment|deploy|bff|backend/i },
{ id: 'design-frontend', title: 'Design systems and frontend quality', re: /design|frontend|ui|component|playwright|browser|layout|wcag/i },
{ id: 'tool-radar', title: 'Open-source tool radar and selection', re: /github\.com|open source|langflow|dify|open-webui|openhands|crawl4ai|coolify|papermark|twenty|crowdsec/i },
+ { id: 'startup-strategy', title: 'Startup strategy and founder-led growth', re: /стартап|фаундер|основател|корпораци|гигант|голодн|узк(?:ая|ой|ую|ом)\s+ниш|mvp|партизан|голиаф|airbnb|uber/i },
{ id: 'content-growth', title: 'Content experiments and growth loops', re: /ad |ads|hook|cta|offer|short-form|reels|tiktok|youtube|content|moneyprinter/i },
{ id: 'research-workflow', title: 'Research workflow and source verification', re: /research|source|citation|academic|verify|evidence/i }
]
@@ -102,6 +117,12 @@ const topicTemplates = {
how: '- Score tools by fit, maturity, license, API, self-hosting, and operational burden.\n- Tie tools to concrete projects.\n- Re-check source repositories before adopting.',
next: 'Сделать schema для tool-radar и заполнять её из извлечённых GitHub-ссылок.'
},
+ 'startup-strategy': {
+ what: 'Startup strategy is the operating pattern for small teams beating larger incumbents: narrow focus, fast customer feedback, founder-led trust, and manual work before scale.',
+ why: 'The captured carousel is useful only if it becomes a reusable decision rule, not motivational noise.',
+ how: '- Pick a narrow ignored segment.\n- Talk to customers directly.\n- Ship small changes faster than incumbents can route approvals.\n- Treat manual founder service as learning, not as permanent process.',
+ next: 'Привязать startup strategy к ближайшему проекту: ниша, скорость, founder-led trust, ручной сервис.'
+ },
'content-growth': {
what: 'Content growth loops treat ads, hooks, CTAs, short-form scripts, and publishing as experiments with feedback.',
why: 'One generated video or ad is not learning. Learning appears when variants, metric, result, and next control are stored.',
@@ -159,6 +180,12 @@ const topicTemplatesRu = {
how: ['Оценивать fit, maturity, license, API, self-hosting и operational burden.', 'Связывать инструмент с конкретным проектом.', 'Перед adoption перепроверять primary source.'],
next: 'Сделать schema для tool-radar и заполнять её из GitHub links.'
},
+ 'startup-strategy': {
+ what: 'Startup strategy - это набор ходов, где маленькая команда обходит крупного игрока не бюджетом, а узкой нишей, скоростью, прямым контактом с клиентом и founder-led доверием.',
+ why: 'Такие карточки легко превращаются в мотивационный шум. Польза появляется, когда из них выходит конкретное правило для проекта: кого выбрать, что урезать, как быстро проверить и где основатель должен говорить лично.',
+ how: ['Выбрать один узкий сегмент, который крупный игрок игнорирует.', 'Не копировать весь продукт корпорации, а закрыть одну боль лучше.', 'Собирать обратную связь напрямую от клиентов.', 'Выкатывать маленькие изменения быстрее корпоративного цикла согласований.', 'Ручной сервис основателя использовать как обучение, а не как вечный процесс.'],
+ next: 'Привязать startup strategy к ближайшему проекту: ниша, скорость, founder-led trust, ручной сервис.'
+ },
'content-growth': {
what: 'Контентные петли роста рассматривают ads, hooks, CTA, scripts и публикации как эксперименты с обратной связью.',
why: 'Один ролик или объявление ещё не обучение. Обучение появляется, когда есть variant, metric, result и next control.',
@@ -254,6 +281,7 @@ function clusterTitleRu(id) {
'engineering-ops': 'Инженерные операции и воспроизводимая доставка',
'design-frontend': 'Дизайн-системы и качество фронтенда',
'tool-radar': 'Радар инструментов и выбор open-source',
+ 'startup-strategy': 'Стратегия стартапа и founder-led рост',
'content-growth': 'Контентные эксперименты и петли роста',
'research-workflow': 'Исследовательский workflow и проверка источников',
misc: 'Прочие сигналы знаний'
@@ -305,22 +333,54 @@ async function fetchText(url, limit = 40000) {
}
}
+function looksLikeCode(text) {
+ // JS-heavy pages (YouTube et al) leak `(function() {window.ytplayer={};` and
+ // `ytcfg.set({"KEY":...})` into "external facts". Prose has no braces/arrows
+ // and is mostly letters and spaces.
+ const value = String(text || '')
+ if (/[{}]|=>|\);|\w+\.\w+\(|^\(function/.test(value)) return true
+ const letters = (value.match(/[\p{L}\s.,;:!?()'"-]/gu) || []).length
+ return letters / Math.max(1, value.length) < 0.85
+}
+
function readmePoints(readme, max = 6) {
const points = []
for (const line of stripHtmlText(readme).split('\n')) {
const clean = compact(line.replace(/^#+\s*/, '').replace(/^[-*]\s+/, ''), 220)
if (clean.length < 32) continue
+ if (/^[,.;:]/.test(clean) || /^https?:\/\//i.test(clean)) continue
if (/^(install|usage|license|contributing|table of contents|badges?)$/i.test(clean)) continue
if (/^!\[|^
/i.test(clean)) continue
+ if (looksLikeCode(clean)) continue
points.push(clean)
if (points.length >= max) break
}
return points
}
+function latinCount(text) {
+ return (String(text || '').match(/[A-Za-z]/g) || []).length
+}
+
+function cyrillicCount(text) {
+ return (String(text || '').match(/[А-Яа-яЁё]/g) || []).length
+}
+
+function russianSourceSignal(text, fallback = 'проверяемый сигнал первоисточника') {
+ const clean = compact(text, 180)
+ if (!clean) return fallback
+ const low = clean.toLowerCase()
+ if (/critical vulnerab|vulnerab/.test(low)) return 'заявленный security-риск marketplace skills'
+ if (/secure|validated|hardened|confidence/.test(low)) return 'позиционирование как проверенный каталог skills'
+ if (/registry|library|catalog/.test(low)) return 'каталог skills и reusable capabilities'
+ if (/agent|skill|claude|cursor|copilot|antigravity/.test(low)) return 'поддержка skills для AI coding agents и IDE'
+ if (latinCount(clean) > Math.max(40, cyrillicCount(clean) * 2)) return fallback
+ return clean
+}
+
function htmlDescription(html) {
const raw = String(html || '')
const hit = raw.match(/ russianSourceSignal(point, 'README-сигнал требует ручной сверки')).filter(Boolean)
const license = api.license?.spdx_id || api.license?.name || 'лицензия неизвестна'
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) || 'дата неизвестна'})` : 'GitHub API не вернул latest release'
const addedFacts = [
- `${api.full_name}: ${api.description || 'официальный GitHub-репозиторий'}.`,
+ `${api.full_name}: ${description}.`,
`Метаданные GitHub: ${api.stargazers_count} звёзд, ${api.forks_count} форков, ${api.open_issues_count} открытых issues, лицензия ${license}, основной язык ${api.language || 'unknown'}.`,
`Свежесть репозитория: основная ветка ${api.default_branch || 'unknown'}, последний push ${pushed}, последний release ${releaseLine}.`,
- ...points.slice(0, 5).map(point => `Сигнал README: ${point}`)
+ ...pointSignals.slice(0, 5).map(point => `Сигнал README: ${point}.`)
]
const addedSources = [
api.html_url,
@@ -406,10 +468,10 @@ async function enrichClusterFromGithub(cluster, sources) {
].filter(Boolean)
const enriched = [
`Расширение по официальному GitHub для ${api.full_name}.`,
- `Описание: ${api.description || 'GitHub не дал описание.'}`,
+ `Описание: ${description}.`,
`Метаданные: ${api.stargazers_count} звёзд, ${api.forks_count} форков, ${api.open_issues_count} открытых issues, ${license}, язык ${api.language || 'unknown'}, последний push ${pushed}.`,
`Последний release: ${releaseLine}.`,
- points.length ? `Из README извлечены стабильные сигналы:\n${points.map(point => `- ${point}`).join('\n')}` : 'README не дал устойчивых feature-пунктов без ручной проверки.',
+ pointSignals.length ? `Из README извлечены рабочие сигналы:\n${pointSignals.map(point => `- ${point}`).join('\n')}` : 'README не дал устойчивых feature-пунктов без ручной проверки.',
`Локальные source refs: ${cluster.records.map(r => r.source_ref).join(', ')}.`
].join('\n\n')
return { enriched, addedSources, addedFacts, github: { api, readmeUrl, release, points } }
@@ -450,13 +512,15 @@ function atomsFromGithub(part, sources) {
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 points = (github.points || []).map(point => russianSourceSignal(point, 'README-сигнал требует ручной сверки')).filter(Boolean)
const license = api.license?.spdx_id || api.license?.name || 'unknown license'
const releaseLine = github.release?.tag_name || 'no latest release returned'
+ const description = russianSourceSignal(api.description, 'англоязычное описание GitHub; точная формулировка в primary source')
return [
{
title: `${repo}: проверенная карточка инструмента`,
- what: `${repo} - официальный GitHub-репозиторий инструмента из inbox. GitHub показывает: ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, лицензия ${license}, основной язык ${api.language || 'unknown'}, последний push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}.`,
+ source_refs: part.records.map(record => record.source_ref).filter(Boolean),
+ what: `${repo} - официальный GitHub-репозиторий инструмента из inbox. Описание: ${description}. GitHub показывает: ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, лицензия ${license}, основной язык ${api.language || 'unknown'}, последний push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}.`,
why: 'Это превращает скриншот или карточку со звёздами в проверяемую запись: есть primary source, дата свежести, лицензия и базовый риск.',
how: ['Сначала смотреть метаданные: лицензия, свежесть, stars, forks, issues.', 'Перед установкой открыть README и issues, скриншот считать только подсказкой.', 'Решение фиксировать отдельно: установить сейчас, протестировать позже или забыть.'],
sources: sourceUrls,
@@ -464,7 +528,8 @@ function atomsFromGithub(part, sources) {
},
{
title: `${repo}: что реально обещает README`,
- what: points.length ? points.slice(0, 4).join(' ') : `${repo} имеет официальный README, но Mnemazine не нашла в нём устойчивые продуктовые тезисы без ручной проверки.`,
+ source_refs: part.records.map(record => record.source_ref).filter(Boolean),
+ what: points.length ? `README даёт проверяемые сигналы: ${points.slice(0, 4).join('; ')}.` : `${repo} имеет официальный README, но Mnemazine не нашла в нём устойчивые продуктовые тезисы без ручной проверки.`,
why: 'README ближе к рабочей правде, чем подпись на скриншоте. Он показывает, что авторы реально поддерживают и документируют.',
how: points.slice(0, 5).map(point => `Проверить по README: ${point}`),
sources: sourceUrls,
@@ -472,6 +537,7 @@ function atomsFromGithub(part, sources) {
},
{
title: `${repo}: риск эксплуатации и поддержки`,
+ source_refs: part.records.map(record => record.source_ref).filter(Boolean),
what: `Поверхность риска: ${api.open_issues_count} open issues, последний release ${releaseLine}, последний push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}, лицензия ${license}.`,
why: 'Популярный репозиторий всё равно может быть плохой зависимостью, если релизы, лицензия или issue-профиль не подходят под workflow.',
how: ['Проверить issues на security, потерю данных и ошибки установки.', 'Сначала гонять в одноразовом workspace, не добавлять сразу в глобальные правила агента.', 'Если это станет Skill/MCP/plugin, записать source ledger и usage ledger.'],
@@ -480,6 +546,7 @@ function atomsFromGithub(part, sources) {
},
{
title: `${repo}: решение для Mnemazine`,
+ source_refs: part.records.map(record => record.source_ref).filter(Boolean),
what: `Этот атом связывает локальный захват с primary GitHub evidence по ${repo}. Это не команда установить, а кандидат на разбор.`,
why: 'Полезная память - не "увидел репозиторий", а решение: что инструмент делает, подходит ли он, какой риск остаётся и что делать дальше.',
how: ['Хранить репозиторий как кандидата в рабочие возможности, не как инструкцию к установке.', 'Если принять, зеркалировать docs/skill metadata и логировать usage.', 'Если отклонить, записать причину, чтобы репозиторий не возвращался шумом.'],
@@ -497,6 +564,7 @@ function atomsFromSources(part, sources) {
return [
{
title: `${clusterTitleRu(part.id)}: проверенный рабочий паттерн`,
+ source_refs: part.records.map(record => record.source_ref).filter(Boolean),
what: `${template.what} Источники добавили проверяемые опорные факты: ${facts.slice(0, 2).join(' ')}`,
why: template.why,
how: [...how, ...facts.slice(2, 4).map(fact => `Проверить по источнику: ${fact}`)].slice(0, 5),
@@ -535,6 +603,7 @@ function topicSignals(cluster, sources) {
'engineering-ops': ['Повторяются инженерные сигналы: воспроизводимые окружения, IaC, worktrees, observability, release checks и secret injection.', sourceLine],
'design-frontend': ['Повторяются UI-сигналы: DESIGN.md, taste rules, frontend structure, Playwright/browser checks и WCAG constraints.', sourceLine],
'tool-radar': ['Повторяются tool-radar сигналы: GitHub repos, self-hosting, AI tools и open-source alternatives.', sourceLine],
+ 'startup-strategy': ['Повторяются startup-сигналы: узкая ниша, скорость внедрения, прямой контакт с клиентом, founder-led доверие и ручной сервис до scale.', sourceLine],
'content-growth': ['Повторяются growth-сигналы: ad variants, hooks, CTA, short-form generation, metrics и winner/loser loops.', sourceLine],
'research-workflow': ['Повторяются research-сигналы: сбор источников, проверка claims, evidence, drafting и revision.', sourceLine],
misc: ['Слабые misc-сигналы отделены от сильных knowledge atoms.', sourceLine]
@@ -589,10 +658,12 @@ function makeNote(cluster) {
: 'Публичного источника в extraction не было; это локальный memory atom, а не внешне подтверждённый claim.'
return `---
title: "${title.replace(/"/g, '\\"')}"
-type: "knowledge-note"
+type: "synthesis"
+subject: world
source_type: "synthesis-cluster"
+source: "session:${SESSION}/${cluster.id}"
source_ref: "session:${SESSION}/${cluster.id}"
-verified: false
+verified: ${specVerified(localVerdict.status)}
verification_status: "${localVerdict.status}"
verification: "${sourceStatus}"
status: "draft"
@@ -628,7 +699,12 @@ ${sourceRefs.length > 30 ? `- ... ещё ${sourceRefs.length - 30} source refs
Публичные источники:
${sourceLines.join('\n')}
-## Проверка
+## 🎯 Как это поможет мне
+
+- ${template.next}
+- Тема: ${clusterTitleRu(cluster.id)} — черновик собран, но требует проверки перед применением.
+
+## Достоверность
- **Автоматический fact-check не запускался.** Это unverified synthesis cluster (\`status: draft\`). URL из extraction или topic hints - указатели, не подтверждение конкретного claim.
- Повышать до \`status: final\` только после проверки человеком или verify gate по primary sources.
@@ -638,7 +714,7 @@ ${sourceLines.join('\n')}
## Связанные заметки
- [[Mnemazine Protocol]]
-- [[${clusterTitle(cluster.id)}]]
+- [[${clusterTitleRu(cluster.id)}]]
## Следующее действие
@@ -656,35 +732,56 @@ const ATOM_SCHEMA = {
items: {
type: 'object',
additionalProperties: false,
- required: ['title', 'what', 'why', 'how', 'next', 'sources'],
+ required: ['title', 'what', 'why', 'how', 'next', 'sources', 'source_refs'],
properties: {
title: { type: 'string' },
what: { type: 'string' },
why: { type: 'string' },
how: { type: 'array', items: { type: 'string' } },
next: { type: 'string' },
- sources: { type: 'array', items: { type: 'string' } }
+ sources: { type: 'array', items: { type: 'string' } },
+ source_refs: { type: 'array', items: { type: 'string' } }
}
}
}
}
}
+// Owner projects come from the vault (99 Система/_ПРОЕКТЫ.md), never hardcoded —
+// the spec gate rejects a "как это поможет мне" block that names no real project.
+let OWNER_PROJECTS = null
+function ownerProjects() {
+ if (OWNER_PROJECTS) return OWNER_PROJECTS
+ try {
+ const text = readFileSync(path.join(VAULT, '99 Система', '_ПРОЕКТЫ.md'), 'utf8')
+ OWNER_PROJECTS = [...text.matchAll(/^##\s+(.+?)\s*$/gm)].map(m => m[1]).filter(Boolean)
+ } catch { OWNER_PROJECTS = [] }
+ return OWNER_PROJECTS
+}
+
function atomPrompt(cluster, sources, materialOverride) {
// When enrichment ran, atomize the EXPANDED knowledge; else the raw capture.
const text = materialOverride
- ? String(materialOverride).slice(0, 28000)
- : cluster.records.map(r => compact(r.text, 4000)).join('\n---\n').slice(0, 24000)
+ ? String(materialOverride).slice(0, Math.max(28000, MAX_MATERIAL_CHARS))
+ : cluster.records.map(r => `SOURCE_REF: ${r.source_ref}\n${compact(r.text, MAX_RECORD_CHARS)}`).join('\n---\n').slice(0, MAX_MATERIAL_CHARS)
const urls = sources.map(s => s.url).join(', ') || 'none detected'
- 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).
+ const refs = cluster.records.map(r => r.source_ref).filter(Boolean).join(', ')
+ 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", the subset of source URLs that support it (from: ${urls}; [] only if truly local/private), and the subset of local source_refs that support this exact atom (from: ${refs}; never include an unrelated source_ref just because it is in the same cluster).
Пиши значения JSON на русском языке. Return ONLY JSON matching the schema.
+Заголовок атома (title) — живой русский без канцелярита: запрещены «является/являются», «данный», «осуществляет», «представляет собой». Пиши «X — Y», а не «X является Y»: заголовок уходит в имя файла и в ссылки, канцелярит оттуда расползается по всей базе.
+
+Поле "next" (следующее действие) обязано НАЧИНАТЬСЯ с имени проекта владельца, которому этот атом полезен, — дословно одним из списка: ${ownerProjects().join(' · ') || 'Саморазвитие/инструментарий'}. Если ни один проект по теме не подходит, пиши «Саморазвитие/инструментарий». Формат: «<Проект>: <одно конкретное действие>». Проект не выдумывать и не переименовывать.
+
${fenceUntrusted('MATERIAL', text)}`
}
async function atomizeCluster(cluster, sources, materialOverride) {
- const result = await llmJson(atomPrompt(cluster, sources, materialOverride), ATOM_SCHEMA)
+ const result = await llmJson(atomPrompt(cluster, sources, materialOverride), ATOM_SCHEMA, {
+ provider: ATOMIZER_PROVIDER,
+ label: `atomize:${cluster.id}`
+ })
const atoms = Array.isArray(result?.atoms) ? result.atoms : []
return atoms.filter(a => a && a.title && a.what).slice(0, MAX_ATOMS)
}
@@ -717,10 +814,12 @@ ${fenceUntrusted('MATERIAL', text)}`
}
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, Math.max(6000, MAX_RECORD_CHARS))).join('\n---\n').slice(0, MAX_MATERIAL_CHARS)
const res = await llmJson(enrichPrompt(text, sources), ENRICH_SCHEMA, {
- tools: ['WebSearch', 'WebFetch', 'mcp__firecrawl', 'mcp__tavily'],
- timeoutMs: ENRICH_TIMEOUT_MS
+ provider: VERIFIER_PROVIDER,
+ tools: ['WebSearch', 'WebFetch'],
+ timeoutMs: ENRICH_TIMEOUT_MS,
+ label: `enrich:${cluster.id}`
})
const enriched = typeof res?.enriched === 'string' ? res.enriched.trim() : ''
const addedSources = Array.isArray(res?.sources) ? res.sources.filter(isPublicHttpUrl) : []
@@ -735,9 +834,60 @@ function atomFingerprint(atom, clusterId = '') {
return crypto.createHash('sha1').update(key).digest('hex').slice(0, 10)
}
+function words(value) {
+ return String(value || '')
+ .toLowerCase()
+ .split(/[^a-zа-яё0-9]+/i)
+ .filter(word => word.length >= 4)
+}
+
+function localSourceRefsForAtom(cluster, atom) {
+ const valid = new Set(cluster.records.map(record => record.source_ref).filter(Boolean))
+ const explicit = Array.isArray(atom.source_refs)
+ ? atom.source_refs.filter(ref => valid.has(ref))
+ : []
+ if (explicit.length) return [...new Set(explicit)]
+
+ const atomText = `${atom.title || ''}\n${atom.what || ''}\n${(atom.sources || []).join('\n')}`.toLowerCase()
+ const tokens = new Set(words(atomText))
+ const scored = cluster.records
+ .map(record => {
+ const text = String(record.text || '').toLowerCase()
+ let score = 0
+ for (const source of atom.sources || []) {
+ const url = String(source || '').toLowerCase()
+ if (url && text.includes(url.replace(/^https?:\/\//, '').replace(/^www\./, ''))) score += 8
+ try {
+ const parsed = new URL(url)
+ const pathBits = parsed.pathname.split('/').filter(Boolean).slice(0, 2).join('/')
+ if (pathBits && text.includes(pathBits.toLowerCase())) score += 6
+ if (parsed.hostname && text.includes(parsed.hostname.replace(/^www\./, ''))) score += 3
+ } catch {}
+ }
+ for (const token of tokens) if (text.includes(token)) score += 1
+ return { ref: record.source_ref, score }
+ })
+ .filter(item => item.ref && item.score > 0)
+ .sort((a, b) => b.score - a.score)
+ const best = scored[0]?.score || 0
+ return scored.filter(item => item.score === best).map(item => item.ref)
+}
+
+// NOTE-SPEC enum is the single truth for `verified:` (SPEC_VERIFIED). Deep verify
+// speaks verified|assumed|unknown, so map it here instead of writing a boolean the
+// spec gate rejects.
+function specVerified(status) {
+ const map = { verified: SPEC_VERIFIED[0], assumed: SPEC_VERIFIED[2], unknown: SPEC_VERIFIED[5] }
+ return map[status] || SPEC_VERIFIED[5]
+}
+
function makeAtomNote(cluster, atom, verdict) {
const how = (atom.how || []).filter(Boolean).map(h => `- ${compact(h, 240)}`).join('\n') || '- Проверить и применить в контексте.'
- const sourceRefs = cluster.records.map(record => `- ${record.source_ref}`).join('\n')
+ const localRefs = localSourceRefsForAtom(cluster, atom)
+ const sourceRefs = (localRefs.length ? localRefs : cluster.records.map(record => record.source_ref))
+ .filter(Boolean)
+ .map(ref => `- ${ref}`)
+ .join('\n')
const addedFacts = (cluster.enrichment?.addedFacts || []).map(f => `- ${compact(f, 300)}`).join('\n') || '- Внешние факты не записаны.'
const srcs = (atom.sources || []).filter(isPublicHttpUrl)
const sourceLines = srcs.length
@@ -748,10 +898,12 @@ function makeAtomNote(cluster, atom, verdict) {
const isVerified = v.status === 'verified'
return `---
title: "${String(atom.title).replace(/"/g, '\\"').slice(0, 120)}"
-type: "knowledge-note"
+type: "synthesis"
+subject: world
source_type: "synthesis-atom"
+source: "session:${SESSION}/${cluster.id}#${fp}"
source_ref: "session:${SESSION}/${cluster.id}#${fp}"
-verified: ${isVerified}
+verified: ${specVerified(v.status)}
verification_status: "${v.status}"
verification: "llm-atomized; ${String(v.note || 'sources unverified').replace(/"/g, "'")}"
status: "${isVerified ? 'final' : 'draft'}"
@@ -787,7 +939,12 @@ ${sourceLines}
Факты, добавленные до атомизации:
${addedFacts}
-## Проверка
+## 🎯 Как это поможет мне
+
+- ${compact(atom.next, 240) || 'Применить в ближайшей задаче по теме кластера.'}
+- Тема: ${clusterTitleRu(cluster.id)} — смотреть сюда, когда всплывёт этот вопрос.
+
+## Достоверность
- Статус проверки: **${v.status}**${v.note ? ` (${v.note})` : ''}.
${isVerified
@@ -807,6 +964,25 @@ ${isVerified
}
await fs.mkdir(path.join(VAULT, '01 Concepts'), { recursive: true })
+// One runnable check for the source-scrape junk filter: real prose survives,
+// leaked page JS does not. Run: node scripts/mnemazine-synthesize.mjs --selftest
+if (argv.includes('--selftest')) {
+ const junk = [
+ '(function() {window.ytplayer={};',
+ 'ytcfg.set({"CLIENT_CANARY_STATE":"none","DEVICE":"ceng\\u003dUSER_DEFINED"});',
+ 'document.querySelector("#player").play();'
+ ]
+ const prose = [
+ 'Obsidian хранит заметки как обычные markdown-файлы в локальной папке без облака.',
+ 'Wikilinks connect notes into a graph you can open and inspect from the sidebar.'
+ ]
+ for (const line of junk) if (!looksLikeCode(line)) throw new Error(`selftest: junk passed the filter: ${line}`)
+ for (const line of prose) if (looksLikeCode(line)) throw new Error(`selftest: prose rejected by the filter: ${line}`)
+ if (readmePoints(junk.concat(prose).join('\n'), 6).length !== prose.length) throw new Error('selftest: readmePoints kept the wrong lines')
+ console.log(JSON.stringify({ ok: true, selftest: 'source-scrape junk filter' }))
+ process.exit(0)
+}
+
const records = await listRecords()
const clusters = new Map()
for (const record of records) {
@@ -847,8 +1023,19 @@ async function processPart(part, parts, index) {
let material
if (ENRICH) {
try {
- const deterministic = await enrichClusterFromGithub(part, sources) || await enrichClusterFromSources(part, sources)
- const { enriched, addedSources, addedFacts } = deterministic || await enrichCluster(part, sources)
+ // GitHub API/README is a real primary source, so it stays first. The
+ // generic page-scrape path builds a canned topic template and skips the
+ // LLM atomizer, so it only runs when the LLM enricher gave nothing.
+ let deterministic = await enrichClusterFromGithub(part, sources)
+ let llmEnriched = null
+ if (!deterministic) {
+ llmEnriched = await enrichCluster(part, sources).catch(() => null)
+ if (!llmEnriched?.enriched || (llmEnriched.addedFacts || []).length < MIN_ADDED_FACTS) {
+ deterministic = await enrichClusterFromSources(part, sources)
+ if (deterministic) llmEnriched = null
+ }
+ }
+ const { enriched, addedSources, addedFacts } = deterministic || llmEnriched || { enriched: '', addedSources: [], addedFacts: [] }
if (enriched && enriched.length > 200) {
material = enriched
for (const u of addedSources) if (!sources.some(s => s.url === u)) sources.push({ name: hostOf(u) || 'Source', url: u })
@@ -875,15 +1062,25 @@ async function processPart(part, parts, index) {
: await atomizeCluster(part, sources, material)
let wroteAtom = false
const allowedSourceUrls = new Set(sources.map(source => source.url).filter(isPublicHttpUrl))
+ // Atom verdicts are independent read-only calls, so they are collected in
+ // parallel (same verifyDeep args — call quality is unchanged). File writes
+ // and counters stay serial. Cap via MNEMAZINE_VERIFY_CONCURRENCY.
+ const pendingAtoms = []
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`)
if (await fs.access(out).then(() => true).catch(() => false)) { skipped += 1; continue }
- const verdict = part.enrichment?.deterministic
- ? { status: 'verified', checked: atom.sources || [], evidence: part.enrichment.kind === 'github' ? 'Fetched GitHub API/README/release for primary-source enrichment.' : 'Fetched public source pages from configured source hints.', note: `deterministic ${part.enrichment.kind} source check` }
+ pendingAtoms.push({ atom, out, verdict: null })
+ }
+ const VERIFY_CONCURRENCY = Math.max(1, Number(process.env.MNEMAZINE_VERIFY_CONCURRENCY || '8'))
+ await mapLimit(pendingAtoms, VERIFY_CONCURRENCY, async (entry) => {
+ entry.verdict = part.enrichment?.deterministic
+ ? { status: 'verified', checked: entry.atom.sources || [], evidence: part.enrichment.kind === 'github' ? 'Fetched GitHub API/README/release for primary-source enrichment.' : 'Fetched public source pages from configured source hints.', note: `deterministic ${part.enrichment.kind} source check` }
: DEEP
- ? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources)
- : verifyLocal(atom.sources)
+ ? await verifyDeep(`${entry.atom.what}\n${entry.atom.why}`, entry.atom.sources, { provider: VERIFIER_PROVIDER, label: `verify:${part.id}` })
+ : verifyLocal(entry.atom.sources)
+ })
+ for (const { atom, out, verdict } of pendingAtoms) {
if (STRICT_ENRICH && verdict.status !== 'verified') {
console.error(`[synthesize] strict verification rejected atom "${atom.title}": ${verdict.status}`)
continue
@@ -893,8 +1090,16 @@ async function processPart(part, parts, index) {
wroteAtom = true
}
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`)
+ // Strict verify rejected every atom. Writing nothing leaves the source
+ // "unvisited": the next run re-atomizes it, gets fresh fingerprints and
+ // re-verifies from scratch — the loop that burned 1755 verify calls on one
+ // source. Fall through to the honest draft note instead (its own verdict
+ // fields stay unverified), so the source has an artifact and stops recurring.
+ if (STRICT_ENRICH) {
+ console.error(`[synthesize] strict verification rejected all atoms for cluster ${part.id}; writing honest draft note instead of looping`)
+ } else {
+ console.error(`[synthesize] atomize produced no atoms for cluster ${part.id}; using template note`)
+ }
} catch (err) {
if (STRICT_ENRICH) throw err
console.error(`[synthesize] atomize failed for cluster ${part.id}: ${err.message}; using template note`)
@@ -922,7 +1127,10 @@ for (const cluster of clusters.values()) {
}
// Swarm only helps when each task spawns an agent (deep); local template writes
// stay serial. Cap concurrency so we are cheap+fast, not a fork bomb.
-const CONCURRENCY = Number(arg('concurrency', process.env.MNEMAZINE_CONCURRENCY || '4'))
+// Premium-tier CLIs are rate-limited/expensive → run atomization serial; cheaper
+// tiers parallelize. Read from the registry (cost_tier), never a name list.
+const DEFAULT_CONCURRENCY = providerCostTier(RESOLVED_ATOMIZER_PROVIDER) === 'premium' ? '1' : '4'
+const CONCURRENCY = Number(arg('concurrency', process.env.MNEMAZINE_CONCURRENCY || DEFAULT_CONCURRENCY))
await mapLimit(tasks, useAtomize ? CONCURRENCY : 1, async ({ part, parts, index }) => {
// Outer guard: a part must never break the swarm, even on an unexpected throw.
try { await processPart(part, parts, index) }
diff --git a/scripts/mnemazine-telegram-poll.sh b/scripts/mnemazine-telegram-poll.sh
index 098f6b7..e718943 100755
--- a/scripts/mnemazine-telegram-poll.sh
+++ b/scripts/mnemazine-telegram-poll.sh
@@ -6,10 +6,16 @@
set -euo pipefail
REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
+ENV_DRAFT_ONLY="${MNEMAZINE_DRAFT_ONLY:-}"
+ENV_REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-}"
+ENV_REMOTE_REPORTS="${MNEMAZINE_REMOTE_REPORTS:-}"
# Live host/key/paths live in a gitignored config, never hardcoded here.
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
# Non-secret personal overrides (e.g. MNEMAZINE_INBOX), gitignored.
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
+[ -n "$ENV_DRAFT_ONLY" ] && export MNEMAZINE_DRAFT_ONLY="$ENV_DRAFT_ONLY"
+[ -n "$ENV_REMOTE_INBOX" ] && export MNEMAZINE_REMOTE_INBOX="$ENV_REMOTE_INBOX"
+[ -n "$ENV_REMOTE_REPORTS" ] && export MNEMAZINE_REMOTE_REPORTS="$ENV_REMOTE_REPORTS"
VPS="${MNEMAZINE_VPS:-deploy@YOUR_VPS_HOST}"
KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}"
REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-mnemazine/inbox}"
@@ -17,13 +23,83 @@ 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}"
+print_remote_paths() {
+ reports_count="$(find "$REPO/reports" -type f 2>/dev/null | wc -l | tr -d ' ')"
+ capability_report="$REPO/reports/2026-06-15-capability-link-suggestions.md"
+ capability_size="unknown"
+ [ -f "$capability_report" ] && capability_size="$(wc -c < "$capability_report" | tr -d ' ')"
+ cat < | delete only after successful local protocol run | scripts/mnemazine-telegram-sync.sh:65 |
+| ${REMOTE_REPORTS%/}/ | upload local reports/ only after the data-class gate allows a staged export | scripts/mnemazine-telegram-poll.sh:130 |
+| mnemazine/inbox, mnemazine/bot | create directories | setup.sh:178 |
+| mnemazine/bot/mnemazine-telegram-bot.mjs | overwrite bot script | setup.sh:179 |
+| mnemazine/bot/.env | write bot token under umask 177 | setup.sh:183 |
+| pm2 process mnemazine-bot | start/restart and save process | setup.sh:185 |
+
+WARNING: reports/ upload was 88 files on 2026-08-22; current local count is ${reports_count}. It includes 2026-06-15-capability-link-suggestions.md (${capability_size} bytes) and live vault audit files. Bulk upload is disabled; reports can leave only through the P24 data-class gate.
+
+Owner step after review:
+ add MNEMAZINE_REMOTE_MUTATION=1 to $REPO/.mnemazine/config.env
+EOF
+}
+
+record_blocked() {
+ reason="$1"
+ mkdir -p "$REPO/.mnemazine/state"
+ set +e
+ node - "$REPO/.mnemazine/state/telegram-blocked.json" "$reason" <<'NODE'
+const fs = require('node:fs')
+const [file, reason] = process.argv.slice(2)
+const now = new Date().toISOString()
+let prev = {}
+try { prev = JSON.parse(fs.readFileSync(file, 'utf8')) } catch {}
+const changed = prev.reason !== reason
+const lastPrinted = Date.parse(prev.last_printed_at || '')
+const shouldPrint = changed || !Number.isFinite(lastPrinted) || Date.now() - lastPrinted >= 86400000
+const next = {
+ reason,
+ first_seen: changed || !prev.first_seen ? now : prev.first_seen,
+ last_seen: now,
+ count: changed ? 1 : Number(prev.count || 0) + 1,
+ last_printed_at: shouldPrint ? now : prev.last_printed_at
+}
+fs.writeFileSync(file, JSON.stringify(next, null, 2) + '\n')
+process.exit(shouldPrint ? 0 : 3)
+NODE
+ rc="$?"
+ set -e
+ case "$rc" in
+ 0) return 0 ;;
+ 3) return 1 ;;
+ *) return 0 ;;
+ esac
+}
+
+case "${1:-}" in
+ --print-remote-paths) print_remote_paths; exit 0 ;;
+ "") ;;
+ *) echo "Usage: $0 [--print-remote-paths]" >&2; exit 2 ;;
+esac
+
# ponytail: fail fast if still on the placeholder — beats a confusing ssh error.
if [ "$VPS" = "deploy@YOUR_VPS_HOST" ]; then
- echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2
+ if record_blocked "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env"; then
+ echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2
+ fi
exit 1
fi
if [ "${MNEMAZINE_REMOTE_MUTATION:-0}" != "1" ]; then
- echo "Set MNEMAZINE_REMOTE_MUTATION=1 after reviewing VPS paths; poll mutates remote flags/reports." >&2
+ if record_blocked "Set MNEMAZINE_REMOTE_MUTATION=1 after reviewing VPS paths; poll mutates remote flags/reports."; then
+ echo "Set MNEMAZINE_REMOTE_MUTATION=1 after reviewing VPS paths; poll mutates remote flags/reports." >&2
+ fi
exit 1
fi
ATTEMPT_MARKER="$REPO/.mnemazine/.last-daily-attempt"
@@ -57,8 +133,21 @@ if [ -n "$queue" ]; then
[ -z "$topic" ] && continue
MNEMAZINE_DEEP=1 npm run --silent search -- --topic "$topic" || echo "search failed: $topic" >&2
done <<< "$topics"
- # Push reports back so the mini app can read them (reverse channel Mac->VPS).
- [ -d "$REPO/reports" ] && rsync -az -e "$SSH" "$REPO/reports/" "$VPS:$REMOTE_REPORTS/" 2>/dev/null || true
+ # Заливка reports наружу — только через классовый барьер П24: партия
+ # описывается манифестом, манифест проходит machine-class-gate, ненулевой код
+ # ОСТАНАВЛИВАЕТ отправку. rsync ниже ОБЯЗАН стоять после вызова гейта — это
+ # требование проверяет release-check machine-class-gate (грепом по этому файлу).
+ if [ "${MNEMAZINE_PUSH_REPORTS:-0}" = "1" ]; then
+ REPORTS_MANIFEST="$REPO/.mnemazine/state/reports-export-manifest.txt"
+ mkdir -p "$REPO/.mnemazine/state"
+ find "$REPO/reports" -type f -name '*.md' > "$REPORTS_MANIFEST"
+ if node "$REPO/scripts/mnemazine-machine-class-gate.mjs" --batch "$REPORTS_MANIFEST" --target vps; then
+ rsync -az -e "$SSH" "$REPO/reports/" "$VPS:$REMOTE_REPORTS/"
+ else
+ echo "reports export заблокирован гейтом класса данных П24 (pd/personal или неопределимый класс в партии)." >&2
+ exit 1
+ fi
+ fi
fi
run=0; manual=0; daily=0
diff --git a/scripts/mnemazine-telegram-sync.sh b/scripts/mnemazine-telegram-sync.sh
index 8ec9dfa..75c8226 100755
--- a/scripts/mnemazine-telegram-sync.sh
+++ b/scripts/mnemazine-telegram-sync.sh
@@ -6,16 +6,23 @@
set -euo pipefail
REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
+ENV_REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-}"
# Live host/key/paths live in a gitignored config, never hardcoded here.
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
# Non-secret personal overrides (e.g. MNEMAZINE_INBOX), gitignored.
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
+[ -n "$ENV_REMOTE_INBOX" ] && export MNEMAZINE_REMOTE_INBOX="$ENV_REMOTE_INBOX"
VPS="${MNEMAZINE_VPS:-deploy@YOUR_VPS_HOST}"
KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}"
REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-mnemazine/inbox/}"
REMOTE_INBOX="${REMOTE_INBOX%/}/"
-# Inbox honours MNEMAZINE_INBOX (from config.env); defaults to repo-local inbox.
-LOCAL_INBOX="${MNEMAZINE_INBOX:-$REPO/inbox}"
+# Inbox must be explicit: otherwise Telegram traffic splits into a repo-local
+# inbox that the desktop protocol does not use.
+if [ -z "${MNEMAZINE_INBOX:-}" ]; then
+ echo "Set MNEMAZINE_INBOX in $REPO/.mnemazine/config.env; sync refuses to use $REPO/inbox silently." >&2
+ exit 1
+fi
+LOCAL_INBOX="$MNEMAZINE_INBOX"
LOCAL_INBOX="${LOCAL_INBOX%/}/"
STAGING="${LOCAL_INBOX}.staging/"
# Export so the protocol runner reads the same inbox.
diff --git a/scripts/mnemazine-tool-decision-queue.mjs b/scripts/mnemazine-tool-decision-queue.mjs
index 9e426b0..06b5669 100644
--- a/scripts/mnemazine-tool-decision-queue.mjs
+++ b/scripts/mnemazine-tool-decision-queue.mjs
@@ -2,6 +2,7 @@
import { promises as fs } from 'node:fs'
import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'
+import { SPEC_TYPES } from './mnemazine-note-spec.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
@@ -63,6 +64,11 @@ function titleOf(text, file) {
path.basename(file, '.md')
}
+function frontmatterType(text) {
+ const match = String(text || '').match(/^type:\s*["']?([^"'\n#]+)["']?\s*(?:#.*)?$/m)
+ return match ? match[1].trim() : ''
+}
+
async function walk(dir) {
const out = []
async function visit(folder) {
@@ -158,7 +164,7 @@ async function collectTools() {
const stat = await fs.stat(file)
if (SINCE_MS && stat.mtimeMs < SINCE_MS) continue
const text = await fs.readFile(file, 'utf8').catch(() => '')
- if (!/type:\s*"knowledge-note"/.test(text)) continue
+ if (!SPEC_TYPES.has(frontmatterType(text))) continue
if (!/github\.com\//i.test(text)) continue
if (!/verified:\s*true/.test(text)) continue
const repos = reposFrom(text)
diff --git a/scripts/mnemazine-ui.sh b/scripts/mnemazine-ui.sh
new file mode 100644
index 0000000..e5c1530
--- /dev/null
+++ b/scripts/mnemazine-ui.sh
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+# Shared terminal UI helpers for install.sh and setup.sh. Sourced, never run.
+# Bilingual: MNEMAZINE_LANG is ru|en, chosen once from the locale. A public
+# repo defaults to English so the first question a stranger sees is in English.
+
+# Locale → language, one case. Explicit MNEMAZINE_LANG wins; otherwise ru_* → ru.
+case "${MNEMAZINE_LANG:-}" in
+ ru|en) : ;;
+ *)
+ case "${LC_ALL:-}${LANG:-}" in
+ ru_*|ru|*ru_RU*|*ru.*) MNEMAZINE_LANG=ru ;;
+ *) MNEMAZINE_LANG=en ;;
+ esac
+ ;;
+esac
+export MNEMAZINE_LANG
+
+# L "" "": echo the string for the active language (no trailing newline).
+L() { if [ "$MNEMAZINE_LANG" = ru ]; then printf '%s' "$1"; else printf '%s' "$2"; fi; }
+
+b() { printf '\033[1m%s\033[0m\n' "$*"; }
+ok() { printf ' \033[32m✓\033[0m %s\n' "$*"; }
+no() { printf ' \033[31m✗\033[0m %s\n' "$*"; }
+note() { printf ' • %s\n' "$*"; }
+warn() { printf ' \033[33m[!]\033[0m %s\n' "$*"; }
+# stage "" "" — numbered with a denominator so progress is legible.
+stage() { printf '\n\033[1m\033[36m── %s %s ──\033[0m %s\n' "$(L 'Этап' 'Stage')" "$1" "$2"; }
+miss() { printf '\n \033[33m%s\033[0m %s\n' "$1" "${2:-}"; }
+halt() { printf '\n\033[1m%s\033[0m\n' "$(L 'Установи это и запусти снова — продолжим со следующего этапа.' 'Install this, run again — we continue from the next stage.')"; exit 1; }
diff --git a/scripts/mnemazine-update.sh b/scripts/mnemazine-update.sh
index 71316f5..64c477c 100755
--- a/scripts/mnemazine-update.sh
+++ b/scripts/mnemazine-update.sh
@@ -4,12 +4,34 @@ set -euo pipefail
ROOT="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
cd "$ROOT"
-git pull --ff-only
+echo "Update touches code only. Your data stays put — inbox/, vault/, reports/"
+echo "are gitignored and never pulled or rebuilt."
+
+# git pull can fail on a local edit; say what to do instead of dying silently.
+if ! git pull --ff-only; then
+ echo "git pull --ff-only failed (local edits, or history diverged)." >&2
+ echo "Your data is untouched. Inspect with: git status" >&2
+ echo "Then: git stash (or commit) your changes, run this again, and reapply." >&2
+ exit 1
+fi
+
+# install.sh now exits with its status. Code 2 = skeleton rebuilt, some optional
+# capability degraded (deps intentionally skipped on update) — normal, not a stop.
+# Code 1 = real failure — stop and surface it.
+set +e
MNEMAZINE_FROM_SETUP=1 MNEMAZINE_SKIP_DEPS=1 bash install.sh
+rc=$?
+set -e
+case "$rc" in
+ 0) : ;;
+ 2) echo "Some optional capabilities are degraded (deps skipped on update) — that is expected." ;;
+ *) echo "install.sh failed (code $rc) — update not finished." >&2; exit "$rc" ;;
+esac
npm run audit:local
echo "Mnemazine updated."
+echo "Sign of life: npm run doctor"
echo "Preflight before live run: npm run preflight:live"
echo "Run from chat: Mnemazine"
echo "Run from terminal: mnemazine"
diff --git a/scripts/mnemazine-vault-final-audit.mjs b/scripts/mnemazine-vault-final-audit.mjs
new file mode 100644
index 0000000..d6da902
--- /dev/null
+++ b/scripts/mnemazine-vault-final-audit.mjs
@@ -0,0 +1,248 @@
+#!/usr/bin/env node
+import { promises as fs } from 'node:fs'
+import { existsSync, readFileSync } from 'node:fs'
+import path from 'node:path'
+import { resolveVault } from './mnemazine-paths.mjs'
+
+const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
+const argv = process.argv.slice(2)
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+
+function flag(name) {
+ return argv.includes(`--${name}`)
+}
+
+const VAULT = resolveVault({ cli: arg('vault') })
+const MAX_FAILURES = Number(arg('max-failures', '50'))
+const WIKI_SCOPE = arg('wiki-scope', flag('strict-wiki') ? 'all' : 'critical')
+const STRICT_WIKI = flag('strict-wiki')
+
+const rawAllowed = new Set([
+ '99 Система/Лог обработки.md',
+ '99 Система/Протокол_Мнемозина.md',
+ 'Лог обработки.md'
+])
+
+const wikiTargetIgnore = new Set(['...', '…', 'note', 'Название'])
+
+const rawRules = [
+ ['raw-media-name', /\b(?:temp[_-]?image|tmpImage|IMG_\d+)(?:\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4))?\b/gi],
+ ['draft-marker', /\b(?:intake-draft|draft-local)\b/gi],
+ ['raw-ocr', /\braw\s+ocr\b|сыр[оы]й\s+ocr|Локальное извлечение/gi],
+ ['external-sandbox-ref', /\b(?:attached_file:\/\/|sandbox:\/mnt\/data\/|oai_citation|turn\d+(?:search|fetch|view)\d+)\b/gi],
+ ['chatgpt-tracking-ref', /[?&]utm_source=chatgpt\.com\b/gi],
+ ['english-section-shell', /^##\s+(What This Is|Why It Matters|How To Use It|Source|Verification|Related Notes|Reuse)\b/gm]
+]
+
+function norm(value) {
+ return String(value || '')
+ .replace(/\\+$/g, '')
+ .replace(/\.md$/i, '')
+ .replace(/[—–]/g, '-')
+ .replace(/\s+/g, ' ')
+ .trim()
+}
+
+function stripDate(value) {
+ return norm(value)
+ .replace(/^\d{4}-\d{2}-\d{2}\s*[-—–]\s*/, '')
+ .replace(/-\d+$/, '')
+ .trim()
+}
+
+function pathRel(file) {
+ return path.relative(VAULT, file).replace(/\\/g, '/')
+}
+
+function addFailure(failures, rule, file, details) {
+ if (failures.length >= MAX_FAILURES) return
+ failures.push({ rule, file, details })
+}
+
+function addIndex(index, key, file) {
+ const normalized = norm(key)
+ if (!normalized) return
+ if (!index.has(normalized)) index.set(normalized, new Set())
+ index.get(normalized).add(file)
+}
+
+function frontmatterValue(text, key) {
+ const match = text.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'))
+ if (!match) return ''
+ return match[1].trim().replace(/^['"]|['"]$/g, '')
+}
+
+function frontmatterAliases(text) {
+ const out = []
+ const inline = text.match(/^aliases:\s*\[([^\]]+)\]/m)
+ if (inline) {
+ out.push(...inline[1].split(',').map(item => item.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean))
+ }
+ const block = text.match(/^aliases:\s*\n((?:\s+-\s+.+\n?)+)/m)
+ if (block) {
+ out.push(...block[1].split('\n')
+ .map(line => line.replace(/^\s+-\s+/, '').trim().replace(/^['"]|['"]$/g, ''))
+ .filter(Boolean))
+ }
+ return out
+}
+
+function strictWikiFile(rel) {
+ return [
+ '_МАСТЕР-ИНДЕКС.md',
+ '10 Карта возможностей.md',
+ 'AGENTS.md',
+ 'CLAUDE.md',
+ '99 Система/Протокол_Мнемозина.md',
+ '99 Система/Agent_Handoff_Graph.md'
+ ].includes(rel) || rel.startsWith('08 AI и Инструменты/Capabilities/_СПОСОБНОСТИ')
+}
+
+async function collectVault() {
+ const files = []
+ const dirs = new Set([''])
+ const nestedGraphify = []
+
+ async function walk(dir) {
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ if (['.git', '.obsidian', '.mnemazine'].includes(item.name)) continue
+ const file = path.join(dir, item.name)
+ const rel = pathRel(file)
+ if (item.isDirectory()) {
+ if (item.name.startsWith('graphify-out')) {
+ if (path.dirname(rel) !== '.') nestedGraphify.push(rel)
+ continue
+ }
+ dirs.add(rel)
+ await walk(file)
+ } else if (item.isFile() && item.name.endsWith('.md')) {
+ files.push(file)
+ }
+ }
+ }
+
+ await walk(VAULT)
+ return { files, dirs, nestedGraphify }
+}
+
+function rawMarkerFailures(files) {
+ const failures = []
+ for (const file of files) {
+ const rel = pathRel(file)
+ const basename = path.basename(file)
+ if (/Users [^/ ]+|\/Users\/[^/]+|Проекты mnemazine|личный vault 0\d/.test(basename)) {
+ addFailure(failures, 'private-path-filename', rel, [basename])
+ }
+ if (rawAllowed.has(rel)) continue
+ const text = existsSync(file) ? String(readFileSync(file, 'utf8')) : ''
+ const haystack = `${basename}\n${text}`
+ for (const [rule, re] of rawRules) {
+ const matches = [...haystack.matchAll(re)].slice(0, 5).map(match => match[0])
+ if (matches.length) addFailure(failures, rule, rel, matches)
+ }
+ }
+ return failures
+}
+
+function buildWikiIndex(files, dirs) {
+ const index = new Map()
+ for (const file of files) {
+ const rel = pathRel(file)
+ const withoutExt = rel.replace(/\.md$/, '')
+ const basename = path.basename(withoutExt)
+ const text = existsSync(file) ? String(readFileSync(file, 'utf8')) : ''
+ for (const key of [
+ rel,
+ withoutExt,
+ basename,
+ stripDate(basename),
+ frontmatterValue(text, 'title'),
+ ...frontmatterAliases(text)
+ ]) {
+ addIndex(index, key, rel)
+ }
+ }
+ return { index, dirs }
+}
+
+function wikiTargetExists(target, wiki) {
+ let clean = String(target || '').split('|')[0].split('#')[0].split('^')[0].trim()
+ clean = clean.replace(/\\+$/g, '').trim()
+ if (!clean || clean.startsWith('#') || /^https?:\/\//i.test(clean)) return true
+ if (wikiTargetIgnore.has(clean)) return true
+
+ const normalized = norm(clean)
+ if (!normalized) return true
+ if (wiki.dirs.has(normalized) || wiki.index.has(normalized)) return true
+ const basename = path.basename(normalized)
+ return wiki.index.has(basename) || wiki.index.has(stripDate(basename))
+}
+
+function linkScanText(text) {
+ return String(text || '')
+ .replace(/```[\s\S]*?```/g, block => block.replace(/[^\n]/g, ' '))
+ .replace(/`[^`\n]*`/g, block => ' '.repeat(block.length))
+}
+
+function wikiFailures(files, wiki) {
+ const failures = []
+ const warnings = []
+ const linkRe = /\[\[([^\]\n]+)\]\]/g
+ for (const file of files) {
+ const rel = pathRel(file)
+ if (WIKI_SCOPE === 'none') continue
+ if (WIKI_SCOPE === 'critical' && !strictWikiFile(rel)) continue
+ const text = existsSync(file) ? linkScanText(readFileSync(file, 'utf8')) : ''
+ let match
+ while ((match = linkRe.exec(text))) {
+ const target = match[1].split('|')[0].trim()
+ if (wikiTargetExists(target, wiki)) continue
+ const item = { rule: 'broken-wiki-link', file: rel, details: [target] }
+ if (STRICT_WIKI || WIKI_SCOPE === 'critical') {
+ if (failures.length < MAX_FAILURES) failures.push(item)
+ } else if (warnings.length < MAX_FAILURES) {
+ warnings.push(item)
+ }
+ }
+ }
+ return { failures, warnings }
+}
+
+async function main() {
+ const failures = []
+ const warnings = []
+ const { files, dirs, nestedGraphify } = await collectVault()
+
+ for (const rel of nestedGraphify) addFailure(failures, 'nested-graphify-runtime', rel, ['move graphify runtime out of note folders'])
+ for (const failure of rawMarkerFailures(files)) addFailure(failures, failure.rule, failure.file, failure.details)
+
+ const wiki = wikiFailures(files, buildWikiIndex(files, dirs))
+ for (const failure of wiki.failures) addFailure(failures, failure.rule, failure.file, failure.details)
+ warnings.push(...wiki.warnings)
+
+ const result = {
+ ok: failures.length === 0,
+ vault: VAULT,
+ checked: {
+ markdown_files: files.length,
+ nested_graphify_dirs: nestedGraphify.length,
+ wiki_scope: WIKI_SCOPE,
+ strict_wiki: STRICT_WIKI
+ },
+ failures,
+ warnings
+ }
+
+ console.log(JSON.stringify(result, null, 2))
+ if (!result.ok) process.exit(1)
+}
+
+main().catch(error => {
+ console.error(error.message || error)
+ process.exit(1)
+})
diff --git a/scripts/mnemazine-vault-hygiene-check.mjs b/scripts/mnemazine-vault-hygiene-check.mjs
new file mode 100644
index 0000000..39fe3c8
--- /dev/null
+++ b/scripts/mnemazine-vault-hygiene-check.mjs
@@ -0,0 +1,362 @@
+#!/usr/bin/env node
+// mnemazine-vault-hygiene-check.mjs — прибор П15 «Гигиена vault».
+//
+// Три режима:
+// --snapshot --out слепок vault: basename всех .md, sha256 каждого,
+// вес по каталогам, wikilink-вхождения внутри/вне
+// graphify-каталогов, число путей в git status.
+// --compare [before] множество basename before-слепка == ЖИВОМУ диску:
+// свежий срез vault снимается самим --compare в момент
+// запуска, отдельный after-слепок не нужен (можно вывести
+// побочно через --after-out ). Без позиционного
+// аргумента before берётся из .mnemazine/state/vault-
+// hygiene-before.json. Нет before-слепка → exit 2
+// (fail-closed: сверка без базиса — это не «зелёный»).
+// Расхождение → exit 1 с именами пропавших/появившихся
+// файлов. Допустимые новые basename читаются из манифеста
+// .mnemazine/state/vault-hygiene-allowed-new.json — объявление
+// живёт в ДАННЫХ, а не во флаге вызова.
+// --converge сходимость замерщиков битых wikilink: число от
+// mnemazine-kb-lint.mjs --json --limit=500 против
+// независимого грубого обхода ниже. Расхождение → exit 1.
+//
+// Грубый обход сознательно НЕ исключает graphify-out* — именно этим два замерщика
+// расходились до П15 (один считал внутри graphify, другой снаружи). После выноса
+// мёртвых бэкапов оба обязаны давать одно число; вернувшийся бэкап снова их разводит,
+// и --converge обязан упасть (враждебная проба 3 плана П15).
+//
+// Все обходы — под LC_ALL=C: BSD uniq/sort под en_US.UTF-8 схлопывает разные
+// кириллические имена (инвариант 4 мастер-плана).
+
+import fs from 'node:fs/promises'
+import { existsSync } from 'node:fs'
+import path from 'node:path'
+import crypto from 'node:crypto'
+import { spawnSync } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+import { resolveVault as resolveVaultPath } from './mnemazine-paths.mjs'
+
+process.env.LC_ALL = 'C'
+
+const argv = process.argv.slice(2)
+function arg(name, fallback = '') {
+ const i = argv.indexOf(`--${name}`)
+ if (i !== -1 && argv[i + 1] && !argv[i + 1].startsWith('--')) return argv[i + 1]
+ const eq = argv.find(a => a.startsWith(`--${name}=`))
+ return eq ? eq.slice(name.length + 3) : fallback
+}
+const flag = name => argv.includes(`--${name}`)
+
+const nfc = value => String(value || '').normalize('NFC')
+
+function resolveVault() {
+ return resolveVaultPath({ cli: arg('vault'), requireExists: false })
+}
+
+const KB_LINT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'mnemazine-kb-lint.mjs')
+
+const ALLOWED_NEW_MANIFEST = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)), '..', '.mnemazine', 'state', 'vault-hygiene-allowed-new.json'
+)
+
+// Манифест допустимых появлений — единственный канал объявления новых basename.
+// Отсутствующий файл = пустой манифест; битый JSON = exit 1 (молчаливого пропуска нет).
+async function readAllowedNew() {
+ if (!existsSync(ALLOWED_NEW_MANIFEST)) return []
+ let doc
+ try {
+ doc = JSON.parse(await fs.readFile(ALLOWED_NEW_MANIFEST, 'utf8'))
+ } catch (err) {
+ console.error(`FAIL: манифест допустимых появлений — битый JSON: ${ALLOWED_NEW_MANIFEST} (${err.message})`)
+ process.exit(1)
+ }
+ const list = Array.isArray(doc?.allowed) ? doc.allowed : []
+ return list
+ .map(entry => ({ basename: nfc(entry?.basename), reason: String(entry?.reason || ''), added: String(entry?.added || '') }))
+ .filter(entry => entry.basename)
+}
+
+async function writeAllowedNew(entries) {
+ const doc = {
+ description: 'Манифест допустимых появлений прибора П15 (mnemazine-vault-hygiene-check.mjs --compare). Новый basename в vault считается законным только если он объявлен здесь, с причиной. Любой необъявленный — exit 1 с именем. Флаг --allow-new лишь ДОБАВЛЯЕТ запись в этот файл, обхода сверки нет.',
+ allowed: entries
+ }
+ await fs.mkdir(path.dirname(ALLOWED_NEW_MANIFEST), { recursive: true })
+ await fs.writeFile(ALLOWED_NEW_MANIFEST, JSON.stringify(doc, null, 2) + '\n', 'utf8')
+}
+
+const SKIP_DIRS = new Set(['.git', '.obsidian', '.mnemazine'])
+
+// --- Обход vault -------------------------------------------------------------
+// graphify: 'none' — повторяет исключения kb-lint (все graphify-out*, 99 Система/_lint).
+// graphify: 'extra' — грубый обход для --converge: видит любые graphify-out* КРОМЕ
+// рабочего graphify-out (его GRAPH_REPORT.md линкует метки кластеров,
+// а не ноты). Вернувшийся из архива бэкап грубый обход увидит — и
+// замерщики разойдутся, чего требует враждебная проба 3 плана П15.
+// graphify: 'all' — слепок: видит вообще всё.
+async function walkVault(vault, { graphify = 'none' } = {}) {
+ const md = []
+ const dirs = new Set()
+ const fileKeys = new Set()
+ async function walk(dir) {
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ const abs = path.join(dir, item.name)
+ const rel = nfc(path.relative(vault, abs).replace(/\\/g, '/'))
+ if (item.isDirectory()) {
+ if (SKIP_DIRS.has(item.name)) continue
+ if (item.name.startsWith('graphify-out') && graphify !== 'all' && !(graphify === 'extra' && item.name !== 'graphify-out')) continue
+ if (rel === '99 Система/_lint') continue
+ dirs.add(rel)
+ await walk(abs)
+ } else if (item.isFile()) {
+ fileKeys.add(rel)
+ fileKeys.add(nfc(item.name))
+ fileKeys.add(nfc(item.name).replace(/\.md$/i, ''))
+ if (item.name.endsWith('.md')) md.push({ abs, rel })
+ }
+ }
+ }
+ await walk(vault)
+ return { md, dirs, fileKeys }
+}
+
+// Код-блоки гасятся пробелами — позиции не едут (та же дисциплина, что в kb-lint).
+function scanText(text) {
+ return text
+ .replace(/```[\s\S]*?```/g, block => block.replace(/[^\n]/g, ' '))
+ .replace(/`[^`\n]*`/g, block => ' '.repeat(block.length))
+}
+
+function linkTarget(raw) {
+ return nfc(raw.split('|')[0].split('#')[0].split('^')[0].trim().replace(/\\+$/, ''))
+}
+
+// --- Независимый грубый замер битых wikilink ---------------------------------
+// Отдельная реализация (не импорт kb-lint): разрешение цели через плоское
+// множество ключей. Семантика совпадает с kb-lint, код — свой.
+async function roughBrokenCount(vault) {
+ const wiki = await walkVault(vault, { graphify: 'extra' })
+ const resolvable = new Set()
+ for (const key of wiki.dirs) resolvable.add(key)
+ for (const key of wiki.fileKeys) resolvable.add(key)
+ for (const file of wiki.md) {
+ const base = nfc(path.basename(file.rel))
+ resolvable.add(file.rel.replace(/\.md$/i, ''))
+ resolvable.add(base)
+ resolvable.add(base.replace(/\.md$/i, ''))
+ }
+ let broken = 0
+ const brokenTargets = new Map()
+ const linkRe = /\[\[([^\]\n]+)\]\]/g
+ for (const file of wiki.md) {
+ const text = scanText(await fs.readFile(file.abs, 'utf8'))
+ let match
+ while ((match = linkRe.exec(text))) {
+ const target = linkTarget(match[1])
+ if (!target || target.startsWith('#') || /^(https?|mailto):/i.test(target)) continue
+ const base = nfc(path.basename(target))
+ const keys = [target, target.replace(/\.md$/i, ''), base, base.replace(/\.md$/i, '')]
+ if (keys.some(key => resolvable.has(key))) continue
+ broken += 1
+ brokenTargets.set(target, (brokenTargets.get(target) || 0) + 1)
+ }
+ }
+ return { count: broken, targets: brokenTargets }
+}
+
+// --- Слепок ------------------------------------------------------------------
+async function takeSnapshot(vault) {
+ const wiki = await walkVault(vault, { graphify: 'all' })
+ const files = []
+ const weightByTop = new Map()
+ let wikilinksInGraphify = 0
+ let wikilinksOutGraphify = 0
+ const linkRe = /\[\[([^\]\n]+)\]\]/g
+ for (const file of wiki.md) {
+ const buf = await fs.readFile(file.abs)
+ const sha256 = crypto.createHash('sha256').update(buf).digest('hex')
+ const text = buf.toString('utf8')
+ const occurrences = (text.match(linkRe) || []).length
+ const inGraphify = file.rel.split('/').some(part => part.startsWith('graphify-out'))
+ if (inGraphify) wikilinksInGraphify += occurrences
+ else wikilinksOutGraphify += occurrences
+ files.push({ path: file.rel, basename: nfc(path.basename(file.rel)), sha256, bytes: buf.length })
+ }
+ // Вес по каталогам — все файлы, не только .md.
+ async function weigh(dir) {
+ let total = 0
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ const abs = path.join(dir, item.name)
+ if (item.isDirectory()) total += await weigh(abs)
+ else if (item.isFile()) total += (await fs.stat(abs).catch(() => ({ size: 0 }))).size
+ }
+ return total
+ }
+ for (const item of await fs.readdir(vault, { withFileTypes: true })) {
+ const abs = path.join(vault, item.name)
+ const bytes = item.isDirectory() ? await weigh(abs) : (await fs.stat(abs).catch(() => ({ size: 0 }))).size
+ weightByTop.set(nfc(item.name), bytes)
+ }
+ const git = spawnSync('git', ['-C', vault, 'status', '--porcelain'], { encoding: 'utf8', env: { ...process.env, LC_ALL: 'C' } })
+ const gitStatusPaths = git.status === 0 ? git.stdout.split('\n').filter(Boolean).length : null
+ const basenames = [...new Set(files.map(f => f.basename))].sort()
+ const snap = {
+ tool: 'mnemazine-vault-hygiene-check',
+ created_at: new Date().toISOString(),
+ vault,
+ markdown_files: files.length,
+ basenames,
+ files: files.sort((a, b) => a.path < b.path ? -1 : 1),
+ weight_bytes_by_top: Object.fromEntries([...weightByTop.entries()].sort()),
+ wikilinks: { inside_graphify: wikilinksInGraphify, outside_graphify: wikilinksOutGraphify, total: wikilinksInGraphify + wikilinksOutGraphify },
+ git_status_paths: gitStatusPaths
+ }
+ return snap
+}
+
+async function snapshot(outPath) {
+ const snap = await takeSnapshot(resolveVault())
+ await fs.mkdir(path.dirname(path.resolve(outPath)), { recursive: true })
+ await fs.writeFile(outPath, JSON.stringify(snap, null, 2) + '\n', 'utf8')
+ console.log(`слепок записан: ${outPath}`)
+ console.log(`markdown: ${snap.markdown_files}, basename уникальных: ${snap.basenames.length}, git status: ${snap.git_status_paths}`)
+ console.log(`wikilinks: внутри graphify ${snap.wikilinks.inside_graphify}, вне ${snap.wikilinks.outside_graphify}`)
+}
+
+// --- Сверка before-слепка с ЖИВЫМ диском -------------------------------------
+// --compare [before] сверяет before-слепок со свежим срезом vault, который
+// снимается самим --compare в момент запуска. До П15b сравнивались два
+// СОХРАНЁННЫХ JSON — гейт был слеп к подложке в живом vault, если after-слепок
+// не пересняли. Отдельный after-слепок больше не участвует в сверке; при нужде
+// живой срез можно вывести побочно через --after-out .
+// Fail-closed: нет before-слепка (или он битый) → exit 2, сверка без базиса
+// не считается «зелёной».
+// Допустимые новые basename живут в манифесте .mnemazine/state/vault-hygiene-allowed-new.json
+// и читаются самим --compare, без флагов. --allow-new [--reason <текст>] —
+// НЕ обход: он дописывает записи в манифест, после чего сверка идёт по манифесту.
+// Любая другая пропажа/появление → exit 1 с именем.
+async function compare(beforePath) {
+ let before
+ try {
+ before = JSON.parse(await fs.readFile(beforePath, 'utf8'))
+ } catch (err) {
+ console.error(`compare FAIL: нет читаемого before-слепка: ${beforePath} (${err.message})`)
+ process.exit(2)
+ }
+ if (!Array.isArray(before?.basenames)) {
+ console.error(`compare FAIL: before-слепок без массива basenames: ${beforePath}`)
+ process.exit(2)
+ }
+ const vault = resolveVault()
+ if (!existsSync(vault)) {
+ console.error(`compare FAIL: живой vault не существует: ${vault}`)
+ process.exit(2)
+ }
+ const after = await takeSnapshot(vault)
+ console.log(`живой срез снят с диска: ${vault} (${after.markdown_files} markdown, ${after.basenames.length} уникальных basename)`)
+ const afterOut = arg('after-out', '')
+ if (afterOut) {
+ await fs.mkdir(path.dirname(path.resolve(afterOut)), { recursive: true })
+ await fs.writeFile(afterOut, JSON.stringify(after, null, 2) + '\n', 'utf8')
+ console.log(`живой срез записан побочно: ${afterOut}`)
+ }
+ let entries = await readAllowedNew()
+ const cliNew = arg('allow-new', '').split(',').map(s => nfc(s.trim())).filter(Boolean)
+ if (cliNew.length) {
+ const reason = arg('reason', '').trim()
+ if (!reason) { console.error('нужен --reason <причина> вместе с --allow-new: объявление без причины не пишется'); process.exit(2) }
+ const have = new Set(entries.map(e => e.basename))
+ const fresh = cliNew.filter(x => !have.has(x))
+ entries = entries.concat(fresh.map(basename => ({ basename, reason, added: new Date().toISOString().slice(0, 10) })))
+ if (fresh.length) await writeAllowedNew(entries)
+ console.log(`манифест допустимых появлений дополнен (${fresh.length} новых): ${fresh.join(', ') || '—'}`)
+ }
+ const allowNew = new Set(entries.map(e => e.basename))
+ const reasonByName = new Map(entries.map(e => [e.basename, e.reason]))
+ const b = new Set(before.basenames)
+ const a = new Set(after.basenames)
+ const missing = [...b].filter(x => !a.has(x)).sort()
+ const added = [...a].filter(x => !b.has(x)).sort()
+ const undeclared = added.filter(x => !allowNew.has(x))
+ const declared = added.filter(x => allowNew.has(x))
+ for (const name of declared) console.log(`ожидаемая новая (манифест): ${name} — ${reasonByName.get(name) || 'без причины'}`)
+ if (missing.length === 0 && undeclared.length === 0) {
+ console.log(`compare OK: пропавших нет, появившихся сверх объявленных нет (${b.size} имён до)`)
+ process.exit(0)
+ }
+ for (const name of missing) console.log(`ПРОПАЛА: ${name}`)
+ for (const name of undeclared) console.log(`ПОЯВИЛАСЬ (не объявлена): ${name}`)
+ console.error(`compare FAIL: пропало ${missing.length}, появилось необъявленных ${undeclared.length}`)
+ process.exit(1)
+}
+
+// --- Сходимость замерщиков ---------------------------------------------------
+async function converge() {
+ const vault = resolveVault()
+ const run = spawnSync(process.execPath, [KB_LINT, '--json', '--limit=500', '--vault', vault], {
+ encoding: 'utf8', env: { ...process.env, LC_ALL: 'C' }, maxBuffer: 64 * 1024 * 1024
+ })
+ // kb-lint возвращает 1 при critical-находках — это не ошибка запуска, JSON всё равно в stdout.
+ const raw = String(run.stdout || '')
+ const start = raw.indexOf('{')
+ const end = raw.lastIndexOf('}')
+ if (start === -1 || end < start) {
+ console.error('converge FAIL: kb-lint не вернул JSON')
+ console.error(run.stderr || '')
+ process.exit(1)
+ }
+ const lint = JSON.parse(raw.slice(start, end + 1))
+ const lintCount = lint?.checks?.broken_wikilinks?.count
+ if (typeof lintCount !== 'number') {
+ console.error('converge FAIL: в JSON kb-lint нет checks.broken_wikilinks.count')
+ process.exit(1)
+ }
+ const rough = await roughBrokenCount(vault)
+ console.log(`kb-lint: битых wikilink = ${lintCount}`)
+ console.log(`грубый: битых wikilink = ${rough.count}`)
+ if (lintCount === rough.count) {
+ console.log('converge OK: замерщики сошлись')
+ process.exit(0)
+ }
+ const lintTargets = new Map((lint.checks.broken_wikilinks.worst || []).map(item => [item.target, item.count]))
+ console.error(`converge FAIL: расхождение ${Math.abs(lintCount - rough.count)}`)
+ for (const [target, count] of [...rough.targets.entries()].sort((x, y) => y[1] - x[1]).slice(0, 20)) {
+ console.error(` грубый-only/расход: ${target} ×${count} (kb-lint worst: ${lintTargets.get(target) ?? '—'})`)
+ }
+ process.exit(1)
+}
+
+// --- Точка входа -------------------------------------------------------------
+if (flag('snapshot')) {
+ const out = arg('out', '')
+ if (!out) { console.error('нужен --out '); process.exit(2) }
+ await snapshot(out)
+} else if (arg('compare') || argv[0] === '--compare') {
+ const rest = []
+ for (let i = argv.indexOf('--compare') + 1; i < argv.length; i++) {
+ if (argv[i] === '--allow-new' || argv[i] === '--reason' || argv[i] === '--after-out' || argv[i] === '--vault') { i++; continue }
+ if (argv[i].startsWith('--allow-new=') || argv[i].startsWith('--reason=') || argv[i].startsWith('--after-out=')) continue
+ if (argv[i].startsWith('--')) continue
+ rest.push(argv[i])
+ }
+ if (rest.length > 1) {
+ console.error('лишний позиционный аргумент: --compare [before]. after-слепок больше не участвует в сверке — живой срез снимается с диска самим --compare; побочный вывод — --after-out ')
+ process.exit(2)
+ }
+ const beforePath = rest[0] || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '.mnemazine', 'state', 'vault-hygiene-before.json')
+ await compare(beforePath)
+} else if (flag('converge')) {
+ await converge()
+} else {
+ console.log(`mnemazine-vault-hygiene-check.mjs — прибор П15
+ --snapshot --out слепок vault (basename, sha256, веса, wikilinks, git status)
+ --compare [before] basename before-слепка против ЖИВОГО диска (срез снимается
+ самим --compare; иначе exit 1 с именами). Без аргумента before —
+ .mnemazine/state/vault-hygiene-before.json; нет слепка → exit 2;
+ допустимые новые — из .mnemazine/state/vault-hygiene-allowed-new.json
+ --after-out (с --compare) записать живой срез побочным слепком
+ --allow-new --reason <текст> (с --compare) дописать basename в манифест, не обход
+ --converge kb-lint против грубого обхода: одно число битых wikilink (иначе exit 1)
+ --vault переопределить vault (дефолт — нейтральный, см. mnemazine-paths.mjs)`)
+ process.exit(2)
+}
diff --git a/scripts/mnemazine-vault-quality-gate.mjs b/scripts/mnemazine-vault-quality-gate.mjs
index ef9ebf6..3a1d9b0 100755
--- a/scripts/mnemazine-vault-quality-gate.mjs
+++ b/scripts/mnemazine-vault-quality-gate.mjs
@@ -1,10 +1,9 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import path from 'node:path'
-import os from 'node:os'
+import { MIN_CYR_SHARE, SPEC_TYPES, SPEC_SUBJECTS, SPEC_DATA_CLASSES, SPEC_VERIFIED, SPEC_VERIFIED_NORM, TYPE_REQUIRED_FIELDS, normSpecValue } from './mnemazine-note-spec.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
-const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const argv = process.argv.slice(2)
function arg(name, fallback = '') {
@@ -13,10 +12,49 @@ function arg(name, fallback = '') {
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
}
+if (argv.includes('--help')) {
+ console.log(`mnemazine-vault-quality-gate.mjs — гейт качества нот корпуса.
+Без --spec: маркеры сырья + обязательные секции. С --spec: строгая проверка NOTE-SPEC.
+Только читает корпус, ничего не пишет.
+
+Использование: node scripts/mnemazine-vault-quality-gate.mjs [флаги] [файлы...]
+ --vault <путь> корпус (иначе MNEMAZINE_VAULT или repo-local vault)
+ --spec режим NOTE-SPEC (frontmatter enum, блоки, слаги проектов)
+ --json отчёт в JSON
+ --require-dossier требовать полное досье секций (старый режим)
+ --changed-since <время> проверять только ноты, изменённые после отметки
+ --max-failures N остановиться после N провалов
+ --allow-empty разрешить зелёный на пустом наборе (иначе 0 проверенных — exit 2)
+ --help эта справка
+
+Коды возврата: 0 — чисто; 1 — есть провалы; 2 — пустой набор без --allow-empty
+или нечитаемый _ПРОЕКТЫ.md в режиме --spec.`)
+ process.exit(0)
+}
+
const VAULT = resolveVault({ cli: arg('vault') })
+const SPEC_MODE = argv.includes('--spec')
+const JSON_OUT = argv.includes('--json')
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'))
+// fail-closed: ноль проверенных нот (пустой/нечитаемый vault, или changed-since
+// не совпал ни с одним файлом) — это НЕ «сдано 0/0 ✓», а exit 2. Только явный
+// --allow-empty разрешает зелёный на пустом наборе.
+const ALLOW_EMPTY = argv.includes('--allow-empty')
+
+// Flags whose value is the NEXT argv item — without this list positional
+// file arguments are indistinguishable from flag values.
+const VALUE_FLAGS = new Set(['--vault', '--changed-since', '--max-failures'])
+const FILE_ARGS = []
+for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]
+ if (a.startsWith('--')) {
+ if (VALUE_FLAGS.has(a)) i += 1
+ continue
+ }
+ FILE_ARGS.push(path.resolve(a))
+}
function sinceMs(value) {
if (!value) return 0
@@ -62,6 +100,254 @@ async function walk(dir) {
return out
}
+function isServicePath(rel) {
+ // «99 Система» — служебная секция живого корпуса владельца; «00 System» — её
+ // близнец в свежесобранном (публичном) корпусе, куда install.sh кладёт
+ // «Mnemazine Protocol.md». Оба — сервис, не знание: NOTE-SPEC их не судит (П22).
+ return (
+ rel.includes('/graphify-out/') ||
+ rel.includes('/_legacy-index ') ||
+ rel.includes('/_архив-дублей/') ||
+ rel.includes('/Capabilities/_') ||
+ /^99 Система\//.test(rel) ||
+ /^00 System\//.test(rel) ||
+ /(^|\/)_(Содержание|МАСТЕР-ИНДЕКС|ROUTING|ШАБЛОНЫ)\.md$/.test(rel) ||
+ ['AGENTS.md', 'CLAUDE.md', '_ROUTING.md', 'Лог обработки.md'].includes(rel)
+ )
+}
+
+// ── NOTE-SPEC (docs/NOTE-SPEC.md проекта mnemazine) — режим --spec ──
+
+// «не-проверялось» добавлено 2026-07-25 по решению владельца: 1235 старых нот пришли без поля verified
+// или со значением false, и ни одно из пяти прежних значений не описывает «никто не проверял» — впихнуть
+// их в «источник-не-найден» значило бы записать в корпус ложь ради зелёного гейта.
+// НОВАЯ нота это значение носить не должна: конвейер верифицирует материал до записи (стадия 3).
+// ё/е считаются одной буквой при сравнении: «подтверждён» и «подтвержден» —
+// одно слово, а слаги проектов в нотах пишут в обеих орфографиях.
+const norm = s => normSpecValue(s)
+
+function unquote(v) {
+ const m = v.match(/^"(.*)"$/s) || v.match(/^'(.*)'$/s)
+ return m ? m[1] : v
+}
+
+// Минимальный YAML-подмножество-парсер: только то, что реально встречается во
+// frontmatter нот (скаляры, инлайн- и блок-списки). Незнакомая форма = провал,
+// потому что гейт fail-closed. Дубль ключа — провал (дубль YAML-ключа уже был
+// измеренной дырой: вторая строка молча побеждает первую).
+function parseFrontmatter(text) {
+ const lines = text.split('\n')
+ if (!/^---\s*$/.test(lines[0] ?? '')) return { error: 'файл не начинается с ---', body: text }
+ let close = -1
+ for (let i = 1; i < lines.length; i++) {
+ if (/^---\s*$/.test(lines[i])) { close = i; break }
+ }
+ if (close === -1) return { error: 'frontmatter не закрыт второй строкой ---', body: text }
+ const body = lines.slice(close + 1).join('\n')
+ const data = {}
+ let listKey = null
+ for (let i = 1; i < close; i++) {
+ const line = lines[i].replace(/\r$/, '')
+ if (!line.trim() || line.trim().startsWith('#')) continue
+ const kv = line.match(/^([\w.-]+):(?:\s+(.*))?$/)
+ if (kv) {
+ const key = kv[1]
+ if (Object.hasOwn(data, key)) return { error: `дубль ключа «${key}» во frontmatter`, body }
+ const raw = (kv[2] ?? '').trim()
+ if (!raw) {
+ data[key] = []
+ listKey = key
+ } else if (/^\[.*\]$/.test(raw)) {
+ data[key] = raw.slice(1, -1).split(',').map(s => unquote(s.trim())).filter(Boolean)
+ listKey = null
+ } else {
+ data[key] = unquote(raw)
+ listKey = null
+ }
+ continue
+ }
+ const item = line.match(/^\s*-\s+(.*)$/)
+ if (item && listKey) {
+ data[listKey].push(unquote(item[1].trim()))
+ continue
+ }
+ if (/^\s/.test(line)) continue
+ return { error: `непарсибельная строка frontmatter ${i + 1}: «${line.slice(0, 60)}»`, body }
+ }
+ return { data, body }
+}
+
+const scalar = v => (Array.isArray(v) ? '' : String(v ?? '').trim())
+
+function cyrillicShare(body) {
+ const prose = body
+ .replace(/```[\s\S]*?```/g, ' ')
+ .replace(/`[^`\n]*`/g, ' ')
+ .replace(/https?:\/\/\S+/g, ' ')
+ const cyr = (prose.match(/[А-Яа-яЁё]/g) || []).length
+ const lat = (prose.match(/[A-Za-z]/g) || []).length
+ return { cyr, lat, share: cyr + lat ? cyr / (cyr + lat) : 0 }
+}
+
+function sectionBody(body, headingRe) {
+ const lines = body.split('\n')
+ const start = lines.findIndex(l => headingRe.test(l))
+ if (start === -1) return null
+ const out = []
+ for (let i = start + 1; i < lines.length; i++) {
+ if (/^##\s/.test(lines[i])) break
+ out.push(lines[i])
+ }
+ return out.join('\n')
+}
+
+// Источник засчитывается ТОЛЬКО структурно (план П06 шаг 3): непустое значение
+// source: во frontmatter ИЛИ заголовок Source/Источник с непустым телом. Голая
+// подстрока source: в теле файла, в кодовом блоке или в цитате источником не считается.
+function hasStructuredSource(text) {
+ const fm = parseFrontmatter(text)
+ const fmSource = fm.data?.source
+ const fmSourceOk = Array.isArray(fmSource) ? fmSource.some(s => String(s).trim()) : Boolean(scalar(fmSource))
+ if (fmSourceOk) return true
+ // (?:\s|$), не \b: JS \b — ASCII-only, после кириллицы («Источники») не срабатывает.
+ const heading = sectionBody(fm.body ?? text, /^#{2,}\s+(Source|Sources|Источник|Источники)(?:\s|$)/i)
+ return heading !== null && heading.trim().length > 0
+}
+
+// Слаги проектов — только грепом ## заголовков _ПРОЕКТЫ.md, не хардкод.
+// Однословные имена проектов покрыты полным заголовком;
+// из многословных дополнительно берутся «кавычечные» имена и латинские токены
+// ≥5 символов — кириллические токены («Просто»,
+// «партнеры») дают ложные совпадения с обычной прозой, поэтому исключены.
+function projectSlugs(text) {
+ const slugs = new Set()
+ for (const [, h] of text.matchAll(/^##\s+(.+?)\s*$/gm)) {
+ slugs.add(norm(h))
+ for (const [, q] of h.matchAll(/«([^»]+)»/g)) slugs.add(norm(q))
+ for (const t of h.split(/\s+/)) {
+ const tok = t.replace(/[«»()"'.,:;]/g, '')
+ if (tok.length >= 5 && /[A-Za-z]/.test(tok)) slugs.add(norm(tok))
+ }
+ }
+ return [...slugs]
+}
+
+function checkSpec(text, slugs, changedSince = false) {
+ const reasons = []
+ const fm = parseFrontmatter(text)
+ if (fm.error) reasons.push(`frontmatter: ${fm.error}`)
+ else {
+ const data = fm.data
+ const source = data.source
+ const sourceOk = Array.isArray(source) ? source.some(s => String(s).trim()) : Boolean(scalar(source))
+ if (!sourceOk) reasons.push('source: пуст или отсутствует')
+ const type = scalar(data.type)
+ if (!SPEC_TYPES.has(type)) reasons.push(`type: «${type || '—'}» вне enum спеки (${[...SPEC_TYPES].join(' | ')})`)
+ const verifiedRaw = scalar(data.verified)
+ if (!SPEC_VERIFIED_NORM.has(norm(verifiedRaw))) reasons.push(`verified: «${verifiedRaw || '—'}» вне enum спеки (${SPEC_VERIFIED.join(' | ')})`)
+ for (const key of TYPE_REQUIRED_FIELDS[type] || []) {
+ const v = data[key]
+ const ok = Array.isArray(v) ? v.length > 0 : Boolean(scalar(v))
+ if (!ok) reasons.push(`type: ${type} требует непустое поле ${key}`)
+ }
+ // subject (мастер §18): нота различает «факт о мире» и «факт обо мне».
+ // (а) значение вне закрытого списка → провал ВСЕГДА;
+ // (б) отсутствие поля → провал ТОЛЬКО в проходах с --changed-since (новая нота
+ // обязана нести поле; старый корпус до переогранки П16 за отсутствие не карается);
+ // (в) subject: self при source_type video|article|repo → self-нота с чужим источником (§18.4).
+ const subject = scalar(data.subject)
+ if (subject) {
+ if (!SPEC_SUBJECTS.has(subject)) {
+ reasons.push(`subject: «${subject}» вне закрытого списка (${[...SPEC_SUBJECTS].join(' | ')})`)
+ } else if (subject === 'self') {
+ const sourceType = scalar(data.source_type)
+ if (['video', 'article', 'repo'].includes(sourceType)) reasons.push(`subject: self при source_type: ${sourceType} — self-нота с чужим источником (§18.4)`)
+ }
+ } else if (changedSince) {
+ reasons.push('subject: отсутствует (обязателен для новой/изменённой ноты)')
+ }
+
+ // data_class (§17.8, П24): необязательное; если есть — из закрытого списка
+ // config/data-classes.json. Отсутствие дефектом НЕ считается — класс тогда
+ // берут правила по разделу и наследование от источника (machine-class-gate).
+ const dataClass = scalar(data.data_class)
+ if (dataClass && SPEC_DATA_CLASSES && !SPEC_DATA_CLASSES.has(dataClass)) {
+ reasons.push(`data_class: «${dataClass}» вне закрытого списка config/data-classes.json (${[...SPEC_DATA_CLASSES].join(' | ')})`)
+ }
+ }
+ const body = fm.body
+ const { cyr, lat, share } = cyrillicShare(body)
+ if (share < MIN_CYR_SHARE) reasons.push(`кириллица ${(share * 100).toFixed(1)}% прозы (< 30%): ${cyr} кир. против ${lat} лат. букв`)
+ const help = sectionBody(body, /^#{2,3}\s+(?:🎯\s*)?Как (?:это )?поможет мне\s*$/)
+ if (help === null) reasons.push('нет блока «Как это поможет мне»')
+ else {
+ const normHelp = norm(help)
+ if (!slugs.some(s => normHelp.includes(s))) reasons.push('блок «Как это поможет мне» не упоминает ни один проект из «99 Система/_ПРОЕКТЫ.md»')
+ }
+ const dost = sectionBody(body, /^##\s+Достоверность\s*$/)
+ if (dost === null) reasons.push('нет блока «Достоверность»')
+ else if (!dost.trim()) reasons.push('блок «Достоверность» пуст')
+ return reasons
+}
+
+if (SPEC_MODE) {
+ const projectsFile = path.join(VAULT, '99 Система', '_ПРОЕКТЫ.md')
+ // fail-closed: файла проектов нет или он нечитаем → exit 2, а не стек-трейс ENOENT
+ // и код 1. Без списка слагов гейт не может судить блок «Как это поможет мне».
+ let projectsText
+ try {
+ projectsText = await fs.readFile(projectsFile, 'utf8')
+ } catch (error) {
+ console.error(`Не прочитан ${projectsFile} (${error.code || error.message}) — режим --spec судить корпус не может`)
+ process.exit(2)
+ }
+ const slugs = projectSlugs(projectsText)
+ if (!slugs.length) {
+ console.error(`Ни одного ## заголовка в ${projectsFile} — гейт не может судить блок «Как это поможет мне»`)
+ process.exit(2)
+ }
+ let targets = FILE_ARGS
+ if (!targets.length) {
+ targets = []
+ for (const file of await walk(VAULT)) {
+ if (isServicePath(path.relative(VAULT, file))) continue
+ if (CHANGED_SINCE_MS && (await fs.stat(file)).mtimeMs < CHANGED_SINCE_MS) continue
+ targets.push(file)
+ }
+ }
+ const failures = []
+ let checked = 0
+ for (const file of targets) {
+ checked += 1
+ const text = await fs.readFile(file, 'utf8')
+ // Naming files explicitly means "check these fresh/touched notes", same
+ // contract as --changed-since. Without this the subject rule (§18) stayed
+ // silent in per-file mode and 64 notes shipped without `subject:`.
+ const reasons = checkSpec(text, slugs, CHANGED_SINCE_MS > 0 || FILE_ARGS.length > 0)
+ if (reasons.length) {
+ failures.push({ file: path.relative(VAULT, file), reasons })
+ if (MAX_FAILURES > 0 && failures.length >= MAX_FAILURES) break
+ }
+ }
+ if (checked === 0 && !ALLOW_EMPTY) {
+ console.error('vault пуст или нечитаем: 0 проверенных (--allow-empty чтобы разрешить)')
+ process.exit(2)
+ }
+ const report = { ok: failures.length === 0, mode: 'spec', checked, failures }
+ if (JSON_OUT) {
+ ;(failures.length ? console.error : console.log)(JSON.stringify(report, null, 2))
+ } else {
+ for (const f of failures) {
+ console.error(`FAIL ${f.file}`)
+ for (const r of f.reasons) console.error(` - ${r}`)
+ }
+ ;(failures.length ? console.error : console.log)(`spec: проверено ${checked}, провалов ${failures.length}`)
+ }
+ process.exit(failures.length ? 1 : 0)
+}
+
+// ── Старый режим (без --spec): маркеры сырья + обязательные секции ──
+
const files = await walk(VAULT)
const failures = []
let checked = 0
@@ -69,22 +355,18 @@ 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)
- if (
- rel.includes('/graphify-out/') ||
- rel.includes('/_legacy-index ') ||
- rel.includes('/_архив-дублей/') ||
- rel.includes('/Capabilities/_') ||
- /^99 Система\//.test(rel) ||
- /(^|\/)_(Содержание|МАСТЕР-ИНДЕКС|ROUTING|ШАБЛОНЫ)\.md$/.test(rel) ||
- ['AGENTS.md', 'CLAUDE.md', '_ROUTING.md', 'Лог обработки.md'].includes(rel)
- ) continue
+ if (isServicePath(rel)) continue
checked += 1
const text = await fs.readFile(file, 'utf8')
- if (/^##\s+Атомизировано(?:\s|$)/m.test(text)) continue
+ // «## Атомизировано» больше НЕ освобождает ноту от суда (план П06 шаг 1):
+ // сырьё (badMarkers), отсутствие источника и смыслового блока валят её как любую
+ // другую. Единственное смягчение — при --require-dossier такая нота не обязана
+ // нести шесть секций старого досье: это другой формат, а не индульгенция.
+ const atomized = /^##\s+Атомизировано(?:\s|$)/m.test(text)
const hit = badMarkers.find(re => re.test(text))
- const hasSource = /#{2,}\s+(Source|Sources|Источник|Источники|Источники и подтверждения)(?:\s|$)|source:/i.test(text)
- const hasMeaning = /#{2,}\s+(What This Is|Что это|Что это и зачем|Суть|Полное объяснение)(?:\s|$)/i.test(text)
- const missingDossier = REQUIRE_DOSSIER
+ const hasSource = hasStructuredSource(text)
+ const hasMeaning = /#{2,}\s+(What This Is|Что это|Что это и зачем|Суть|Полное объяснение|Короткий ответ|Короткий вывод|Кратко|Главное|Главный вывод)(?:\s|$)/i.test(text)
+ const missingDossier = (REQUIRE_DOSSIER && !atomized)
? [
['Короткий ответ', /^##\s+Короткий ответ(?:\s|$)/m],
['Полное объяснение', /^##\s+Полное объяснение(?:\s|$)/m],
@@ -100,6 +382,11 @@ for (const file of files) {
}
}
+if (checked === 0 && !ALLOW_EMPTY) {
+ console.error('vault пуст или нечитаем: 0 проверенных (--allow-empty чтобы разрешить)')
+ process.exit(2)
+}
+
if (failures.length) {
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)
diff --git a/scripts/mnemazine-verify.mjs b/scripts/mnemazine-verify.mjs
index 1687e09..ee2ed75 100644
--- a/scripts/mnemazine-verify.mjs
+++ b/scripts/mnemazine-verify.mjs
@@ -141,7 +141,7 @@ ${fenceUntrusted('CLAIM', String(claim).slice(0, 4000))}
SOURCES:
${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'], label: options.label || 'verify:claim' })
let status = ['verified', 'assumed', 'unknown'].includes(res?.status) ? res.status : 'unknown'
if (status === 'verified' && !live.length) status = 'unknown'
const checked = Array.isArray(res?.checked) ? res.checked.filter(isPublicHttpUrl) : []
diff --git a/scripts/mnemazine-weekly-state.mjs b/scripts/mnemazine-weekly-state.mjs
index 64379e8..d91d379 100644
--- a/scripts/mnemazine-weekly-state.mjs
+++ b/scripts/mnemazine-weekly-state.mjs
@@ -22,7 +22,8 @@ function arg(name, fallback = '') {
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
}
-const VAULT = resolveVault({ cli: arg('vault') })
+const SELFTEST = argv.includes('--selftest')
+const VAULT = SELFTEST ? '' : resolveVault({ cli: arg('vault') })
// Default state dir matches README:224 (~/Desktop/Mnemazine/.mnemazine/state),
// the canonical pickup for the weekly-brief export. Override with MNEMAZINE_STATE
// / --state-dir, or point --state straight at the downloaded file.
@@ -110,7 +111,7 @@ function spawnRunner(root) {
}
async function main() {
- if (argv.includes('--selftest')) return selftest()
+ if (SELFTEST) return selftest()
const state = JSON.parse(await fs.readFile(STATE_FILE, 'utf8').catch(() => '{}'))
const result = { read: 0, work: 0, forget: 0, missing: 0, invalid: 0 }
for (const [id, action] of Object.entries(state)) {
diff --git a/scripts/mnemazine-wiki-link-cleanup.mjs b/scripts/mnemazine-wiki-link-cleanup.mjs
new file mode 100644
index 0000000..65b5435
--- /dev/null
+++ b/scripts/mnemazine-wiki-link-cleanup.mjs
@@ -0,0 +1,486 @@
+#!/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 { resolveVault } from './mnemazine-paths.mjs'
+
+const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
+const argv = process.argv.slice(2)
+
+function arg(name, fallback = '') {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
+}
+
+function flag(name) {
+ return argv.includes(`--${name}`)
+}
+
+function norm(value) {
+ return String(value || '')
+ .replace(/\\+$/g, '')
+ .replace(/\.md$/i, '')
+ .replace(/[—–]/g, '-')
+ .replace(/\s+/g, ' ')
+ .trim()
+}
+
+function stripDate(value) {
+ return norm(value)
+ .replace(/^\d{4}-\d{2}-\d{2}\s*[-—–]\s*/, '')
+ .replace(/-\d+$/, '')
+ .trim()
+}
+
+function frontmatterValue(text, key) {
+ const match = text.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'))
+ if (!match) return ''
+ return match[1].trim().replace(/^['"]|['"]$/g, '')
+}
+
+function frontmatterAliases(text) {
+ const out = []
+ const inline = text.match(/^aliases:\s*\[([^\]]+)\]/m)
+ if (inline) out.push(...inline[1].split(',').map(item => item.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean))
+ const block = text.match(/^aliases:\s*\n((?:\s+-\s+.+\n?)+)/m)
+ if (block) {
+ out.push(...block[1].split('\n')
+ .map(line => line.replace(/^\s+-\s+/, '').trim().replace(/^['"]|['"]$/g, ''))
+ .filter(Boolean))
+ }
+ return out
+}
+
+function addIndex(index, key, file) {
+ const normalized = norm(key)
+ if (!normalized) return
+ if (!index.has(normalized)) index.set(normalized, new Set())
+ index.get(normalized).add(file)
+}
+
+function targetParts(raw) {
+ const display = String(raw || '').trim()
+ const target = display.split('|')[0].split('#')[0].split('^')[0].trim()
+ return { display, target, normalized: norm(target) }
+}
+
+function linkScanText(text) {
+ return String(text || '')
+ .replace(/```[\s\S]*?```/g, block => block.replace(/[^\n]/g, ' '))
+ .replace(/`[^`\n]*`/g, block => ' '.repeat(block.length))
+}
+
+function sectionOf(file) {
+ return file.includes('/') ? file.split('/')[0] : '(root)'
+}
+
+function classifyTarget(target) {
+ const clean = target.trim()
+ if (!clean || ['...', '…', 'note', 'Название'].includes(clean)) return 'placeholder'
+ if (/\\$/.test(clean)) return 'escaped-link'
+ if (/\.(pdf|docx?|xlsx?|pptx?|png|jpe?g|webp|heic|mov|mp4|canvas)$/i.test(clean)) return 'file-or-asset'
+ if (clean.includes('/')) return 'path-link'
+ if (/^[A-ZА-ЯЁ0-9 _-]{2,}$/i.test(clean) && clean.length <= 40) return 'concept'
+ return 'missing-note'
+}
+
+function suggestedAction(kind) {
+ if (kind === 'placeholder') return 'удалить placeholder или заменить на реальную заметку'
+ if (kind === 'escaped-link') return 'убрать лишний escape/backslash или пересобрать индекс'
+ if (kind === 'file-or-asset') return 'заменить wiki-link на обычный путь/markdown-link или создать заметку-обёртку'
+ if (kind === 'path-link') return 'уточнить путь до существующей заметки или заменить на текстовую ссылку'
+ if (kind === 'concept') return 'создать короткую понятиевую заметку или заменить на обычный текст'
+ return 'найти новое имя заметки, создать мост или удалить ссылку'
+}
+
+function yamlString(value) {
+ return JSON.stringify(String(value || ''))
+}
+
+function safeRelTarget(target) {
+ const clean = targetParts(target).target
+ if (!clean || clean.startsWith('/') || clean.split('/').some(part => part === '..')) return ''
+ return `${clean.replace(/\.md$/i, '')}.md`
+}
+
+function bridgeTitle(target) {
+ return path.basename(targetParts(target).target).replace(/\.md$/i, '') || 'Wiki link bridge'
+}
+
+function shouldPlainText(target, kind) {
+ const clean = targetParts(target).target
+ return kind === 'placeholder' ||
+ kind === 'escaped-link' ||
+ kind === 'file-or-asset' ||
+ clean.startsWith('artifacts/') ||
+ /(?:^|[\s"`])[$][A-Z_]+/.test(clean) ||
+ /[<>=~]/.test(clean)
+}
+
+function plainReplacement(target, kind) {
+ const clean = targetParts(target).target.replace(/\\+$/g, '').trim()
+ if (kind === 'placeholder') return clean === '…' ? '...' : clean
+ if (kind === 'file-or-asset' || clean.startsWith('artifacts/')) return `\`${clean}\``
+ if (/[<>=~]/.test(clean)) return `\`${clean}\``
+ return clean
+}
+
+function bridgeNote(target, kind) {
+ const clean = targetParts(target).target.replace(/\\+$/g, '').trim()
+ const title = bridgeTitle(clean)
+ const isPath = clean.includes('/')
+ const aliasLines = [...new Set([clean, title, stripDate(title)].filter(Boolean))]
+ .map(alias => ` - ${yamlString(alias)}`)
+ .join('\n')
+ const noteKind = isPath ? 'точного пути' : kind === 'concept' ? 'понятия' : 'старой ссылки'
+ return `---
+title: ${yamlString(title)}
+type: "knowledge-note"
+source_type: "wiki-link-bridge"
+source_ref: "wiki-link-cleanup:${new Date().toISOString().slice(0, 10)}"
+verified: false
+verification_status: "unknown"
+status: "bridge"
+aliases:
+${aliasLines}
+---
+
+# ${title}
+
+## Что это
+
+Это мостовая заметка для ${noteKind} \`${clean}\`. Она нужна, чтобы старая wiki-ссылка в базе знаний вела в живой узел, а не оставалась битой.
+
+## Зачем это нужно
+
+В vault много исторических ссылок из digest, старых заметок и автоматических синтезов. Мост сохраняет навигацию и не выдаёт себя за новый проверенный источник.
+
+## Как использовать
+
+- Если тема стала рабочей, заменить этот мост полноценной заметкой.
+- Если ссылка была только техническим хвостом digest, оставить мост как совместимость.
+- Если рядом найдена лучшая целевая заметка, перенести alias туда и удалить этот мост.
+
+## Источники
+
+- Внутренний отчёт Mnemazine: \`npm run wiki:links\`.
+- Тип цели: \`${kind}\`.
+- Исходная цель: \`${clean}\`.
+
+## Проверка
+
+Статус: навигационный мост, внешняя факт-проверка не требуется. Содержательные утверждения надо брать из связанных заметок, не из этого файла.
+
+## Связанные заметки
+
+- Протокол Мнемозина.
+
+## Следующее действие
+
+При ближайшей ручной чистке заменить мост на полноценный атом знания или привязать alias к существующей заметке.
+`
+}
+
+async function rewritePlainLinks(vault, targets) {
+ const changes = []
+ const byFile = new Map()
+ for (const target of targets) {
+ for (const example of target.examples || []) {
+ const rel = example.file
+ if (!byFile.has(rel)) byFile.set(rel, [])
+ byFile.get(rel).push({ display: example.display, target: target.target, kind: target.kind })
+ }
+ }
+
+ for (const [rel, items] of byFile) {
+ const file = path.join(vault, rel)
+ let text = await fs.readFile(file, 'utf8')
+ const before = text
+ for (const item of items) {
+ const escapedDisplay = item.display.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ text = text.replace(new RegExp(`\\[\\[${escapedDisplay}\\]\\]`, 'g'), plainReplacement(item.target, item.kind))
+ }
+ text = text.replace(/\[\[([^\]\n]*?)\\+\]\]/g, (_, inner) => `[[${inner.trim()}]]`)
+ if (text !== before) {
+ await fs.writeFile(file, text, 'utf8')
+ changes.push(rel)
+ }
+ }
+ return changes
+}
+
+async function createBridgeNotes(vault, targets) {
+ const created = []
+ const skipped = []
+ for (const target of targets) {
+ if (shouldPlainText(target.target, target.kind)) continue
+ const rel = target.target.includes('/')
+ ? safeRelTarget(target.target)
+ : path.posix.join('99 Система', 'Wiki Link Bridges', `${bridgeTitle(target.target)}.md`)
+ if (!rel) {
+ skipped.push({ target: target.target, reason: 'unsafe path' })
+ continue
+ }
+ const file = path.join(vault, rel)
+ if (existsSync(file)) {
+ skipped.push({ target: target.target, reason: 'exists', file: rel })
+ continue
+ }
+ await fs.mkdir(path.dirname(file), { recursive: true })
+ await fs.writeFile(file, bridgeNote(target.target, target.kind), 'utf8')
+ created.push(rel)
+ }
+ return { created, skipped }
+}
+
+async function applyCleanup({ vault, reportsDir, limit }) {
+ const first = await runAudit({ vault, reportsDir, limit })
+ const targets = first.report.targets
+ const plainTargets = targets.filter(item => shouldPlainText(item.target, item.kind))
+ const rewritten = await rewritePlainLinks(vault, plainTargets)
+ const mid = await runAudit({ vault, reportsDir, limit })
+ const bridges = await createBridgeNotes(vault, mid.report.targets)
+ const second = await runAudit({ vault, reportsDir, limit })
+ return { before: first.report.broken, after: second.report.broken, rewritten, bridges, report: second }
+}
+
+async function collectVault(vault) {
+ const files = []
+ const dirs = new Set([''])
+
+ async function walk(dir) {
+ for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ if (['.git', '.obsidian', '.mnemazine'].includes(item.name) || item.name.startsWith('graphify-out')) continue
+ const file = path.join(dir, item.name)
+ const rel = path.relative(vault, file).replace(/\\/g, '/')
+ if (item.isDirectory()) {
+ dirs.add(rel)
+ await walk(file)
+ } else if (item.isFile() && item.name.endsWith('.md')) {
+ files.push(file)
+ }
+ }
+ }
+
+ await walk(vault)
+ return { files, dirs }
+}
+
+function buildIndex(vault, files, dirs) {
+ const index = new Map()
+ for (const file of files) {
+ const rel = path.relative(vault, file).replace(/\\/g, '/')
+ const withoutExt = rel.replace(/\.md$/, '')
+ const basename = path.basename(withoutExt)
+ const text = linkScanText(readFileSync(file, 'utf8'))
+ for (const key of [
+ rel,
+ withoutExt,
+ basename,
+ stripDate(basename),
+ frontmatterValue(text, 'title'),
+ ...frontmatterAliases(text)
+ ]) {
+ addIndex(index, key, rel)
+ }
+ }
+ return { index, dirs }
+}
+
+function targetExists(target, wiki) {
+ const { normalized } = targetParts(target)
+ if (!normalized || normalized.startsWith('#') || /^https?:\/\//i.test(normalized)) return true
+ if (wiki.dirs.has(normalized) || wiki.index.has(normalized)) return true
+ const basename = path.basename(normalized)
+ return wiki.index.has(basename) || wiki.index.has(stripDate(basename))
+}
+
+function collectBrokenLinks(vault, files, wiki) {
+ const byTarget = new Map()
+ const bySection = new Map()
+ const byFile = new Map()
+ const linkRe = /\[\[([^\]\n]+)\]\]/g
+ let totalLinks = 0
+
+ for (const file of files) {
+ const rel = path.relative(vault, file).replace(/\\/g, '/')
+ const text = linkScanText(readFileSync(file, 'utf8'))
+ let match
+ while ((match = linkRe.exec(text))) {
+ totalLinks += 1
+ const { display, target } = targetParts(match[1])
+ if (targetExists(target, wiki)) continue
+
+ const line = text.slice(0, match.index).split('\n').length
+ const kind = classifyTarget(target)
+ const hit = { file: rel, line, target, display, section: sectionOf(rel), kind }
+
+ if (!byTarget.has(target)) byTarget.set(target, { target, kind, action: suggestedAction(kind), count: 0, files: new Set(), examples: [] })
+ const group = byTarget.get(target)
+ group.count += 1
+ group.files.add(rel)
+ if (group.examples.length < 5) group.examples.push({ file: rel, line, display })
+
+ if (!bySection.has(hit.section)) bySection.set(hit.section, { section: hit.section, count: 0, targets: new Set(), files: new Set() })
+ const sec = bySection.get(hit.section)
+ sec.count += 1
+ sec.targets.add(target)
+ sec.files.add(rel)
+
+ if (!byFile.has(rel)) byFile.set(rel, { file: rel, section: hit.section, count: 0, targets: [] })
+ const fileGroup = byFile.get(rel)
+ fileGroup.count += 1
+ if (fileGroup.targets.length < 20) fileGroup.targets.push({ line, target, kind })
+ }
+ }
+
+ const targets = [...byTarget.values()]
+ .map(item => ({ ...item, files: [...item.files], file_count: item.files.size }))
+ .sort((a, b) => b.count - a.count || a.target.localeCompare(b.target))
+ const sections = [...bySection.values()]
+ .map(item => ({ section: item.section, count: item.count, unique_targets: item.targets.size, files: item.files.size }))
+ .sort((a, b) => b.count - a.count || a.section.localeCompare(b.section))
+ const filesOut = [...byFile.values()]
+ .sort((a, b) => b.count - a.count || a.file.localeCompare(b.file))
+
+ return { totalLinks, targets, sections, files: filesOut }
+}
+
+function renderMarkdown(report, limit) {
+ const lines = []
+ lines.push(`# Wiki-link cleanup — ${report.date}`, '')
+ lines.push('## Сводка', '')
+ lines.push(`- Vault: \`${report.vault}\``)
+ lines.push(`- Markdown files: ${report.checked.markdown_files}`)
+ lines.push(`- Wiki links scanned: ${report.checked.wiki_links}`)
+ lines.push(`- Broken links: ${report.broken.total}`)
+ lines.push(`- Unique targets: ${report.broken.unique_targets}`)
+ lines.push(`- Files with broken links: ${report.broken.files}`)
+ lines.push('')
+ lines.push('## Разделы', '')
+ for (const section of report.sections.slice(0, limit)) {
+ lines.push(`- ${section.section}: ${section.count} links · ${section.unique_targets} targets · ${section.files} files`)
+ }
+ lines.push('', '## Очередь по целям', '')
+ for (const target of report.targets.slice(0, limit)) {
+ lines.push(`### ${target.target}`)
+ lines.push('')
+ lines.push(`- Тип: ${target.kind}`)
+ lines.push(`- Вхождений: ${target.count}`)
+ lines.push(`- Файлов: ${target.file_count}`)
+ lines.push(`- Действие: ${target.action}`)
+ lines.push('- Примеры:')
+ for (const example of target.examples) lines.push(` - \`${example.file}:${example.line}\` — \`[[${example.display}]]\``)
+ lines.push('')
+ }
+ lines.push('## Очередь по файлам', '')
+ for (const file of report.files.slice(0, limit)) {
+ lines.push(`### ${file.file}`)
+ lines.push('')
+ lines.push(`- Broken links: ${file.count}`)
+ for (const target of file.targets.slice(0, 10)) lines.push(`- L${target.line}: \`[[${target.target}]]\` (${target.kind})`)
+ lines.push('')
+ }
+ return `${lines.join('\n').trim()}\n`
+}
+
+async function runAudit({ vault, reportsDir, limit }) {
+ const { files, dirs } = await collectVault(vault)
+ const wiki = buildIndex(vault, files, dirs)
+ const broken = collectBrokenLinks(vault, files, wiki)
+ const date = new Date().toISOString().slice(0, 10)
+ const report = {
+ ok: true,
+ date,
+ vault,
+ checked: {
+ markdown_files: files.length,
+ wiki_links: broken.totalLinks
+ },
+ broken: {
+ total: broken.targets.reduce((sum, item) => sum + item.count, 0),
+ unique_targets: broken.targets.length,
+ files: broken.files.length
+ },
+ sections: broken.sections,
+ targets: broken.targets,
+ files: broken.files
+ }
+
+ await fs.mkdir(reportsDir, { recursive: true })
+ const base = path.join(reportsDir, `${date}-wiki-link-cleanup`)
+ const json = `${base}.json`
+ const md = `${base}.md`
+ await fs.writeFile(json, `${JSON.stringify(report, null, 2)}\n`, 'utf8')
+ await fs.writeFile(md, renderMarkdown(report, limit), 'utf8')
+ return { report, json, md }
+}
+
+async function selftest() {
+ const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-wiki-cleanup-'))
+ const vault = path.join(temp, 'vault')
+ const reports = path.join(temp, 'reports')
+ await fs.mkdir(path.join(vault, '01 Concepts'), { recursive: true })
+ await fs.writeFile(path.join(vault, '01 Concepts', 'target.md'), `---
+title: "Живая цель"
+aliases: ["Алиас цели"]
+---
+
+# Живая цель
+`, 'utf8')
+ await fs.writeFile(path.join(vault, '01 Concepts', 'source.md'), `# Source
+
+Живая ссылка: [[Алиас цели]].
+Битая ссылка: [[Несуществующая цель]].
+Placeholder: [[...]].
+Asset: [[artifacts/final.pdf]].
+Escaped: [[2026-05-29 — Kronos\\]].
+`, 'utf8')
+ const { report } = await runAudit({ vault, reportsDir: reports, limit: 10 })
+ if (report.broken.total !== 4) throw new Error(`selftest expected 4 broken links, got ${report.broken.total}`)
+ if (!report.targets.some(item => item.target === 'Несуществующая цель')) throw new Error('selftest missed missing target')
+ if (!report.targets.some(item => item.kind === 'placeholder')) throw new Error('selftest missed placeholder target')
+ const applied = await applyCleanup({ vault, reportsDir: reports, limit: 10 })
+ if (applied.after.total !== 0) throw new Error(`selftest apply expected 0 broken links, got ${applied.after.total}: ${applied.report.report.targets.map(item => item.target).join(', ')}`)
+ console.log(JSON.stringify({ ok: true, selftest: true }, null, 2))
+}
+
+if (flag('selftest')) {
+ await selftest()
+} else {
+ const vault = resolveVault({ cli: arg('vault') })
+ const reportsDir = path.resolve(arg('reports', process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')))
+ const limit = Number(arg('limit', '50'))
+ if (flag('apply')) {
+ const result = await applyCleanup({ vault, reportsDir, limit })
+ console.log(JSON.stringify({
+ ok: result.after.total === 0,
+ vault,
+ before: result.before,
+ after: result.after,
+ rewritten_files: result.rewritten.length,
+ created_bridge_notes: result.bridges.created.length,
+ skipped: result.bridges.skipped.length,
+ report: {
+ json: path.relative(ROOT, result.report.json),
+ md: path.relative(ROOT, result.report.md)
+ }
+ }, null, 2))
+ if (result.after.total !== 0) process.exit(1)
+ } else {
+ const { report, json, md } = await runAudit({ vault, reportsDir, limit })
+ const output = {
+ ok: true,
+ vault,
+ broken: report.broken,
+ sections: report.sections.slice(0, 10),
+ report: {
+ json: path.relative(ROOT, json),
+ md: path.relative(ROOT, md)
+ }
+ }
+ console.log(JSON.stringify(output, null, 2))
+ }
+}
diff --git a/scripts/mnemozina-session-review.mjs b/scripts/mnemozina-session-review.mjs
new file mode 100755
index 0000000..a59f63c
--- /dev/null
+++ b/scripts/mnemozina-session-review.mjs
@@ -0,0 +1,189 @@
+#!/usr/bin/env node
+import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'
+import { existsSync } from 'node:fs'
+import { join } from 'node:path'
+
+// No default vault path: a fallback here would write one person's layout into
+// everyone's install. Say what is missing and stop.
+const VAULT = process.env.MNEMAZINE_VAULT
+if (!VAULT) {
+ console.error('MNEMAZINE_VAULT не задан — укажите путь к своему vault и повторите.')
+ process.exit(1)
+}
+const SYS = join(VAULT, '99 Система')
+const OBS_LOG = join(SYS, '_run-observability.jsonl')
+const LEDGER = join(SYS, '_session-learning-ledger.jsonl')
+const REPORT = join(SYS, '_last-session-review.md')
+
+const argv = process.argv.slice(2)
+const arg = (name, fallback = '') => {
+ const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
+ if (!hit) return fallback
+ if (hit.includes('=')) return hit.split('=').slice(1).join('=')
+ const idx = argv.indexOf(hit)
+ return argv[idx + 1] || fallback
+}
+
+const RUN_ID = arg('run-id', process.env.MNEMAZINE_RUN_ID || 'unknown')
+const RUNTIME = arg('runtime', process.env.MNEMAZINE_RUNTIME || 'unknown')
+const TOKEN_JSON = arg('token-json', '')
+const RESULT_JSON = arg('result-json', '')
+
+function parseJson(value, fallback = null) {
+ if (!value) return fallback
+ try { return JSON.parse(value) } catch { return fallback }
+}
+
+function compact(value, n = 240) {
+ return String(value || '').replace(/\s+/g, ' ').trim().slice(0, n)
+}
+
+function numberFromTokens(value) {
+ const raw = String(value || '').replace(/[^0-9]/g, '')
+ return raw ? Number(raw) : null
+}
+
+const tokenUsage = parseJson(TOKEN_JSON, {})
+const result = parseJson(RESULT_JSON, {})
+const lines = existsSync(OBS_LOG) ? (await readFile(OBS_LOG, 'utf8')).split('\n').filter(Boolean) : []
+const samples = lines.map(line => {
+ try { return JSON.parse(line) } catch { return null }
+}).filter(row => row && row.run_id === RUN_ID)
+
+const nums = samples.map(row => numberFromTokens(row.tokens)).filter(n => Number.isFinite(n))
+const startTokens = tokenUsage.start_tokens ?? (nums.length ? nums[0] : null)
+const endTokens = tokenUsage.end_tokens ?? (nums.length ? nums[nums.length - 1] : null)
+const deltaTokens = tokenUsage.delta_tokens ?? tokenUsage.total_tokens ?? (
+ startTokens != null && endTokens != null ? endTokens - startTokens : null
+)
+
+const localRuns = Array.isArray(tokenUsage.local_runs) ? tokenUsage.local_runs : []
+const cloudRuns = Array.isArray(tokenUsage.runs) ? tokenUsage.runs : []
+const localLabels = new Set(localRuns.map(r => r.label).filter(Boolean))
+const cloudLabels = new Set(cloudRuns.map(r => r.label).filter(Boolean))
+const localFirstLabels = ['ocr-pass', 'transcribe-pass', 'triage', 'process', 'store', 'hash-record', 'embed-add', 'graphify', 'briefing']
+const localFirstViolations = localFirstLabels.filter(label => cloudLabels.has(label) && !localLabels.has(label))
+
+const errors = []
+if (result && result.error) errors.push(String(result.error))
+if (Array.isArray(result?.unaccounted) && result.unaccounted.length) {
+ errors.push(`unaccounted:${result.unaccounted.length}`)
+}
+if (result && result.balanced === false) errors.push('coverage_not_balanced')
+if (localFirstViolations.length) errors.push(`local_first_violations:${localFirstViolations.join(',')}`)
+if (deltaTokens != null && deltaTokens > 0 && cloudRuns.length === 0 && RUNTIME.includes('codex')) {
+ errors.push('token_delta_without_cloud_runs')
+}
+
+const tokenSummary = {
+ runtime: RUNTIME,
+ run_id: RUN_ID,
+ source: tokenUsage.source || (tokenUsage.runtime === 'codex' ? 'codex exec output' : 'abtop'),
+ total_tokens: deltaTokens,
+ start_tokens: startTokens,
+ end_tokens: endTokens,
+ samples: tokenUsage.samples ?? samples.length,
+ codex_agent_calls: tokenUsage.codex_agent_calls ?? cloudRuns.length,
+ local_agent_calls: tokenUsage.local_agent_calls ?? localRuns.length,
+ measured_agent_calls: tokenUsage.measured_agent_calls ?? null,
+}
+
+const audit = {
+ local_first_ok: localFirstViolations.length === 0,
+ local_first_violations: localFirstViolations,
+ protected_local_engines: ['Apple Vision OCR', 'whisper', 'MarkitDown', 'fastembed', 'Graphify', 'mnemozina-brief'],
+ rule: 'OCR/transcribe/parse/dedup/embed/graph/brief must stay local unless user explicitly asks deep LLM synthesis.',
+}
+
+const learning = {
+ ts: new Date().toISOString(),
+ run_id: RUN_ID,
+ runtime: RUNTIME,
+ token_summary: tokenSummary,
+ audit,
+ errors,
+ lesson: errors.length
+ ? `Следующий прогон: сначала проверить ${errors.join('; ')}. Не тратить LLM на локальные стадии.`
+ : 'Ошибок хвоста не найдено. Сохранять local-first cascade.',
+}
+
+const agentTrace = Array.isArray(result?.agent_trace) ? result.agent_trace : []
+const okAgents = agentTrace.filter(a => a && (a.status === 'ok' || a.status === 'repaired')).map(a => a.name).filter(Boolean)
+const badAgents = agentTrace.filter(a => a && !['ok', 'repaired'].includes(a.status)).map(a => `${a.name}:${a.status}`).filter(Boolean)
+const gates = result?.gates && typeof result.gates === 'object' ? result.gates : {}
+const worked = []
+if (result?.status === 'done') worked.push('coverage closed with status=done')
+if (result?.graph_updated) worked.push('Graphify updated after intake')
+if (result?.briefing?.brief_md) worked.push('brief_md returned to chat')
+if (audit.local_first_ok) worked.push('local-first audit passed')
+if (okAgents.length) worked.push(`agent trace closed: ${okAgents.join(', ')}`)
+
+const failed = []
+if (result?.status && result.status !== 'done') failed.push(`status=${result.status}`)
+if (Array.isArray(result?.unaccounted) && result.unaccounted.length) failed.push(`unaccounted=${result.unaccounted.length}`)
+if (result?.balanced === false) failed.push('ledger not balanced')
+if (!result?.graph_updated) failed.push('Graphify not updated or skipped')
+if (!result?.briefing?.brief_md) failed.push('brief_md missing')
+if (!audit.local_first_ok) failed.push(`local-first violations: ${audit.local_first_violations.join(', ')}`)
+if (badAgents.length) failed.push(`agent trace problems: ${badAgents.join(', ')}`)
+if (errors.length) failed.push(`errors: ${errors.join('; ')}`)
+
+const mistakes = []
+if (failed.length) mistakes.push(...failed)
+if (result?.status === 'done' && !errors.length && audit.local_first_ok) {
+ mistakes.push('no blocking mistakes detected')
+}
+
+const fixes = []
+if (Array.isArray(result?.unaccounted) && result.unaccounted.length) fixes.push('rerun only unaccounted files before archive; keep them in inbox')
+if (result?.balanced === false) fixes.push('recompute ledger from disk, not agent summary')
+if (!audit.local_first_ok) fixes.push('move violated stages back to local engines before next intake')
+if (!result?.briefing?.brief_md) fixes.push('run mnemozina-brief and return brief_md in chat')
+if (!result?.graph_updated) fixes.push('initialize or repair Graphify before next knowledge run')
+if (!fixes.length) fixes.push('keep current contract; next improvement is more precise agent trace metrics')
+
+const selfReflection = {
+ worked,
+ did_not_work: failed.length ? failed : ['no blocking failures detected'],
+ mistakes,
+ fixes,
+ most_important: failed.length
+ ? `Fix first: ${failed[0]}`
+ : 'Contract held: keep local-first, named-agent trace, Graphify, brief_md, and session review as non-optional tail.',
+ agent_trace: agentTrace,
+ gates,
+}
+learning.self_reflection = selfReflection
+
+await mkdir(SYS, { recursive: true })
+await appendFile(LEDGER, JSON.stringify(learning) + '\n')
+
+const md = `---\n` +
+ `title: "Session Review"\n` +
+ `type: "session-review"\n` +
+ `run_id: "${RUN_ID}"\n` +
+ `date: "${new Date().toISOString().slice(0, 10)}"\n` +
+ `token_usage: ${deltaTokens == null ? 'null' : deltaTokens}\n` +
+ `---\n\n` +
+ `# Session Review: ${RUN_ID}\n\n` +
+ `## Расход токенов\n\n` +
+ `- Runtime: ${RUNTIME}\n` +
+ `- Total/delta: ${deltaTokens == null ? 'unknown' : deltaTokens}\n` +
+ `- Start/end: ${startTokens ?? 'unknown'} / ${endTokens ?? 'unknown'}\n` +
+ `- Calls: cloud ${tokenSummary.codex_agent_calls}, local ${tokenSummary.local_agent_calls}\n\n` +
+ `## Local-first audit\n\n` +
+ `- Status: ${audit.local_first_ok ? 'OK' : 'VIOLATION'}\n` +
+ `- Violations: ${localFirstViolations.length ? localFirstViolations.join(', ') : 'none'}\n` +
+ `- Protected engines: ${audit.protected_local_engines.join(', ')}\n\n` +
+ `## Ошибки и урок\n\n` +
+ `- Errors: ${errors.length ? errors.map(compact).join('; ') : 'none'}\n` +
+ `- Lesson: ${learning.lesson}\n\n` +
+ `## Саморефлексия Мнемозины\n\n` +
+ `- Что сработало: ${worked.length ? worked.map(compact).join('; ') : 'none'}\n` +
+ `- Что не сработало: ${failed.length ? failed.map(compact).join('; ') : 'no blocking failures detected'}\n` +
+ `- Ошибки: ${mistakes.length ? mistakes.map(compact).join('; ') : 'none'}\n` +
+ `- Как исправить: ${fixes.length ? fixes.map(compact).join('; ') : 'none'}\n` +
+ `- Самое важное: ${selfReflection.most_important}\n`
+
+await writeFile(REPORT, md)
+console.log(JSON.stringify({ review_path: REPORT, ledger_path: LEDGER, token_summary: tokenSummary, audit, self_reflection: selfReflection, errors }, null, 2))
diff --git a/setup.sh b/setup.sh
index dbfd2a4..d9b37c3 100755
--- a/setup.sh
+++ b/setup.sh
@@ -11,14 +11,9 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DRY="${MNEMAZINE_SETUP_DRYRUN:-0}"
KNOWN_HOSTS="$ROOT/.mnemazine/known_hosts"
-# ---- ui helpers -------------------------------------------------------------
-b() { printf '\033[1m%s\033[0m\n' "$*"; }
-ok() { printf ' \033[32m✓\033[0m %s\n' "$*"; }
-no() { printf ' \033[31m✗\033[0m %s\n' "$*"; }
-note() { printf ' • %s\n' "$*"; }
-stage() { printf '\n\033[1m\033[36m── Этап %s ──\033[0m %s\n' "$1" "$2"; }
-miss() { printf '\n \033[33mДруг, значит %s тебе не оставим.\033[0m %s\n' "$1" "${2:-}"; }
-halt() { printf '\n\033[1mУстанови вот это, потом запусти setup.sh снова — перейдём к следующему этапу.\033[0m\n'; exit 1; }
+# ---- ui helpers (shared with install.sh) -----------------------------------
+# shellcheck source=scripts/mnemazine-ui.sh
+. "$ROOT/scripts/mnemazine-ui.sh"
# ask_choice "Question?" "opt1" "opt2" ... -> sets REPLY_IDX (1-based) and REPLY_VAL
ask_choice() {
@@ -28,22 +23,22 @@ ask_choice() {
for i in "${!opts[@]}"; do printf ' %d) %s\n' $((i+1)) "${opts[$i]}"; done
local sel
while true; do
- printf 'Выбери [1-%d]: ' "${#opts[@]}"
+ printf '%s' "$(L "Выбери [1-${#opts[@]}]: " "Choose [1-${#opts[@]}]: ")"
if ! read -r sel; then
- printf '\nНет TTY (ввод закрыт). Запусти setup.sh интерактивно или используй install.sh без вопросов.\n' >&2
+ printf '\n%s\n' "$(L 'Нет TTY (ввод закрыт). Запусти setup.sh интерактивно или install.sh без вопросов.' 'No TTY (input closed). Run setup.sh interactively, or install.sh without questions.')" >&2
exit 1
fi
if [[ "$sel" =~ ^[0-9]+$ ]] && [ "$sel" -ge 1 ] && [ "$sel" -le "${#opts[@]}" ]; then
REPLY_IDX="$sel"; REPLY_VAL="${opts[$((sel-1))]}"; return 0
fi
- no "Не понял. Введи число от 1 до ${#opts[@]}."
+ no "$(L "Не понял. Введи число от 1 до ${#opts[@]}." "Didn't get it. Enter a number from 1 to ${#opts[@]}.")"
done
}
ask_text() { # ask_text "prompt" [silent] -> REPLY_TXT
local p="$1" silent="${2:-}"
- if [ "$silent" = "secret" ]; then printf '%s: ' "$p"; read -rs REPLY_TXT || { printf '\nНет TTY.\n' >&2; exit 1; }; printf '\n'
- else printf '%s: ' "$p"; read -r REPLY_TXT || { printf '\nНет TTY.\n' >&2; exit 1; }; fi
+ if [ "$silent" = "secret" ]; then printf '%s: ' "$p"; read -rs REPLY_TXT || { printf '\n%s\n' "$(L 'Нет TTY.' 'No TTY.')" >&2; exit 1; }; printf '\n'
+ else printf '%s: ' "$p"; read -r REPLY_TXT || { printf '\n%s\n' "$(L 'Нет TTY.' 'No TTY.')" >&2; exit 1; }; fi
}
run() { # run a command unless dry-run
@@ -55,106 +50,153 @@ sq() {
printf "'%s'" "$(printf "%s" "$1" | sed "s/'/'\\\\''/g")"
}
-b "Mnemazine — установка по шагам."
-note "Каждый этап завершается прежде чем начнётся следующий."
-[ "$DRY" = "1" ] && note "DRY RUN — ничего не ставится и не деплоится."
+keychain_account() {
+ printf '%s' "${MNEMAZINE_TELEGRAM_KEYCHAIN_ACCOUNT:-telegram-bot}"
+}
+
+keychain_store_token() {
+ local token="$1" account
+ account="$(keychain_account)"
+ if ! command -v security >/dev/null 2>&1; then
+ if [ "$DRY" = "1" ]; then
+ note "[dry] security add-generic-password -s mnemazine-telegram -a $account -w "
+ return 0
+ fi
+ no "$(L 'macOS Keychain недоступен: команда security не найдена.' 'macOS Keychain unavailable: the security command is missing.')"
+ halt
+ fi
+ run security add-generic-password -U -s mnemazine-telegram -a "$account" -w "$token"
+ ok "$(L "Токен сохранён в Keychain: service=mnemazine-telegram account=$account." "Token stored in Keychain: service=mnemazine-telegram account=$account.")"
+}
+
+keychain_read_token() {
+ local account
+ account="$(keychain_account)"
+ security find-generic-password -s mnemazine-telegram -a "$account" -w 2>/dev/null
+}
+
+b "$(L 'Mnemazine — установка по шагам.' 'Mnemazine — step-by-step install.')"
+note ""
+note "$(L 'Что это. Система превращает то, что вы сохраняете — скриншоты, статьи, PDF, видео —' 'What this is. The system turns what you save — screenshots, articles, PDFs, videos —')"
+note "$(L 'в готовые заметки: разбирает материал, проверяет источник, связывает с тем, что уже есть.' 'into finished notes: it reads the material, checks the source, links it to what you already have.')"
+note "$(L 'Заметки лежат обычными файлами Markdown — их читает Obsidian и любой редактор.' 'Notes are plain Markdown files — Obsidian and any editor can read them.')"
+note ""
+note "$(L 'Что сейчас будет. Семь коротких этапов, примерно пять минут. Четыре вопроса — меню:' 'What happens now. Seven short stages, about five minutes. Four questions are menus:')"
+note "$(L 'куда класть входящие, чем разбирать материал, нужен ли Telegram-бот, есть ли сервер.' 'where incoming files land, what parses the material, whether you want a Telegram bot, whether you have a server.')"
+note "$(L 'Ничего необратимого: прервать можно в любой момент через Ctrl+C.' 'Nothing is irreversible: stop at any moment with Ctrl+C.')"
+note "$(L 'Посмотреть весь путь, ничего не устанавливая: MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh' 'Preview the whole path without installing: MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh')"
+note ""
+note "$(L 'Каждый этап завершается прежде чем начнётся следующий.' 'Each stage finishes before the next begins.')"
+[ "$DRY" = "1" ] && note "$(L 'DRY RUN — ничего не ставится и не деплоится.' 'DRY RUN — nothing is installed or deployed.')"
# ---- Stage 1: base environment (hard gate) ---------------------------------
-stage 1 "Базовое окружение (обязательно)"
+stage "1/7" "$(L 'Базовое окружение (обязательно)' 'Base environment (required)')"
fail=0
-if command -v git >/dev/null 2>&1; then ok "git"; else no "git нет"; note "macOS: xcode-select --install · Linux: apt install git"; fail=1; fi
+if command -v git >/dev/null 2>&1; then ok "git"; else no "$(L 'git нет' 'git missing')"; note "macOS: xcode-select --install · Linux: apt install git"; fail=1; fi
if command -v node >/dev/null 2>&1; then
ver="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
- if [ "$ver" -ge 20 ]; then ok "node $(node -v)"; else no "node слишком старый ($(node -v)), нужен >=20"; note "https://nodejs.org или nvm install 20"; fail=1; fi
-else no "node нет (нужен >=20)"; note "https://nodejs.org или: brew install node"; fail=1; fi
+ if [ "$ver" -ge 20 ]; then ok "node $(node -v)"; else no "$(L "node слишком старый ($(node -v)), нужен >=20" "node too old ($(node -v)), need >=20")"; note "https://nodejs.org · nvm install 20"; fail=1; fi
+else no "$(L 'node нет (нужен >=20)' 'node missing (need >=20)')"; note "https://nodejs.org · brew install node"; fail=1; fi
[ "$fail" = "1" ] && halt
-ok "База готова."
+ok "$(L 'База готова.' 'Base ready.')"
# ---- Stage 2: local engines (optional, degrade gracefully) -----------------
-stage 2 "Локальные движки распознавания (по желанию — экономят токены)"
+stage "2/7" "$(L 'Локальные движки распознавания (по желанию — экономят токены)' 'Local recognition engines (optional — they save tokens)')"
+note "$(L 'Зачем: текст со скриншотов и речь из видео читаются на вашем компьютере, без облака и без токенов.' 'Why: text on screenshots and speech in video are read on your machine — no cloud, no tokens.')"
+note "$(L 'Чего нет — подскажу команду установки; можно поставить позже, система будет работать и без них.' 'Anything missing gets an exact install command; you can add it later — the system works without it.')"
have_py=0; have_ff=0; have_whisper=0; have_swift=0
-command -v python3 >/dev/null 2>&1 && { ok "python3 (markitdown: PDF/DOCX/PPTX/XLSX/HTML)"; have_py=1; } || miss "разбор офис-файлов локально" "поставь python3 — иначе их распознает LLM в deep-режиме."
-command -v ffmpeg >/dev/null 2>&1 && { ok "ffmpeg (видео-кадры/аудио)"; have_ff=1; } || miss "локальную обработку видео/аудио" "brew install ffmpeg / apt install ffmpeg."
-command -v whisper >/dev/null 2>&1 && { ok "whisper (транскрипт речи)"; have_whisper=1; } || miss "локальный транскрипт речи" "pip install openai-whisper — иначе только субтитры/LLM."
+command -v python3 >/dev/null 2>&1 && { ok "python3 (markitdown: PDF/DOCX/PPTX/XLSX/HTML)"; have_py=1; } || miss "$(L 'Разбор офис-файлов локально не оставим:' 'No local office-file parsing:')" "$(L 'поставь python3 — иначе их распознает LLM в deep-режиме.' 'install python3 — otherwise the LLM reads them in deep mode.')"
+command -v ffmpeg >/dev/null 2>&1 && { ok "ffmpeg $(L '(видео-кадры/аудио)' '(video frames/audio)')"; have_ff=1; } || miss "$(L 'Локальную обработку видео/аудио не оставим:' 'No local video/audio processing:')" "brew install ffmpeg · apt install ffmpeg."
+command -v whisper >/dev/null 2>&1 && { ok "whisper $(L '(транскрипт речи)' '(speech transcript)')"; have_whisper=1; } || miss "$(L 'Локальный транскрипт речи не оставим:' 'No local speech transcript:')" "$(L 'pip install openai-whisper — иначе только субтитры/LLM.' 'pip install openai-whisper — otherwise only subtitles/LLM.')"
if [ "$(uname)" = "Darwin" ]; then
- command -v swiftc >/dev/null 2>&1 && { ok "swiftc (Apple Vision OCR картинок)"; have_swift=1; } || miss "Apple Vision OCR" "xcode-select --install — картинки распознает LLM."
+ command -v swiftc >/dev/null 2>&1 && { ok "swiftc (Apple Vision OCR)"; have_swift=1; } || miss "Apple Vision OCR:" "$(L 'xcode-select --install — иначе картинки распознает LLM.' 'xcode-select --install — otherwise images are read by the LLM.')"
else
- miss "Apple Vision OCR" "доступен только на macOS — на этом устройстве картинки распознает LLM."
+ miss "Apple Vision OCR:" "$(L 'доступен только на macOS — на этом устройстве картинки распознает LLM.' 'macOS only — images are read by the LLM on this device.')"
fi
-note "Это не блокеры. Каркас поставится и без них."
+note "$(L 'Это не блокеры. Каркас поставится и без них.' 'These are not blockers. The skeleton installs without them.')"
# ---- Stage 3: inbox location (required question) ---------------------------
-stage 3 "Куда класть inbox?"
-ask_choice "Входящие материалы будут падать сюда:" \
- "На рабочий стол — $HOME/Desktop/Mnemazine Inbox" \
- "Внутри репозитория — $ROOT/inbox"
+stage "3/7" "$(L 'Куда класть inbox?' 'Where does the inbox go?')"
+note "$(L 'Зачем: это единственная папка, куда вы бросаете материал. Всё остальное система делает сама.' 'Why: this is the one folder you drop material into. The system handles everything after that.')"
+ask_choice "$(L 'Входящие материалы будут падать сюда:' 'Incoming material lands here:')" \
+ "$(L 'На рабочий стол' 'On the Desktop') — $HOME/Desktop/Mnemazine Inbox" \
+ "$(L 'Внутри репозитория' 'Inside the repo') — $ROOT/inbox"
if [ "$REPLY_IDX" = "1" ]; then INBOX="$HOME/Desktop/Mnemazine Inbox"; else INBOX="$ROOT/inbox"; fi
ok "Inbox: $INBOX"
# ---- Stage 4: LLM provider (deep mode) -------------------------------------
-stage 4 "LLM-провайдер для deep-режима (атомизация/обогащение/проверка)"
+stage "4/7" "$(L 'LLM-провайдер для deep-режима (атомизация/обогащение/проверка)' 'LLM provider for deep mode (atomize/enrich/verify)')"
+note "$(L 'Зачем: глубокий режим режет материал на отдельные мысли, ищет источники и проверяет утверждения.' 'Why: deep mode splits material into separate ideas, finds sources and checks claims.')"
+note "$(L 'Без него система тоже работает — извлекает текст и раскладывает файлы, но не проверяет факты.' 'Without it the system still works — it extracts text and files things away, but does not verify facts.')"
has_claude=0; has_codex=0
command -v claude >/dev/null 2>&1 && has_claude=1
command -v codex >/dev/null 2>&1 && has_codex=1
if [ "$has_claude" = "1" ] || [ "$has_codex" = "1" ]; then
- opts=(); [ "$has_claude" = "1" ] && opts+=("Claude CLI"); [ "$has_codex" = "1" ] && opts+=("Codex CLI"); opts+=("Без deep — только локальный разбор")
- ask_choice "Найдены провайдеры. Чем работать?" "${opts[@]}"
+ opts=(); [ "$has_claude" = "1" ] && opts+=("Claude CLI"); [ "$has_codex" = "1" ] && opts+=("Codex CLI"); opts+=("$(L 'Без deep — только локальный разбор' 'No deep — local parsing only')")
+ ask_choice "$(L 'Найдены провайдеры. Чем работать?' 'Providers found. Which one?')" "${opts[@]}"
case "$REPLY_VAL" in
"Claude CLI") LLM=claude ;; "Codex CLI") LLM=codex ;; *) LLM="" ;;
esac
- [ -n "$LLM" ] && ok "Провайдер: $LLM" || ok "Deep выключен (conservative, 0 токенов)."
+ [ -n "$LLM" ] && ok "$(L "Провайдер: $LLM" "Provider: $LLM")" || ok "$(L 'Deep выключен (conservative, 0 токенов).' 'Deep off (conservative, 0 tokens).')"
else
LLM=""
- miss "deep-режим (атомизация/обогащение через LLM)" "не найден ни claude, ни codex CLI. Каркас и локальный разбор работают."
+ miss "$(L 'deep-режим (атомизация/обогащение через LLM) не оставим:' 'no deep mode (LLM atomize/enrich):')" "$(L 'не найден ни claude, ни codex CLI. Каркас и локальный разбор работают.' 'neither claude nor codex CLI found. Skeleton and local parsing still work.')"
fi
# ---- Stage 5: Telegram bot --------------------------------------------------
-stage 5 "Telegram-бот для приёма входящих"
+stage "5/7" "$(L 'Telegram-бот для приёма входящих' 'Telegram bot for intake')"
+note "$(L 'Зачем: увидели что-то с телефона — отправили боту, и материал уже в инбоксе. Шаг необязательный.' 'Why: spot something on your phone, send it to the bot, and it is already in the inbox. Optional step.')"
BOT_TOKEN=""; BOT_MODE="none"
-ask_choice "Подключить Telegram-бота? (шлёшь боту — падает в inbox)" "Да" "Нет"
+ask_choice "$(L 'Подключить Telegram-бота? (шлёшь боту — падает в inbox)' 'Connect a Telegram bot? (send it a file — it lands in the inbox)')" "$(L 'Да' 'Yes')" "$(L 'Нет' 'No')"
if [ "$REPLY_IDX" = "1" ]; then
- ask_text "Вставь токен бота от @BotFather" secret; BOT_TOKEN="$REPLY_TXT"
+ ask_text "$(L 'Вставь токен бота от @BotFather' 'Paste the bot token from @BotFather')" secret; BOT_TOKEN="$REPLY_TXT"
if [ -z "$BOT_TOKEN" ]; then
- miss "Telegram-бота" "токен пустой — пропускаем."
+ miss "$(L 'Telegram-бота не оставим:' 'no Telegram bot:')" "$(L 'токен пустой — пропускаем.' 'token empty — skipping.')"
+ note "$(L 'Как включить бота позже — docs/telegram-intake.md.' 'How to enable the bot later — docs/telegram-intake.md.')"
else
- ok "Токен принят (в git не пишем)."
- b "Бот должен идти через VPS (всегда-онлайн, принимает пока твоё устройство спит)."
- ask_choice "Есть VPS для бота?" "Да, есть VPS" "Нет VPS"
+ ok "$(L 'Токен принят (в git не пишем).' 'Token accepted (never written to git).')"
+ keychain_store_token "$BOT_TOKEN"
+ BOT_TOKEN=""
+ b "$(L 'Бот должен идти через VPS (всегда-онлайн, принимает пока твоё устройство спит).' 'The bot needs a VPS (always-on, receives while your device sleeps).')"
+ ask_choice "$(L 'Есть VPS для бота?' 'Do you have a VPS for the bot?')" "$(L 'Да, есть VPS' 'Yes, I have a VPS')" "$(L 'Нет VPS' 'No VPS')"
if [ "$REPLY_IDX" = "1" ]; then
- 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 fingerprint хоста (SHA256:..., из панели VPS или ssh-keygen -lf)"; BOT_FP="$REPLY_TXT"
- [ -z "$BOT_FP" ] && { no "fingerprint пустой — небезопасно."; halt; }
+ ask_text "$(L 'VPS (user@host)' 'VPS (user@host)')"; BOT_VPS="$REPLY_TXT"
+ ask_text "$(L 'Путь к SSH-ключу (Enter = ~/.ssh/id_rsa)' 'SSH key path (Enter = ~/.ssh/id_rsa)')"; BOT_KEY="${REPLY_TXT:-$HOME/.ssh/id_rsa}"
+ ask_text "$(L 'SSH fingerprint хоста (SHA256:..., из панели VPS или ssh-keygen -lf)' 'Host SSH fingerprint (SHA256:..., from the VPS panel or ssh-keygen -lf)')"; BOT_FP="$REPLY_TXT"
+ [ -z "$BOT_FP" ] && { no "$(L 'fingerprint пустой — небезопасно.' 'fingerprint empty — unsafe.')"; halt; }
if [ "$DRY" != "1" ]; then
mkdir -p "$ROOT/.mnemazine"
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
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."
+ no "$(L 'VPS недоступен или нет node+pm2.' 'VPS unreachable or missing node+pm2.')"
halt
fi
- BOT_MODE="vps"; ok "VPS на связи (node+pm2 есть)."
+ BOT_MODE="vps"; ok "$(L 'VPS на связи (node+pm2 есть).' 'VPS reachable (node+pm2 present).')"
else
- miss "бота через VPS" "Без VPS постоянного приёма нет. Можешь запускать бота локально, пока устройство включено."
+ miss "$(L 'бота через VPS не оставим:' 'no bot over a VPS:')" "$(L 'Без VPS постоянного приёма нет. Можешь запускать бота локально, пока устройство включено.' 'Without a VPS there is no round-the-clock intake. You can run the bot locally while your device is on.')"
+ note "$(L 'Как жить без VPS — docs/telegram-intake.md.' 'Living without a VPS — docs/telegram-intake.md.')"
BOT_MODE="manual"
fi
fi
else
- note "Бот пропущен."
+ note "$(L 'Бот пропущен.' 'Bot skipped.')"
+ note "$(L 'Захочешь позже — docs/telegram-intake.md.' 'If you want it later — docs/telegram-intake.md.')"
fi
# ---- Stage 6: build the skeleton -------------------------------------------
-stage 6 "Ставлю каркас Mnemazine"
-ok "Запускаю install.sh (vault, папки, venv, OCR-сборка)…"
-if ! MNEMAZINE_FROM_SETUP=1 MNEMAZINE_ROOT="$ROOT" MNEMAZINE_INBOX="$INBOX" run bash "$ROOT/install.sh"; then
- no "install.sh завершился с ошибкой — каркас не собран."
+stage "6/7" "$(L 'Ставлю каркас Mnemazine' 'Building the Mnemazine skeleton')"
+note "$(L 'Зачем: создаю папки базы знаний и служебные файлы. Ничего за пределами проекта без спроса не трогаю.' 'Why: creating the knowledge-base folders and service files. Nothing outside the project is touched without asking.')"
+ok "$(L 'Запускаю install.sh (vault, папки, venv, OCR-сборка)…' 'Running install.sh (vault, folders, venv, OCR build)…')"
+if ! MNEMAZINE_FROM_SETUP=1 MNEMAZINE_YES=1 MNEMAZINE_ROOT="$ROOT" MNEMAZINE_INBOX="$INBOX" run bash "$ROOT/install.sh"; then
+ no "$(L 'install.sh завершился с ошибкой — каркас не собран.' 'install.sh failed — skeleton not built.')"
halt
fi
# deploy bot if VPS path chosen
if [ "$BOT_MODE" = "vps" ]; then
- stage 6.1 "Деплой бота на VPS"
+ stage "6.1" "$(L 'Деплой бота на VPS' 'Deploying the bot to the VPS')"
REMOTE_ROOT="mnemazine"
REMOTE_INBOX="$REMOTE_ROOT/inbox"
REMOTE_BOT="$REMOTE_ROOT/bot"
@@ -166,46 +208,82 @@ if [ "$BOT_MODE" = "vps" ]; then
MNEMAZINE_VPS="$BOT_VPS"
MNEMAZINE_VPS_KEY="$BOT_KEY"
MNEMAZINE_REMOTE_INBOX="$REMOTE_INBOX"
+MNEMAZINE_INBOX="$INBOX"
MNEMAZINE_REMOTE_MUTATION=1
+MNEMAZINE_PUSH_REPORTS=0
CFG
umask 022
- ok "Записал .mnemazine/config.env (chmod 600, gitignored)."
+ ok "$(L 'Записал .mnemazine/config.env (chmod 600, gitignored).' 'Wrote .mnemazine/config.env (chmod 600, gitignored).')"
fi
if [ "$DRY" = "1" ]; then
note "[dry] scp bot → $BOT_VPS:$REMOTE_BOT/ ; pm2 start с токеном"
else
SSH_OPTS=(-i "$BOT_KEY" -o "UserKnownHostsFile=$KNOWN_HOSTS" -o StrictHostKeyChecking=yes)
- 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; }
+ BOT_TOKEN_FROM_KEYCHAIN="$(keychain_read_token)" || { no "$(L 'Не смог прочитать токен из Keychain.' 'Could not read the token from Keychain.')"; halt; }
+ ssh "${SSH_OPTS[@]}" "$BOT_VPS" "mkdir -p $REMOTE_BOT $REMOTE_INBOX" || { no "$(L 'Не смог создать папки на VPS.' 'Could not create folders on the VPS.')"; halt; }
+ ssh "${SSH_OPTS[@]}" "$BOT_VPS" "cat > $REMOTE_BOT/mnemazine-telegram-bot.mjs" < "$ROOT/scripts/mnemazine-telegram-bot.mjs" || { no "$(L 'Не смог загрузить bot script на VPS.' 'Could not upload the bot script to the VPS.')"; halt; }
{
- printf 'TELEGRAM_BOT_TOKEN=%s\n' "$(sq "$BOT_TOKEN")"
+ printf 'TELEGRAM_BOT_TOKEN=%s\n' "$(sq "$BOT_TOKEN_FROM_KEYCHAIN")"
printf 'MNEMAZINE_INBOX=%s\n' "$(sq "$REMOTE_INBOX")"
- } | ssh "${SSH_OPTS[@]}" "$BOT_VPS" "umask 177; cat > $REMOTE_BOT/.env" || { no "Не смог записать .env на VPS."; halt; }
+ } | ssh "${SSH_OPTS[@]}" "$BOT_VPS" "umask 177; cat > $REMOTE_BOT/.env" || { no "$(L 'Не смог записать .env на VPS.' 'Could not write .env on the VPS.')"; halt; }
+ BOT_TOKEN_FROM_KEYCHAIN=""
# Idempotent: start, or restart if the process already exists (rerun-safe).
- 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-режим)."
- note "Напиши боту сообщение, затем на VPS: pm2 logs mnemazine-bot — увидишь свой chat_id."
- note "Закрой доступ: перезапусти с ALLOWED_CHAT_IDS= (см. docs/telegram-intake.md)."
+ 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 "$(L 'Не смог запустить pm2 на VPS.' 'Could not start pm2 on the VPS.')"; halt; }
+ ok "$(L 'Бот запущен на VPS (bootstrap-режим).' 'Bot started on the VPS (bootstrap mode).')"
+ note "$(L 'Напиши боту сообщение, затем на VPS: pm2 logs mnemazine-bot — увидишь свой chat_id.' 'Message the bot, then on the VPS: pm2 logs mnemazine-bot — you will see your chat_id.')"
+ note "$(L 'Закрой доступ: пустой ALLOWED_CHAT_IDS отвергает всех (fail-closed). Перезапусти с ALLOWED_CHAT_IDS= — см. docs/telegram-intake.md.' 'Lock it down: an empty ALLOWED_CHAT_IDS rejects everyone (fail-closed). Restart with ALLOWED_CHAT_IDS= — see docs/telegram-intake.md.')"
fi
elif [ "$BOT_MODE" = "manual" ]; then
- stage 6.1 "Бот локально (вручную)"
- note "Запусти когда нужно:"
- note "TELEGRAM_BOT_TOKEN=<токен> MNEMAZINE_INBOX=$INBOX node $ROOT/scripts/mnemazine-telegram-bot.mjs"
+ stage "6.1" "$(L 'Бот локально (вручную)' 'Bot locally (manual)')"
+ note "$(L 'Запусти когда нужно:' 'Run it when you need it:')"
+ note "TELEGRAM_BOT_TOKEN=<$(L 'токен' 'token')> MNEMAZINE_INBOX=$INBOX node $ROOT/scripts/mnemazine-telegram-bot.mjs"
+ note "$(L 'Подробнее и как закрыть бота на себя — docs/telegram-intake.md.' 'Details and how to lock the bot to yourself — docs/telegram-intake.md.')"
fi
# ---- Stage 7: done ----------------------------------------------------------
-stage 7 "Готово"
-ok "Каркас: $ROOT"
+stage "7/7" "$(L 'Готово' 'Done')"
+ok "$(L "Каркас: $ROOT" "Skeleton: $ROOT")"
ok "Inbox: $INBOX"
-[ -n "$LLM" ] && ok "Deep-провайдер: $LLM" || note "Deep выключен — включишь позже через MNEMAZINE_LLM."
-note "Открой папку vault в Obsidian."
-note "Открой проект: $ROOT"
-note "Клади файлы: $INBOX"
-note "В чате агента: Mnemazine"
-note "В терминале: npm start"
-note "Если ~/.local/bin есть в PATH: mnemazine"
-[ "$BOT_MODE" = "vps" ] && note "Mini App + ежедневный pull: см. docs/telegram-intake.md (этапы 2-3)."
-b "Всё. Пользуйся."
+[ -n "$LLM" ] && ok "$(L "Deep-провайдер: $LLM" "Deep provider: $LLM")" || note "$(L 'Deep выключен — включишь позже через MNEMAZINE_LLM.' 'Deep off — enable later via MNEMAZINE_LLM.')"
+note "$(L 'Открой папку vault в Obsidian.' 'Open the vault folder in Obsidian.')"
+note "$(L "Открой проект: $ROOT" "Open the project: $ROOT")"
+note "$(L "Клади файлы: $INBOX" "Drop files into: $INBOX")"
+note "$(L 'В чате агента: Mnemazine' 'In the agent chat: Mnemazine')"
+note "$(L 'В терминале: npm start' 'In the terminal: npm start')"
+note "$(L 'Признак жизни: npm run doctor' 'Sign of life: npm run doctor')"
+note "$(L 'Если ~/.local/bin есть в PATH: mnemazine' 'If ~/.local/bin is on your PATH: mnemazine')"
+
+# First real result beats any amount of documentation: offer one demo pass so the
+# user sees a finished note before deciding whether this belongs in their life.
+if [ "$DRY" != "1" ] && [ -f "$ROOT/demo/inbox/example-guide.md" ]; then
+ ask_choice "$(L 'Показать, как это работает, прямо сейчас? Возьму демо-файл из репозитория и сделаю из него заметку.' 'Want to see it work right now? I will take a demo file from the repo and turn it into a note.')" \
+ "$(L 'Да, покажи' 'Yes, show me')" "$(L 'Нет, я сам' 'No, I will do it myself')"
+ if [ "$REPLY_IDX" = "1" ]; then
+ demo_dir="$(mktemp -d "${TMPDIR:-/tmp}/mnemazine-first-run.XXXXXX")"
+ mkdir -p "$demo_dir/inbox" "$demo_dir/vault"
+ cp "$ROOT/demo/inbox/example-guide.md" "$demo_dir/inbox/"
+ note "$(L 'Прогон идёт в отдельной песочнице — ваша база знаний не тронута.' 'The run happens in a sandbox — your own knowledge base is untouched.')"
+ if MNEMAZINE_INBOX="$demo_dir/inbox" MNEMAZINE_VAULT="$demo_dir/vault" \
+ MNEMAZINE_REPORTS="$demo_dir/reports" MNEMAZINE_STATE="$demo_dir/state" \
+ MNEMAZINE_CACHE="$demo_dir/cache.json" MNEMAZINE_EXTRACTS="$demo_dir/extracts" \
+ MNEMAZINE_ARCHIVE="$demo_dir/archive" MNEMAZINE_DEEP=0 MNEMAZINE_REQUIRE_DEEP=0 \
+ MNEMAZINE_FINISH=0 node "$ROOT/scripts/mnemazine-run.mjs" >/dev/null 2>&1; then
+ first_note="$(find "$demo_dir/vault" -name '*.md' | head -1)"
+ if [ -n "$first_note" ]; then
+ ok "$(L 'Готовая заметка:' 'Here is the finished note:')"
+ printf '\n'; sed -n '1,24p' "$first_note"; printf '\n'
+ note "$(L 'Так же будет с вашими файлами — только с проверкой источников, если включён deep-режим.' 'Your own files go the same way — with source checks too, when deep mode is on.')"
+ else
+ note "$(L 'Демо-прогон прошёл, но заметки не видно — напишите нам, это баг.' 'The demo ran but produced no note — tell us, that is a bug.')"
+ fi
+ else
+ note "$(L 'Демо-прогон не завершился. Установка в порядке: проверьте npm run doctor.' 'The demo run did not finish. The install is fine: check npm run doctor.')"
+ fi
+ rm -rf "$demo_dir"
+ fi
+fi
+[ "$BOT_MODE" = "vps" ] && note "$(L 'Mini App + ежедневный pull: см. docs/telegram-intake.md (этапы 2-3).' 'Mini App + daily pull: see docs/telegram-intake.md (stages 2-3).')"
+b "$(L 'Всё. Пользуйся.' 'All set. Enjoy.')"
# Author greeting last, so it is what the user sees at the end (not buried
# mid-flow inside install.sh, which stays silent under MNEMAZINE_FROM_SETUP).
diff --git a/skills/humanizer-ru/scripts/humanizer_metrics/__init__.py b/skills/humanizer-ru/scripts/humanizer_metrics/__init__.py
new file mode 100644
index 0000000..35e1ad7
--- /dev/null
+++ b/skills/humanizer-ru/scripts/humanizer_metrics/__init__.py
@@ -0,0 +1,74 @@
+"""humanizer_metrics — детерминированные метрики живости текста.
+
+Это грепабельная половина режима «Аудит» из SKILL.md: то, что считается
+машиной, а не LLM. Используется и как локальный буст для Claude Code, и как
+движок eval-харнеса (eval/run_eval.py), и как self-test самого скилла
+(scripts/lint_skill.py).
+
+Семантику (кальки, ирония, translationese, голос) тут не ловим — для этого
+нужен сам скилл. Скрипты не работают в claude.ai web; скилл от них не зависит.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from .burstiness import RhythmStats, rhythm, rhythm_verdict
+from .markers import (
+ MarkerHit,
+ marker_verdict,
+ scan_hard_bans,
+ scan_markers,
+)
+from .morphology import MorphStats, morph_stats, morph_verdict
+from .score import ScoreResult, cleanliness_score
+
+__all__ = [
+ "Report",
+ "analyze",
+ "RhythmStats",
+ "MorphStats",
+ "MarkerHit",
+ "ScoreResult",
+ "cleanliness_score",
+ "rhythm",
+ "morph_stats",
+ "scan_hard_bans",
+ "scan_markers",
+]
+
+
+@dataclass
+class Report:
+ hard_bans: list[MarkerHit]
+ markers: list[MarkerHit]
+ rhythm: RhythmStats
+ morph: MorphStats
+
+ @property
+ def hard_ban_count(self) -> int:
+ return sum(h.count for h in self.hard_bans)
+
+ @property
+ def marker_count(self) -> int:
+ return sum(h.count for h in self.markers)
+
+ def as_dict(self) -> dict:
+ return {
+ "hard_ban_count": self.hard_ban_count,
+ "hard_bans": [(h.marker, h.count) for h in self.hard_bans],
+ "marker_count": self.marker_count,
+ "markers": [(h.category, h.marker, h.count) for h in self.markers],
+ "rhythm": self.rhythm.as_dict(),
+ "morph": self.morph.as_dict(),
+ }
+
+
+def analyze(text: str) -> Report:
+ """Полный детерминированный прогон текста."""
+ return Report(
+ hard_bans=scan_hard_bans(text),
+ markers=scan_markers(text),
+ rhythm=rhythm(text),
+ morph=morph_stats(text),
+ )
diff --git a/skills/humanizer-ru/scripts/humanizer_metrics/burstiness.py b/skills/humanizer-ru/scripts/humanizer_metrics/burstiness.py
new file mode 100644
index 0000000..1ba3ac1
--- /dev/null
+++ b/skills/humanizer-ru/scripts/humanizer_metrics/burstiness.py
@@ -0,0 +1,88 @@
+"""Ритм и типографика: то, что скилл велит мерить дисперсией, а не на глаз.
+
+Закрывает пункты чеклиста «вариативность длины предложений — не средняя, а
+ДИСПЕРСИЯ» и «ноль длинных тире». Burstiness тут — статистический прокси, не сам
+детектор: высокий разброс длины предложений коррелирует с человеческим письмом
+(SKILL.md, раздел «Что ловят детекторы»).
+"""
+
+from __future__ import annotations
+
+import re
+import statistics
+from dataclasses import dataclass
+
+from razdel import sentenize, tokenize
+
+
+@dataclass
+class RhythmStats:
+ sentences: int
+ words: int
+ mean_len: float # средняя длина предложения в словах
+ stdev_len: float # стандартное отклонение длины
+ cv_len: float # коэффициент вариации = stdev/mean (главный показатель)
+ min_len: int
+ max_len: int
+ short_share: float # доля предложений < 5 слов
+ long_share: float # доля предложений > 25 слов
+ em_dash: int # длинных тире «—»
+ ellipsis: int # многоточий
+ parentheses: int # скобочных ремарок
+ questions: int # вопросительных предложений
+
+ def as_dict(self) -> dict:
+ return self.__dict__.copy()
+
+
+_WORD_RE = re.compile(r"[А-Яа-яЁёA-Za-z0-9]")
+
+
+def _word_count(sentence: str) -> int:
+ return sum(1 for t in tokenize(sentence) if _WORD_RE.search(t.text))
+
+
+def rhythm(text: str) -> RhythmStats:
+ sents = [s.text for s in sentenize(text)]
+ lengths = [_word_count(s) for s in sents]
+ lengths = [n for n in lengths if n > 0]
+ n = len(lengths)
+ total_words = sum(lengths)
+
+ mean = statistics.mean(lengths) if lengths else 0.0
+ stdev = statistics.pstdev(lengths) if n > 1 else 0.0
+ cv = (stdev / mean) if mean else 0.0
+
+ return RhythmStats(
+ sentences=n,
+ words=total_words,
+ mean_len=round(mean, 1),
+ stdev_len=round(stdev, 1),
+ cv_len=round(cv, 3),
+ min_len=min(lengths) if lengths else 0,
+ max_len=max(lengths) if lengths else 0,
+ short_share=round(sum(1 for x in lengths if x < 5) / n, 3) if n else 0.0,
+ long_share=round(sum(1 for x in lengths if x > 25) / n, 3) if n else 0.0,
+ em_dash=text.count("—"),
+ ellipsis=text.count("…") + len(re.findall(r"\.\.\.", text)),
+ parentheses=text.count("("),
+ questions=sum(1 for s in sents if s.rstrip().endswith("?")),
+ )
+
+
+# Эвристические пороги (откалиброваны под русский грубо, см. eval/RESULTS.md).
+# cv_len < 0.35 — слишком ровный ритм, признак AI. Человеческий текст обычно > 0.45.
+CV_AI_THRESHOLD = 0.35
+CV_HUMAN_TARGET = 0.45
+
+
+def rhythm_verdict(s: RhythmStats) -> str:
+ if s.em_dash > 0:
+ dash = f"⚠ {s.em_dash} длинных тире (норма 0)"
+ else:
+ dash = "✓ тире чисто"
+ if s.cv_len < CV_AI_THRESHOLD:
+ rhythm_v = f"⚠ ровный ритм (CV={s.cv_len}, цель ≥{CV_HUMAN_TARGET})"
+ else:
+ rhythm_v = f"✓ ритм рваный (CV={s.cv_len})"
+ return f"{rhythm_v}; {dash}"
diff --git a/skills/humanizer-ru/scripts/humanizer_metrics/markers.py b/skills/humanizer-ru/scripts/humanizer_metrics/markers.py
new file mode 100644
index 0000000..81313af
--- /dev/null
+++ b/skills/humanizer-ru/scripts/humanizer_metrics/markers.py
@@ -0,0 +1,180 @@
+"""Лексические маркеры AI-текста: HARD BANS и быстрый сканер.
+
+Вордлисты вынесены один-в-один из SKILL.md (разделы «Жёсткие запреты» и
+«Быстрый сканер: слова-маркеры AI»). Это детерминированная, грепабельная половина
+режима «Аудит» — то, что не требует LLM. Семантика (кальки, ирония, translationese)
+тут не ловится принципиально, для неё нужен сам скилл.
+
+Источник правды — SKILL.md. При обновлении банов/маркеров правь оба файла;
+scripts/lint_skill.py проверяет, что списки не разошлись по числу пунктов.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+
+# --- HARD BANS -----------------------------------------------------------
+# 20 конструкций с абсолютным запретом. Каждая — (имя, regex). Regex
+# регистронезависимый, по словоформам где это безопасно.
+HARD_BANS: list[tuple[str, str]] = [
+ ("Не просто X, а Y", r"\bне\s+просто\b[^.!?]{1,40}?\bа\b"),
+ ("Не только X, но и Y", r"\bне\s+только\b[^.!?]{1,40}?\bно\s+и\b"),
+ ("В современном мире", r"\bв\s+современном\s+мире\b"),
+ ("Стоит отметить, что", r"\bстоит\s+отметить\b"),
+ ("Важно понимать, что", r"\bважно\s+понимать\b"),
+ # Только единственное число (как в SKILL.md HARD BAN). Множественные формы
+ # «данные/данных/данным/данными» совпадают с существительным «данные» (data)
+ # и давали ложные срабатывания на ML/статистических текстах.
+ ("Данный/Данная/Данное", r"\bданн(ый|ая|ое|ого|ой|ом|ую)\b"),
+ ("Является", r"\bявля(ется|ются)\b"),
+ ("Играет важную/ключевую роль", r"\bигра(ет|ют)\s+(важн\w+|ключев\w+)\s+роль\b"),
+ ("Можно с уверенностью сказать", r"\bможно\s+с\s+уверенностью\s+сказать\b"),
+ ("Подводя итог / Таким образом", r"\b(подводя\s+итог|таким\s+образом)\b"),
+ ("Длинное тире", r"—"),
+ ("от X до Y (ложный диапазон)", r"\bот\s+\w+\s+до\s+\w+\b"),
+ ("В условиях [прил.] [сущ.]", r"\bв\s+условиях\s+\w+"),
+ ("Погрузимся / посмотрим поближе", r"\b(погрузимся|посмотрим\s+\w+\s+поближе|давайте\s+посмотрим)\b"),
+ ("И вот здесь начинается самое интересное", r"\bвот\s+(здесь|тут)\s+начинается\s+самое\s+интересное\b"),
+ ("Раскрыть потенциал", r"\bраскры(ть|ва\w+)\s+потенциал\b"),
+ ("Вывести на новый уровень", r"\bвыв(ести|одит)\s+на\s+новый\s+уровень\b"),
+ ("Комплексный подход/решение", r"\bкомплексн(ый|ое|ого|ым)\s+(подход\w*|решени\w+)\b"),
+ ("В связи с этим", r"\bв\s+связи\s+с\s+этим\b"),
+ ("Открывает новые горизонты/перспективы", r"\bоткрыва(ет|ют)\s+новые\s+(горизонт\w+|перспектив\w+)\b"),
+]
+
+# --- Быстрый сканер: категории слов-маркеров -----------------------------
+# Ровно 20 категорий из SKILL.md. Значения — фразы для подстрочного поиска
+# (регистронезависимо). Часть фраз — основы, чтобы ловить словоформы.
+SCANNER: dict[str, list[str]] = {
+ "Канцелярит": [
+ "осуществлени", "реализаци", "внедрени", "оптимизаци", "функционировани",
+ "взаимодействи", "в рамках", "в целях", "в контексте", "на основе",
+ "посредством", "в соответствии с",
+ ],
+ "Кальки": [
+ "является", "стоит отметить", "важно понимать", "можно сказать",
+ "что касается", "в то время как", "с другой стороны", "тем не менее",
+ "несмотря на то что",
+ ],
+ "Раздувание": [
+ "ключев", "важнейш", "значительн", "огромн", "колоссальн", "переломн",
+ "фундаментальн", "невозможно переоценить", "играет роль",
+ ],
+ "Формула-выводы": [
+ "таким образом", "подводя итог", "в заключение", "можно сделать вывод",
+ "суммируя вышесказанное", "на основании вышеизложенного",
+ ],
+ "Чатбот": [
+ "конечно!", "отличный вопрос", "давайте разберёмся", "давайте разберемся",
+ "рад помочь", "надеюсь это было полезно", "с удовольствием",
+ ],
+ "Параллелизмы": ["не просто", "не только", "это не "],
+ "Вводные-открытия": [
+ "в современном мире", "в эпоху", "не секрет что", "не секрет, что",
+ "всё чаще", "все чаще", "по мнению экспертов", "специалисты отмечают",
+ ],
+ "Модальные хеджи": [
+ "может стать", "может повлиять", "может быть полезн", "способен обеспечить",
+ "призван решить", "позволяет достичь",
+ ],
+ "Мотивационные клише": [
+ "раскрыть потенциал", "погрузимся", "вывести на новый уровень",
+ "открывает новые горизонты", "расширить границы", "комплексный подход",
+ ],
+ "Контекстуализаторы": [
+ "в условиях", "в свете", "на фоне", "с учётом", "с учетом",
+ "принимая во внимание", "в связи с этим",
+ ],
+ "Маркетинговые штампы": [
+ "связь с аудиторией", "доверительные отношения", "ключевой момент",
+ "ключевая роль", "индивидуальный подход", "инновационное решение",
+ ],
+ "Псевдо-сократические": [
+ "зачем? потому что", "и что? а то", "почему? сейчас расскажу",
+ ],
+ "Авторитетные трюизмы": [
+ "вот ключевой вывод", "самое важное — это", "самое важное - это",
+ "первый шаг — это", "первый шаг - это", "по своей сути", "в конечном счёте",
+ "в конечном счете",
+ ],
+ "Псевдо-терапевтические": [
+ "ты не ошибаешься", "ты имеешь право", "тихое подтверждение",
+ "это не слабость", "ты настоящий", "сам факт этого",
+ ],
+ "Эмодзи-декор": ["⚡", "✨", "🎯", "🔥", "💡"],
+ "Деепричастные-кальки": [
+ "стоит помнить", "следует учитывать", "необходимо отметить",
+ ],
+ # Технические следы копирования из интерфейса чат-бота. Однозначные улики:
+ # в человеческом тексте не встречаются.
+ # Префикс "re:" = регулярное выражение, остальное — подстрока.
+ "Артефакты копипасты": [
+ ":contentReference", "oai_citation", "utm_source=chatgpt.com",
+ "utm_source=openai", "grok_card://", "attached_file://",
+ "vertexaisearch.cloud.google.com/grounding-api-redirect",
+ "](sandbox:/mnt/data/", "attributableIndex",
+ r"re:oaicite:\d+",
+ r"re:turn\d+(?:search|fetch|file)\d+", # turnNsearchN и родня
+ r"re:citeturn\d+[a-z]+\d+", # слитная метка цитаты
+ r"re:【\d+(?::\d+)?†source】", # OpenAI Assistants
+ r"re:\[citation:\d+\]", # Perplexity-стиль
+ "re:[\ue200-\ue204]", # невидимые разделители цитат ChatGPT
+ r"re:?think>", # остатки рассуждения DeepSeek и др.
+ ],
+}
+
+# Канцелярит-номинализации: суффиксы отглагольных существительных, которые
+# скилл велит разворачивать обратно в глаголы (паттерн #6, #14).
+NOMINALIZATION_SUFFIXES = ("ение", "ание", "ация", "изация", "ировка", "ость")
+
+
+@dataclass
+class MarkerHit:
+ category: str
+ marker: str
+ count: int
+ positions: list[int] = field(default_factory=list)
+
+
+def _find_all(text: str, needle_regex: str) -> list[int]:
+ return [m.start() for m in re.finditer(needle_regex, text, re.IGNORECASE)]
+
+
+def scan_hard_bans(text: str) -> list[MarkerHit]:
+ """Находит конструкции из HARD BANS. Любое попадание = провал."""
+ hits: list[MarkerHit] = []
+ for name, pat in HARD_BANS:
+ pos = _find_all(text, pat)
+ if pos:
+ hits.append(MarkerHit("HARD BAN", name, len(pos), pos))
+ return hits
+
+
+def scan_markers(text: str) -> list[MarkerHit]:
+ """Прогоняет 20 категорий быстрого сканера. Возвращает только попадания.
+
+ Элемент с префиксом "re:" трактуется как регулярное выражение,
+ остальные — как литеральная подстрока (регистронезависимо).
+ """
+ hits: list[MarkerHit] = []
+ for cat, phrases in SCANNER.items():
+ for phrase in phrases:
+ pat = phrase[3:] if phrase.startswith("re:") else re.escape(phrase)
+ pos = _find_all(text, pat)
+ if pos:
+ hits.append(MarkerHit(cat, phrase.removeprefix("re:"), len(pos), pos))
+ return hits
+
+
+def marker_verdict(marker_hits: list[MarkerHit]) -> str:
+ """Шкала из SKILL.md: 0-2 чисто, 3-5 подозрительно, 6+ AI.
+ Артефакт копипасты — однозначная улика: вердикт сразу, без шкалы."""
+ if any(h.category == "Артефакты копипасты" for h in marker_hits):
+ return "артефакты копипасты из чат-бота — текст вставлен из ответа ИИ"
+ total = sum(h.count for h in marker_hits)
+ if total <= 2:
+ return f"{total} — скорее всего чистый текст"
+ if total <= 5:
+ return f"{total} — подозрительно"
+ return f"{total} — AI-генерация с высокой вероятностью"
diff --git a/skills/humanizer-ru/scripts/humanizer_metrics/morphology.py b/skills/humanizer-ru/scripts/humanizer_metrics/morphology.py
new file mode 100644
index 0000000..7e135de
--- /dev/null
+++ b/skills/humanizer-ru/scripts/humanizer_metrics/morphology.py
@@ -0,0 +1,78 @@
+"""Морфология: соотношение существительных к глаголам через pymorphy3.
+
+Закрывает пункт чеклиста «соотношение существительных к глаголам ≤ 2.5:1» —
+тот, который LLM не умеет считать на глаз. У AI-русского ~3:1, у людей ~2:1
+(SKILL.md, паттерн #14, Biber framework). Чем выше отношение, тем «номинальнее»
+текст, тем сильнее канцелярит.
+"""
+
+from __future__ import annotations
+
+import functools
+from dataclasses import dataclass
+
+import pymorphy3
+from razdel import tokenize
+
+
+@functools.lru_cache(maxsize=1)
+def _morph() -> "pymorphy3.MorphAnalyzer":
+ return pymorphy3.MorphAnalyzer()
+
+
+@dataclass
+class MorphStats:
+ nouns: int
+ verbs: int # глаголы + инфинитивы + деепричастия + причастия как глагольные формы
+ noun_verb_ratio: float
+ nominalizations: int # отглагольные существительные (потенциальный канцелярит)
+ tokens: int
+
+ def as_dict(self) -> dict:
+ return self.__dict__.copy()
+
+
+# Что считаем «глагольным» — pymorphy3 теги (OpenCorpora):
+_VERBAL = {"VERB", "INFN", "GRND", "PRTF", "PRTS"}
+_NOUN = {"NOUN"}
+_NOMINAL_SUFFIXES = ("ение", "ание", "ания", "ения", "ация", "изация", "ировка", "ость", "остей")
+
+
+def _is_cyrillic_word(tok: str) -> bool:
+ return any("а" <= c.lower() <= "я" or c.lower() == "ё" for c in tok)
+
+
+def morph_stats(text: str) -> MorphStats:
+ m = _morph()
+ nouns = verbs = nominal = total = 0
+ for t in tokenize(text):
+ w = t.text
+ if not _is_cyrillic_word(w):
+ continue
+ total += 1
+ p = m.parse(w)[0]
+ pos = p.tag.POS
+ if pos in _NOUN:
+ nouns += 1
+ lemma = p.normal_form
+ if lemma.endswith(_NOMINAL_SUFFIXES):
+ nominal += 1
+ elif pos in _VERBAL:
+ verbs += 1
+ ratio = (nouns / verbs) if verbs else float(nouns)
+ return MorphStats(
+ nouns=nouns,
+ verbs=verbs,
+ noun_verb_ratio=round(ratio, 2),
+ nominalizations=nominal,
+ tokens=total,
+ )
+
+
+NV_TARGET = 2.5 # из чеклиста SKILL.md
+
+
+def morph_verdict(s: MorphStats) -> str:
+ if s.noun_verb_ratio <= NV_TARGET:
+ return f"✓ сущ./глаг. = {s.noun_verb_ratio} (цель ≤{NV_TARGET})"
+ return f"⚠ сущ./глаг. = {s.noun_verb_ratio} (цель ≤{NV_TARGET}, канцелярит); номинализаций: {s.nominalizations}"
diff --git a/skills/humanizer-ru/scripts/humanizer_metrics/score.py b/skills/humanizer-ru/scripts/humanizer_metrics/score.py
new file mode 100644
index 0000000..abacb17
--- /dev/null
+++ b/skills/humanizer-ru/scripts/humanizer_metrics/score.py
@@ -0,0 +1,112 @@
+"""Score чистоты: сворачивает детерминированные сигналы в одно число 0-100.
+
+Выше = текст читается живее/человечнее. Это НЕ детектор и НЕ вероятность ИИ:
+просто агрегат уже считаемых метрик (хард-баны, маркеры, ритм, морфология),
+поданный как обратная связь «было/стало». Опирается на пороги, которые уже
+откалиброваны в burstiness/morphology и задокументированы в eval/RESULTS.md.
+
+Пороги штрафов подобраны на eval/corpus (human → высокий score, raw-AI →
+низкий, humanized → между). Калибровочный прогон: см. eval/run_eval.py.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from .burstiness import CV_HUMAN_TARGET
+from .morphology import NV_TARGET
+
+# Тире — отдельный случай: оно и хард-бан, и штатная русская пунктуация
+# (Википедия, диапазоны, «это —»). Поэтому в score не рубим потолком, а
+# штрафуем по плотности с допуском. Имя берём из HARD_BANS markers.py.
+EM_DASH_NAME = "Длинное тире"
+COPY_PASTE_CATEGORY = "Артефакты копипасты"
+
+# Полосы. Совпадают с порогами вмешательства из SKILL.md и тёзки-конкурента.
+BAND_CLEAN = 85 # ≥ — следы ИИ не мешают, не править
+BAND_EDIT = 60 # ≥ — точечная правка; < — полный рерайт
+
+
+@dataclass
+class ScoreResult:
+ score: int # 0-100, выше = чище
+ band: str # "чисто" | "правка" | "рерайт"
+ penalties: list[tuple[str, int]] # (причина, -очки) — это и есть verbose-отчёт
+
+ def as_dict(self) -> dict:
+ return {
+ "score": self.score,
+ "band": self.band,
+ "penalties": [{"reason": r, "points": p} for r, p in self.penalties],
+ }
+
+
+def _band(score: float) -> str:
+ if score >= BAND_CLEAN:
+ return "чисто"
+ if score >= BAND_EDIT:
+ return "правка"
+ return "рерайт"
+
+
+def _per100(count: int, words: int) -> float:
+ return (count / words * 100) if words else 0.0
+
+
+def cleanliness_score(report) -> ScoreResult:
+ """Считает score 0-100 из готового Report (см. humanizer_metrics.analyze)."""
+ words = report.rhythm.words or 1
+ penalties: list[tuple[str, int]] = []
+ score = 100.0
+
+ # 1. Фразовые хард-баны (кроме тире). Однозначные AI-обороты: дорого.
+ hard_phrase = sum(h.count for h in report.hard_bans if h.marker != EM_DASH_NAME)
+ if hard_phrase:
+ pen = min(45, 12 * hard_phrase)
+ score -= pen
+ penalties.append((f"хард-баны (фразы): {hard_phrase}", -pen))
+
+ # 2. Артефакты копипасты из чат-бота: текст буквально вставлен из ответа ИИ.
+ copy_paste = sum(h.count for h in report.markers if h.category == COPY_PASTE_CATEGORY)
+ if copy_paste:
+ pen = 60
+ score -= pen
+ penalties.append((f"артефакты копипасты: {copy_paste}", -pen))
+
+ # 3. Мягкие маркеры (кроме копипасты) по плотности на 100 слов.
+ soft = sum(h.count for h in report.markers if h.category != COPY_PASTE_CATEGORY)
+ if soft:
+ pen = min(30, round(2 * _per100(soft, words)))
+ if pen:
+ score -= pen
+ penalties.append((f"маркеры: {soft} ({_per100(soft, words):.1f}/100 слов)", -pen))
+
+ # 4. Длинное тире по плотности с допуском ~2 на 100 слов: «—» штатно
+ # используется в русском (Википедия, «это —», диапазоны). Слабый сигнал.
+ dash_density = _per100(report.rhythm.em_dash, words)
+ if dash_density > 2.0:
+ pen = min(8, round(3 * (dash_density - 2.0)))
+ if pen:
+ score -= pen
+ penalties.append((f"тире: {report.rhythm.em_dash} ({dash_density:.1f}/100 слов)", -pen))
+
+ # 5. Ровный ритм: чем ниже CV относительно цели 0.45, тем больше штраф.
+ cv = report.rhythm.cv_len
+ if report.rhythm.sentences >= 4 and cv < CV_HUMAN_TARGET:
+ pen = min(20, round((CV_HUMAN_TARGET - cv) / CV_HUMAN_TARGET * 30))
+ if pen:
+ score -= pen
+ penalties.append((f"ровный ритм (CV={cv}, цель ≥{CV_HUMAN_TARGET})", -pen))
+
+ # 6. Номинальность: сущ./глаг. выше цели 2.5 = канцелярит. Слабый сигнал и
+ # главный источник ложных срабатываний (энциклопедический/юр. регистр
+ # легитимно номинален), поэтому штраф мягкий и низко ограничен.
+ nv = report.morph.noun_verb_ratio
+ if nv > NV_TARGET:
+ pen = min(8, round((nv - NV_TARGET) / 0.5 * 3))
+ if pen:
+ score -= pen
+ penalties.append((f"номинальность (сущ./глаг.={nv}, цель ≤{NV_TARGET})", -pen))
+
+ final = max(0, min(100, round(score)))
+ return ScoreResult(score=final, band=_band(final), penalties=penalties)
diff --git a/skills/humanizer-ru/scripts/scan.py b/skills/humanizer-ru/scripts/scan.py
new file mode 100644
index 0000000..73c912e
--- /dev/null
+++ b/skills/humanizer-ru/scripts/scan.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""CLI-сканер: прогоняет текст через детерминированные метрики humanizer-ru.
+
+Использование (из корня репо; у установленного скилла путь: <папка скилла>/scripts/scan.py):
+ python skills/humanizer-ru/scripts/scan.py path/to/text.txt
+ echo "ваш текст" | python skills/humanizer-ru/scripts/scan.py -
+ python skills/humanizer-ru/scripts/scan.py text.txt --json
+
+Это машинная половина режима «Аудит». Для полного очеловечивания (семантика,
+голос, рерайт) нужен сам скилл — этот сканер только подсвечивает грепабельные
+маркеры и считает метрики, которые LLM не умеет мерить на глаз.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from humanizer_metrics import analyze, cleanliness_score
+from humanizer_metrics.burstiness import rhythm_verdict
+from humanizer_metrics.markers import marker_verdict
+from humanizer_metrics.morphology import morph_verdict
+
+
+def _read(src: str) -> str:
+ if src == "-":
+ return sys.stdin.read()
+ return Path(src).read_text(encoding="utf-8")
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description="Детерминированный сканер AI-маркеров (humanizer-ru)")
+ ap.add_argument("source", help="файл с текстом или '-' для stdin")
+ ap.add_argument("--json", action="store_true", help="вывод в JSON")
+ args = ap.parse_args()
+
+ text = _read(args.source)
+ rep = analyze(text)
+ sc = cleanliness_score(rep)
+
+ if args.json:
+ out = rep.as_dict()
+ out["score"] = sc.as_dict()
+ print(json.dumps(out, ensure_ascii=False, indent=2))
+ return 1 if rep.hard_ban_count else 0
+
+ print(f"=== humanizer-ru scan: {args.source} ===\n")
+
+ print(f"ЧИСТОТА: {sc.score}/100 [{sc.band}]")
+ print(" (≥85 чисто · 60-84 точечная правка · <60 рерайт)")
+ for reason, pts in sc.penalties:
+ print(f" {pts:+d} {reason}")
+ print()
+
+ print("HARD BANS:")
+ if rep.hard_bans:
+ for h in rep.hard_bans:
+ print(f" ⛔ {h.marker} ×{h.count}")
+ else:
+ print(" ✓ чисто")
+ print()
+
+ print(f"Маркеры (быстрый сканер): {marker_verdict(rep.markers)}")
+ for h in sorted(rep.markers, key=lambda x: -x.count)[:12]:
+ print(f" • [{h.category}] «{h.marker}» ×{h.count}")
+ print()
+
+ print("Ритм / типографика:")
+ print(f" {rhythm_verdict(rep.rhythm)}")
+ print(f" предложений: {rep.rhythm.sentences}, средняя длина: {rep.rhythm.mean_len} "
+ f"(min {rep.rhythm.min_len} / max {rep.rhythm.max_len}), CV: {rep.rhythm.cv_len}")
+ print(f" многоточий: {rep.rhythm.ellipsis}, скобок: {rep.rhythm.parentheses}, "
+ f"вопросов: {rep.rhythm.questions}")
+ print()
+
+ print("Морфология:")
+ print(f" {morph_verdict(rep.morph)}")
+ print(f" сущ.: {rep.morph.nouns}, глаг.форм: {rep.morph.verbs}, "
+ f"номинализаций: {rep.morph.nominalizations}")
+
+ # Exit code: ненулевой, если есть HARD BANS — удобно для CI/pre-commit.
+ return 1 if rep.hard_ban_count else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/humanizer-ru/scripts/scan_corpus.py b/skills/humanizer-ru/scripts/scan_corpus.py
new file mode 100644
index 0000000..3f5b756
--- /dev/null
+++ b/skills/humanizer-ru/scripts/scan_corpus.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python3
+"""Батч-драйвер сканера: JSONL {path, score, band, hard_ban_count} по всем .md
+корпуса. Переиспользует humanizer_metrics (analyze + cleanliness_score) — своего
+измерителя канцелярита не строит (запрет ДОПОЛНЕНИЯ-1). Один процесс на весь
+корпус вместо N спавнов scan.py.
+
+ python skills/humanizer-ru/scripts/scan_corpus.py
+"""
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from humanizer_metrics import analyze, cleanliness_score
+
+SKIP_DIR_MARK = "graphify-out"
+# Длинное тире сквозное в корпусе (даты/заголовки), считаем его отдельно от
+# настоящего слопа — иначе 78% нот «грязные» только из-за типографики.
+EM_DASH_BAN = "Длинное тире"
+
+
+def iter_md(root: str):
+ for dirpath, dirnames, filenames in os.walk(root):
+ # graphify-каталоги (и их бэкапы/снапшоты) — не знание
+ dirnames[:] = [d for d in dirnames if SKIP_DIR_MARK not in d]
+ for name in filenames:
+ if name.endswith(".md"):
+ yield os.path.join(dirpath, name)
+
+
+def main() -> int:
+ if len(sys.argv) < 2:
+ print("usage: scan_corpus.py ", file=sys.stderr)
+ return 2
+ root = sys.argv[1]
+ if not os.path.isdir(root):
+ print(f"not a directory: {root}", file=sys.stderr)
+ return 2
+ for md in iter_md(root):
+ try:
+ text = Path(md).read_text(encoding="utf-8")
+ except Exception as err: # нечитаемый файл — не роняем весь прогон
+ print(json.dumps({"path": md, "error": str(err)[:120]}, ensure_ascii=False))
+ continue
+ rep = analyze(text)
+ sc = cleanliness_score(rep)
+ slop = sum(h.count for h in rep.hard_bans if h.marker != EM_DASH_BAN)
+ print(json.dumps(
+ {"path": md, "score": sc.score, "band": sc.band,
+ "hard_ban_count": rep.hard_ban_count, "slop_ban_count": slop},
+ ensure_ascii=False,
+ ))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/mnemazine/SKILL.md b/skills/mnemazine/SKILL.md
index c8dc471..330320e 100644
--- a/skills/mnemazine/SKILL.md
+++ b/skills/mnemazine/SKILL.md
@@ -1,87 +1,462 @@
---
-name: mnemazine
-description: Use when turning raw files, links, screenshots, transcripts, PDFs, guides, or repositories into verified reusable knowledge for an Obsidian-compatible vault.
+name: mnemazina
+description: Мнемозина — агентный конвейер знаний. Превращает всё, что попало в ~/Desktop/Mnemazine Inbox/ (скриншоты, PDF, ссылки, видео, аудио, заметки), в проверенные классифицированные Obsidian-ноты с блоком «как это поможет мне», обновляет оглавления разделов и мастер-индекс, возвращает справку к действию. Use whenever the user runs /kb, /mnemazina, /kb find, /kb fix, /kb backlog, /kb migrate, or says anything about processing collected material — «обработай входящие», «разбери инбокс», «разложи по базе знаний», «process my inbox», «ingest this». Also use when the user pastes a link, text, or screenshot asking to save/remember it («сохрани это в базу», «добавь в vault», «запомни на будущее»), and when the user asks what their knowledge base holds on a topic («/kb find », «найди в базе знаний», «что у меня есть про…»). Trigger even if the user never names Мнемозина or /kb — any request to file material INTO the personal vault ($MNEMAZINE_VAULT) or retrieve knowledge FROM it belongs here.
---
-# Mnemazine
+# Мнемозина — агентный конвейер знаний
-Mnemazine is a knowledge refinery skill.
+Превращает сырьё из инбокса в проверенное, разложенное по разделам знание с пометкой
+«как это поможет мне» и короткой справкой к действию.
-Use it when the user gives raw material and wants it preserved as durable knowledge, not as a dump.
+**Порядок истины при расхождении:** `$MNEMAZINE_VAULT/99 Система/00 СИСТЕМА — Агентный конвейер знаний.md`
+(принципы/таксономия/формат справки) и `$MNEMAZINE_VAULT/99 Система/Протокол_Мнемозина.md` (ворота полноты)
+бьют этот файл, потому что SSOT на диске обновляется чаще скилла. Прочитай «00 СИСТЕМА…» перед
+исполнением. У нового пользователя этого файла может не быть — это не ошибка: первый запуск
+работает без него.
-## Chat Shortcut
+**Три слоя Карпаты — у каждого свой владелец правки:** сырьё (инбокс + `_archive`) неизменяемо,
+конвейер его не редактирует никогда · ноты принадлежат конвейеру — в разделы vault они попадают и
+меняются только через него · схема («00 СИСТЕМА…» + `Протокол_Мнемозина.md`) со-эволюционирует с
+владельцем: её меняет решение владельца, не прогон. Слой, правленный не своим владельцем,
+перестаёт быть доказуемым.
-If the user says `Mnemazine update`, `Мнемозина update`, or `обнови Mnemazine`, run from the project root:
+## Рой (основной режим)
-```bash
-npm run update
+Запускай через **mnemazina-coordinator** — единую точку входа для всего, потому что он один
+держит гейты полноты; ручной обход координатора теряет ворота и делает тихий дроп возможным.
+Координатор сам делает guard, triage, fan-out процессоров, storage, retrieval.
+
+```
+Agent(
+ subagent_type: "mnemazina-coordinator",
+ prompt: "{команда пользователя или контент}"
+)
```
-This updates from GitHub with `git pull --ff-only`, preserves local config, reinstalls local wrappers, and runs syntax checks. It must not process inbox files.
+**Четыре агента роя** (`~/.claude/agents/mnemazina-pipeline/`):
-If the user says `Mnemazine`, `Mnemazine inbox`, `Мнемозина`, `Мнемозина, inbox`, or `запусти Мнемозину`, run from the project root:
+| Агент | Модель | Роль |
+|---|---|---|
+| `mnemazina-coordinator` | sonnet | Оркестратор-контролёр: census→triage→ГЕЙТ-1→fan-out→store→ГЕЙТ-2→ГЕЙТ-3→леджер |
+| `mnemazina-processor` | haiku/sonnet/opus (по тиру) | Стадии 2–5 для одного материала (параллельно). Пишет `source:` во frontmatter |
+| `mnemazina-librarian` | haiku→sonnet | Стадии 6–7 (хранение, без архива) + retrieval + архивация только за ГЕЙТ-3 |
+| `mnemazina-reconciler` | sonnet | «Менделеев» — сверщик полноты: каждый файл инбокса → нота/причина. Блокирует архив и «done» |
-```bash
-npm start
+**Выбор модели по тиру (решает координатор):**
+
+| Тир | Условие | Модель |
+|---|---|---|
+| 0 | Код/tech-структура | Ollama `qwen2.5-coder:7b` pre-pass → haiku |
+| 1 | Простой текст/скриншот | haiku extract + sonnet verify+refine |
+| 2 | Стандарт (статья/промт/методика) | sonnet на всех стадиях |
+| 3 | Мед/юр/фин факт · спорное · сложный синтез | sonnet + opus verify+refine |
+
+**Fable 5 — именованный опциональный тир, не дефолт.** Для стадий Extract/Verify/Classify/Refine
+(`mnemazina-extract`/`-verify`/`-classify`/`-refine` или комбинированный `mnemazina-processor`)
+координатор спавнит агентов с `model: "fable"` (Claude Fable 5) вместо haiku/sonnet/opus только
+когда пользователь явно просит Fable 5 на прогон («прогони через Fable 5», «модель — Fable 5»),
+потому что это самый дорогой тир и без явной просьбы его цена не оправдана.
+Guard/Triage/Distribute/Store/Index/Reconciler остаются на дефолтном тире (haiku/sonnet) — оверрайд
+касается только синтез-стадий одного материала, не механических и не gate-стадий. Без явной
+просьбы — таблица тиров 0–3 как обычно.
+
+**MCP и инструменты в конвейере:**
+
+| Инструмент | Где использует | Зачем |
+|---|---|---|
+| `mcp__markitdown__convert_to_markdown` | mnemazina-processor стадия 2 | PDF/DOCX → markdown до чтения Claude (−60% токенов) |
+| `kb-fetch ` CLI | mnemazina-processor стадия 3 | Чтение первоисточника локально за $0 (markitdown для бинарников, trafilatura для HTML; честные exit-коды вместо выдумки) |
+| `kb-search "<запрос>" [--ru]` CLI | mnemazina-processor стадия 3 | Метапоиск без ключей (ddgs: brave/ddg/mojeek/startpage, --ru добавляет yandex) — фолбэк, когда встроенный WebSearch пуст |
+| YouTube-сабы через `yt-dlp --write-subs --write-auto-subs` | стадия 0 | Готовые субтитры за секунды и $0 вместо ~30 мин whisper-транскрипции часового ролика; сабов нет → whisper как раньше |
+| `agent-reach` CLI (`doctor`) | стадия 3, платформы | Роутер платформ: RSS/Bilibili/V2EX работают; его web-канал (Jina, квота) не использовать — kb-fetch локальнее; Reddit/Twitter выключены — аккаунтов у владельца нет, живые треды соцсетей без логина не отдаёт никто |
+| Ollama `localhost:11434` | mnemazina-processor pre-pass | Бесплатная очистка кода/техконтента |
+| Memory MCP (если доступен) | mnemazina-librarian FIND | Быстрый cross-session поиск |
+
+**Retrieval:**
+- `/kb find <запрос>` → mnemazina-coordinator → mnemazina-librarian (FIND mode)
+- Быстрый grep по vault, ранжирование, проектный контекст из `_ПРОЕКТЫ.md`
+- Ответ: топ-7 заметок с relevance score + связь с проектами + действие
+- Нетривиальный синтез ответа (сравнение, найденная связь между нотами) → предложи сохранить его
+ заявкой в инбокс тем же путём (`agent-research--…`), потому что синтез, умерший в чате,
+ не накапливается.
+
+**Inline-контент от пользователя:** пользователь вставил текст/ссылку прямо в чат → координатор
+сохраняет в инбокс и обрабатывает, потому что нота без файла-источника не пройдёт сверку покрытия.
+
+**Боковая дверь агента:** файл-заявка `agent-research----.md` в
+`~/Desktop/Mnemazine Inbox/` — законный вход наравне с inline владельца, потому что файл, положенный
+в раздел vault напрямую, минует census и гейты (канон — `docs/AGENT-MEMORY.md` проекта mnemazine).
+Конвейер обрабатывает заявку как обычное сырьё; нота получает `type: agent-research`,
+`claim_status: provisional` — в проверенный корпус агентское знание переходит только операцией
+graduate после ревью, потому что агентская верификация слабее владельческого конвейера.
+
+**Резервный режим:** mnemazina-coordinator недоступен — это не ошибка, выполняй стадии ниже
+вручную сам; недоступный отдельный агент `mnemazina-*` — тоже: бери его инструкцию из
+`~/.claude/agents/mnemazina-pipeline/` и исполняй сам.
+
+## Режимы
+
+| Команда | Что делает |
+|---|---|
+| `/kb` или `/mnemazina` | Обработать новое сырьё из `~/Desktop/Mnemazine Inbox/` (см. Пути) |
+| `/kb backlog` | Легаси-бэклог удалён 2026-05-31; режим — для будущих массовых дампов, если появятся |
+| `/kb migrate` | Перенести `AI Knowledge Base/` → `08 AI и Инструменты/`, починить связи |
+| `/kb fix <файл> [<раздел>]` | Ре-классификация заметки без Finder → агент `mnemazina-fix` |
+| `/kb watch` | Авто-обработка, по умолчанию выключена (включение — см. Авто-режим ниже) |
+
+### OPS вызова (важно)
+
+- Движок Workflow **запрещает** `Date.now()`/`new Date()` в скриптах, потому что это ломает
+ resume. RUN_ID/created_at берутся из `args.now` (ISO), иначе fallback `unstamped000000`.
+ Не возвращай Date в скрипты — движок отвергнет прогон на resume.
+- Named-вызов `Workflow({name:"mnemazina-pipeline"})` **кэширует скрипт на старте сессии**, поэтому
+ правка `~/.claude/workflows/mnemazina-pipeline.js` мид-сессии не подхватится — гони через
+ `Workflow({scriptPath:"~/.claude/workflows/mnemazina-pipeline.js"})` или новую сессию.
+- **Уникальный RUN_ID:** mode-detect читает `args.message` отдельно от `args.now`, так что объект
+ слать безопасно. Всегда: `Workflow({name:"mnemazina-pipeline", args:{now:"", message:"<команда|пусто>"}})`.
+ ISO брать из Bash `date -u +%FT%TZ` (Date в скрипте запрещён). Без `now` все прогоны получают
+ id `kb-unstamped000000` и сталкиваются в `_run-observability.jsonl` — леджер наблюдаемости
+ становится нечитаем.
+- Форматы `args`: строка-команда (`"найди кофе"`), строка-JSON (`'{"now":"…","message":"…"}'`) или
+ объект (`{now,message}`) — все три дают одинаковый mode-detect. INLINE-режим срабатывает по длине
+ `message`>80, не по сериализации объекта.
+- **Census детерминирован:** состав инбокса = `find -maxdepth 1 -type f` (агент `census-list`),
+ не haiku-census-агент, потому что LLM-перепись врёт в обе стороны — дропает реальные файлы и
+ считает мусор подпапок типа `.claude/scheduled_tasks.lock`. Empty-check по `trueCount` с диска.
+ Top-level счётчики итоговой сводки тоже могут врать — сверяй диск (`ls` инбокса, ctime архива),
+ не поля сводки.
+- **Codex fallback:** если Claude Code недоступен, запускай `~/.codex/bin/mnemazine-kb [команда]`.
+ Это адаптер того же `mnemazina-pipeline.js`: `agent(...)` исполняется через `codex exec`, агенты
+ берутся из `~/.codex/agents/mnemazina-pipeline/`, OCR из `~/.codex/skills/mnemazina/vision-ocr`.
+ Проверка паритета зеркал — одной командой (отдельного скрипта нет):
+ `diff -rq ~/.claude/agents/mnemazina-pipeline ~/.codex/agents/mnemazina-pipeline && diff -q ~/.claude/workflows/mnemazina-pipeline.js ~/.codex/workflows/mnemazina-pipeline.js`.
+ Дифф не пустой — это не ошибка, а сигнал пересинхронизировать codex-зеркало из канона `~/.claude`.
+- **Токены в финале обязательны:** итоговый результат всегда содержит `token_usage`, потому что
+ без него token-аудит сессии слеп. Claude runtime берёт оценку из `abtop`/`_run-observability.jsonl`;
+ Codex fallback суммирует `tokens used` каждого `codex exec` agent-вызова.
+
+## Пути
+
+- **База знаний** (стабильна): `$MNEMAZINE_VAULT/` · Стейджинг: `$MNEMAZINE_VAULT/00 Входящие/`
+- **Инбокс** (ЗАКРЕПЛЁН на Рабочем столе): `~/Desktop/Mnemazine Inbox/`. Сюда юзер кидает сырьё —
+ иди сюда сразу, не спрашивай и не ищи, потому что поиск инбокса по диску жжёт токены на
+ решённый вопрос. (Старый симлинк-алиас на эту же папку может существовать для совместимости.)
+- **Проект** «Полезные промты» (бэклог + tools/docs + архив) — может переезжать, поэтому ищи по
+ маркер-файлу, а не по запомненному пути:
+ ```bash
+ INBOX="$HOME/Desktop/Mnemazine Inbox" # закреплён; создай, если нет
+ PROJ=$(dirname "$(find ~/Desktop ~ -maxdepth 5 -name 'AI_KNOWLEDGE_BASE_SYSTEM.md' 2>/dev/null | head -1)")
+ ARCHIVE="$INBOX/_archive" # durable: mv обработанных исходников в подпапки ГГГГ-ММ/ (вне git-vault, БЕЗ авто-удаления)
+ ```
+ Маркер не нашёлся → `PROJ` пуст — это не ошибка: обычный `/kb` работает без проекта, `PROJ`
+ нужен только режимам backlog/migrate; сообщи об этом в справке и продолжай.
+- Легаси-бэклог: удалён 2026-05-31 (пусто). Новый массовый дамп → клади папкой в `$PROJ` и зови `/kb backlog`.
+- Транскрипция (Стадия ⓪): движок `~/.npm-global/bin/whisper` (openai-whisper, модель small);
+ рабочая папка `$INBOX/_work/`.
+
+## Подготовка (один проход в начале) — агент `mnemazina-guard` (haiku)
+
+1. Проверь, что база доступна на запись и пути существуют (создай отсутствующее), потому что
+ отказ записи в середине прогона оставляет пол-обработанный инбокс.
+1б) **Git-снапшот vault** — до первого `mv` и до merge дублей в Стадии ⑥, потому что merge без
+ снапшота необратим:
+ ```bash
+ VAULT="${MNEMAZINE_VAULT:?укажите путь к vault}"
+ git -C "$VAULT" rev-parse --git-dir >/dev/null 2>&1 || git -C "$VAULT" init .
+ git -C "$VAULT" add -A && git -C "$VAULT" commit -m "pre-/kb $(date +%Y-%m-%dT%H:%M)" --allow-empty
+ ```
+ При сбое: `git -C "$VAULT" log --oneline -5` → точка восстановления.
+1в) **Lockfile прогона** — защита read-modify-write индексов от параллельного `/kb`:
+ ```bash
+ LOCKFILE=/tmp/kb-run.lock
+ [ -f "$LOCKFILE" ] && { echo "Уже идёт прогон (PID $(cat $LOCKFILE)). Удалите $LOCKFILE."; exit 1; }
+ echo $$ > "$LOCKFILE"; trap "rm -f $LOCKFILE" EXIT
+ ```
+ Lockfile занят — это не сбой твоего кода, а параллельный прогон: сообщи пользователю и
+ остановись; чужой lock не удаляй сам, потому что удаление на живом прогоне даёт гонку
+ в `_МАСТЕР-ИНДЕКС`.
+2. Прочитай `_ROUTING.md` (корень vault) и `99 Система/_ШАБЛОНЫ.md` — дешёвый первый проход,
+ который избавляет от переспрашивания таксономии на каждом материале.
+3. Собери список только нового сырья: пропусти `README.md` и уже обработанное (сверь с
+ `99 Система/Лог обработки.md`). Для каждого материала пиши в лог при старте каждой стадии,
+ не только в финале, потому что лог только-по-финалу теряет след упавшей стадии.
+ Инбокс пуст — это не ошибка: скажи об этом и предложи `/kb backlog`.
+4. **Durable-архив:** обработанные исходники `mv` в `$ARCHIVE/ГГГГ-ММ/` (подпапка по дате прогона),
+ БЕЗ авто-удаления, потому что оригиналы нужны для claim↔источник ре-верификации нот.
+
+## Конвейер (⓪ транскрипция + 7 стадий)
+
+Вход — медиа (ссылка/файл видео/аудио/подкаст) → сначала Стадия ⓪ (`mnemazina-transcribe`), затем 1–7.
+Один материал = одно самостоятельное знание = один `.md`. Обрабатывай ВСЕ материалы инбокса,
+не один: они независимы и могут быть на разные темы → разные разделы и заметки; батч — не одна
+тема. Группируй только настоящие дубли/связанное (стадия 1). Много материалов → распараллель
+субагентами (рой по умолчанию). Каждый материал проходит все стадии независимо; индексацию делай
+батчем в конце, потому что per-материальная индексация даёт N перезаписей одного индекса.
+Тяжёлое чтение (картинки, PDF, веб) делегируй субагентам — в основном контексте оно вытесняет
+план прогона.
+
+Субагенты (`~/.claude/agents/mnemazina-pipeline/`), модели по сложности:
+
+| Стадия | Агент | Модель | Выход |
+|---|---|---|---|
+| pre-run | `mnemazina-guard` | **haiku** | git-снапшот + lockfile + retention. Блокирует конвейер при гонке |
+| ⓪ Транскрипция | `mnemazina-transcribe` | haiku | `transcript.md` + сырой `segments.json` (если вход — медиа) |
+| 1 Триаж | `mnemazina-triage` | haiku | список материалов + тип + группы, дубли отсеяны |
+| 2 Извлечение | `mnemazina-extract` | sonnet | чистое ядро (OCR/чтение, шум убран) |
+| 3 Верификация | `mnemazina-verify` | sonnet (спорное→**opus**) | первоисточник + VERIFIED-ENUM + факт/реконструкция/добавлено |
+| 4 Классификация | `mnemazina-classify` | sonnet | раздел (или предложение нового по правилам) |
+| 5 Огранка | `mnemazina-refine` | sonnet (сложное→**opus**) | готовая заметка + блок «как поможет мне» + справка |
+| 6 Распределение | `mnemazina-distribute` | sonnet | `.md` записан в раздел, вики-связи, дубли слиты (с git-снапшотом ДО merge) |
+| 7 Индексация | `mnemazina-index` | haiku | обновлены `_Содержание.md`, `_МАСТЕР-ИНДЕКС.md`, `_ROUTING.md`, лог |
+| 7.5 Сверка (ГЕЙТ) | `mnemazina-reconciler` | sonnet | «Менделеев»: каждый файл инбокса → нота (по `source:`)/причина. Маркер `ПОКРЫТИЕ ПОЛНОЕ ✓` или список дыр. Блокирует архивацию |
+| fix | `mnemazina-fix` | sonnet | ре-классификация: `mv` + frontmatter + индексы + лог |
+
+## Ворота полноты (принудительное исполнение)
+
+Главное правило системы: **ни один файл инбокса не архивируется и прогон не закрывается «done»,
+пока на диске не доказано, что файл учтён** — потому что единственный смертный грех конвейера
+это тихий дроп материала. SSOT: `99 Система/Протокол_Мнемозина.md`.
+
+Мнемозина здесь — надзиратель, а не участник: маркер отсутствует → СТОП, следующая стадия не
+стартует; каждая стадия отчитывается «✓ Стадия N» / «❌ Стадия N — причина»; 2 провала подряд →
+СТОП + уведомить пользователя; архив открывается только за ГЕЙТ-3 (а он требует пройденного ГЕЙТ-2); `done` — лишь при
+`unaccounted==0` и сходящемся леджере.
+
+Три ворот-маркера. Условие проверяет **код** workflow (детерминированная сверка списков файлов),
+не суждение агента, потому что агент-автор не судит полноту своей же работы:
+
+| Гейт | Маркер | Когда | Условие (не выполнено → СТОП/ремонт) |
+|---|---|---|---|
+| ГЕЙТ-1 | `## МАНИФЕСТ ПОЛНЫЙ ✓` | после триажа | `union(units.files) ∪ classified == census(инбокс)`. Файлы, что триаж пропустил, **форсируются** в юниты — триажу на полноту не доверяем |
+| ГЕЙТ-2 | `## ПОКРЫТИЕ ПОЛНОЕ ✓` | после Store | каждый census-файл → нота с `source:` на диске ИЛИ причина (`dup`/`noise`/`unreadable`/`deferred`). Дыры → авто-ретрай-раунд (Sonnet) |
+| ГЕЙТ-3 | `## АРХИВ РАЗРЕШЁН ✓` | после сверки | `mv` в архив **только** учтённых файлов. Непокрытые **остаются в инбоксе** + флаг — не теряются |
+
+**Гейт качества ноты (NOTE-SPEC):** после Store, до Reconcile —
+`node "$MNEMAZINE_ROOT/scripts/mnemazine-vault-quality-gate.mjs" --spec --changed-since <старт прогона>`.
+Провал ноты = она уходит в ретрай, не в раздел, потому что пожелание шаблона исполняется
+вероятностно, а код-гейт всегда (канон — `docs/NOTE-SPEC.md` проекта mnemazine).
+
+**Контракт ноты (обязателен):** каждый процессор пишет `source: <точное_имя_исходного_файла>`
+во frontmatter, потому что это единственный ключ наземной сверки — нота без `source:` покрытием
+не засчитывается, и файл будет числиться дырой.
+
+**Леджер в финале** (всегда в сводке): `noted + dup + noise + unreadable + deferred + unaccounted == census`.
+Расхождение → статус `done_with_gaps` (не `done`), дыры названы поимённо.
+
+**Census ≠ триаж.** Census (Кирилов, haiku) механически перечисляет ВСЕ файлы инбокса — наземная
+правда. Триаж (Сопиков) классифицирует. Сверщик (Менделеев) сверяет триаж с census и с диском.
+Три независимых взгляда, потому что пропуск одного ловится другим.
+
+## Токеносбережение (встроено в workflow)
+
+База — 95% скриншоты; токены утекают на спавне агента-на-материал и повторной обработке. Меры:
+
+| Мера | Стадия | Эффект |
+|---|---|---|
+| **hash-cache** (`99 Система/_processed-hashes.json`) | Census | SHA-256 каждого файла; уже обработанный → скип за **0 токенов** (ни агента, ни vision). Все cached → ранний выход + архив. Закрывает корень инцидента «дроп-124» — повторную обработку, на которой терялись файлы |
+| **markitdown** CLI | Извлечение | PDF/DOCX/PPTX/XLSX/EPUB → markdown локально до Claude (не vision/сырьё). Уже установлен |
+| **локальный OCR** (Apple Vision) | OCR-проход (до триажа) | Скрин/картинка → `vision-ocr "<файл>"` локально → текст-сайдкар `.ocr/*.txt`, **0 токенов**, русский точно. Облачный vision — только фолбэк (пусто+TIER3). Не ollama/llava — галлюцинирует на русском |
+| **локальная транскрипция** (openai-whisper) | TRANSCRIBE-проход | Видео/аудио → `whisper --model small` локально → `.transcript/*.txt`, $0. Видео больше не deferred |
+| **cost-aware тиры** | Process | text/pdf/docx/xlsx/url/video → Haiku (тир 1); код → тир 0; мед/юр/фин → Sonnet/Opus |
+| **семантический дедуп** (fastembed) | Process 4.5 | пере-скриншот/пере-сейв того же знания (другой хэш, та же суть) → cosine ≥0.72 к ноте vault → дубль, новую не плодим. Локально (`~/.venvs/kb-embed`, multilingual-MiniLM), без Ollama. Индекс `99 Система/_embeddings.json`, дозапись после Store. Скрипт `kb-embed.py` (build/add/query) |
+
+После Store librarian дописывает хэши обработанного в кэш, чтобы следующий прогон их не тронул.
+**Извлечение — LOCAL-FIRST, $0:** OCR = Apple Vision (`vision-ocr`), транскрипция = openai-whisper,
+текст-доки = markitdown, дедуп = fastembed. Облачный vision — только фолбэк. Для извлечения Ollama
+не нужен (llava отклонён — галлюцинирует на русском); pre-pass кода на `qwen2.5-coder:7b` (тир 0) —
+отдельная, живая роль.
+
+### Стадия ⓪ (транскрипция) — вход видео/аудио/URL
+
+Материал-ссылка (YouTube/1000+ сайтов) или файл (видео/аудио/подкаст) → `mnemazina-transcribe`:
+`yt-dlp` → `ffmpeg` (wav 16k mono) → `~/.npm-global/bin/whisper --model small` → `transcript.md` +
+сырой `segments.json`. Транскрипт держи сырым (без summary), потому что ценное из него извлекают
+стадии 2–3, а ранний summary срезает то, что они ищут. Модель: дефолт `small` (кэш, ~0.5x realtime,
+авто-язык RU/EN); макс точность → `medium`/`large-v3`. Нет инструмента (yt-dlp/ffmpeg/whisper) —
+это не тупик: предложи установку с объяснением «зачем», решает юзер (пункт «Проверка инструментов»
+в справке). Приватное видео → нужны cookies, спроси.
+
+### Контроль стадии 3 (верификация + обогащение)
+
+**Обогащение — всегда, это дефолт.** Внешний поиск разрешён без спроса, потому что каждая нота
+строится из исследованного первоисточника, не из семени-скрина. `--private` — только опт-ин
+(юзер явно пишет), тогда: локальная верификация, `verified` → `непроверяемо-методом (--private)`.
+
+**Token-frugal контракт** — тяжёлое чтение сети несёт локальный `kb-fetch` за $0, контекст агента ест минимум:
+- **GitHub-репо/инструмент → сначала GitHub MCP** (`mcp__github__*`, владелец его выдал —
+ авторизация внутри); MCP недоступен → REST API, не scrape, потому что scrape на GitHub
+ блокируется: `curl -s https://api.github.com/repos/{owner}/{repo}` → точные звёзды/`pushed_at`/license;
+ релиз `.../releases/latest`. Парсь `jq`/`python3`. Лимита 60/ч хватает; больше → keychain-токен
+ (`printf 'protocol=https\nhost=github.com\n\n' | git credential fill` — по host, метка аккаунта
+ несущественна; токен не печатать и не коммитить — утечка в лог/git необратима).
+- **Не-GitHub URL → `kb-fetch `** (симлинк в `~/.local/bin`, канон —
+ `~/Проекты/mnemazine/scripts/kb-fetch.py`): один вызов → один JSON с `markdown`, бинарники
+ (pdf/docx/…) конвертит markitdown, HTML — trafilatura, кодировки легаси-рунета чинит сам.
+ Exit-коды честные: `2` = needs_js (эскалируй на Playwright MCP или WebFetch), `3` = заблокировано
+ (пометь «источник недоступен», содержимое не выдумывай), `4` = сеть. `ok:false` → факт остаётся
+ непроверенным, это штатный исход, не сбой.
+- **Поиск: встроенный WebSearch первым** (бесплатен, уже оплачен подпиской); пусто/рунет →
+ `kb-search "<запрос>" [--ru]` (ddgs-метапоиск без ключей: brave/ddg/mojeek/startpage, `--ru`
+ добавляет yandex последним — он лучше индексирует рунет, но банит агрессивнее всех).
+- **Firecrawl — только по явной команде владельца** («жги кредит»), потому что это платные кредиты
+ и его Fire-engine нужен лишь классу сайтов за жёсткой анти-бот-защитой; sgai из конвейера удалён
+ (бесплатного режима у него нет, кредиты разовые).
+- В ноту — дистиллят ≤120 слов (что это · выгода · звёзды/версия/цена · 1 подводный камень · URL),
+ не дамп, потому что дамп в ноте — это те же токены при каждом будущем чтении vault.
+- Дедуп: перед вызовом `grep` vault (тема покрыта → скип). Кэш `99 Система/_enrich-cache.json`
+ (повтор = 0 вызовов). Батч похожих нот → 1 заход.
+
+Приоритет источников: WebSearch (встроенный) → `kb-search` (ddgs) — для поиска; `kb-fetch` →
+Playwright MCP/WebFetch (needs_js) — для чтения URL; Firecrawl — только по явной команде владельца.
+Промт из материала прогони сам (выполним ли, даёт ли заявленное), потому что заявление автора —
+не факт. Факт/цифру/мед./юр./фин. сверь с официальным источником.
+
+`verified` — пять значений (VERIFIED-ENUM):
+- `подтверждён` — факт проверен по внешнему источнику
+- `источник-не-найден` — искали, не нашли (это не значит «неверно»)
+- `непроверяемо-методом` — PDF за paywall, личный черновик
+- `проверено-практикой` — выставляет только пользователь после применения, потому что практику агент за него не проживёт
+- `облако-недоступно` — сеть/поиск деградировали: kb-search исчерпал бэкенды, kb-fetch вернул blocked, WebSearch пуст
+
+Не подтвердилось — это не повод дропать: ставь одно из четырёх non-`подтверждён` значений,
+заметку сохраняй, факт вынеси в справку — решает пользователь.
+
+### Стадия 4 — новый раздел
+
+Новый раздел — только при выполнении всех условий контракта (не лёг ≥70% никуда · устойчивая
+область · ≥2 знания со временем), потому что лёгкое создание разделов размывает таксономию до
+нечитаемости. Иначе — ближайший раздел + уточняющий тег. Создал раздел → обнови мастер-индекс,
+роутинг, лог и обязательно вынеси в справку, чтобы пользователь мог отменить.
+
+### Стадия 5 — фрейминг «как поможет мне»
+
+Каждая заметка обязана иметь блок (без него знание лежит мёртвым — нет входа в действие):
+- Текущие проекты — к чему применимо. Список берётся только из
+ `$MNEMAZINE_VAULT/99 Система/_ПРОЕКТЫ.md` (единый источник; не хардкодить здесь, потому что хардкод
+ протухает молча). Файл пуст или отсутствует — это не ошибка, ставь общий шаблон: «Применить
+ к задаче, над которой работаете сейчас. Чтобы получать персональные шаги — добавьте проекты
+ в `_ПРОЕКТЫ.md`».
+- Саморазвитие — какой навык/привычку качает.
+- Следующее действие — одно конкретное действие на сегодня.
+
+### Стадия 5.6 — самообучающиеся референсы доменов
+
+Знание несёт **actionable-способность по домену** (новый скилл, MCP, CLI, инструмент, правило,
+техника) → конвейер дозаписывает её в `~/.claude/references/<домен>.md`, потому что так карты
+инструментов умнеют вместе с vault, а не отстают от него.
+
+**Маппинг знание → домен → файл:**
+
+| Сигнал ноты (теги/раздел/суть) | Домен | Файл |
+|---|---|---|
+| security / уязвимость / auth / секреты / OWASP / pentest | безопасность | `references/security.md` |
+| дизайн / UI / UX / Figma / анимация / типографика / бренд | дизайн | `references/design.md` |
+| агентные системы / рой / оркестрация / GSD / loop / harness / суб-агенты | агенты | `references/agents.md` |
+| веб-поиск / скрейп | бесплатный стек kb-fetch/kb-search | `~/Проекты/mnemazine/scripts/kb-fetch.py` (Firecrawl — легаси, только по команде владельца: `references/firecrawl.md`) |
+| деплой / сервер / VPS / CI | деплой | `references/deploy.md` |
+| новый устойчивый capability-домен | — | создать `references/<домен>.md` по образцу `security.md` |
+
+**Правила дозаписи:**
+- Только actionable (имя скилла · команда установки · когда применять) — пересказ ноты в референсе
+ дублирует vault и протухает вторым экземпляром.
+- Дедуп: уже в референсе → не дублировать (можно уточнить).
+- Внешний код (установка) — правило зависит от типа находки, см. Стадию 5.65: Claude Code/агентный
+ скилл → автоустановка; MCP-сервер/open-source система/tool → «добрать (явное добро)».
+- Что дозаписано — строкой в сводную справку: «Референсы обновлены: …».
+
+### Стадия 5.65 — автоустановка скилла vs подтверждение для MCP/tool
+
+Развилка на находках, которые документируют внешнюю способность для агента — применяется ДО
+Стадии 5.7 (регистрация в routing-реестре) и решает, ставить ли находку молча или ждать владельца:
+
+- **Материал документирует Claude Code / агентный скилл** (переиспользуемая процедура/промт-паттерн
+ для AI-агента) → устанавливать автоматически: добавить в `~/.claude/skills/`, зарегистрировать в
+ `~/.agents/SHARED-SKILLS-WORKFLOWS.md` и `~/.agents/GITHUB-STARS-LEDGER.md` (если применимо),
+ без дополнительного подтверждения владельца — скилл это текст, риск низкий, откат = удаление папки.
+- **Материал документирует MCP-сервер или open-source систему/инструмент, требующий установки**
+ (npm/pip/docker/clone) → НЕ устанавливать автоматически, потому что это внешний код с большей
+ поверхностью риска (сеть, credentials, системные изменения). Вынеси находку в отчёт прогона и
+ дождись явного «да» от владельца перед установкой. _(Правило 2026-07-12, kb-20260712T131126.)_
+
+### Стадия 5.7 — регистрация способности в routing-реестре
+
+Знание несёт **скилл/MCP/CLI/инструмент с именем-id** (не просто технику) → зарегистрируй его в
+реестре способностей, чтобы автоподбор route-skills увидел его немедленно, а не после
+weekly-пересбора.
+
+**Как:** дописать JSONL-строку в `~/.agents/registry/overrides.jsonl`:
+```json
+{"id":"<имя-скилла-как-в-skills>","rating":4,"model":"S","domains":["<домен>"],"purpose":"<одной строкой>","use_when":"<триггер-слова задачи>"}
```
+- `id` = точное имя скилла (папка в `skills/`), потому что только так `build_registry` свяжет
+ запись с установленным скиллом. Знание-only (ещё не установлен) → запись = «кандидат», станет
+ полной после установки.
+- `domains`/`use_when` — чтобы routing ловил по задаче (включая RU-слова).
+- Запись в `overrides.jsonl` под `WatchPaths` → launchd `com.athena.registry-watch` сам гонит
+ `registry-rebuild.sh` (index+registry+views+graphify+validate) → routable «сразу же».
+ Гарантированно-сразу (без ожидания watch): `bash ~/.agents/registry/scripts/registry-rebuild.sh --now`.
+- Дедуп: id уже в `overrides.jsonl`/`registry.jsonl` → уточни строку, не плоди дубль — дубль id
+ делает выбор реестра недетерминированным.
+- В сводку: «Реестр способностей: + (routable)».
+- Зеркалировать обновлённый референс по правилу зеркалирования (после справки/решения).
-For live inbox work, do not use `npm run run`. `npm start` runs the strict desktop protocol and fails before archive if deep atomization/enrichment did not happen.
+## Финал
-## Contract
+1. Источник опустел: обработанный исходник перемещён (`mv`) в `$ARCHIVE`, в инбоксе только
+ `README.md`. (Политика: durable-архив БЕЗ авто-удаления — см. Подготовку, шаг 4.)
+2. Обязательные код-шаги (детерминированный код с exit-кодом, не суждение агента):
+ - `node "$MNEMAZINE_ROOT/scripts/mnemazine-refresh-core-indexes.mjs"`, затем его
+ `--check` гейт — exit ≠ 0 значит индексы не сошлись, чинить до справки.
+ - `graphify --update` по vault (граф — память Мнемозины).
+ - Catch-up линта: `$MNEMAZINE_VAULT/99 Система/_lint/.last-lint` отсутствует или старше 36 часов →
+ прогнать `node "$MNEMAZINE_ROOT/scripts/mnemazine-kb-lint.mjs"`, потому что ночное
+ расписание могло не сработать — догоняем при ближайшем запуске.
+3. Верни пользователю **сводную справку** (таблица: знание · раздел · verified (причина) ·
+ как поможет · следующее действие; + новые разделы; + требуют решения; + 🔧 Проверка инструментов;
+ + **Референсы обновлены** (какие `references/<домен>.md` дозаписаны — Стадия 5.6)).
+4. Дозапиши `99 Система/Лог обработки.md`.
-The vault stores final knowledge only.
+**Условие останова.** Прогон закончен, когда леджер сходится и справка выдана. Проверь свой
+последний абзац: сводная таблица с леджером и `token_usage` — закончено; обещание («сейчас
+обработаю…»), план или вопрос без справки — не закончено, продолжай, потому что обещание в
+финале = прогон, который никто не завершил.
-Do not write raw OCR, copied fragments, noisy transcripts, or unverified paste dumps directly into the vault.
+## Авто-режим (`/kb watch`, по умолчанию выключен)
-## Workflow
+Задел под автозапуск без команды. Включать только по явному запросу пользователя, потому что
+watch + ручной `/kb` без lockfile прогона (Подготовка, шаг 1в) дают гонку read-modify-write
+в `_МАСТЕР-ИНДЕКС`. Два способа:
+- **launchd/cron** на Mac: watcher следит за инбоксом, при новых файлах дёргает `claude -p "/kb"`.
+- **Scheduled task / hook**: периодический прогон `/kb`, если инбокс непуст.
+Скрипт-watcher и пример конфига: `~/.claude/skills/mnemazina/watch/` (README там же). Секреты
+в скрипт/конфиг не зашивать — plist и cron-строки читаемы всем локальным процессам.
-1. Identify what the source is: screenshot, PDF, site, code repo, video, transcript, guide, or inline text.
-2. Extract locally when possible: text parser, PDF parser, Apple Vision OCR, or transcription.
-3. Understand the topic before writing.
-4. Research public sources when the claim depends on current or external facts.
-5. Split one source into multiple notes when it contains multiple unrelated ideas.
-6. Write clear notes with source links, verification status, practical use, and related concepts.
-7. Run the vault quality gate.
-8. Update Graphify when available.
-9. Produce a short action brief when the new knowledge implies work.
-10. Produce a visual post-run knowledge report with clusters, atoms, duplicates, and top-20 actions.
+## Зеркалирование (всегда, но строго ПОСЛЕ решения пользователя)
-YouTube channels can be auto-harvested into the inbox as transcript notes (`docs/youtube-ingestion.md`); they then flow through this same workflow.
+Зеркалить нужно всегда (скилл — общая способность → Codex `~/.codex/skills/mnemazina/` + VPS
+`root@ATHENAOS_HOST:/srv/agent-os`, без секретов). Порядок жёсткий, потому что зеркало до решения
+пользователя разносит по машинам то, от чего он ещё может отказаться:
-## Note Shape
+1. Сначала выдай пользователю **короткую справку о полученном знании**: что это + куда применить
+ прямо сейчас (проекты из `99 Система/_ПРОЕКТЫ.md`).
+2. Если что-то надо ставить/подключать — предложи явно: «**давай установим …**».
+3. Только после решения пользователя (применили/установили или отказались) → зеркаль на
+ Codex + VPS, затем обнови каталоги.
-Every durable note should contain:
+Не зеркаль молча и не раньше справки.
-- Russian title when the user's working language is Russian;
-- `What This Is`;
-- `Why It Matters`;
-- `How To Use It`;
-- `Source`;
-- `Verification`;
-- `Atomization` when the source contains several ideas;
-- `Related Notes`;
-- `Reuse`.
+## Когда НЕ применять (и чем заменить)
-Use `source_ref` and `source_hash` for local files. Do not expose raw private filenames when a stable local-media reference is enough.
-
-## Agent Parity
-
-Claude Code and Codex must use the same knowledge contract:
-
-- same scripts;
-- same gates;
-- same note shape;
-- same post-run visual report;
-- same public-safe agent role passports.
-
-## Local Paths
-
-Use environment variables:
-
-- `MNEMAZINE_ROOT`;
-- `MNEMAZINE_INBOX`;
-- `MNEMAZINE_VAULT`;
-- `MNEMAZINE_REPORTS`;
-- `MNEMAZINE_STATE`.
-
-Never assume a specific username, home path, private project, SSH host, or API key.
+- **«Прочитай/перескажи этот файл» без просьбы сохранить** — просто прочитай и ответь: конвейер
+ добавит стадии, гейты и токены к задаче, у которой нет выхода в vault.
+- **Вопрос по коду/проекту** (любой репозиторий) — это `graphify`-запрос или обычная работа с
+ кодом: Мнемозина хранит жизненные знания в `$MNEMAZINE_VAULT`, а не код-контекст проектов.
+- **Факт о владельце/сессии на будущее** («запомни, что я предпочитаю X») — это auto-memory
+ (`MEMORY.md` проекта), не нота vault: авто-память per-project и дешёвая, vault — для durable-знания
+ с источником.
+- **Рабочее дело со своим конвейером** (например ведение клиентских дел) — отдельная сессия в
+ своём репозитории: у таких дел собственная раскладка, ноты vault им не замена.
+- **Правка содержимого существующей ноты** — правь файл в vault напрямую; `/kb fix` — только
+ ре-классификация (перенос раздела + frontmatter + индексы), не редактор текста.
+- **Включение `/kb watch` «заодно»** — только по явной просьбе: см. Авто-режим, причина — гонка
+ индексов.
diff --git a/skills/mnemazine/kb-embed.py b/skills/mnemazine/kb-embed.py
index 3443474..dc93b4e 100644
--- a/skills/mnemazine/kb-embed.py
+++ b/skills/mnemazine/kb-embed.py
@@ -1,22 +1,26 @@
#!/usr/bin/env python3
"""kb-embed — локальный семантический индекс vault для дедупа Мнемозины.
-Без Ollama/облака: fastembed (onnxruntime) + multilingual-e5-small, CPU.
+Без Ollama/облака: fastembed (onnxruntime) + multilingual-MiniLM, CPU.
Ловит смысловые дубли, которые hash-cache (байтовый) пропускает —
пере-скриншот/пере-сейв того же знания с другим хэшем.
-Запуск:
- python skills/mnemazine/kb-embed.py ...
+Запуск через venv: ~/.venvs/kb-embed/bin/python kb-embed.py ...
Команды:
build — эмбеддит все ноты → индекс
add [note.md...] — дозаписать ноты в индекс
- query [topk] [thr] — топ-похожих нот (cosine)
+ query [topk] [thr] — топ-похожих + зона merge/flag/new
+ (первая строка text считается заголовком)
+ rerank [topk] — top-30 cosine → кросс-энкодер → top-k
+ pairs [note.md...] — попарные cosine внутри списка
+ (дедуп свежего батча, слепого к индексу)
Все ответы — одна строка JSON (для парсинга агентом).
"""
import sys
import os
+import re
import json
import glob
import math
@@ -27,6 +31,18 @@ warnings.filterwarnings("ignore") # чистый JSON-выхлоп для па
MODEL = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" # 384d, ~220MB, мультиязык RU
MAX_CHARS = 2000 # хвост ноты не нужен для темы
+# Пороги зон/заголовков подобраны замером на корпусе vault 2026-07-25
+# (кластер Camofox ×4 в «08 AI и Инструменты»); при смене MODEL перекалибровать замером.
+ZONE_MERGE = 0.90 # combined ≥ — кандидат на слияние (вердикт всё равно за судьёй)
+ZONE_FLAG = 0.72 # combined ≥ — показать на ревью; ниже — законная новая нота
+TITLE_WEIGHT = 0.3 # вклад совпадения заголовков в combined
+TITLE_SIM_MIN = 0.5 # ниже — заголовки несвязаны, вклад 0 (не топить cosine шумом)
+RERANK_MODEL = "jinaai/jina-reranker-v2-base-multilingual" # единственный RU-способный в fastembed 0.8
+RERANK_POOL = 30 # сколько cosine-кандидатов уходит в кросс-энкодер
+RERANK_DOC_CHARS = 1000 # документ для кросс-энкодера: дальше 1000 симв — обрезка токенайзером
+LEX_DOC_CHARS = 400 # fallback-реранк смотрит заголовок + первые 400 симв тела
+LEX_STEM = 5 # псевдо-лемма = первые 5 симв токена (грубая замена стеммера, stdlib-only)
+
def _emb(texts, prefix):
from fastembed import TextEmbedding
@@ -48,7 +64,9 @@ def _is_content_note(p):
bad = ("/graphify-out/", "/.git/", "/.obsidian/")
if any(b in p for b in bad):
return False
- return not os.path.basename(p).startswith("_")
+ # сегмент с "_" — служебная плоскость (_archive, _lint, _digest): дубль с уже
+ # архивированной нотой — не находка, а шум, поэтому режем весь путь, не только basename
+ return not any(seg.startswith("_") for seg in p.split(os.sep))
def _read_body(p):
@@ -65,6 +83,34 @@ def _cos(a, b):
return d / (na * nb) if na and nb else 0.0
+def _title(p):
+ """Заголовок ноты из имени файла: без даты-префикса и расширения."""
+ t = os.path.splitext(os.path.basename(p))[0]
+ return re.sub(r"^\d{4}-\d{2}-\d{2}\s*[—–-]\s*", "", t)
+
+
+def _tokens(s):
+ s = s.lower().replace("ё", "е")
+ return {w for w in re.findall(r"[a-zа-я0-9]+", s) if len(w) >= 2}
+
+
+def _title_sim(a, b):
+ """Containment по токенам, не SequenceMatcher: перестановка слов не штрафуется."""
+ ta, tb = _tokens(a), _tokens(b)
+ if not ta or not tb:
+ return 0.0
+ return len(ta & tb) / min(len(ta), len(tb))
+
+
+def _combined(cos, tsim):
+ boost = TITLE_WEIGHT * tsim if tsim >= TITLE_SIM_MIN else 0.0
+ return min(1.0, cos + boost)
+
+
+def _zone(c):
+ return "merge" if c >= ZONE_MERGE else "flag" if c >= ZONE_FLAG else "new"
+
+
def cmd_build(vault, out):
notes = [p for p in glob.glob(vault + "/**/*.md", recursive=True) if _is_content_note(p)]
bodies = [_read_body(p) for p in notes]
@@ -92,16 +138,79 @@ def cmd_query(idxfile, text, topk=3, thr=0.0):
if not idx:
print(json.dumps({"matches": [], "top": 0.0, "note": "index empty"}))
return
+ qtitle = text.strip().splitlines()[0] if text.strip() else ""
qv = _emb([text[:MAX_CHARS]], "")[0]
- scored = sorted(((_cos(qv, v), p) for p, v in idx.items()), reverse=True)[:topk]
- matches = [{"note": p, "score": round(s, 4)} for s, p in scored if s >= thr]
- print(json.dumps({"matches": matches, "top": round(scored[0][0], 4) if scored else 0.0},
+ scored = []
+ for p, v in idx.items():
+ cos = _cos(qv, v)
+ tsim = _title_sim(qtitle, _title(p))
+ scored.append((_combined(cos, tsim), cos, tsim, p))
+ scored.sort(reverse=True)
+ matches = [{"note": p, "score": round(cos, 4), "title_sim": round(tsim, 4),
+ "combined": round(comb, 4), "zone": _zone(comb)}
+ for comb, cos, tsim, p in scored[:topk] if cos >= thr]
+ top = max(cos for _, cos, _, _ in scored) # top остаётся чистым cosine — старые вызовы его парсят
+ print(json.dumps({"matches": matches, "top": round(top, 4)}, ensure_ascii=False))
+
+
+def _lex_score(query, doc):
+ qs = {w[:LEX_STEM] for w in _tokens(query)}
+ ds = {w[:LEX_STEM] for w in _tokens(doc)}
+ return len(qs & ds) / len(qs) if qs else 0.0
+
+
+def cmd_rerank(idxfile, text, topk=5):
+ idx = json.load(open(idxfile)) if os.path.exists(idxfile) else {}
+ if not idx:
+ print(json.dumps({"matches": [], "reranker": None, "note": "index empty"}))
+ return
+ qv = _emb([text[:MAX_CHARS]], "")[0]
+ pool = sorted(((_cos(qv, v), p) for p, v in idx.items()), reverse=True)[:RERANK_POOL]
+ docs = [_title(p) + "\n" + _read_body(p)[:RERANK_DOC_CHARS] for _, p in pool]
+ try:
+ from fastembed.rerank.cross_encoder import TextCrossEncoder
+ scores = list(TextCrossEncoder(RERANK_MODEL).rerank(text, docs))
+ method = "cross-encoder:" + RERANK_MODEL
+ except ImportError:
+ # старый fastembed без TextCrossEncoder; псевдо-леммы, качество ниже кросс-энкодера
+ scores = [_lex_score(text, d[:len(_title(p)) + 1 + LEX_DOC_CHARS])
+ for d, (_, p) in zip(docs, pool)]
+ method = "lexical-fallback"
+ ranked = sorted(zip(scores, pool), key=lambda x: x[0], reverse=True)[:topk]
+ matches = [{"note": p, "cosine": round(cos, 4), "rerank": round(float(s), 4)}
+ for s, (cos, p) in ranked]
+ print(json.dumps({"matches": matches, "reranker": method, "pool": len(pool)},
+ ensure_ascii=False))
+
+
+def cmd_pairs(idxfile, notes):
+ # idx-аргумент — для единообразия CLI; вектора всегда свежие с диска,
+ # потому что кэш индекса протухает после правки ноты
+ read = [(p, _read_body(p)) for p in notes]
+ unreadable = [p for p, b in read if not b]
+ alive = [(p, b) for p, b in read if b]
+ if len(alive) < 2:
+ print(json.dumps({"error": "pairs needs >=2 readable notes",
+ "unreadable": unreadable}, ensure_ascii=False))
+ sys.exit(1)
+ vecs = _emb([b for _, b in alive], "")
+ out = []
+ for i in range(len(alive)):
+ for j in range(i + 1, len(alive)):
+ cos = _cos(vecs[i], vecs[j])
+ tsim = _title_sim(_title(alive[i][0]), _title(alive[j][0]))
+ comb = _combined(cos, tsim)
+ out.append({"a": alive[i][0], "b": alive[j][0], "score": round(cos, 4),
+ "title_sim": round(tsim, 4), "combined": round(comb, 4),
+ "zone": _zone(comb)})
+ out.sort(key=lambda r: -r["combined"])
+ print(json.dumps({"pairs": out, "n": len(alive), "unreadable": unreadable},
ensure_ascii=False))
def main():
if len(sys.argv) < 2:
- print(json.dumps({"error": "usage: build|add|query"}))
+ print(json.dumps({"error": "usage: build|add|query|rerank|pairs"}))
sys.exit(1)
cmd = sys.argv[1]
try:
@@ -113,6 +222,11 @@ def main():
topk = int(sys.argv[4]) if len(sys.argv) > 4 else 3
thr = float(sys.argv[5]) if len(sys.argv) > 5 else 0.0
cmd_query(sys.argv[2], sys.argv[3], topk, thr)
+ elif cmd == "rerank":
+ topk = int(sys.argv[4]) if len(sys.argv) > 4 else 5
+ cmd_rerank(sys.argv[2], sys.argv[3], topk)
+ elif cmd == "pairs":
+ cmd_pairs(sys.argv[2], sys.argv[3:])
else:
print(json.dumps({"error": "unknown cmd: " + cmd}))
sys.exit(1)
diff --git a/tests/fixtures/data-classes/broken-frontmatter.md b/tests/fixtures/data-classes/broken-frontmatter.md
new file mode 100644
index 0000000..952b16b
--- /dev/null
+++ b/tests/fixtures/data-classes/broken-frontmatter.md
@@ -0,0 +1,4 @@
+---
+title: "Битый frontmatter — нет закрывающей черты"
+section: "08 AI и Инструменты"
+тело без закрытия ---
diff --git a/tests/fixtures/data-classes/explicit-raise.md b/tests/fixtures/data-classes/explicit-raise.md
new file mode 100644
index 0000000..05619e5
--- /dev/null
+++ b/tests/fixtures/data-classes/explicit-raise.md
@@ -0,0 +1,9 @@
+---
+title: "Явное поле поднимает класс"
+type: concept
+data_class: pd
+section: "08 AI и Инструменты"
+source: "IMG_0002.PNG"
+---
+## Короткий ответ
+Текстовый раздел, но явное data_class:pd поднимает до pd.
diff --git a/tests/fixtures/data-classes/inherit-project.md b/tests/fixtures/data-classes/inherit-project.md
new file mode 100644
index 0000000..075cfd4
--- /dev/null
+++ b/tests/fixtures/data-classes/inherit-project.md
@@ -0,0 +1,9 @@
+---
+title: "Наследование класса от проекта"
+type: concept
+section: "08 AI и Инструменты"
+projects: [themis, olympuz]
+source: "IMG_0003.PNG"
+---
+## Короткий ответ
+projects содержит themis (by_project) → pd.
diff --git a/tests/fixtures/data-classes/inherit-source.md b/tests/fixtures/data-classes/inherit-source.md
new file mode 100644
index 0000000..c441513
--- /dev/null
+++ b/tests/fixtures/data-classes/inherit-source.md
@@ -0,0 +1,8 @@
+---
+title: "Наследование класса от источника-заявки"
+type: agent-research
+section: "08 AI и Инструменты"
+source: "agent-research--themis--corporate-dispute.md"
+---
+## Короткий ответ
+source совпал с ^agent-research--themis-- → pd.
diff --git a/tests/fixtures/data-classes/lower-trap.md b/tests/fixtures/data-classes/lower-trap.md
new file mode 100644
index 0000000..d20b9a6
--- /dev/null
+++ b/tests/fixtures/data-classes/lower-trap.md
@@ -0,0 +1,9 @@
+---
+title: "Ловушка понижения (враждебная проба 2)"
+type: concept
+data_class: text
+section: "01 Право и Юриспруденция"
+source: "local-media:0badf00d"
+---
+## Короткий ответ
+Юрраздел (pd) + дописанное data_class:text. Строгое побеждает → всё равно pd.
diff --git a/tests/fixtures/data-classes/no-field.md b/tests/fixtures/data-classes/no-field.md
new file mode 100644
index 0000000..75ffb88
--- /dev/null
+++ b/tests/fixtures/data-classes/no-field.md
@@ -0,0 +1,8 @@
+---
+title: "Обычная нота из известного текстового раздела"
+type: concept
+section: "08 AI и Инструменты"
+source: "IMG_0001.PNG"
+---
+## Короткий ответ
+Известный раздел vault без спец-правила → text (VPS-ok).
diff --git a/tests/fixtures/data-classes/pd-section.md b/tests/fixtures/data-classes/pd-section.md
new file mode 100644
index 0000000..2c44ec7
--- /dev/null
+++ b/tests/fixtures/data-classes/pd-section.md
@@ -0,0 +1,8 @@
+---
+title: "Нота юридического раздела"
+type: concept
+section: "01 Право и Юриспруденция"
+source: "local-media:deadbeef"
+---
+## Короткий ответ
+Раздел в by_section → pd.
diff --git a/tests/fixtures/data-classes/personal-section.md b/tests/fixtures/data-classes/personal-section.md
new file mode 100644
index 0000000..3a6068a
--- /dev/null
+++ b/tests/fixtures/data-classes/personal-section.md
@@ -0,0 +1,8 @@
+---
+title: "Личная нота"
+type: concept
+section: "02 Здоровье"
+source: "local-media:cafef00d"
+---
+## Короткий ответ
+Раздел в by_section → personal.
diff --git a/tests/fixtures/data-classes/unknown-section.md b/tests/fixtures/data-classes/unknown-section.md
new file mode 100644
index 0000000..10b9201
--- /dev/null
+++ b/tests/fixtures/data-classes/unknown-section.md
@@ -0,0 +1,8 @@
+---
+title: "Раздел вне таксономии"
+type: concept
+section: "ZZ Раздел вне таксономии"
+source: "IMG_0004.PNG"
+---
+## Короткий ответ
+Раздела нет ни в by_section, ни среди известных разделов vault → undetermined (2).
diff --git a/tests/fixtures/humanize/note-after-broken.md b/tests/fixtures/humanize/note-after-broken.md
new file mode 100644
index 0000000..41d739d
--- /dev/null
+++ b/tests/fixtures/humanize/note-after-broken.md
@@ -0,0 +1,45 @@
+---
+type: "concept"
+subject: "world"
+verification_status: "verified"
+---
+
+# Пример ноты для гейта сохранности
+
+## Короткий ответ
+Гейт смотрит, что все факты заметки дожили от старого варианта до нового. Потеряли хоть один - вариант в корзину, в базе остаётся исходник. Обкатано на Supabase и fastembed.
+
+## Механика
+На одну заметку уходит 200 мс. Скрипт `scripts/mnemazine-run.mjs` дёргает сканер и пересчитывает классы инвариантов: числа, ссылки, пути.
+
+## Применение
+Запускаешь вот так и открываешь отчёт: https://github.com/example/repo
+
+```bash
+node scripts/mnemazine-humanize-gate.mjs --before a.md --after b.md
+```
+
+Чистота ниже 60 баллов - текст идёт на рерайт.
+
+## Опыт практиков
+Народ жалуется, что при рерайте ссылки отваливаются, но тред уже потерялся.
+
+## Как это поможет мне
+Для демо-проекта это подстраховка: факты в заметках не текут, когда их переписываешь.
+
+| метрика | значение |
+|---|---|
+| порог | 60 |
+| латентность | 200 |
+
+> Цитата источника: ни один факт не должен удаляться при очеловечивании.
+
+## Достоверность
+- Проверено практикой на корпусе, 2026-08-22, версия v2.0, источник https://example.org/spec
+- Автор заметки: Мнемазина, конвейер знаний
+
+## Связанные темы
+- инструмент-для [[Мнемозина]]
+
+## Следующий ход
+Врезать гейт в конвейер записи заметок.
diff --git a/tests/fixtures/humanize/note-after-ok.md b/tests/fixtures/humanize/note-after-ok.md
new file mode 100644
index 0000000..e202c43
--- /dev/null
+++ b/tests/fixtures/humanize/note-after-ok.md
@@ -0,0 +1,45 @@
+---
+type: "concept"
+subject: "world"
+verification_status: "verified"
+---
+
+# Пример ноты для гейта сохранности
+
+## Короткий ответ
+Гейт смотрит, что все факты заметки дожили от старого варианта до нового. Потеряли хоть один - вариант в корзину, в базе остаётся исходник. Обкатано на Supabase и fastembed.
+
+## Механика
+На одну заметку уходит 200 мс. Скрипт `scripts/mnemazine-run.mjs` дёргает сканер и пересчитывает 3 класса инвариантов: числа, ссылки, пути.
+
+## Применение
+Запускаешь вот так и открываешь отчёт: https://github.com/example/repo
+
+```bash
+node scripts/mnemazine-humanize-gate.mjs --before a.md --after b.md
+```
+
+Чистота ниже 60 баллов - текст идёт на рерайт.
+
+## Опыт практиков
+Народ жалуется, что при рерайте ссылки отваливаются, вот тред: https://docs.example.com/guide
+
+## Как это поможет мне
+Для демо-проекта это подстраховка: факты в заметках не текут, когда их переписываешь.
+
+| метрика | значение |
+|---|---|
+| порог | 60 |
+| латентность | 200 |
+
+> Цитата источника: ни один факт не должен удаляться при очеловечивании.
+
+## Достоверность
+- Проверено практикой на корпусе, 2026-08-22, версия v2.0, источник https://example.org/spec
+- Автор заметки: Мнемазина, конвейер знаний
+
+## Связанные темы
+- инструмент-для [[Мнемозина]]
+
+## Следующий ход
+Врезать гейт в конвейер записи заметок.
diff --git a/tests/fixtures/humanize/note-before.md b/tests/fixtures/humanize/note-before.md
new file mode 100644
index 0000000..201a0db
--- /dev/null
+++ b/tests/fixtures/humanize/note-before.md
@@ -0,0 +1,45 @@
+---
+type: "concept"
+subject: "world"
+verification_status: "verified"
+---
+
+# Пример ноты для гейта сохранности
+
+## Короткий ответ
+Гейт сверяет инварианты заметки до и после очеловечивания. Если пропал хоть один факт, вариант отвергается. Проверено на Supabase и fastembed.
+
+## Механика
+Прогон занимает 200 мс на заметку. Скрипт `scripts/mnemazine-run.mjs` зовёт сканер и считает 3 класса инвариантов: числа, ссылки, пути.
+
+## Применение
+Запусти так и открой отчёт: https://github.com/example/repo
+
+```bash
+node scripts/mnemazine-humanize-gate.mjs --before a.md --after b.md
+```
+
+Порог чистоты - 60 баллов, ниже идёт рерайт.
+
+## Опыт практиков
+Люди жалуются на потерю ссылок при рерайте, тред тут: https://docs.example.com/guide
+
+## Как это поможет мне
+Для демо-проекта это страховка: факты в заметках не утекают при переписывании.
+
+| метрика | значение |
+|---|---|
+| порог | 60 |
+| латентность | 200 |
+
+> Цитата источника: ни один факт не должен удаляться при очеловечивании.
+
+## Достоверность
+- Проверено практикой на корпусе, 2026-08-22, версия v2.0, источник https://example.org/spec
+- Автор заметки: Мнемазина, конвейер знаний
+
+## Связанные темы
+- инструмент-для [[Мнемозина]]
+
+## Следующий ход
+Врезать гейт в конвейер записи заметок.
diff --git a/tests/fixtures/quality-gate/vault-amnesty/99 Система/_ПРОЕКТЫ.md b/tests/fixtures/quality-gate/vault-amnesty/99 Система/_ПРОЕКТЫ.md
new file mode 100644
index 0000000..b28fde7
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-amnesty/99 Система/_ПРОЕКТЫ.md
@@ -0,0 +1,5 @@
+# Проекты (фикстура)
+
+## mnemazine
+
+Учебный слаг проекта для фикстуры калибровки гейта.
diff --git a/tests/fixtures/quality-gate/vault-amnesty/note.md b/tests/fixtures/quality-gate/vault-amnesty/note.md
new file mode 100644
index 0000000..8356d15
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-amnesty/note.md
@@ -0,0 +1,6 @@
+# Скриншот без обработки
+
+## Атомизировано
+
+Сырой захват: IMG_1234.PNG, распознанный текст без обработки, источник не найден.
+Блока смысла и структурного источника нет — это сырьё, не знание.
diff --git a/tests/fixtures/quality-gate/vault-bad-subject/99 Система/_ПРОЕКТЫ.md b/tests/fixtures/quality-gate/vault-bad-subject/99 Система/_ПРОЕКТЫ.md
new file mode 100644
index 0000000..b28fde7
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-bad-subject/99 Система/_ПРОЕКТЫ.md
@@ -0,0 +1,5 @@
+# Проекты (фикстура)
+
+## mnemazine
+
+Учебный слаг проекта для фикстуры калибровки гейта.
diff --git a/tests/fixtures/quality-gate/vault-bad-subject/note.md b/tests/fixtures/quality-gate/vault-bad-subject/note.md
new file mode 100644
index 0000000..b3ac665
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-bad-subject/note.md
@@ -0,0 +1,21 @@
+---
+title: "Локальный OCR до модели"
+type: concept
+section: "08 AI и Инструменты"
+source: "demo/inbox/example.md"
+verified: подтверждён
+subject: personal
+---
+
+## Короткий ответ
+
+По спеке нота полна, но поле subject несёт значение вне закрытого списка
+self | world | mixed — гейт обязан покраснеть всегда.
+
+## 🎯 Как это поможет мне
+
+Ускоряет mnemazine: проверяет, что subject вне enum валит спеку независимо от --changed-since.
+
+## Достоверность
+
+- Проверено практикой на прогонах гейта, 2026.
diff --git a/tests/fixtures/quality-gate/vault-clean/99 Система/_ПРОЕКТЫ.md b/tests/fixtures/quality-gate/vault-clean/99 Система/_ПРОЕКТЫ.md
new file mode 100644
index 0000000..b28fde7
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-clean/99 Система/_ПРОЕКТЫ.md
@@ -0,0 +1,5 @@
+# Проекты (фикстура)
+
+## mnemazine
+
+Учебный слаг проекта для фикстуры калибровки гейта.
diff --git a/tests/fixtures/quality-gate/vault-clean/note.md b/tests/fixtures/quality-gate/vault-clean/note.md
new file mode 100644
index 0000000..66e46de
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-clean/note.md
@@ -0,0 +1,21 @@
+---
+title: "Локальный OCR до модели"
+type: concept
+section: "08 AI и Инструменты"
+source: "demo/inbox/example.md"
+verified: подтверждён
+subject: world
+---
+
+## Короткий ответ
+
+Локальный OCR достаёт читаемый текст из скриншота до того, как его смотрит модель:
+дешевле, быстрее и кэшируется как стабильный артефакт.
+
+## 🎯 Как это поможет мне
+
+Ускоряет mnemazine: входящие скриншоты превращаются в текст локально, без облака и без лишних токенов.
+
+## Достоверность
+
+- Проверено практикой на macOS через Apple Vision, 2026.
diff --git a/tests/fixtures/quality-gate/vault-fake-source/99 Система/_ПРОЕКТЫ.md b/tests/fixtures/quality-gate/vault-fake-source/99 Система/_ПРОЕКТЫ.md
new file mode 100644
index 0000000..b28fde7
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-fake-source/99 Система/_ПРОЕКТЫ.md
@@ -0,0 +1,5 @@
+# Проекты (фикстура)
+
+## mnemazine
+
+Учебный слаг проекта для фикстуры калибровки гейта.
diff --git a/tests/fixtures/quality-gate/vault-fake-source/note.md b/tests/fixtures/quality-gate/vault-fake-source/note.md
new file mode 100644
index 0000000..62f7cf7
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-fake-source/note.md
@@ -0,0 +1,16 @@
+# Заметка с источником только в коде
+
+## Короткий ответ
+
+Здесь блок смысла есть, но структурного источника нет: строка `source:` спрятана
+внутри кодового блока и не должна засчитываться гейтом.
+
+## Пример конфига
+
+```yaml
+source: "demo/inbox/example.md"
+sources:
+ - "demo/inbox/example.md"
+```
+
+Голая подстрока `source:` в теле файла источником не является.
diff --git a/tests/fixtures/quality-gate/vault-help-form/99 Система/_ПРОЕКТЫ.md b/tests/fixtures/quality-gate/vault-help-form/99 Система/_ПРОЕКТЫ.md
new file mode 100644
index 0000000..b28fde7
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-help-form/99 Система/_ПРОЕКТЫ.md
@@ -0,0 +1,5 @@
+# Проекты (фикстура)
+
+## mnemazine
+
+Учебный слаг проекта для фикстуры калибровки гейта.
diff --git a/tests/fixtures/quality-gate/vault-help-form/note.md b/tests/fixtures/quality-gate/vault-help-form/note.md
new file mode 100644
index 0000000..e7e210a
--- /dev/null
+++ b/tests/fixtures/quality-gate/vault-help-form/note.md
@@ -0,0 +1,21 @@
+---
+title: "Кэш извлечений экономит токены"
+type: concept
+section: "08 AI и Инструменты"
+source: "demo/inbox/cache.md"
+verified: проверено-практикой
+subject: world
+---
+
+## Короткий ответ
+
+Кэш извлечений хранит результат один раз и переиспользует его: повторный прогон
+не платит за то же извлечение снова.
+
+## Как поможет мне
+
+Ускоряет mnemazine: повторная обработка того же источника идёт из кэша, без затрат токенов.
+
+## Достоверность
+
+- Проверено практикой на прогонах конвейера, 2026.
diff --git a/tests/fixtures/readonly/01 Concepts/агентная-память.md b/tests/fixtures/readonly/01 Concepts/агентная-память.md
new file mode 100644
index 0000000..34f2a67
--- /dev/null
+++ b/tests/fixtures/readonly/01 Concepts/агентная-память.md
@@ -0,0 +1,19 @@
+---
+source: fixture
+type: concept
+verified: не-проверялось
+created: 2026-08-20
+updated: 2026-08-20
+---
+
+# Агентная память
+
+Фикстурная нота прибора readonly-gate. Связана со [[вторая-нота]].
+
+## Как это поможет мне
+
+Проверяет, что команды просмотра не меняют корпус проекта Мнемозина.
+
+## Достоверность
+
+Синтетический материал тестовой фикстуры, внешних источников нет.
diff --git a/tests/fixtures/readonly/01 Concepts/вторая-нота.md b/tests/fixtures/readonly/01 Concepts/вторая-нота.md
new file mode 100644
index 0000000..3c58441
--- /dev/null
+++ b/tests/fixtures/readonly/01 Concepts/вторая-нота.md
@@ -0,0 +1,19 @@
+---
+source: fixture
+type: concept
+verified: не-проверялось
+created: 2026-08-20
+updated: 2026-08-20
+---
+
+# Вторая нота
+
+Фикстурная нота прибора readonly-gate. Ссылается на [[агентная-память]].
+
+## Как это поможет мне
+
+Даёт вторую точку связности для линта проекта Мнемозина.
+
+## Достоверность
+
+Синтетический материал тестовой фикстуры, внешних источников нет.
diff --git a/tests/fixtures/readonly/99 Система/_embeddings.json b/tests/fixtures/readonly/99 Система/_embeddings.json
new file mode 100644
index 0000000..0967ef4
--- /dev/null
+++ b/tests/fixtures/readonly/99 Система/_embeddings.json
@@ -0,0 +1 @@
+{}
diff --git a/tests/fixtures/readonly/99 Система/_ПРОЕКТЫ.md b/tests/fixtures/readonly/99 Система/_ПРОЕКТЫ.md
new file mode 100644
index 0000000..4e00a25
--- /dev/null
+++ b/tests/fixtures/readonly/99 Система/_ПРОЕКТЫ.md
@@ -0,0 +1,5 @@
+# Проекты фикстуры
+
+## Мнемозина
+
+Конвейер знаний владельца.
diff --git a/tests/fixtures/readonly/_МАСТЕР-ИНДЕКС.md b/tests/fixtures/readonly/_МАСТЕР-ИНДЕКС.md
new file mode 100644
index 0000000..b969ec5
--- /dev/null
+++ b/tests/fixtures/readonly/_МАСТЕР-ИНДЕКС.md
@@ -0,0 +1,6 @@
+# Мастер-индекс фикстуры
+
+Всего markdown: **4**
+
+- [[агентная-память]]
+- [[вторая-нота]]
diff --git a/tests/fixtures/readonly/graphify-out/graph.json b/tests/fixtures/readonly/graphify-out/graph.json
new file mode 100644
index 0000000..65881b0
--- /dev/null
+++ b/tests/fixtures/readonly/graphify-out/graph.json
@@ -0,0 +1 @@
+{"nodes": [], "edges": []}
diff --git a/tests/fixtures/readonly/graphify-out/needs_update b/tests/fixtures/readonly/graphify-out/needs_update
new file mode 100644
index 0000000..e4dc26e
--- /dev/null
+++ b/tests/fixtures/readonly/graphify-out/needs_update
@@ -0,0 +1,2 @@
+semantic graph refresh pending since fixture creation — намеренно без «deferred:»,
+чтобы воспроизводить ветку протухшего маркера complete-check (план П08).
diff --git a/tests/fixtures/retrieval-questions.example.json b/tests/fixtures/retrieval-questions.example.json
new file mode 100644
index 0000000..44a906b
--- /dev/null
+++ b/tests/fixtures/retrieval-questions.example.json
@@ -0,0 +1,11 @@
+{
+ "version": 1,
+ "note": "Образец набора вопросов для retrieval-eval. Скопируйте рядом как retrieval-questions.json (файл вне git) и замените на СВОИ вопросы к своей базе: смысл замера в том, находится ли то, что нужно лично вам. expect — уникальная подстрока имени файла ожидаемой заметки, в нижнем регистре.",
+ "questions": [
+ { "section": "инструменты", "q": "чем запускать модель локально, без облака", "expect": ["локального запуска"] },
+ { "section": "инструменты", "q": "как подтянуть свежую документацию библиотеки в контекст", "expect": ["документаци"] },
+ { "section": "рабочие процессы", "q": "как не потерять длинную задачу, если сессия оборвалась", "expect": ["хэндофф"] },
+ { "section": "проекты", "q": "что решили по архитектуре в прошлый раз", "expect": ["решение"] },
+ { "section": "финансы", "q": "как считать окупаемость привлечения клиента", "expect": ["окупаем"] }
+ ]
+}
diff --git a/tests/retrieval-eval.mjs b/tests/retrieval-eval.mjs
new file mode 100644
index 0000000..5b2d0a4
--- /dev/null
+++ b/tests/retrieval-eval.mjs
@@ -0,0 +1,258 @@
+#!/usr/bin/env node
+// Retrieval-eval на живом vault (юнит F): 20 реальных вопросов владельца, три
+// пайплайна — (а) rg -li по словам запроса, (б) kb-embed query, (в) kb-embed
+// rerank — метрика hit@7 (ожидаемая нота в топ-7 по уникальной подстроке basename).
+// Ожидания зафиксированы ДО первого прогона (2026-07-25): промах — легитимный
+// замер качества поиска, вопросы под ответы не подгоняются.
+// tests/search-eval.mjs меряет синтетический фикстур-vault; этот — живой личный vault,
+// поэтому кейс, чьё ожидание исчезло из корпуса (нота уехала/переименована),
+// валит прогон fail-loud до замера — протухший замер хуже отсутствующего.
+// node tests/retrieval-eval.mjs [--vault ] [--index
] [--python ]
+// [--kb-embed ] [--limit ] [--report ] [--baseline ]
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { spawnSync } from 'node:child_process'
+import { resolveVault } from '../scripts/mnemazine-paths.mjs'
+
+const LOCAL_PYTHON = path.resolve('.venv', 'bin', 'python')
+const DEFAULT_PYTHON = fs.existsSync(LOCAL_PYTHON) ? LOCAL_PYTHON : path.join(os.homedir(), '.venvs', 'kb-embed', 'bin', 'python')
+const DEFAULT_KB_EMBED = path.resolve('skills', 'mnemazine', 'kb-embed.py')
+const TOPK = 7
+const SPAWN_TIMEOUT_MS = 900_000 // rerank грузит кросс-энкодер в каждом вызове — минуты, не секунды
+const MAX_BUF = 64 * 1024 * 1024
+
+// Ожидание = подстроки basename (lowercase, NFC); хит, если ЛЮБАЯ нота топ-7
+// несёт ЛЮБУЮ из них. Несколько подстрок — только когда в vault несколько
+// легитимно правильных нот про то же самое, не для смягчения замера.
+// Questions live outside the code: they are personal by nature — what YOU need to
+// find in YOUR vault. Copy tests/fixtures/retrieval-questions.example.json to
+// tests/fixtures/retrieval-questions.json (git-ignored) and put your own there.
+const QUESTIONS_FILE = process.env.MNEMAZINE_RETRIEVAL_QUESTIONS
+ || path.resolve('tests', 'fixtures', 'retrieval-questions.json')
+const QUESTIONS_FALLBACK = path.resolve('tests', 'fixtures', 'retrieval-questions.example.json')
+const QUESTIONS = (() => {
+ const file = fs.existsSync(QUESTIONS_FILE) ? QUESTIONS_FILE : QUESTIONS_FALLBACK
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
+ const list = Array.isArray(parsed) ? parsed : parsed.questions
+ if (!Array.isArray(list) || !list.length) {
+ console.error(`Нет вопросов для замера: ${file}`)
+ process.exit(2)
+ }
+ return list
+})()
+
+// Только служебные слова: генеративные глаголы не стоп-листим, чтобы не
+// подстраивать rg-пайплайн под конкретные вопросы.
+const STOP = new Set(['как', 'что', 'чтобы', 'для', 'при', 'перед', 'через', 'без',
+ 'это', 'мой', 'мои', 'мне', 'меня', 'мной', 'какой', 'какие', 'чем', 'или',
+ 'где', 'когда', 'кто', 'есть', 'надо', 'нужно', 'нужны'])
+
+const nfc = s => s.normalize('NFC')
+
+function parseArgs(argv) {
+ const flags = {}
+ for (let i = 2; i < argv.length; i += 2) {
+ const k = argv[i]
+ if (!k.startsWith('--') || argv[i + 1] === undefined) { console.error(`bad arg: ${k}`); process.exit(1) }
+ flags[k.slice(2)] = argv[i + 1]
+ }
+ return flags
+}
+
+// Зеркало _is_content_note из kb-embed.py — иначе rg-пайплайн меряет другой корпус.
+function isServicePath(p) {
+ const parts = p.split(path.sep)
+ if (parts.some(seg => seg === 'graphify-out' || seg === 'graphify-out-snapshots' || seg.startsWith('graphify-out-backup-'))) return true
+ return parts.some((seg, i) => seg === '99 Система' && parts[i + 1] === '_archive')
+}
+
+function isContentNote(p) {
+ if (isServicePath(p) || p.includes('/.git/') || p.includes('/.obsidian/')) return false
+ return !p.split(path.sep).some(seg => seg.startsWith('_'))
+}
+
+function listCorpus(vault) {
+ return fs.readdirSync(vault, { recursive: true })
+ .filter(rel => rel.endsWith('.md'))
+ .map(rel => path.join(vault, rel))
+ .filter(isContentNote)
+}
+
+function isHit(paths, expect) {
+ return paths.some(p => {
+ const base = nfc(path.basename(p)).toLowerCase()
+ return expect.some(e => base.includes(nfc(e).toLowerCase()))
+ })
+}
+
+function queryWords(q) {
+ const tokens = q.toLowerCase().match(/[a-zа-яё0-9][a-zа-яё0-9-]*/g) || []
+ return [...new Set(tokens.filter(w => w.length >= 3 && !STOP.has(w)))]
+}
+
+// Пайплайн (а): rg -li на каждое слово, ранжирование по числу совпавших слов.
+// --no-ignore — python-индексатор gitignore не читает, корпуса должны совпадать.
+function runRg(q, vault) {
+ const votes = new Map()
+ for (const w of queryWords(q)) {
+ const r = spawnSync('rg', ['-liF', '--no-ignore', '--no-messages', '-g', '*.md', '--', w, vault],
+ { encoding: 'utf8', maxBuffer: MAX_BUF })
+ if (r.status !== 0 && r.status !== 1) throw new Error(`rg failed on "${w}": ${r.stderr || r.status}`)
+ for (const line of (r.stdout || '').split('\n')) {
+ const p = line.trim()
+ if (p && isContentNote(p)) { const k = nfc(p); votes.set(k, (votes.get(k) || 0) + 1) }
+ }
+ }
+ return [...votes.entries()]
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
+ .slice(0, TOPK).map(([p]) => p)
+}
+
+function runKbEmbed(cfg, cmd, q) {
+ const r = spawnSync(cfg.python, [cfg.kbEmbed, cmd, cfg.index, q, String(TOPK)],
+ { encoding: 'utf8', maxBuffer: MAX_BUF, timeout: SPAWN_TIMEOUT_MS })
+ const line = (r.stdout || '').trim().split('\n').pop()
+ let parsed
+ try { parsed = JSON.parse(line) } catch {
+ throw new Error(`kb-embed ${cmd} non-JSON (exit ${r.status}): ${line || r.stderr?.slice(-300)}`)
+ }
+ if (parsed.error) throw new Error(`kb-embed ${cmd}: ${parsed.error}`)
+ return parsed
+}
+
+function readBaseline(file) {
+ if (!file) return null
+ try {
+ const b = JSON.parse(fs.readFileSync(file, 'utf8'))
+ for (const k of ['rg', 'query', 'rerank']) {
+ if (!Number.isFinite(Number(b[k]))) throw new Error(`bad ${k}`)
+ }
+ return { file, rg: Number(b.rg), query: Number(b.query), rerank: Number(b.rerank), n: Number(b.n || b.total || 20), date: b.date || '2026-07-25' }
+ } catch (e) {
+ console.error(`baseline not readable: ${file} (${e.message})`)
+ process.exit(2)
+ }
+}
+
+function buildReport({ results, corpusSize, indexSize, index, rerankMethod, hits, baseline }) {
+ const n = results.length
+ const row = r => `| ${r.id} | ${r.q} | ${r.section} | ${r.rg ? '✓' : '✗'} | ${r.query ? '✓' : '✗'} | ${r.rerank ? '✓' : '✗'} |`
+ const missBlock = key => {
+ const misses = results.filter(r => !r[key])
+ if (!misses.length) return '- промахов нет'
+ return misses.map(r => `- ${r.id} «${r.q}» — ждали: ${r.expect.join(' | ')}`).join('\n')
+ }
+ const gain = hits.rerank - hits.query
+ const verdict = gain > 0
+ ? `Реранк ДАЁТ прирост над query: +${gain} (query ${hits.query}/${n} → rerank ${hits.rerank}/${n}).`
+ : gain === 0
+ ? `Реранк НЕ меняет hit@7 (query ${hits.query}/${n} = rerank ${hits.rerank}/${n}).`
+ : `Реранк УХУДШАЕТ hit@7: ${gain} (query ${hits.query}/${n} → rerank ${hits.rerank}/${n}).`
+ const compare = baseline
+ ? `Сравнимо с базой ${baseline.date}: ДА, набор вопросов сохранён. Старые числа: rg ${baseline.rg}/${baseline.n} · query ${baseline.query}/${baseline.n} · rerank ${baseline.rerank}/${baseline.n}. Новые числа: rg ${hits.rg}/${n} · query ${hits.query}/${n} · rerank ${hits.rerank}/${n}.`
+ : 'Сравнимо с базой 25.07: НЕТ — baseline-файл не передан.'
+ const nextMetric = 'Метрика следующего поколения зафиксирована до этого замера: hit@fragment@7 — найден точный фрагмент ответа внутри ноты, а не только basename ноты. В П14 не включается, чтобы не ломать сравнимость с 25.07.'
+ const queryReview = 'Рецензия запросов перед замером: 20 формулировок сверены с живым корпусом через fail-loud проверку ожиданий; вопросы не подгонялись под ответы.'
+ return `# Retrieval-eval — живой vault, 2026-08-22
+
+Юнит F: ${n} вопросов владельца по разделам корпуса, ожидания зафиксированы до прогона
+(tests/retrieval-eval.mjs в проекте mnemazine — прогон воспроизводим).
+Корпус: ${corpusSize} контент-нот · индекс: ${indexSize} векторов (${index}).
+Пайплайны: (а) rg -li по словам запроса, ранжирование по числу совпавших слов, top-7;
+(б) kb-embed query — cosine + title-boost, top-7; (в) kb-embed rerank — top-30 cosine
+→ кросс-энкодер (${rerankMethod}), top-7. Метрика: hit@7 — ожидаемая нота в топ-7
+по уникальной подстроке basename.
+
+## hit@7
+
+| # | Вопрос | Раздел | rg | query | rerank |
+|---|---|---|---|---|---|
+${results.map(row).join('\n')}
+| — | **Итого** | | **${hits.rg}/${n}** | **${hits.query}/${n}** | **${hits.rerank}/${n}** |
+
+## Вердикт
+
+${verdict}
+Лексический rg: ${hits.rg}/${n}; эмбеддинги (query): ${hits.query}/${n}.
+${compare}
+${queryReview}
+${nextMetric}
+
+## Промахи
+
+### rg (${n - hits.rg})
+${missBlock('rg')}
+
+### query (${n - hits.query})
+${missBlock('query')}
+
+### rerank (${n - hits.rerank})
+${missBlock('rerank')}
+`
+}
+
+function main() {
+ const flags = parseArgs(process.argv)
+ const baseline = readBaseline(flags.baseline)
+ const vault = resolveVault({ cli: flags.vault, env: process.env.MNEMAZINE_VAULT })
+ const cfg = {
+ python: flags.python || DEFAULT_PYTHON,
+ kbEmbed: flags['kb-embed'] || DEFAULT_KB_EMBED,
+ index: flags.index || path.join(vault, '99 Система', '_embeddings.json')
+ }
+ for (const [name, p] of [['python', cfg.python], ['kb-embed', cfg.kbEmbed], ['index', cfg.index]]) {
+ if (!fs.existsSync(p)) { console.error(`${name} not found: ${p}`); process.exit(1) }
+ }
+ if (spawnSync('rg', ['--version']).status !== 0) { console.error('rg not found'); process.exit(1) }
+
+ const corpus = listCorpus(vault)
+ const corpusBases = corpus.map(p => nfc(path.basename(p)).toLowerCase())
+ const cases = QUESTIONS.slice(0, flags.limit ? Number(flags.limit) : QUESTIONS.length)
+
+ const broken = cases.filter(c => !c.expect.some(e => corpusBases.some(b => b.includes(nfc(e).toLowerCase()))))
+ if (broken.length) {
+ console.error('ожидания не найдены в корпусе (нота уехала или подстрока с опечаткой):')
+ for (const c of broken) console.error(` «${c.q}» → ${c.expect.join(' | ')}`)
+ process.exit(1)
+ }
+
+ const indexSize = Object.keys(JSON.parse(fs.readFileSync(cfg.index, 'utf8'))).length
+ let rerankMethod = ''
+ const results = cases.map((c, i) => {
+ const id = String(i + 1).padStart(2, '0')
+ process.stderr.write(`[${id}/${cases.length}] ${c.q}\n`)
+ const rg = isHit(runRg(c.q, vault), c.expect)
+ const query = isHit(runKbEmbed(cfg, 'query', c.q).matches.map(m => m.note), c.expect)
+ const rr = runKbEmbed(cfg, 'rerank', c.q)
+ rerankMethod = rr.reranker
+ const rerank = isHit(rr.matches.map(m => m.note), c.expect)
+ console.log(`${id} rg:${rg ? '✓' : '✗'} query:${query ? '✓' : '✗'} rerank:${rerank ? '✓' : '✗'} ${c.q}`)
+ return { id, q: c.q, section: c.section, expect: c.expect, rg, query, rerank }
+ })
+
+ const hits = {
+ rg: results.filter(r => r.rg).length,
+ query: results.filter(r => r.query).length,
+ rerank: results.filter(r => r.rerank).length
+ }
+ console.log(`\nhit@7: rg ${hits.rg}/${results.length} · query ${hits.query}/${results.length} · rerank ${hits.rerank}/${results.length} (${rerankMethod})`)
+
+ const report = flags.report || path.join('reports', 'retrieval-eval-2026-08-22.md')
+ if (report) {
+ fs.mkdirSync(path.dirname(report), { recursive: true })
+ const md = buildReport({ results, corpusSize: corpus.length, indexSize, index: cfg.index, rerankMethod, hits, baseline })
+ fs.writeFileSync(report, md, 'utf8')
+ console.log(`report: ${report}`)
+ }
+
+ if (baseline) {
+ const worse = ['rg', 'query', 'rerank'].filter(k => hits[k] < baseline[k])
+ if (worse.length) {
+ console.error(`hit@7 below baseline ${baseline.date}: ${worse.map(k => `${k} ${hits[k]}/${results.length} < ${baseline[k]}/${baseline.n}`).join('; ')}`)
+ process.exit(1)
+ }
+ }
+}
+
+main()
diff --git a/tests/search-eval.mjs b/tests/search-eval.mjs
index 349bb30..25512b5 100644
--- a/tests/search-eval.mjs
+++ b/tests/search-eval.mjs
@@ -23,7 +23,7 @@ const DEEP = process.argv.includes('--deep')
// Synthetic corpus: 3 on-topic clusters + 2 noise notes.
const FIXTURES = {
'harness-vs-model.md': '# Harness важнее модели\nСреда и workflow дают до 90% выигрыша. Контекст это бюджет, не свалка. Чинить harness, не менять модель.',
- 'context-budget.md': '# Контекст как бюджет\n73% токенов уходят до промпта. CLAUDE.md короткий роутер до 200 строк. Субагенты изолируют контекст.',
+ 'context-budget.md': '# Контекст как бюджет\n73% токенов уходят до промпта; токены тратятся до запроса. CLAUDE.md короткий роутер до 200 строк. Субагенты изолируют контекст.',
'swarm-fan-out.md': '# Рой и fan-out\nOrchestrator-worker, recon до fan-out, read параллельно write изолировать. Рой ~15x токенов, оправдан при независимости.',
'autonomy-loops.md': '# Автономные петли\nCircuit breaker и cost cap, keep-or-revert, generator не равно evaluator, status-файлы.',
'coffee.md': '# Кофе\nЭспрессо, молоко, ростер, обжарка зерна.',
diff --git a/tests/test-archive-basename-coverage.mjs b/tests/test-archive-basename-coverage.mjs
new file mode 100644
index 0000000..9a3b844
--- /dev/null
+++ b/tests/test-archive-basename-coverage.mjs
@@ -0,0 +1,24 @@
+// Регресс на баг archive-гейта: покрытие индексировалось только по `local-media:`/
+// `source_hash` (провенанс скриншота), поэтому нота именованного файла (PDF/DOCX)
+// с `source: ` гейтом не виделась и архивация никогда не открывалась.
+import assert from 'node:assert'
+import { sourceBasenames } from '../scripts/mnemazine-archive-covered.mjs'
+
+const has = (text, name) => sourceBasenames(text).has(name)
+
+// скалярная форма — канон для одного именованного файла
+assert.ok(has('---\nsource: 2604.03136--StoryScope.pdf\nverified: подтверждён\n---\n\nтело', '2604.03136--StoryScope.pdf'))
+// кавычки и путь: сверяется basename, не строка целиком
+assert.ok(has('---\nsource: "~/Desktop/Mnemazine Inbox/report.docx"\n---\n', 'report.docx'))
+// список — несколько исходников у одной ноты
+assert.ok(has('---\nsources:\n - a.pdf\n - b.pdf\n---\n', 'b.pdf'))
+// inline-массив
+assert.ok(has('---\nsources: [a.pdf, b.pdf]\n---\n', 'a.pdf'))
+// провенанс скриншота полем source: не притворяется
+assert.deepEqual([...sourceBasenames('---\nlocal-media: abc123\n---\n')], [])
+// упоминание имени в теле — не провенанс, ложного покрытия быть не должно
+assert.deepEqual([...sourceBasenames('---\ntitle: x\n---\n\nсм. файл leak.pdf в архиве\n')], [])
+// список закрыт следующим ключом — чужие значения не подхватываются
+assert.ok(!has('---\nsources:\n - a.pdf\ntags:\n - noise.pdf\n---\n', 'noise.pdf'))
+
+console.log('ok - archive basename coverage: 7/7')
diff --git a/tests/test-coverage-fix.mjs b/tests/test-coverage-fix.mjs
new file mode 100644
index 0000000..48d2c1e
--- /dev/null
+++ b/tests/test-coverage-fix.mjs
@@ -0,0 +1,84 @@
+// TDD/характеризационный тест фикса покрытия группировки (kb-pipeline).
+// Доказывает: (1) gap-split верно делит provenance vs real; (2) НОВАЯ проверка
+// покрытия (basename где угодно во frontmatter) ловит склеенные файлы, а СТАРАЯ
+// (точно "source: ") их теряет — это и был баг.
+import assert from 'node:assert'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+const base = p => p.split('/').pop()
+let pass = 0, fail = 0
+const ok = (c, m) => { if (c) { pass++; console.log(' ok -', m) } else { fail++; console.error(' FAIL-', m) } }
+
+// ---- логика из kb-pipeline.js (закрытие-дыр), скопирована дословно ----
+function splitGaps (units, processResults, unaccounted) {
+ const notePathByFile = {}
+ units.forEach(function (u) {
+ const res = processResults.find(function (r) { return r && r.group_id === u.group_id && r.outcome === 'note' })
+ if (res) (u.files || []).forEach(function (uf) { notePathByFile[base(uf)] = res.note_md || res.filename || '' })
+ })
+ const provenanceGaps = unaccounted.filter(function (f) { return notePathByFile[base(f)] })
+ const realGaps = unaccounted.filter(function (f) { return !notePathByFile[base(f)] })
+ return { provenanceGaps, realGaps }
+}
+
+console.log('TEST 1 — gap-split (группа дала ноту → provenance; не дала → real)')
+{
+ const units = [
+ { group_id: 'g1', files: ['/in/a.webp', '/in/b.webp', '/in/c.webp'] }, // 1 юнит, 3 файла
+ { group_id: 'g2', files: ['/in/d.webp'] } // юнит без ноты
+ ]
+ const pr = [{ group_id: 'g1', outcome: 'note', note_md: '/v/note1.md' }] // g1 дал ноту, g2 нет
+ const un = ['/in/b.webp', '/in/c.webp', '/in/d.webp'] // сверщик счёл «дырами»
+ const { provenanceGaps, realGaps } = splitGaps(units, pr, un)
+ ok(JSON.stringify(provenanceGaps) === JSON.stringify(['/in/b.webp', '/in/c.webp']), 'provenance = b,c (дёшево патчатся)')
+ ok(JSON.stringify(realGaps) === JSON.stringify(['/in/d.webp']), 'real = d (идёт в Sonnet-ресёрч)')
+}
+
+console.log('TEST 2 — покрытие: НОВАЯ ловит склеенные, СТАРАЯ теряет (=баг)')
+{
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kbcov-'))
+ // склеенная нота группы: source = первый, sources = все 3
+ fs.writeFileSync(path.join(dir, 'note1.md'), '---\nsource: a.webp\nsources:\n - a.webp\n - b.webp\n - c.webp\n---\n# знание\n')
+ fs.writeFileSync(path.join(dir, 'note2.md'), '---\nsource: x.webp\n---\n# одиночка\n')
+ const blobs = fs.readdirSync(dir).map(function (f) { return fs.readFileSync(path.join(dir, f), 'utf8') })
+ const newCov = function (bn) { return blobs.some(function (c) { return c.includes(bn) }) } // basename где угодно во frontmatter
+ const oldCov = function (bn) { return blobs.some(function (c) { return c.includes('source: ' + bn) }) } // точная строка source:
+ for (const bn of ['a.webp', 'b.webp', 'c.webp', 'x.webp']) ok(newCov(bn), 'НОВАЯ покрывает ' + bn)
+ ok(oldCov('a.webp') && oldCov('x.webp'), 'СТАРАЯ покрывает первичные a,x')
+ ok(!oldCov('b.webp') && !oldCov('c.webp'), 'СТАРАЯ ТЕРЯЕТ склеенные b,c → ложные дыры (баг воспроизведён)')
+ fs.rmSync(dir, { recursive: true, force: true })
+}
+
+console.log('TEST 3 — durable-архив: нет авто-удаления исходников (анти-регрессия)')
+{
+ const HOME = os.homedir()
+ const files = [
+ HOME + '/.claude/workflows/mnemazina-pipeline.js',
+ HOME + '/.codex/workflows/mnemazina-pipeline.js',
+ HOME + '/.claude/agents/mnemazina-pipeline/mnemazina-guard.md',
+ HOME + '/.codex/agents/mnemazina-pipeline/mnemazina-guard.md'
+ ]
+ const ARCHIVE_TOKEN = /ARCHIVE|_archive|archivePath|archiveDir|kb-processed-source/
+ const DELETE_OP = /-delete\b|\brm\s+-[rf]/
+ const RETENTION = /-mtime\s+\+\s*\d+\s+-delete/ // тот самый паттерн ретеншна, что тихо удалял оригиналы
+ let checked = 0
+ const violations = []
+ files.forEach(function (fp) {
+ let txt
+ try { txt = fs.readFileSync(fp, 'utf8') } catch (e) { return } // codex-зеркало опционально
+ checked++
+ if (RETENTION.test(txt)) violations.push(base(fp) + ': retention -mtime+N-delete')
+ txt.split('\n').forEach(function (ln, i) {
+ if (DELETE_OP.test(ln) && ARCHIVE_TOKEN.test(ln)) violations.push(base(fp) + ':' + (i + 1) + ' ' + ln.trim().slice(0, 64))
+ })
+ })
+ ok(checked >= 3, 'проверено файлов: ' + checked + ' (≥3 канон)')
+ ok(violations.length === 0, 'нет delete/rm на архивном пути' + (violations.length ? ' — НАРУШЕНИЯ:\n ' + violations.join('\n ') : ''))
+ const wf = fs.readFileSync(files[0], 'utf8')
+ ok(/const ARCHIVE = INBOX \+ '\/_archive'/.test(wf), 'ARCHIVE = INBOX + /_archive (durable-локация зафиксирована)')
+}
+
+console.log('\n' + pass + ' passed, ' + fail + ' failed')
+process.exit(fail ? 1 : 0)
diff --git a/vault/00 System/Mnemazine Protocol.md b/vault/00 System/Mnemazine Protocol.md
new file mode 100644
index 0000000..ef2fe71
--- /dev/null
+++ b/vault/00 System/Mnemazine Protocol.md
@@ -0,0 +1,21 @@
+# Mnemazine Protocol
+
+## Короткий ответ
+
+The vault contains finished knowledge only.
+
+Первичное распознавание, copied fragments, transcripts, screenshots, and unverified dumps stay in `inbox/`, `.mnemazine/cache/`, or `99 Archive/`.
+
+## Источники
+
+This file documents the repo fixture protocol.
+
+Every durable note should contain:
+
+- clear title;
+- short explanation;
+- source links;
+- verified facts;
+- open questions;
+- practical use;
+- related notes.
diff --git a/vault/99 Система/_ПРОЕКТЫ.md b/vault/99 Система/_ПРОЕКТЫ.md
new file mode 100644
index 0000000..52d62ba
--- /dev/null
+++ b/vault/99 Система/_ПРОЕКТЫ.md
@@ -0,0 +1,11 @@
+# Проекты (репо-фикстура)
+
+Минимальные слаги проектов для NOTE-SPEC гейта в тестовом корпусе.
+
+## mnemazine
+
+Репо-фикстура Mnemazine.
+
+## demo-project
+
+Учебный проект для проверки блока «Как это поможет мне».
diff --git a/workflows/kb-pipeline.md b/workflows/kb-pipeline.md
index a592bc1..94e5ba1 100644
--- a/workflows/kb-pipeline.md
+++ b/workflows/kb-pipeline.md
@@ -1,38 +1,5 @@
-# Mnemazine KB Pipeline
+# Archived Pointer
-```text
-inbox -> census -> extraction -> understanding -> research -> verification -> atomization -> vault -> reconcile -> Graphify -> weekly brief -> visual knowledge report
-```
+Старое поколение workflow сохранено в `~/Архив/разобрано-2026-08/mnemazine-workflow-старое-поколение/`.
-The pipeline is intentionally strict. A source is not done when text is extracted. It is done when a durable note exists or a clear rejection reason is recorded.
-
-## Agents
-
-- Mnemosyne, `kb-coordinator`: owns the full run, handoffs, final brief, and post-run report.
-- Ivan Kirilov, `kb-guard`: owns census, source hashes, archive safety, and gates.
-- Vasily Sopikov, `kb-extract`: owns local-first extraction and triage.
-- Mikhail Lomonosov, `kb-verify`: owns explanation, public verification, and atomization.
-- Nikolai Kalachov, `kb-librarian`: owns vault placement, naming, links, and reuse shape.
-- Dmitry Mendeleev, `kb-reconciler`: owns coverage accounting: note, duplicate, noise, unreadable, or deferred.
-
-## Required Output
-
-Every useful item must become reproducible knowledge, not a scanned fragment:
-
-- clear Russian title;
-- plain explanation of what it is;
-- why it matters;
-- how to use it;
-- what is verified, assumed, or unknown;
-- source references with `source_ref` and `source_hash`;
-- small atoms when the source contains several ideas;
-- next action when the knowledge implies work.
-
-Every full pass must also create a visual post-run report in `reports/`:
-
-- schematic clusters;
-- note-to-atom breakdown;
-- duplicate accounting;
-- top-20 recommended actions.
-
-Claude Code and Codex must follow this same contract. Runtime wrappers may differ, but the public workflow, scripts, gates, and agent role passports are shared.
+Канон тут: `workflows/mnemazina-pipeline.js`.
diff --git a/workflows/mnemazina-pipeline.js b/workflows/mnemazina-pipeline.js
new file mode 100644
index 0000000..ceedbd9
--- /dev/null
+++ b/workflows/mnemazina-pipeline.js
@@ -0,0 +1,926 @@
+export const meta = {
+ name: 'mnemazina-pipeline',
+ description: 'Мнемозина-контролёр: конвейер знаний с воротами полноты + токеносбережение (hash-cache, markitdown, локальный OCR, cost-aware тиры). Ни один файл инбокса не архивируется и прогон не закрывается «done», пока сверщик (mnemazina-reconciler) не докажет на диске, что каждый файл получил ноту или зафиксированную причину. Режимы: INTAKE / FIND / INLINE.',
+ whenToUse: 'Авто-триггер на каждое сообщение в проекте Мнемозина — включая вставленную ссылку, длинный текст, скрин или просьбу «разбери инбокс / сохрани в базу», даже без слов «Мнемозина» и /kb, потому что недосработавший триггер молча теряет материал. Также Workflow({ name: "mnemazina-pipeline", args: "" })',
+ phases: [
+ { title: 'Guard', detail: 'Git-снапшот, lockfile, Ollama-зонд, ретеншн архива' },
+ { title: 'Census', detail: 'Список ВСЕХ файлов + SHA-256 hash-cache (обработанное = 0 токенов)' },
+ { title: 'Triage', detail: 'Классификация: юниты + needs_atomization + дубли/шум/нечитаемо' },
+ { title: 'Process', detail: 'Параллельно: markitdown/локальный-OCR → extract→atomize→verify→classify→refine, нота/атомы с source:' },
+ { title: 'Store', detail: 'Запись нот/атомных managed blocks + индексы (БЕЗ архивации)' },
+ { title: 'Reconcile', detail: 'ГЕЙТ полноты: каждый файл → нота или причина. Ретрай дыр' },
+ { title: 'Archive', detail: 'mv учтённых + cached; дыры остаются в инбоксе. Запись hash-кэша' },
+ { title: 'Graphify', detail: 'Финал всегда, потому что граф — память Мнемозины: обновить + авточистка шаблон-узлов (graphify_clean.py)' },
+ { title: 'VisualReport', detail: 'Светлый Apple-style HTML/MD отчёт: схема знаний, атомы, дубли, топ-20 действий' },
+ { title: 'Briefing', detail: 'Кросс новых знаний с профилем владельца → «что применить сейчас»' },
+ { title: 'SelfReflection', detail: 'После Graphify/Briefing: agent trace + что сработало/сломалось/урок/фикс для самообучения' },
+ { title: 'Find', detail: 'Grep + граф + ранжирование по проектам' },
+ ],
+}
+
+const ARGS_OBJ = (function () {
+ if (!args || typeof args !== 'string') return (args && typeof args === 'object') ? args : {}
+ var t = args.trim()
+ if (t.charAt(0) !== '{') return {}
+ try { var p = JSON.parse(t); return (p && typeof p === 'object') ? p : {} } catch (e) { return {} }
+})()
+const HOME_DIR = (typeof process !== 'undefined' && process.env && process.env.HOME) || '~'
+const REPO_ROOT = String(ARGS_OBJ.repo || (typeof process !== 'undefined' && process.env && process.env.MNEMAZINE_ROOT) || '.')
+const INBOX = String(ARGS_OBJ.inbox || (typeof process !== 'undefined' && process.env && process.env.MNEMAZINE_INBOX) || (HOME_DIR + '/Desktop/Mnemazine Inbox'))
+const ARCHIVE = INBOX + '/_archive' // durable-архив исходников: вне git-vault, БЕЗ авто-удаления — оригиналы нужны для claim↔источник ре-верификации нот
+const VAULT = String(ARGS_OBJ.vault || (typeof process !== 'undefined' && process.env && process.env.MNEMAZINE_VAULT) || (HOME_DIR + '/vault'))
+const AGENT_HOME = String(ARGS_OBJ.agent_home || (typeof process !== 'undefined' && process.env && (process.env.MNEMAZINE_AGENT_HOME || process.env.CODEX_HOME || process.env.CLAUDE_HOME)) || (HOME_DIR + '/.codex'))
+const HASHDB = VAULT + '/99 Система/_processed-hashes.json'
+const EMBED_PY = String(ARGS_OBJ.embed_py || (typeof process !== 'undefined' && process.env && process.env.MNEMAZINE_EMBED_PY) || (HOME_DIR + '/.venvs/kb-embed/bin/python'))
+const EMBED_SC = AGENT_HOME + '/skills/mnemazina/kb-embed.py'
+const EMBED_IDX = VAULT + '/99 Система/_embeddings.json'
+const OCR_BIN = AGENT_HOME + '/skills/mnemazina/vision-ocr' // Apple Vision OCR (локально, ~1.4с, русский точно). НЕ ollama/llava (галлюцинирует, 12мин).
+const WHISPER_BIN = String(ARGS_OBJ.whisper_bin || (typeof process !== 'undefined' && process.env && process.env.MNEMAZINE_WHISPER_BIN) || (HOME_DIR + '/.npm-global/bin/whisper')) // openai-whisper (локально, 0 токенов). Модель small кэширована в ~/.cache/whisper.
+const WHISPER_MODEL = (typeof process !== 'undefined' && process.env && process.env.MNEMAZINE_WHISPER_MODEL) || 'small' // баланс скорость/качество на CPU. Авто-язык.
+const DUP_THRESHOLD = 0.72
+const ABTOP = String(ARGS_OBJ.abtop || (typeof process !== 'undefined' && process.env && process.env.MNEMAZINE_ABTOP) || (HOME_DIR + '/.cargo/bin/abtop'))
+const NOW = (ARGS_OBJ && ARGS_OBJ.now) ? String(ARGS_OBJ.now) : null
+const RUN_ID = 'kb-' + (NOW ? NOW.replace(/[-:.TZ]/g, '').slice(0, 14) : 'unstamped000000')
+const OBS_LOG = REPO_ROOT.replace(/\/+$/, '') + '/.mnemazine/state/run-observability.jsonl'
+const DAG_FILE = VAULT + '/99 Система/_last-run-dag.json'
+const base = function (p) { return String(p).split('/').pop() }
+const fsMod = await import('node:fs')
+const cryptoMod = await import('node:crypto')
+const childProcess = await import('node:child_process')
+const MODEL_POLICY = JSON.parse(fsMod.readFileSync(REPO_ROOT.replace(/\/+$/, '') + '/config/model-policy.json', 'utf8'))
+const modelForRole = function (role, tier) {
+ const value = MODEL_POLICY.roles && MODEL_POLICY.roles[role]
+ if (value === 'by-tier') return MODEL_POLICY.tiers[String(tier)]
+ return value
+}
+const joinPath = function (dir, name) { return String(dir).replace(/\/+$/, '') + '/' + name }
+const activeInboxFiles = function () {
+ return fsMod.readdirSync(INBOX, { withFileTypes: true })
+ .filter(function (entry) { return entry.isFile() && entry.name !== 'README.md' && entry.name !== '.DS_Store' })
+ .map(function (entry) { return joinPath(INBOX, entry.name) })
+ .sort()
+}
+const sha256File = function (file) {
+ return cryptoMod.createHash('sha256').update(fsMod.readFileSync(file)).digest('hex')
+}
+const readJsonFile = function (file, fallback) {
+ try { return JSON.parse(fsMod.readFileSync(file, 'utf8')) } catch (e) { return fallback }
+}
+const countMarkdownFiles = function (dir) {
+ let count = 0
+ for (const entry of fsMod.readdirSync(dir, { withFileTypes: true })) {
+ if (entry.name === '.git' || entry.name === '.obsidian' || entry.name === 'graphify-out') continue
+ const p = joinPath(dir, entry.name)
+ if (entry.isDirectory()) count += countMarkdownFiles(p)
+ else if (entry.isFile() && entry.name.endsWith('.md') && !entry.name.startsWith('_')) count += 1
+ }
+ return count
+}
+const extOf = function (file) {
+ const name = base(file).toLowerCase()
+ const i = name.lastIndexOf('.')
+ return i === -1 ? '' : name.slice(i)
+}
+const tierOfFile = function (file) {
+ const ext = extOf(file)
+ if (['.md', '.txt', '.json', '.csv'].indexOf(ext) !== -1) return 0
+ if (['.pdf', '.docx', '.pptx', '.xlsx', '.html', '.htm'].indexOf(ext) !== -1) return 1
+ if (['.png', '.jpg', '.jpeg', '.heic', '.webp', '.tiff'].indexOf(ext) !== -1) return 2
+ if (['.mp4', '.mov', '.m4v', '.webm', '.mkv', '.mp3', '.wav', '.m4a', '.aac', '.flac', '.ogg', '.opus'].indexOf(ext) !== -1) return 3
+ return 1
+}
+const tierOfUnit = function (unit) {
+ const files = Array.isArray(unit.files) ? unit.files : []
+ return files.reduce(function (max, file) { return Math.max(max, tierOfFile(file)) }, 1)
+}
+const releaseRunLock = async function (label) {
+ return await agent(
+ 'Финальная механика Мнемозины: освободи lockfile, если он stale. Выполни bash без TTY:\n' +
+ 'LOCK=/tmp/kb-run.lock; if [ -f "$LOCK" ]; then PID=$(cat "$LOCK" 2>/dev/null || true); ' +
+ 'if [ -z "$PID" ] || ! kill -0 "$PID" 2>/dev/null; then rm -f "$LOCK"; echo released; else echo live:$PID; fi; else echo no_lock; fi',
+ { label: 'release-lock-' + label, phase: 'Cleanup', model: 'haiku' }
+ )
+}
+
+const observeRun = async function (label) {
+ return await agent(
+ 'Run Observatory для Мнемозины. Выполни bash без TTY, не падай если abtop недоступен:\n' +
+ 'mkdir -p "$(dirname "' + OBS_LOG + '")"; OUT=$([ -x "' + ABTOP + '" ] && "' + ABTOP + '" --once 2>&1 || echo "abtop_unavailable"); ' +
+ 'PROJ=$(basename "$PWD"); LINE=$(printf "%s" "$OUT" | grep "$PROJ" | grep -E "CTX: *[0-9]+%" | head -1 || true); ' +
+ '[ -n "$LINE" ] || LINE=$(printf "%s" "$OUT" | grep -E "CTX: *[0-9]+%" | head -1 || true); ' +
+ 'CTX=$(printf "%s" "$LINE" | grep -Eo "CTX: *[0-9]+%" | head -1 | grep -Eo "[0-9]+" || true); ' +
+ 'TOK=$(printf "%s" "$LINE" | grep -Eo "Tok:[^ ]+" | head -1 | cut -d: -f2 || true); ' +
+ 'printf \'{"ts":"%s","run_id":"' + RUN_ID + '","phase":"' + label + '","ctx_percent":"%s","tokens":"%s","raw":%s}\\n\' "$(date -u +%FT%TZ)" "$CTX" "$TOK" "$(printf "%s" "$OUT" | python3 -c "import json,sys; print(json.dumps(sys.stdin.read()[:4000]))")" >> "' + OBS_LOG + '"; ' +
+ 'if [ "${CTX:-0}" -ge 90 ]; then echo STOP_CTX_90; elif [ "${CTX:-0}" -ge 80 ]; then echo WARN_CTX_80; else echo OK_CTX; fi',
+ { label: 'observe-' + label, phase: 'Observe', model: 'haiku' }
+ )
+}
+
+// Mode-detect: извлечь человеческое сообщение, НЕ сериализуя весь объект args.
+// Объект args = { now, message }: now идёт в RUN_ID (стр.26), message — это userMessage.
+// JSON.stringify(args) тут ломал бы isInlineContent (длина >80) → ложная inline-нота.
+const userMessage = (function () {
+ if (!args) return ''
+ if (typeof args === 'string') {
+ // строка может быть JSON-обёрткой { now, message } или просто текстом
+ var t = args.trim()
+ if (t.charAt(0) === '{') {
+ try { var p = JSON.parse(t); if (p && typeof p === 'object') return String(p.message || p.text || '') } catch (e) {}
+ }
+ return args
+ }
+ if (typeof args === 'object') return String(args.message || args.text || '')
+ return String(args)
+})()
+const msg = userMessage.toLowerCase().trim()
+
+const isFindMode = msg.startsWith('/kb find') || msg.startsWith('/find') ||
+ msg.startsWith('найди ') || msg.startsWith('поищи ') ||
+ msg.startsWith('что знаю о') || msg.startsWith('find:')
+
+const isInlineContent = !isFindMode && userMessage.length > 80
+
+// =================== FIND MODE ===================
+if (isFindMode) {
+ phase('Find')
+ const query = userMessage
+ .replace(/^\/kb find\s*/i, '').replace(/^\/find\s*/i, '')
+ .replace(/^найди\s*/i, '').replace(/^поищи\s*/i, '')
+ .replace(/^что знаю о\s*/i, '').replace(/^find:\s*/i, '').trim()
+ log('Поиск: "' + query + '"')
+ const result = await agent(
+ 'MODE: FIND\nQUERY: ' + query + '\nVAULT: ' + VAULT + '\nMAX_RESULTS: 7\n\n' +
+ 'Ты — mnemazina-librarian. 1) grep -rl по vault (искл. _Содержание/_МАСТЕР/Лог). 2) head -25 топ-кандидатов. ' +
+ '3) Читай _ПРОЕКТЫ.md. 4) Если graphify-out/graph.json есть: python3 -m graphify query "' + query + '" --budget 1500. ' +
+ '5) Ранжируй (ключи +3, тема +2, verified +1, проект +2). 6) Верни топ-7 с путями, snippet, score, связью с проектом, действием.',
+ { label: 'kb-find', phase: 'Find', agentType: 'mnemazina-librarian', model: modelForRole('kb-find') }
+ )
+ return { mode: 'find', query: query, results: result }
+}
+
+// =================== INTAKE MODE ===================
+const observeStart = await observeRun('start')
+if (String(observeStart).indexOf('STOP_CTX_90') !== -1) {
+ return { error: 'ctx_too_high', run_id: RUN_ID, message: 'CTX >= 90%. Новый чат/сжатие перед большим прогоном Мнемозины.', observability_log: OBS_LOG }
+}
+
+// ---------- GATE 0: Guard (+ зонд локальных движков извлечения: Vision/whisper/embed) ----------
+phase('Guard')
+const guardResult = await agent(
+ 'Выполни guard-последовательность Мнемозины:\n\n' +
+ 'VAULT="' + VAULT + '"\nINBOX="' + INBOX + '"\n\n' +
+ '1. Git-снапшот: git -C "$VAULT" rev-parse --git-dir >/dev/null 2>&1 || git -C "$VAULT" init .; ' +
+ 'git -C "$VAULT" add -A && git -C "$VAULT" commit -m "pre-kb-$(date +%Y%m%dT%H%M)" --allow-empty. Сохрани hash.\n' +
+ '2. Lockfile /tmp/kb-run.lock: если жив (kill -0) → error "lock_active"; иначе echo $$ > lock.\n' +
+ '3. Зонд локальных движков (local-first, $0). Исполни ДОСЛОВНО и верни вывод: ' +
+ 'ls -l "' + OCR_BIN + '" "' + WHISPER_BIN + '" 2>&1 | head -4 → в поле ocr_probe. ' +
+ 'Затем ocr_ready = ([ -x "' + OCR_BIN + '" ] даёт истину), whisper_ready = ([ -x "' + WHISPER_BIN + '" ] даёт истину). ' +
+ 'Оба поля ОБЯЗАТЕЛЬНЫ и должны быть результатом реального запуска команды, а не предположением: ' +
+ 'ocr_ready=false останавливает весь прогон, поэтому ложное «нет» дороже любой другой ошибки здесь. ' +
+ 'Ollama не зондируй: для извлечения он не используется (llava галлюцинирует).\n' +
+ '4. Archive (durable, БЕЗ авто-удаления): ARCHIVE="' + ARCHIVE + '"; mkdir -p "$ARCHIVE". Верни archive_path="' + ARCHIVE + '".\n' +
+ '5. mkdir -p "' + INBOX + '". Верни сегодняшнюю дату ГГГГ-ММ-ДД (date +%F).\n' +
+ '6. Семантический дедуп готов? [ -x "' + EMBED_PY + '" ] && [ -f "' + EMBED_SC + '" ] && echo yes. Верни embed_ready bool.\n\n' +
+ 'Верни JSON: { "snapshot", "ocr_ready", "whisper_ready", "embed_ready", "archive_path", "run_date", "error" }',
+ {
+ label: 'guard', phase: 'Guard', agentType: 'mnemazina-guard', model: 'haiku',
+ schema: { type: 'object', properties: {
+ snapshot: { type: 'string' },
+ ocr_ready: { type: 'boolean' }, whisper_ready: { type: 'boolean' },
+ ocr_probe: { type: 'string' }, // сырой вывод `ls -l` по бинарям: улика, по которой видно ложное «нет»
+ embed_ready: { type: 'boolean' },
+ archive_path: { type: 'string' }, run_date: { type: 'string' }, error: { type: ['string', 'null'] }
+ },
+ // ocr_ready/whisper_ready ОБЯЗАТЕЛЬНЫ (2026-07-25, измерено на живом прогоне). Они читаются как
+ // `!!guardResult.ocr_ready`, то есть ОТСУТСТВИЕ поля неотличимо от «движка нет» — и жёсткий гейт
+ // ниже останавливает прогон. Ровно это и случилось: сторож вернул {"embed_ready":true}, поле ocr_ready
+ // не вернул, и 75 файлов встали с вердиктом «Apple Vision недоступен», хотя бинарь работал
+ // (`vision-ocr IMG_5596.PNG` распознал русский текст с первого запуска).
+ // Молчание — не измерение. Схема обязана требовать ответ на каждый зонд, чей ответ имеет право
+ // остановить прогон.
+ required: ['embed_ready', 'ocr_ready', 'whisper_ready'] }
+ }
+)
+if (guardResult && guardResult.error === 'lock_active') {
+ log('Прогон уже идёт. Удали /tmp/kb-run.lock.')
+ return { error: 'lock_active' }
+}
+const embedReady = guardResult ? !!guardResult.embed_ready : false
+const ocrReady = guardResult ? !!guardResult.ocr_ready : false
+const whisperReady = guardResult ? !!guardResult.whisper_ready : false
+const archivePath = ARCHIVE // детерминированно: durable _archive, не зависит от guard-возврата или эвристик поиска проекта
+const runDate = (guardResult && guardResult.run_date) ? guardResult.run_date : ''
+const archiveDir = (/^\d{4}-\d{2}/.test(runDate) ? archivePath + '/' + runDate.slice(0, 7) : archivePath) // датированная подпапка _archive/ГГГГ-ММ (плоский фолбэк если дата неизвестна)
+log('Guard ok. OCR=Apple Vision (' + (ocrReady ? 'ready' : 'НЕТ') + '). Whisper=' + (whisperReady ? 'ready' : 'нет') + '. Embed=' + (embedReady ? 'fastembed' : 'нет'))
+
+if (isInlineContent) {
+ await agent(
+ 'Сохрани inline-контент пользователя как файл в инбокс ' + INBOX + '/inline-' + (runDate || 'content') + '.md ' +
+ '(если занято — числовой суффикс). Контент:\n' + userMessage + '\nWrite tool. Верни путь.',
+ { label: 'save-inline', phase: 'Guard', model: 'haiku' }
+ )
+ log('Inline-контент сохранён в инбокс')
+}
+
+// ---------- CENSUS: наземная правда + hash-cache (обработанное = 0 токенов) ----------
+phase('Census')
+const processedHashCache = readJsonFile(HASHDB, {})
+const realPaths = activeInboxFiles()
+const trueCount = realPaths.length
+
+let allCensus = realPaths.map(function (p) {
+ const hash = sha256File(p)
+ return { path: p, hash: hash, cached: !!processedHashCache[hash], cached_note: processedHashCache[hash] || null }
+})
+
+const inboxFiles = allCensus.filter(function (f) { return !f.cached }).map(function (f) { return f.path })
+const cachedFiles = allCensus.filter(function (f) { return f.cached }).map(function (f) { return f.path })
+const hashOf = {}
+allCensus.forEach(function (f) { if (f.hash) hashOf[f.path] = f.hash })
+
+// Авторитет пустоты — список с диска (trueCount), НЕ census-агент (иначе фантом-мусор → ложная обработка / balanced:false).
+if (trueCount === 0) {
+ log('Инбокс пуст.')
+ await observeRun('end-empty')
+ await releaseRunLock('empty')
+ return { status: 'empty_inbox', run_id: RUN_ID, message: 'Инбокс ~/Desktop/Mnemazine Inbox пуст. Добавь материалы или /kb find <запрос>.', observability_log: OBS_LOG }
+}
+if (inboxFiles.length === 0) {
+ // всё из кэша — ничего не обрабатываем, архивируем и закрываем (0 токенов LLM)
+ if (cachedFiles.length > 0) {
+ await agent(
+ 'mkdir -p "' + archiveDir + '"; перемести (mv) эти уже-обработанные файлы в архив:\n' + cachedFiles.join('\n') + '\nВерни {archived:N}.',
+ { label: 'archive-cached', phase: 'Census', agentType: 'mnemazina-librarian', model: 'haiku' }
+ )
+ }
+ log('Все ' + cachedFiles.length + ' файлов из hash-кэша = 0 токенов')
+ await observeRun('end-all-cached')
+ await releaseRunLock('all-cached')
+ return {
+ status: 'all_cached', run_id: RUN_ID, census: allCensus.length, cached: cachedFiles.length, archived: cachedFiles.length,
+ observability_log: OBS_LOG,
+ message: 'Все ' + cachedFiles.length + ' файлов уже обработаны (hash-cache) → 0 токенов LLM, перемещены в архив.'
+ }
+}
+log('Census: ' + allCensus.length + ' файлов (' + inboxFiles.length + ' новых, ' + cachedFiles.length + ' из кэша = 0 токенов)')
+
+// ---------- OCR PASS: детерминированный локальный OCR ВСЕХ картинок (Apple Vision) ----------
+// Текст пишется в сайдкары INBOX/.ocr/<имя>.txt. Агенты дальше читают ТЕКСТ, не картинки →
+// гарантия 0 cloud-vision токенов. Не полагаемся на дисциплину агента (он бы выбрал Read-vision).
+phase('Triage')
+const OCR_DIR = INBOX + '/.ocr'
+const imageFiles = inboxFiles.filter(function (f) { return /\.(png|webp|jpe?g|heic|heif|tiff?|gif|bmp)$/i.test(f) })
+// ⛔ ЖЁСТКИЙ ГЕЙТ LOCAL-FIRST: есть картинки, но OCR-движок недоступен → СТОП (НЕ тихий облачный фолбэк на весь OCR).
+// На Linux-VPS Apple Vision невозможен → image-батч останавливается; текст/видео-батчи идут дальше. На Mac: чинить бинарь.
+if (imageFiles.length > 0 && !ocrReady) {
+ log('⛔ СТОП: ' + imageFiles.length + ' картинок, но Apple Vision OCR недоступен (' + OCR_BIN + '). Local-first нарушен — облачный fallback на весь OCR запрещён.')
+ await releaseRunLock('ocr-missing')
+ return { error: 'ocr_engine_missing', run_id: RUN_ID, images: imageFiles.length,
+ // Улика вместе с вердиктом: 2026-07-25 этот гейт остановил 75 файлов на РАБОТАЮЩЕМ бинаре — сторож
+ // просто не вернул поле, и `!!undefined` прочиталось как «движка нет». Теперь рядом с отказом лежит
+ // сырой `ls -l`, и первое, что делает оператор, — сверяет вердикт с уликой, а не чинит исправное.
+ ocr_probe: (guardResult && guardResult.ocr_probe) || '(сторож улику не вернул — вердикту не верить, проверить бинарь руками)',
+ fix: 'Сначала ПРОВЕРЬ: "' + OCR_BIN + '" <любая картинка> — если печатает текст, движок исправен и виноват зонд сторожа, а не бинарь. Только если правда не собран: swiftc -O "' + OCR_BIN + '.swift" -o "' + OCR_BIN + '". Linux/VPS: Apple Vision невозможен → обрабатывать картинки только на Mac.',
+ observability_log: OBS_LOG }
+}
+if (imageFiles.length > 0) {
+ log('OCR-проход: ' + imageFiles.length + ' картинок → Apple Vision (локально, ~1.4с/шт)')
+ await agent(
+ 'Выполни один bash без TTY и верни его stdout (последнюю строку JSON). Он гоняет локальный Apple Vision OCR по картинкам и пишет сайдкары:\n\n' +
+ 'python3 <<\'PYEOF\'\n' +
+ 'import subprocess, json, os\n' +
+ 'BIN = ' + JSON.stringify(OCR_BIN) + '\n' +
+ 'OCRDIR = ' + JSON.stringify(OCR_DIR) + '\n' +
+ 'files = ' + JSON.stringify(imageFiles) + '\n' +
+ 'os.makedirs(OCRDIR, exist_ok=True)\n' +
+ 'done = 0; empty = 0\n' +
+ 'for f in files:\n' +
+ ' try:\n' +
+ ' t = subprocess.run([BIN, f], capture_output=True, text=True, timeout=60).stdout\n' +
+ ' except Exception:\n' +
+ ' t = ""\n' +
+ ' open(os.path.join(OCRDIR, os.path.basename(f) + ".txt"), "w").write(t)\n' +
+ ' done += 1\n' +
+ ' if len(t.strip()) < 10: empty += 1\n' +
+ 'print(json.dumps({"ocr_done": done, "empty": empty}))\n' +
+ 'PYEOF',
+ { label: 'ocr-pass', phase: 'Triage', model: 'haiku',
+ schema: { type: 'object', properties: { ocr_done: { type: 'number' }, empty: { type: 'number' } }, required: ['ocr_done'] } }
+ )
+}
+
+// ---------- TRANSCRIBE PASS: детерминированная локальная транскрипция ВСЕХ видео/аудио (whisper) ----------
+// Текст → сайдкары INBOX/.transcript/<имя>.txt. Видео больше НЕ deferred — становится текстом → полный pipeline.
+// Локально (openai-whisper, модель small кэширована), 0 токенов.
+const TRANSCRIPT_DIR = INBOX + '/.transcript'
+const mediaFiles = inboxFiles.filter(function (f) { return /\.(mov|mp4|m4v|avi|mkv|webm|mp3|m4a|wav|aac|ogg|flac)$/i.test(f) })
+if (mediaFiles.length > 0) {
+ log('TRANSCRIBE-проход: ' + mediaFiles.length + ' видео/аудио → whisper ' + WHISPER_MODEL + ' (локально, ~0.5x realtime)')
+ await agent(
+ 'Выполни один bash без TTY и верни stdout (последнюю строку JSON). Локальная транскрипция whisper, пишет сайдкары. Это долго (CPU, ~0.5x realtime) — дождись завершения, таймаут уже заложен в сам скрипт:\n\n' +
+ 'python3 <<\'PYEOF\'\n' +
+ 'import subprocess, json, os\n' +
+ 'BIN = ' + JSON.stringify(WHISPER_BIN) + '\n' +
+ 'MODEL = ' + JSON.stringify(WHISPER_MODEL) + '\n' +
+ 'TDIR = ' + JSON.stringify(TRANSCRIPT_DIR) + '\n' +
+ 'files = ' + JSON.stringify(mediaFiles) + '\n' +
+ 'os.makedirs(TDIR, exist_ok=True)\n' +
+ 'done = 0; empty = 0\n' +
+ 'for f in files:\n' +
+ ' base = os.path.basename(f); stem = os.path.splitext(base)[0]\n' +
+ ' t = ""\n' +
+ ' try:\n' +
+ ' subprocess.run([BIN, f, "--model", MODEL, "--output_format", "txt", "--output_dir", TDIR, "--verbose", "False"], capture_output=True, text=True, timeout=2400)\n' +
+ ' produced = os.path.join(TDIR, stem + ".txt")\n' +
+ ' if os.path.exists(produced): t = open(produced).read()\n' +
+ ' except Exception as e:\n' +
+ ' t = ""\n' +
+ ' open(os.path.join(TDIR, base + ".txt"), "w").write(t)\n' +
+ ' done += 1\n' +
+ ' if len(t.strip()) < 10: empty += 1\n' +
+ 'print(json.dumps({"transcribed": done, "empty": empty}))\n' +
+ 'PYEOF',
+ { label: 'transcribe-pass', phase: 'Triage', model: 'haiku',
+ schema: { type: 'object', properties: { transcribed: { type: 'number' }, empty: { type: 'number' } }, required: ['transcribed'] } }
+ )
+}
+
+// ---------- TRIAGE ----------
+const triageResult = await agent(
+ 'Ты — mnemazina-triage (Сопиков, каталогизатор). Новые файлы инбокса (уже-обработанные исключены hash-кэшем):\n' +
+ inboxFiles.join('\n') + '\n\n' +
+ 'OCR-текст каждой картинки УЖЕ извлечён локально и лежит в ' + OCR_DIR + '/<имя файла>.txt.\n' +
+ 'ТРАНСКРИПТ каждого видео/аудио УЖЕ извлечён локально (whisper) и лежит в ' + TRANSCRIPT_DIR + '/<имя файла>.txt.\n' +
+ '⛔ ЗАПРЕЩЕНО открывать сами .png/.webp/.jpg/.mov/.mp4 (дорого/невозможно). Содержание читай ТОЛЬКО из сайдкар-.txt через Read (дешёвый текст).\n\n' +
+ '1. Сверься с ' + VAULT + '/99 Система/Лог обработки.md.\n' +
+ '2. Картинка → читай ' + OCR_DIR + '/.txt. Видео/аудио (type=video) → читай ' + TRANSCRIPT_DIR + '/.txt. Гипотезу/группировку строй по этому тексту, не по имени файла — имя часто врёт о содержании. Пустой .txt — штатный случай, не ошибка: classified reason=noise (нет текста/речи) или unreadable (битый). Разные видео = разные юниты, потому что юнит рождает одну ноту и склейка разных видео теряет темы.\n' +
+ '3. Для каждого файла реши: часть юнита-знания или причина-исключение.\n' +
+ ' Группируй серии (скрины одного поста/треда → один юнит — сверяй по OCR-тексту). Разные темы → разные юниты.\n' +
+ ' Тип: screenshot|image|pdf|text|url|code|video|other. Причины: dup|noise|unreadable.\n' +
+ '4. Если один файл/гайд/транскрипт явно смешанный (например Карпати: токены, system files, coding, режим жизни, отношения) — не склеивай в одну итоговую ноту, потому что смешанная нота не находится поиском ни по одной из своих тем. Поставь needs_atomization=true и дай atom_hints по будущим атомам.\n' +
+ '4б. Файл `agent-research----.md` — заявка агента проекта (боковая дверь): type=text, hypothesis «исследование агента » (project — второй сегмент имени), свой отдельный юнит, с чужими файлами не группируй.\n' +
+ '5. Каждый файл → либо units.files, либо classified: файл вне обоих списков гейт манифеста форсирует в отдельный юнит без твоей группировки, что дороже и хуже осмысленной серии.\n\n' +
+ 'JSON: { "units": [{ "group_id", "files": ["путь"], "type", "hypothesis", "ocr_preview", "needs_atomization": true|false, "atom_hints": ["тема → раздел"] }], ' +
+ '"classified": [{ "file": "путь", "reason": "dup|noise|unreadable", "note": "пояснение" }] }',
+ {
+ label: 'triage', phase: 'Triage', model: 'haiku',
+ schema: { type: 'object', properties: {
+ units: { type: 'array', items: { type: 'object', properties: {
+ group_id: { type: 'string' }, files: { type: 'array', items: { type: 'string' } },
+ type: { type: 'string' }, hypothesis: { type: 'string' }, ocr_preview: { type: 'string' },
+ needs_atomization: { type: 'boolean' }, atom_hints: { type: 'array', items: { type: 'string' } }
+ }, required: ['group_id', 'files', 'type'] } },
+ classified: { type: 'array', items: { type: 'object', properties: {
+ file: { type: 'string' }, reason: { type: 'string' }, note: { type: 'string' }
+ }, required: ['file', 'reason'] } }
+ }, required: ['units'] }
+ }
+)
+let units = (triageResult && triageResult.units) ? triageResult.units : []
+const classified = (triageResult && triageResult.classified) ? triageResult.classified : []
+
+// ========== ГЕЙТ 1: МАНИФЕСТ ПОЛНЫЙ (детерминированно) ==========
+const manifest = {}
+units.forEach(function (u) { (u.files || []).forEach(function (f) { manifest[base(f)] = true }) })
+classified.forEach(function (c) { manifest[base(c.file)] = true })
+const missing = inboxFiles.filter(function (f) { return !manifest[base(f)] })
+if (missing.length > 0) {
+ log('⚠ ГЕЙТ 1: триаж пропустил ' + missing.length + ' файлов → форсирую в юниты')
+ missing.forEach(function (f, i) {
+ units.push({ group_id: 'forced-' + i, files: [f], type: 'unknown', hypothesis: 'форсирован ГЕЙТ-1 (триаж пропустил)' })
+ })
+}
+log('## МАНИФЕСТ ПОЛНЫЙ ✓ — ' + inboxFiles.length + ' новых учтены (' + units.length + ' юнитов, ' + classified.length + ' исключений)')
+
+// ---------- PROCESS (cost-aware тиры + локальное извлечение) ----------
+phase('Process')
+let tieredUnits = units.map(function (u) {
+ return Object.assign({}, u, { tier: tierOfUnit(u) })
+})
+if (typeof process !== 'undefined' && process.env.MNEMAZINE_SKIP_GROUPS_FILE) {
+ try {
+ const fsMod = await import('node:fs')
+ const skipGroups = JSON.parse(fsMod.readFileSync(process.env.MNEMAZINE_SKIP_GROUPS_FILE, 'utf8'))
+ const skip = new Set(Array.isArray(skipGroups) ? skipGroups : [])
+ const beforeSkip = tieredUnits.length
+ tieredUnits = tieredUnits.filter(function (u) { return !skip.has(u.group_id) })
+ log('RESUME: пропускаю ' + (beforeSkip - tieredUnits.length) + ' уже завершённых групп; осталось ' + tieredUnits.length)
+ } catch (err) {
+ log('RESUME: не смог прочитать MNEMAZINE_SKIP_GROUPS_FILE, иду полным списком: ' + String(err && err.message ? err.message : err))
+ }
+}
+const dag = {
+ run_id: RUN_ID,
+ kind: 'mnemosyne-intake',
+ created_at: NOW || 'unstamped',
+ census_count: allCensus.length,
+ tasks: tieredUnits.map(function (u) {
+ return { id: u.group_id, phase: 'Process', files: u.files, type: u.type, tier: u.tier, depends_on: ['Guard', 'Census', 'Triage'], write_scope: VAULT, status: 'planned' }
+ }),
+ gates: ['## МАНИФЕСТ ПОЛНЫЙ ✓', '## ПОКРЫТИЕ ПОЛНОЕ ✓', '## АРХИВ РАЗРЕШЁН ✓']
+}
+await agent(
+ 'Запиши DAG artifact Мнемозины через Write. Путь: ' + DAG_FILE + '\nJSON:\n' + JSON.stringify(dag, null, 2),
+ { label: 'write-dag', phase: 'Process', model: 'haiku' }
+)
+log('Запускаю ' + tieredUnits.length + ' процессоров (рой' + (tieredUnits.length > 16 ? ', волнами — большой батч' : '') + ')...')
+
+const processorPrompt = function (unit) {
+ return 'Ты — mnemazina-processor (Ломоносов). Обработай один материал через стадии 2-5 Мнемозины.\n\n' +
+ 'MATERIAL_PATH: ' + unit.files.join(', ') + '\nTYPE: ' + unit.type + '\nTIER: ' + unit.tier +
+ '\nGROUP_ID: ' + unit.group_id + '\nVAULT: ' + VAULT + '\n\n' +
+ 'Стадия 2 Извлечение — извлекай локально до Claude, потому что сырьё в контексте жжёт токены без пользы:\n' +
+ ' PDF/DOCX/PPTX/XLSX/EPUB → `markitdown "<файл>"` (CLI) → markdown-текст. Сырьё/vision в контекст не грузи — markdown в разы дешевле.\n' +
+ ' screenshot/image → OCR-текст УЖЕ извлечён локально (Apple Vision) в ' + OCR_DIR + '/<имя файла>.txt. Прочитай этот .txt через Read. ⛔ НЕ открывай саму .png/.webp (дорогой vision). Только если .txt пуст/обрезан И TIER 3 (макс-точность) → разрешён фолбэк Read(vision) на картинку. НЕ ollama/llava.\n' +
+ ' URL → kb-fetch "" (локальный каскад $0: markitdown для бинарников, trafilatura для HTML, кодировки чинит сам; exit 2 = needs_js → Playwright MCP/WebFetch; exit 3 = заблокировано → «источник недоступен», содержимое не выдумывать).\n' +
+ ' video/audio → ТРАНСКРИПТ уже готов локально (whisper) в ' + TRANSCRIPT_DIR + '/<имя файла>.txt. Прочитай через Read. ⛔ НЕ открывай саму .mov/.mp4. Пустой транскрипт (нет речи) → outcome="noise". Иначе транскрипт = вход-семя → обогащай как текст (стадия 3).\n' +
+ (embedReady
+ ? '⚡ Стадия 2.5 Пре-дедуп — до стадии 3, потому что дубль дешевле поймать до дорогого ресёрча: прогони извлечённое семя:\n' +
+ ' ' + EMBED_PY + ' "' + EMBED_SC + '" query "' + EMBED_IDX + '" "<первые ~400 симв извлечённого текста>" 3 ' + DUP_THRESHOLD + '\n' +
+ ' Матч top≥' + DUP_THRESHOLD + ' → прочитай совпавшую ноту. Та же суть → outcome="dup", note_path=совпавшая, стоп: стадию 3 не запускай (никакого Firecrawl) и новую ноту не пиши, потому что ресёрч дубля сжигает бюджет впустую. Разное/нет матча → продолжай на стадию 3.\n'
+ : '') +
+ 'Стадия 3 ИССЛЕДОВАНИЕ+ОБОГАЩЕНИЕ (только если НЕ дубль; извлечённое это ВХОД-СЕМЯ, не тело ноты):\n' +
+ ' 1) Определи тему/сущность/URL из извлечённого. 2) Активно исследуй первоисточник: поиск — WebSearch (встроенный, бесплатный; рунет-темы дополняй kb-search --ru), чтение целевых URL — kb-fetch (локально, $0); recon→оцени→читай целевые. Firecrawl — только по явной команде владельца (кредиты), sgai удалён из конвейера. ' +
+ '3) Вытащи максимум из первоисточника: все разделы, цифры, примеры, тактики, связанные офиц.ресурсы. ' +
+ '3b) Реальный опыт живых пользователей обязателен, потому что нота без практики — пересказ маркетинга: как этим реально пользуются (Reddit, HN, GitHub issues/discussions, профильные/рейтинговые сайты — Product Hunt, G2, отзывы, тематические форумы). Вытащи лайфхаки, баги, подводные камни, паттерны использования, за/против — с тред-URL. ' +
+ '⚠ Фильтр сигнала: бери только реально обсуждаемое — живая дискуссия, много откликов/комментов/upvotes. Игнорируй разовые промо, анонсы, пресс-релизы, низко-сигнальные посты без обсуждения, потому что один голос без откликов — не опыт сообщества. Нет реального обсуждения → пометь «практик-опыт: не найдено живого обсуждения» — это честный штатный результат, не выдумывай. ' +
+ 'Нота строится из ИССЛЕДОВАННОГО, не из одного скрина. 4) Каждый блок фактов → пометь источник-URL; раздели из-первоисточника / из-опыта-юзеров / из-скрина / добавлено-агентом.\n' +
+ ' ⚠ Обогащение обязательно для каждого юнита, потому что без него нота вырождается в подпись к скрину: даже крошечная зацепка (название тулзы, один скрин, обрывок) расширяется через WebSearch+kb-fetch до полного знания. Пропуск обогащения = брак — такая нота не отвечает на вопрос «как применить», ради которого база существует.\n' +
+ ' Антигаллюцинация: каждый добавленный факт ведёт к fetched-источнику (цитируй URL), и контент этого URL реально содержит факт — открой и сверь, потому что «ссылка живая» ≠ подтверждение (числа/даты/ID дословно, репо → GitHub API); скрин-текст один — лишь входной запрос. Глубина по TIER: 0/1 — обогащение обязательно (≥1 первоисточник) · 2 полное исследование · 3 (мед/юр/фин/спорное) глубокое, ≥2 источника, потому что там цена ошибки выше цены токенов. Ни один тир не пропускает обогащение.\n' +
+ ' verified: подтверждён|источник-не-найден|непроверяемо-методом|облако-недоступно.\n' +
+ 'Стадия 3.5 АТОМИЗАЦИЯ — обязательна для смешанных гайдов/транскриптов/лонгридов:\n' +
+ ' Если в материале несколько независимых тем, верни atoms[] и не делай одну обзорную ноту — обзорная нота смешанного источника не находится ни по одной из тем. Один источник может породить 2-20 атомов.\n' +
+ ' Каждый atom: stable atom_id, topic, section, target_note_hint, source_anchor, confidence, note_md. Классифицируй каждый atom отдельно по _ROUTING.md.\n' +
+ ' Если atom дополняет существующую ноту — в note_md дай managed block MNEMOZINA_ATOM_START/END со stable-id; Store обязан слить, а не плодить дубль.\n' +
+ ' Не дроби механически каждый заголовок: дроби только при смене смысла/проекта/раздела.\n' +
+ 'Стадия 4 Классификация: читай _ROUTING.md в корне vault (нет там — 99 Система/_ROUTING.md), выбери уверенный раздел.\n' +
+ (embedReady
+ ? 'Стадия 4.5 Семантический дедуп — до записи, потому что дубль в vault дороже ловить после: прогони извлечённый текст:\n' +
+ ' ' + EMBED_PY + ' "' + EMBED_SC + '" query "' + EMBED_IDX + '" "<первые ~400 симв сути>" 3 ' + DUP_THRESHOLD + '\n' +
+ ' matches непустой (top≥' + DUP_THRESHOLD + ') → прочитай совпавшую ноту. Та же суть → outcome="dup", note_path=совпавшая, новую не создавай — дубль размывает поиск и графовые связи. Разное → пиши.\n'
+ : '') +
+ 'Стадия 5 Огранка: читай _ШАБЛОНЫ.md + _ПРОЕКТЫ.md. Нота — полное знание-досье, а не подпись к скрину и не краткая справка. Исходник — seed; финал расширяет тему максимально полезно. Порядок блоков фиксирован по NOTE-SPEC, потому что агент режет чтение сверху: «Короткий ответ» (первым, 2-4 самодостаточных предложения — прочитавший только его уже может действовать) → «Механика» → «Применение» (команды/шаги/шаблон/конфиг) → «Примеры и контрпримеры» → «Ошибки и границы» → «Опыт практиков» (только с URL тредов/issues) → «🎯 Как это поможет мне» (по именам проектов из _ПРОЕКТЫ.md) → «Достоверность» (каждая строка самодостаточна: кто/когда/версия/URL; внутри подраздел «Рассмотрено и отклонено» — что проверялось и почему исключено) → «Связанные темы» (типизированные связи текстом: расширяет [[X]] · противоречит [[Y]] · предшествует [[Z]] · инструмент-для [[W]]) → «Следующий ход» (конкретное действие, не «изучить глубже»). Если тема типа «принцип Парето» — раскрыть не только 80/20, а происхождение, математику/power-law связь, бизнес-примеры, где правило НЕ работает, типичные ошибки применения, чек-лист использования и связанные концепции. Атом (тонкая нота) законен: блоки «Примеры и контрпримеры»/«Ошибки и границы»/«Опыт практиков» могут отсутствовать, но «Короткий ответ», «🎯 Как это поможет мне» и «Достоверность» обязательны всегда — без них нота не находится и не проходит ре-верификацию claim↔источник.\n\n' +
+ 'Запиши ноту через Write (незаписанная нота = дыра покрытия и дорогой ретрай-раунд) в ' + VAULT + '/<раздел>/<дата> — <русский Заголовок>.md. Frontmatter по NOTE-SPEC: `type: <по содержанию: tool-card (инструмент/репо — тогда ещё repo/stars/license/risk) | concept | synthesis | decision | reference>`, `verified: <подтверждён | источник-не-найден | непроверяемо-методом | облако-недоступно>`, `source: local-media:' + String(hashOf[unit.files[0]] || '').slice(0, 16) + '`, `source_hash: ' + (hashOf[unit.files[0]] || '') + '`, `run_id: ' + RUN_ID + '`, `processor_model: codex-enriched`, `workflow: mnemosyne-mnemazina-pipeline`, `verification_status: verified-with-public-sources`, `status: final`.\n' +
+ 'Также добавь во frontmatter YAML-блок `sources:` с двумя строками на каждый исходник группы — basename и local-media-ref: сверщик (mnemazina-reconciler) считает покрытие грепом basename по `source:`/`sources:`, а local-media:hash нужен для ре-верификации claim↔источник и hash-cache; нота без basename в `sources:` уйдёт в ретрай как провенанс-дыра:\nsources:\n' + unit.files.map(function (uf) { return ' - ' + base(uf) + '\n - local-media:' + String(hashOf[uf] || '').slice(0, 16) }).join('\n') + '\n' +
+ 'Материал — заявка `agent-research----.md` (боковая дверь агента) → frontmatter дополнительно: `type: agent-research`, `project: `, `agent: <кто заявил — из тела заявки; не указан → project>`, `claim_status: provisional`, потому что по NOTE-SPEC агентское знание рождается провизорным и смешивается с проверенным корпусом только операцией graduate.\n' +
+ 'Дубль существующей ноты → outcome="dup", note_path=путь. Смешанный материал → outcome="atoms" и заполненный atoms[]. Шум/нечитаемо → outcome="noise"/"unreadable". Видео с транскриптом → обрабатывается как текст ("note" или "atoms"); видео без речи → "noise"; транскрипт не получен → "deferred". Все эти исходы штатные, не ошибки — честный "noise"/"deferred" лучше выдуманной ноты. Иначе "note".\n\n' +
+ 'Верни JSON: { "group_id", "files": ' + JSON.stringify(unit.files) + ', "outcome", "section", "filename", ' +
+ '"verified", "helps", "next_action", "new_section_candidate", "install_suggestion", "note_md", "atoms": [{ "atom_id", "topic", "section", "target_note_hint", "source_anchor", "confidence", "note_md" }] }'
+}
+const processSchema = { type: 'object', properties: {
+ group_id: { type: 'string' }, files: { type: 'array', items: { type: 'string' } },
+ outcome: { type: 'string' }, section: { type: 'string' }, filename: { type: 'string' },
+ verified: { type: 'string' }, helps: { type: 'string' }, next_action: { type: 'string' },
+ new_section_candidate: { type: 'boolean' }, install_suggestion: { type: ['string', 'null'] }, note_md: { type: 'string' },
+ atoms: { type: 'array', items: { type: 'object', properties: {
+ atom_id: { type: 'string' }, topic: { type: 'string' }, section: { type: 'string' },
+ target_note_hint: { type: 'string' }, source_anchor: { type: 'string' },
+ confidence: { type: 'string' }, note_md: { type: 'string' }
+ }, required: ['atom_id', 'topic', 'section', 'note_md'] } }
+}, required: ['group_id', 'outcome'] }
+
+let processResults = (await parallel(tieredUnits.map(function (unit) {
+ return function () {
+ return agent(processorPrompt(unit), {
+ label: 'proc-' + unit.group_id, phase: 'Process', agentType: 'mnemazina-processor', model: modelForRole('proc', unit.tier), schema: processSchema
+ })
+ }
+}))).filter(Boolean)
+log('Процессоры вернули ' + processResults.length + '/' + tieredUnits.length)
+
+const processClassified = []
+processResults.forEach(function (r) {
+ if (!r || !Array.isArray(r.files)) return
+ if (['dup', 'noise', 'unreadable', 'deferred'].indexOf(r.outcome) === -1) return
+ r.files.forEach(function (f) { processClassified.push({ file: f, reason: r.outcome, group_id: r.group_id }) })
+})
+const classifiedForReconcile = classified.concat(processClassified)
+
+// ---------- STORE (запись + индексы, БЕЗ архивации) ----------
+phase('Store')
+const storeResult = await agent(
+ 'Ты — mnemazina-librarian (Калачов) в режиме STORE-ONLY. Не архивируй и не перемещай исходники: архивация — отдельная фаза после сверки покрытия, преждевременный mv лишит сверщика наземной правды.\n\n' +
+ 'VAULT: ' + VAULT + '\nBATCH: ' + JSON.stringify(processResults.map(function (r) {
+ return { group_id: r.group_id, outcome: r.outcome, section: r.section, filename: r.filename, note_md: r.note_md, atoms: r.atoms || [] }
+ })) + '\n\n' +
+ 'Для outcome="note": grep дубли в разделе; запиши .md (frontmatter с source: сохрани — по нему сверщик находит покрытие файла); wikilinks.\n' +
+ 'Для outcome="atoms": обрабатывай каждый atom отдельно, потому что атомы уходят в разные ноты и разделы. Если target_note_hint/grep показывает существующую ноту — вставь/обнови managed block ` ... `; если подходящей ноты нет — создай отдельную ноту atom.section/atom.target_note_hint. Не плодить обзорную ноту смешанного источника.\n' +
+ 'Стадия 7 (батчем): обнови _Содержание.md, _МАСТЕР-ИНДЕКС.md (пересчёт), _ROUTING.md, Лог обработки.md.\n' +
+ 'Не делай mv и не запускай graphify — это отдельные финальные фазы конвейера, их запуск отсюда задвоит работу. Верни JSON: { "stored": ["путь"], "merged": [], "new_sections": [], "errors": [] }',
+ {
+ label: 'store', phase: 'Store', agentType: 'mnemazina-librarian', model: modelForRole('store'),
+ schema: { type: 'object', properties: {
+ stored: { type: 'array', items: { type: 'string' } }, merged: { type: 'array', items: { type: 'string' } },
+ new_sections: { type: 'array', items: { type: 'string' } }, graph_updated: { type: 'boolean' },
+ needs_graphify_init: { type: 'boolean' }, errors: { type: 'array', items: { type: 'string' } }
+ }, required: ['stored'] }
+ }
+)
+
+// ========== ГЕЙТ КАЧЕСТВА НОТ (NOTE-SPEC): после Store, до Reconcile ==========
+// Провал ноты = её источники уходят в дыры ретрая (та же механика, что провенанс-дыры), не в раздел:
+// пожелание шаблона исполняется вероятностно, а код-гейт всегда (docs/NOTE-SPEC.md проекта mnemazine).
+const storedNotes = (storeResult && storeResult.stored) ? storeResult.stored : []
+const gateSince = NOW || runDate || ''
+let qualityFailedFiles = []
+if (storedNotes.length > 0) {
+ const qualityRun = childProcess.spawnSync(process.execPath, [
+ 'scripts/mnemazine-vault-quality-gate.mjs',
+ '--spec',
+ '--json',
+ ...(gateSince ? ['--changed-since', gateSince] : [])
+ ], { cwd: REPO_ROOT, encoding: 'utf8' })
+ const qualityGate = (function () {
+ const raw = String(qualityRun.stdout || qualityRun.stderr || '').trim()
+ const start = raw.indexOf('{')
+ const end = raw.lastIndexOf('}')
+ if (start === -1 || end < start) return { ok: false, failures: [] }
+ try { return JSON.parse(raw.slice(start, end + 1)) } catch (e) { return { ok: false, failures: [] } }
+ })()
+ const failedRel = ((qualityGate && qualityGate.failures) || []).map(function (x) { return String((x && x.file) || '') }).filter(Boolean)
+ // --changed-since меряет mtime по всему vault → сужаем до нот ЭТОГО прогона: чужие провалы — не наши дыры
+ const failedNotes = storedNotes.filter(function (p) {
+ return failedRel.some(function (rel) { return String(p).indexOf(rel) !== -1 || base(p) === base(rel) })
+ })
+ if (failedNotes.length > 0) {
+ processResults.forEach(function (r) {
+ if (!r || r.outcome !== 'note' || !Array.isArray(r.files) || !r.filename) return
+ const hit = failedNotes.some(function (p) { return String(p).indexOf(r.filename) !== -1 || base(p) === base(r.filename) })
+ if (hit) r.files.forEach(function (f) { if (qualityFailedFiles.indexOf(f) === -1) qualityFailedFiles.push(f) })
+ })
+ log('⚠ ГЕЙТ КАЧЕСТВА: ' + failedNotes.length + ' нот провалили NOTE-SPEC → ' + qualityFailedFiles.length + ' источников в ретрай')
+ } else {
+ log('## КАЧЕСТВО НОТ ✓ — свежезаписанные прошли NOTE-SPEC')
+ }
+}
+
+// ========== ГЕЙТ 2: ПОКРЫТИЕ ПОЛНОЕ (сверщик + ретрай) ==========
+phase('Reconcile')
+const reconcilePrompt = function () {
+ return 'MODE: RECONCILE\n' + JSON.stringify({ census_files: inboxFiles, vault: VAULT, classified: classifiedForReconcile, run_date: runDate })
+}
+let recon = await agent(reconcilePrompt(), {
+ label: 'reconcile', phase: 'Reconcile', agentType: 'mnemazina-reconciler', model: modelForRole('reconcile'),
+ schema: { type: 'object', properties: {
+ census_count: { type: 'number' },
+ ledger: { type: 'object', properties: {
+ noted: { type: 'number' }, dup: { type: 'number' }, noise: { type: 'number' },
+ unreadable: { type: 'number' }, deferred: { type: 'number' }, unaccounted: { type: 'number' } } },
+ unaccounted: { type: 'array', items: { type: 'string' } },
+ balanced: { type: 'boolean' }, verdict: { type: 'string' }, marker: { type: 'string' }
+ }, required: ['unaccounted', 'verdict'] }
+})
+// КОД ПОВЕРХ СУЖДЕНИЯ (2026-07-25, измерено). Прогон kb-20260725201732 закрылся маркером «ПОКРЫТИЕ
+// ПОЛНОЕ ✓» с unaccounted=0, тогда как на диске файл tmpImage_8B654E2A-….JPG не имел ни ноты, ни
+// сайдкара, ни записи причины — и при этом прекрасно читался Apple Vision. Сверщик — LLM, которая сама
+// грепает и сама выносит вердикт по своему грепу (в том же прогоне она чинила собственный баг грепа
+// по ходу проверки). Подсчёт покрытия — не суждение, а греп, значит его место в коде с кодом возврата.
+// Список дыр берём из скрипта; LLM-сверщик остаётся для КЛАССИФИКАЦИИ причины, но перекрыть код не может.
+async function codeCoverageGate(tag) {
+ const r = childProcess.spawnSync(process.execPath, [
+ 'scripts/mnemazine-coverage-check.mjs',
+ '--json',
+ '--vault', VAULT,
+ '--inbox', INBOX
+ ], { cwd: REPO_ROOT, encoding: 'utf8' })
+ let parsed = null
+ try { parsed = JSON.parse(String(r.stdout || '').trim()) } catch (e) {}
+ if (r.status === 0 && parsed && Array.isArray(parsed.uncovered)) return []
+ if (r.status === 1 && parsed && Array.isArray(parsed.uncovered)) return parsed.uncovered
+ log('⚠ КОД-ГЕЙТ coverage-check сломан на проходе ' + tag + ': exit=' + r.status + ' stderr=' + String(r.stderr || '').slice(0, 300))
+ return ['__coverage_check_failed__']
+}
+// Объединение, а не замена: код ловит «ноты нет вообще», сверщик — «нота есть, но не та». Дыра, которую
+// назвал код и не назвала LLM, — ровно тот случай, ради которого этот гейт и появился.
+function mergeCodeGaps(list, codeGaps) {
+ codeGaps.forEach(function (f) {
+ if (list.indexOf(f) === -1) {
+ log('⚠ КОД-ГЕЙТ нашёл дыру, которую сверщик не назвал: ' + base(f))
+ list.push(f)
+ }
+ })
+ return list
+}
+let unaccounted = mergeCodeGaps((recon && recon.unaccounted) ? recon.unaccounted : [], await codeCoverageGate('1'))
+// Провал гейта качества — дыра ретрая даже при полном покрытии: нота есть, но браковая.
+qualityFailedFiles.forEach(function (f) { if (unaccounted.indexOf(f) === -1) unaccounted.push(f) })
+
+if (unaccounted.length > 0) {
+ // Раздели дыры: ПРОВЕНАНС-дыра (файл из юнита, чья группа УЖЕ дала ноту — нота просто не перечислила его в sources:)
+ // vs НАСТОЯЩАЯ дыра-знание (группа ноты не дала). Провенанс чиним дёшево патчем frontmatter; настоящую — Sonnet-ресёрчем.
+ // Quality-провал имеет ноту, но браковую — sources-патч её не чинит, поэтому он всегда настоящая дыра.
+ const notePathByFile = {}
+ tieredUnits.forEach(function (u) {
+ const res = processResults.find(function (r) { return r && r.group_id === u.group_id && r.outcome === 'note' })
+ if (res) (u.files || []).forEach(function (uf) { notePathByFile[base(uf)] = res.note_md || res.filename || '' })
+ })
+ const provenanceGaps = unaccounted.filter(function (f) { return notePathByFile[base(f)] && qualityFailedFiles.indexOf(f) === -1 })
+ const realGaps = unaccounted.filter(function (f) { return !notePathByFile[base(f)] || qualityFailedFiles.indexOf(f) !== -1 })
+ if (provenanceGaps.length > 0) {
+ log('ГЕЙТ 2: ' + provenanceGaps.length + ' провенанс-дыр (группа дала ноту, sources: неполон) → дешёвый патч frontmatter (haiku), БЕЗ ре-ресёрча')
+ await agent(
+ 'Чистая механика, БЕЗ ресёрча и без новых нот. Для каждой пары {file → note} добавь basename файла в frontmatter-блок `sources:` указанной ноты (создай поле `sources:` списком « - », если его ещё нет; не дублируй строки). Этим файл считается покрытым — он уже отражён в этой ноте.\nПАРЫ:\n' + provenanceGaps.map(function (f) { return base(f) + ' → ' + (notePathByFile[base(f)] || '') }).join('\n') + '\nВерни { "patched": N }.',
+ { label: 'patch-sources', phase: 'Reconcile', agentType: 'mnemazina-librarian', model: 'haiku',
+ schema: { type: 'object', properties: { patched: { type: 'number' } } } }
+ )
+ }
+ if (realGaps.length > 0) {
+ log('⚠ ГЕЙТ 2: ' + realGaps.length + ' настоящих дыр (нет ноты или брак NOTE-SPEC) → ретрай-раунд (Sonnet)')
+ await parallel(realGaps.map(function (f) {
+ return function () {
+ const sourceHash = hashOf[f] || ''
+ const sourceRef = sourceHash ? ('local-media:' + String(sourceHash).slice(0, 16)) : base(f)
+ return agent(
+ 'Восстанови ОДНО дропнутое знание. Источник: ' + f + '\n' +
+ 'Скрин/картинка → OCR локально: `"' + OCR_BIN + '" "' + f + '"` (Apple Vision, 0 токенов). Пусто/мусор → Read(vision) — в ретрае это допустимый последний шанс. Не ollama/llava: галлюцинирует.\n' +
+ 'Извлеки контент (это вход-семя, не тело ноты), исследуй первоисточник (WebSearch → чтение URL через kb-fetch; kb-search как фолбэк поиска) и собери максимум по теме, классифицируй (читай ' + VAULT + '/_ROUTING.md — реестр лежит в корне vault), ' +
+ 'запиши ноту через Write в ' + VAULT + '/<раздел>/' + (runDate || '2026-01-01') + ' — <Заголовок>.md ' +
+ 'с обязательным `source: ' + sourceRef + '`' + (sourceHash ? ', `source_hash: ' + sourceHash + '`' : '') + ', `sources: ["' + base(f) + '"' + (sourceHash ? ', "' + sourceRef + '"' : '') + ']` (basename обязателен — сверщик считает покрытие грепом basename) + блоком «Как помогает мне». Нота этого источника уже существует, но провалила гейт NOTE-SPEC → перепиши её по NOTE-SPEC тем же путём, вторую не плоди. Видео/аудио → локальная транскрипция whisper (0 токенов) или deferred — это штатный исход, не ошибка. ' +
+ 'Финальный ответ — только путь записанной ноты.',
+ { label: 'retry-' + base(f), phase: 'Reconcile', model: 'sonnet' }
+ )
+ }
+ }))
+ }
+ recon = await agent(reconcilePrompt(), {
+ label: 'reconcile-2', phase: 'Reconcile', agentType: 'mnemazina-reconciler', model: modelForRole('reconcile-2'),
+ schema: { type: 'object', properties: {
+ census_count: { type: 'number' }, ledger: { type: 'object' },
+ unaccounted: { type: 'array', items: { type: 'string' } },
+ balanced: { type: 'boolean' }, verdict: { type: 'string' }
+ }, required: ['unaccounted', 'verdict'] }
+ })
+ // Код-гейт ЗАНОВО: без этого второй вердикт сверщика молча затирал список дыр, найденный кодом,
+ // и прогон закрывался «ПОКРЫТИЕ ПОЛНОЕ ✓» ровно с той дырой, ради которой гейт и ставился.
+ unaccounted = mergeCodeGaps((recon && recon.unaccounted) ? recon.unaccounted : [], await codeCoverageGate('2'))
+}
+const coverageFull = unaccounted.length === 0
+log(coverageFull ? '## ПОКРЫТИЕ ПОЛНОЕ ✓' : '## ПОКРЫТИЕ НЕПОЛНОЕ ✗ — ' + unaccounted.length + ' дыр остаются в инбоксе')
+
+// ========== ГЕЙТ 3: АРХИВ + запись hash-кэша ==========
+phase('Archive')
+// архивируем учтённые новые + cached (они уже обработаны ранее)
+const accountedNew = inboxFiles.filter(function (f) { return unaccounted.indexOf(f) === -1 })
+const toArchive = accountedNew.concat(cachedFiles)
+// archiveVerified остаётся null, когда архивировать нечего, и числом — когда мера была снята.
+let archiveVerified = null
+if (toArchive.length > 0) {
+ await agent(
+ 'Ты — mnemazina-librarian, ГЕЙТ-3. Перемести (mv) ТОЛЬКО эти учтённые исходники в архив ' + archiveDir + ':\n' +
+ toArchive.join('\n') + '\n\nФайлы НЕ из списка — НЕ трогай: файл вне списка — непокрытая дыра, и mv спрятал бы её от следующего прогона. mkdir -p "' + archiveDir + '"; mv каждый. Верни { "archived": N }.',
+ { label: 'archive', phase: 'Archive', agentType: 'mnemazina-librarian', model: 'haiku',
+ schema: { type: 'object', properties: { archived: { type: 'number' } } } }
+ )
+ // ЗАМЕР, а не отчёт (2026-07-25): прогон вернул archived=73 и маркер «АРХИВ РАЗРЕШЁН ✓», тогда как в
+ // инбоксе осталось 72 из 73 файлов — маркер был литералом в коде, а число пришло от агента о самом себе.
+ // Считаем то, что реально осталось лежать: сколько из toArchive ещё в инбоксе.
+ archiveVerified = fsMod.readdirSync(INBOX, { withFileTypes: true })
+ .filter(function (entry) { return entry.isFile() && !entry.name.startsWith('.') })
+ .length
+ if (archiveVerified !== null && archiveVerified > unaccounted.length + 6) {
+ log('⚠ ГЕЙТ 3: в инбоксе осталось ' + archiveVerified + ' записей при ' + unaccounted.length + ' дырах — архивация НЕ отработала, разбирать руками.')
+ }
+}
+// hash-cache: запиши хэши новых учтённых нот-файлов → следующий прогон их скипнет за 0 токенов
+const hashPayload = accountedNew.map(function (f) { return { hash: hashOf[f] || '', file: base(f) } }).filter(function (x) { return x.hash })
+if (hashPayload.length > 0) {
+ await agent(
+ 'Обнови hash-кэш ' + HASHDB + '. Прочитай его (JSON {hash:путь_ноты}; {} если нет). ' +
+ 'Для каждой записи найди ноту: grep -rl "" в ' + VAULT + ' --include=*.md (первый результат; basename ищется и в source:, и в списке sources:). ' +
+ 'Добавь {hash: путь_ноты}. Записи без найденной ноты пропусти. Запиши JSON обратно через Write. Данные:\n' +
+ JSON.stringify(hashPayload) + '\nВерни { "recorded": N }.',
+ { label: 'hash-record', phase: 'Archive', agentType: 'mnemazina-librarian', model: 'haiku',
+ schema: { type: 'object', properties: { recorded: { type: 'number' } } } }
+ )
+}
+// семантический индекс: дозаписать новые ноты (для будущего дедупа)
+if (embedReady && storeResult && storeResult.stored && storeResult.stored.length > 0) {
+ await agent(
+ 'Дозапиши новые ноты в семантический индекс. Выполни одной командой:\n' +
+ EMBED_PY + ' "' + EMBED_SC + '" add "' + EMBED_IDX + '" ' +
+ storeResult.stored.map(function (p) { return '"' + p + '"' }).join(' ') + '\nВерни { "indexed": N }.',
+ { label: 'embed-add', phase: 'Archive', model: 'haiku',
+ schema: { type: 'object', properties: { indexed: { type: 'number' } } } }
+ )
+}
+log('## АРХИВ — просили перенести ' + toArchive.length + ' (' + cachedFiles.length + ' cached), дыр ' + unaccounted.length +
+ (archiveVerified === null ? '' : ', в инбоксе осталось ' + archiveVerified + ' записей'))
+
+// ---------- GRAPHIFY (финал — ВСЕГДА, граф = память Мнемозины) ----------
+phase('Graphify')
+const vaultMdCount = countMarkdownFiles(VAULT)
+const graphRes = await agent(
+ 'Финал Мнемозины — обнови граф знаний (память системы). Выполни bash:\n' +
+ 'rm -rf "' + OCR_DIR + '" "' + TRANSCRIPT_DIR + '" 2>/dev/null; ' + // чистка осиротевших сайдкаров (источники уже в архиве)
+ 'cd "' + VAULT + '" && if [ -f graphify-out/graph.json ]; then graphify update "' + VAULT + '" 2>&1 | tail -3 && python3 "' + REPO_ROOT + '/scripts/graphify_clean.py" 2>&1 | tail -6 && echo RESULT:updated; ' +
+ 'else if [ ' + vaultMdCount + ' -gt 5 ]; then echo RESULT:needs_init; else echo RESULT:skip; fi; fi\n' +
+ 'Верни { "graph": "updated|needs_init|skip" } по строке RESULT.',
+ { label: 'graphify', phase: 'Graphify', model: 'haiku',
+ schema: { type: 'object', properties: { graph: { type: 'string' } } } }
+)
+log('## ГРАФ ОБНОВЛЁН ✓ — ' + ((graphRes && graphRes.graph) || 'skip') + ' (память Мнемозины, авточистка шаблонов)')
+
+// Обязательные код-шаги финала: core-индексы + --check гейт + lint catch-up 36ч (ночное расписание
+// могло не сработать — догоняем при ближайшем запуске). graphify не дублируем — прогнан агентом выше.
+const finalChecks = await agent(
+ 'Финал Мнемозины — обязательные код-шаги. Чистая механика, без правок нот. Выполни один bash без TTY и верни последнюю строку JSON:\n' +
+ 'cd "' + REPO_ROOT + '"\n' +
+ 'S="scripts"\n' +
+ 'node "$S/mnemazine-refresh-core-indexes.mjs" >/dev/null 2>&1\n' +
+ 'if node "$S/mnemazine-refresh-core-indexes.mjs" --check >/dev/null 2>&1; then IDX=ok; else IDX=fail; fi\n' +
+ 'L="' + VAULT + '/99 Система/_lint/.last-lint"\n' +
+ 'if [ ! -f "$S/mnemazine-kb-lint.mjs" ]; then LINT=missing\n' +
+ 'elif [ ! -f "$L" ] || [ -n "$(find "$L" -mmin +2160 2>/dev/null)" ]; then node "$S/mnemazine-kb-lint.mjs" >/dev/null 2>&1 && LINT=ran || LINT=lint_fail\n' +
+ 'else LINT=fresh; fi\n' +
+ 'printf \'{"indexes":"%s","lint":"%s"}\\n\' "$IDX" "$LINT"\n' +
+ 'LINT=missing — штатный случай (скрипт стоит не на каждой машине), не сбой. Верни JSON как есть: { "indexes": "ok|fail", "lint": "ran|fresh|missing|lint_fail" }.',
+ { label: 'final-code-steps', phase: 'Graphify', model: 'haiku',
+ schema: { type: 'object', properties: {
+ indexes: { type: 'string' }, lint: { type: 'string' }
+ }, required: ['indexes', 'lint'] } }
+)
+log('## КОД-ШАГИ ФИНАЛА — индексы: ' + ((finalChecks && finalChecks.indexes) || '?') + ', линт: ' + ((finalChecks && finalChecks.lint) || '?'))
+
+// ---------- РЕЗОЛВЕР MNEMOZINA/MNEMAZINE-ИНСТРУМЕНТОВ (Claude/Codex parity) ----------
+// Порядок: проект Mnemazine/scripts → $MNEMOZINA_REPO/scripts → ~/.codex/bin → ~/.claude/bin.
+const MZ_RESOLVE =
+ 'mz_run(){ n="$1"; shift; ' +
+ 'for c in "scripts/$n.mjs" "${MNEMOZINA_REPO:+$MNEMOZINA_REPO/scripts/$n.mjs}" "$HOME/.codex/bin/$n" "$HOME/.claude/bin/$n"; do ' +
+ '[ -n "$c" ] && [ -f "$c" ] || continue; ' +
+ 'case "$c" in *.mjs) node "$c" "$@";; *) "$c" "$@";; esac; return $?; ' +
+ 'done; echo "MZ_NOT_FOUND:$n" >&2; return 127; }; '
+
+// ---------- ВИЗУАЛЬНЫЙ POST-RUN ОТЧЁТ (Apple-light, Emil Kowalski design contract) ----------
+phase('VisualReport')
+const reportPayload = processResults.map(function (r) {
+ return {
+ group_id: r.group_id,
+ files: r.files || [],
+ outcome: r.outcome,
+ section: r.section || '',
+ filename: r.filename || '',
+ verified: r.verified || '',
+ helps: r.helps || '',
+ next_action: r.next_action || '',
+ note_md: (r.note_md && String(r.note_md).length < 500) ? r.note_md : '',
+ atoms: r.atoms || []
+ }
+})
+const visualReport = await agent(
+ 'Финал Мнемозины — создай светлый Apple-style визуальный отчёт знаний после прогона: схема кластеров → ноты → малые атомы, плюс топ-20 действий. ' +
+ 'Дизайн-контракт: Emil Kowalski, Apple-light, тихая типографика, 8px radius, без тяжёлых градиентов/теней, prefers-reduced-motion.\n' +
+ 'Выполни bash без TTY:\n' +
+ MZ_RESOLVE +
+ 'TMP="/tmp/mnemazine-postrun-' + RUN_ID + '.json"; cat > "$TMP" <<\\JSON\n' +
+ JSON.stringify({ processResults: reportPayload }) + '\nJSON\n' +
+ 'MNEMAZINE_ROOT="' + REPO_ROOT + '" MNEMAZINE_VAULT="' + VAULT + '" mz_run mnemazine-postrun-knowledge-report --run-id "' + RUN_ID + '" --results-json "$TMP" --title "Mnemazine post-run knowledge report"\n' +
+ 'Верни JSON из stdout как есть. MZ_NOT_FOUND — штатный случай (скрипт не установлен на этой машине), не сбой: верни {"ok":false,"error":"mnemazine-postrun-knowledge-report not found"}.\n',
+ { label: 'visual-report', phase: 'VisualReport', model: 'haiku',
+ schema: { type: 'object', properties: {
+ ok: { type: 'boolean' },
+ run_id: { type: 'string' },
+ groups: { type: 'number' },
+ records: { type: 'number' },
+ fresh: { type: 'number' },
+ duplicates: { type: 'number' },
+ md: { type: 'string' },
+ html: { type: 'string' },
+ error: { type: 'string' }
+ } } }
+)
+log('## ВИЗУАЛЬНЫЙ ОТЧЁТ ГОТОВ ✓ — ' + ((visualReport && visualReport.html) || 'не создан'))
+
+// ---------- БРИФИНГ ПРИМЕНИМОСТИ (финал после графа, local-first, 0 LLM-токенов) ----------
+// Общий слой для Claude и Codex: читает свежие ноты по run_id, ранжирует под проекты,
+// возвращает brief_md в финальный результат. Отдельный briefing-файл не пишем: пользователь взаимодействует с брифингом в чате.
+phase('Briefing')
+const briefing = await agent(
+ 'Финал Мнемозины — сделай локальный брифинг применимости без LLM-анализа контента. Выполни bash без TTY:\n' +
+ MZ_RESOLVE +
+ 'mz_run mnemozina-brief --run-id "' + RUN_ID + '" --limit 10\n' +
+ 'Верни JSON из stdout как есть. Поле brief_md обязательно: показать пользователю прямо в чат, не ссылкой на файл.\n' +
+ 'Пустой вывод или MZ_NOT_FOUND — штатный случай (скрипт стоит не на каждой машине), не сбой: верни {"brief_md":"(агрегат-брифинг недоступен; смотри visual_report.html)","notes":0,"top_now":[],"future_count":0}.',
+ { label: 'briefing', phase: 'Briefing', model: 'haiku',
+ schema: { type: 'object', properties: {
+ brief_path: { type: ['string', 'null'] },
+ brief_md: { type: 'string' },
+ notes: { type: 'number' },
+ top_now: { type: 'array', items: { type: 'object', properties: {
+ title: { type: 'string' }, path: { type: 'string' }, project: { type: 'string' },
+ step: { type: 'string' }, effect: { type: 'string' }, score: { type: 'number' }
+ } } },
+ future_count: { type: 'number' },
+ token_usage: { type: 'number' }
+ }, required: ['brief_md'] } }
+)
+log('## БРИФИНГ ГОТОВ ✓ — ' + ((briefing && briefing.top_now) ? briefing.top_now.length : 0) + ' к применению сейчас → вывести в чат')
+await observeRun('end')
+
+// ---------- AGENT TRACE + SELF-REFLECTION INPUTS ----------
+// Видимая трасса роя: какие named agents закрыли какие ворота. Это нужно пользователю и будущим агентам:
+// не "какой-то worker", а Мнемозина/Кирилов/Сопиков/... с результатом и артефактами.
+const ledger = (recon && recon.ledger) ? recon.ledger : {}
+const balanced = (recon && typeof recon.balanced === 'boolean') ? recon.balanced : null
+const agentTrace = [
+ { name: 'Мнемозина', file: 'mnemazina-coordinator', phase: 'Observe/Orchestrate/Graphify/Briefing/SelfReflection', status: 'ok', tools: ['Agent', 'Bash', 'abtop', 'Graphify', 'mnemozina-brief'], closed: ['run observability', 'graph', 'brief_md'] },
+ { name: 'Иван Кирилов', file: 'mnemazina-guard', phase: 'Guard+Census', status: guardResult && guardResult.error ? 'error' : 'ok', tools: ['git', 'find', 'shasum', 'hash-cache'], closed: ['snapshot', 'lock', 'census'] },
+ { name: 'Василий Сопиков', file: 'mnemazina-triage/mnemazina-classify', phase: 'Triage/Classify', status: missing.length ? 'repaired' : 'ok', tools: ['Read', 'Grep', 'OCR sidecars', '_ROUTING.md'], closed: ['manifest'], note: missing.length ? ('ГЕЙТ-1 форсировал ' + missing.length + ' пропусков') : '' },
+ { name: 'Михаил Ломоносов', file: 'mnemazina-processor/mnemazina-extract/mnemazina-verify/mnemazina-refine', phase: 'Process', status: processResults.length === tieredUnits.length ? 'ok' : 'partial', tools: ['Apple Vision OCR', 'whisper sidecars', 'markitdown', 'kb-fetch/kb-search', 'GitHub API', 'fastembed'], closed: ['notes', 'source/sources'] },
+ { name: 'Николай Калачов', file: 'mnemazina-librarian/mnemazina-distribute/mnemazina-index/mnemazina-fix', phase: 'Store/Archive/FIND', status: 'ok', tools: ['Write', 'Edit', 'mv', 'kb-embed', 'indexes'], closed: ['store', 'indexes', 'archive'] },
+ { name: 'Дмитрий Менделеев', file: 'mnemazina-reconciler', phase: 'Reconcile', status: coverageFull && balanced !== false ? 'ok' : 'gaps', tools: ['grep source:', 'sources:', 'ledger'], closed: [coverageFull ? 'coverage full' : 'coverage gaps'] },
+]
+
+// ---------- TOKEN USAGE (финал — ВСЕГДА после observeRun end) ----------
+const tokenUsage = await agent(
+ 'Финал Мнемозины — посчитай токены этого run_id по Run Observatory.\n' +
+ 'RUN_ID=' + RUN_ID + '\nOBS_LOG=' + OBS_LOG + '\n\n' +
+ 'Выполни bash/python без TTY: прочитай JSONL, возьми строки с этим run_id. ' +
+ 'Из поля tokens попробуй извлечь число токенов start/end и delta=end-start. ' +
+ 'Пустые tokens или abtop_unavailable — штатный случай (abtop стоит не на каждой машине), не сбой: верни null в числовых полях и пояснение в note. Ничего не меняй на диске.\n' +
+ 'Верни JSON: { "runtime":"claude-workflow", "source":"abtop", "observability_log":"' + OBS_LOG + '", ' +
+ '"start_tokens": number|null, "end_tokens": number|null, "delta_tokens": number|null, "samples": number, "note": string }',
+ { label: 'token-usage', phase: 'TokenUsage', model: 'haiku',
+ schema: { type: 'object', properties: {
+ runtime: { type: 'string' },
+ source: { type: 'string' },
+ observability_log: { type: 'string' },
+ start_tokens: { type: ['number', 'null'] },
+ end_tokens: { type: ['number', 'null'] },
+ delta_tokens: { type: ['number', 'null'] },
+ samples: { type: 'number' },
+ note: { type: 'string' }
+ }, required: ['runtime', 'source', 'observability_log', 'samples', 'note'] } }
+)
+phase('SessionReview')
+const sessionReview = await agent(
+ 'Финал Мнемозины — локальный анализ расхода токенов, local-first audit и ledger ошибок. Выполни bash без TTY:\n' +
+ MZ_RESOLVE +
+ 'mz_run mnemozina-session-review ' +
+ '--run-id "' + RUN_ID + '" --runtime "claude-workflow" ' +
+ '--token-json ' + JSON.stringify(JSON.stringify(tokenUsage)) + ' ' +
+ '--result-json ' + JSON.stringify(JSON.stringify({
+ run_id: RUN_ID,
+ status: coverageFull ? 'done' : 'done_with_gaps',
+ balanced: balanced,
+ unaccounted: unaccounted,
+ graph_updated: !!(graphRes && graphRes.graph === 'updated'),
+ briefing: briefing,
+ agent_trace: agentTrace,
+ gates: {
+ manifest: '## МАНИФЕСТ ПОЛНЫЙ ✓',
+ coverage: coverageFull ? '## ПОКРЫТИЕ ПОЛНОЕ ✓' : '## ПОКРЫТИЕ НЕПОЛНОЕ ✗',
+ archive: archiveVerified === null ? '## АРХИВ: нечего переносить' : '## АРХИВ: в инбоксе осталось ' + archiveVerified + ' записей'
+ }
+ })) + '\n' +
+ 'Верни JSON из stdout как есть. Пустой вывод или MZ_NOT_FOUND — штатный случай (скрипт не установлен на этой машине), не сбой: верни {"review_path":"","ledger_path":"","errors":["mnemozina-session-review не найден на этой машине"]}.',
+ { label: 'session-review', phase: 'SessionReview', model: 'haiku',
+ schema: { type: 'object', properties: {
+ review_path: { type: 'string' },
+ ledger_path: { type: 'string' },
+ token_summary: { type: 'object' },
+ audit: { type: 'object' },
+ self_reflection: { type: 'object' },
+ errors: { type: 'array', items: { type: 'string' } }
+ }, required: ['review_path', 'ledger_path'] } }
+)
+await releaseRunLock('done')
+
+// ---------- ЛЕДЖЕР ----------
+const installSuggestions = processResults
+ .filter(function (r) { return r && r.install_suggestion }).map(function (r) { return r.install_suggestion })
+
+return {
+ status: coverageFull ? 'done' : 'done_with_gaps',
+ run_id: RUN_ID,
+ census: allCensus.length,
+ new_processed: inboxFiles.length,
+ cached: cachedFiles.length,
+ ledger: ledger,
+ balanced: balanced,
+ archived: toArchive.length,
+ unaccounted: unaccounted,
+ new_sections: (storeResult && storeResult.new_sections) ? storeResult.new_sections : [],
+ graph_updated: !!(graphRes && graphRes.graph === 'updated'),
+ final_code_steps: finalChecks,
+ quality_gate_failed_sources: qualityFailedFiles,
+ observability_log: OBS_LOG,
+ token_usage: tokenUsage,
+ agent_trace: agentTrace,
+ session_review: sessionReview,
+ visual_report: visualReport,
+ self_reflection: sessionReview && sessionReview.self_reflection ? sessionReview.self_reflection : null,
+ dag_file: DAG_FILE,
+ needs_graphify_init: !!(graphRes && graphRes.graph === 'needs_init'),
+ ocr_engine: 'Apple Vision (vision-ocr, локально)',
+ semantic_dedup: embedReady ? 'on (fastembed, порог ' + DUP_THRESHOLD + ')' : 'off',
+ install_suggestions: installSuggestions,
+ gates: {
+ manifest: '## МАНИФЕСТ ПОЛНЫЙ ✓',
+ coverage: coverageFull ? '## ПОКРЫТИЕ ПОЛНОЕ ✓' : '## ПОКРЫТИЕ НЕПОЛНОЕ ✗',
+ archive: archiveVerified === null ? '## АРХИВ: нечего переносить' : '## АРХИВ: в инбоксе осталось ' + archiveVerified + ' записей'
+ },
+ notes: processResults.filter(function (r) { return r && r.outcome === 'note' }).map(function (r) {
+ return { title: r.filename, section: r.section, verified: r.verified, helps: r.helps, next_action: r.next_action }
+ }),
+ briefing: briefing
+}