Complete Mnemazine intake gate

This commit is contained in:
Зарубин Филипп
2026-06-18 23:14:29 +03:00
parent 73cbc0d30c
commit e2dd73c98a
12 changed files with 289 additions and 42 deletions
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import { existsSync } from 'node:fs'
import path from 'node:path'
import { spawn } from 'node:child_process'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')
const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
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 NEEDS_UPDATE_MAX_DAYS = Number(arg('needs-update-max-days', process.env.MNEMAZINE_NEEDS_UPDATE_MAX_DAYS || '1'))
const STRICT_GRAPH = argv.includes('--strict-graph')
function run(command, args) {
return new Promise(resolve => {
const child = spawn(command, args, { cwd: ROOT, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] })
let stdout = ''
let stderr = ''
child.stdout.on('data', chunk => { stdout += String(chunk) })
child.stderr.on('data', chunk => { stderr += String(chunk) })
child.on('close', code => resolve({ ok: code === 0, code: code ?? 1, stdout: stdout.trim(), stderr: stderr.trim() }))
child.on('error', error => resolve({ ok: false, code: 1, stdout, stderr: `${stderr}\n${error.message}`.trim() }))
})
}
async function newestFileMtime(dir, filter = () => true) {
let newest = 0
async function walk(folder) {
for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) {
if (item.name.startsWith('graphify-out')) continue
const file = path.join(folder, item.name)
if (item.isDirectory()) await walk(file)
else if (item.isFile() && filter(file)) newest = Math.max(newest, (await fs.stat(file)).mtimeMs)
}
}
await walk(dir)
return newest
}
async function latestReport() {
const reports = []
for (const item of await fs.readdir(REPORTS, { withFileTypes: true }).catch(() => [])) {
if (!item.isFile() || !item.name.endsWith('.html')) continue
const file = path.join(REPORTS, item.name)
reports.push({ file, mtimeMs: (await fs.stat(file)).mtimeMs })
}
return reports.sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.file || ''
}
async function main() {
const failures = []
const warnings = []
const inboxFiles = (await fs.readdir(INBOX).catch(() => [])).filter(name => !name.startsWith('.'))
if (inboxFiles.length) failures.push(`inbox not empty: ${inboxFiles.length}`)
const quality = await run(process.execPath, ['scripts/mnemazine-vault-quality-gate.mjs'])
if (!quality.ok) failures.push(`vault quality failed: ${quality.stderr || quality.stdout}`)
const report = await latestReport()
if (!report) failures.push('weekly report missing')
else {
const reportQuality = await run(process.execPath, ['scripts/mnemazine-report-quality-gate.mjs', '--report', report])
if (!reportQuality.ok) failures.push(`report quality failed: ${reportQuality.stderr || reportQuality.stdout}`)
}
const newestNote = await newestFileMtime(VAULT, file => file.endsWith('.md'))
const reportMtime = report ? (await fs.stat(report)).mtimeMs : 0
if (newestNote && reportMtime && reportMtime < newestNote) failures.push('weekly report older than newest vault note')
const brief = path.join(STATE, 'last-action-brief.md')
if (!existsSync(brief)) failures.push('action brief missing')
else if ((await fs.stat(brief)).mtimeMs < newestNote) failures.push('action brief older than newest vault note')
const needsUpdate = path.join(VAULT, 'graphify-out', 'needs_update')
if (existsSync(needsUpdate)) {
const ageDays = (Date.now() - (await fs.stat(needsUpdate)).mtimeMs) / 86400000
const msg = `semantic graph pending (${ageDays.toFixed(2)} days)`
if (STRICT_GRAPH || ageDays > NEEDS_UPDATE_MAX_DAYS) failures.push(msg)
else warnings.push(msg)
}
const result = {
ok: failures.length === 0,
failures,
warnings,
inbox: inboxFiles.length,
report: report ? path.relative(ROOT, report) : null,
brief: existsSync(brief) ? path.relative(ROOT, brief) : null
}
console.log(JSON.stringify(result, null, 2))
if (!result.ok) process.exit(1)
}
main().catch(error => {
console.error(error.message || error)
process.exit(1)
})
+36 -27
View File
@@ -20,7 +20,6 @@ function arg(name, fb = '') {
}
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')))
const GRAPH = path.resolve(arg('graph', path.join(VAULT, 'graphify-out/graph.json')))
const SESSION = arg('session', new Date().toISOString().slice(0, 10))
const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || 'claude')
const FORCE = argv.includes('--force')
@@ -64,32 +63,33 @@ ${conns}
${fenceUntrusted('ЗАМЕТКА', noteText.slice(0, 12000))}`
}
// Map each note (vault-relative path) to neighbor labels from the Graphify graph.
// Map each note (vault-relative path) to related notes (also vault-relative paths).
// ponytail: derive note↔note links from note metadata, not the Graphify code-graph —
// `graphify update` emits only intra-note structural edges (contains), never
// note-to-note semantic links (those need the separate `graphify --update` pass with a
// model key). Same cluster_id = sibling atoms from one source; shared source-URL host =
// topically related. Cheap, deterministic, no extra deps. Cap at 6, siblings first.
const MAX_CONNECTIONS = 6
async function loadConnections() {
const byNote = new Map()
let graph
try { graph = JSON.parse(await fs.readFile(GRAPH, 'utf8')) } catch { return byNote }
const edgeKey = Array.isArray(graph.links) ? 'links' : Array.isArray(graph.edges) ? 'edges' : 'links'
const labelById = new Map()
const fileById = new Map()
for (const n of graph.nodes || []) {
if (!n || !n.id) continue
labelById.set(n.id, n.label || n.norm_label || n.id)
if (n.source_file) fileById.set(n.id, n.source_file)
const notes = [] // { rel, cluster, hosts:Set }
for (const file of await walk(VAULT)) {
const text = await fs.readFile(file, 'utf8').catch(() => '')
if (!text) continue
const cluster = text.match(/^cluster_id:\s*"?([^"\n]+)"?/m)?.[1]?.trim() || null
const hosts = new Set()
for (const m of text.matchAll(/https?:\/\/([^/\s)]+)/g)) hosts.add(m[1].replace(/^www\./, ''))
notes.push({ rel: path.relative(VAULT, file), cluster, hosts })
}
const neighbors = new Map() // id -> Set(label)
for (const e of graph[edgeKey] || []) {
if (!e || e.source == null || e.target == null) continue
for (const [a, b] of [[e.source, e.target], [e.target, e.source]]) {
if (!neighbors.has(a)) neighbors.set(a, new Set())
const lbl = labelById.get(b)
if (lbl) neighbors.get(a).add(lbl)
for (const a of notes) {
const siblings = [], related = []
for (const b of notes) {
if (b.rel === a.rel) continue
if (a.cluster && b.cluster === a.cluster) siblings.push(b.rel)
else if ([...a.hosts].some(h => b.hosts.has(h))) related.push(b.rel)
}
}
for (const [id, file] of fileById) {
const rel = file.replace(/^\.\//, '')
const list = [...(neighbors.get(id) || [])].slice(0, 12)
if (list.length) byNote.set(rel, list)
const list = [...siblings, ...related].slice(0, MAX_CONNECTIONS)
if (list.length) byNote.set(a.rel, list)
}
return byNote
}
@@ -111,7 +111,7 @@ function titleOf(text, file) {
}
function spravkaBlock(d, connections) {
const conns = connections.length ? connections.map(c => `- [[${c.replace(/\.md$/, '')}]]`).join('\n') : '- (связи появятся после графа)'
const conns = connections.length ? connections.map(c => `- [[${c.replace(/\.md$/, '')}]]`).join('\n') : '- (отдельных связей не найдено)'
return `${SPRAVKA}
**${d.zagolovok}**
@@ -148,7 +148,10 @@ async function main() {
continue
}
if (!d?.zagolovok) continue
const stripped = FORCE ? text.replace(new RegExp(`\\n*${SPRAVKA}[\\s\\S]*?(?=\\n## |$)`, 'm'), '\n') : text
// Справка is always appended last, so strip from its first occurrence to EOF.
// (No `m` flag: a per-line `$` would stop at the first newline and leave the old
// Справка in place, duplicating it on every --force run.)
const stripped = FORCE ? text.replace(new RegExp(`\\n*${SPRAVKA}[\\s\\S]*$`), '\n') : text
const block = spravkaBlock(d, connections)
await fs.writeFile(file, `${stripped.trimEnd()}\n\n${block}`, 'utf8')
summary.push({ rel, title: titleOf(text, file), zagolovok: d.zagolovok, connections })
@@ -162,13 +165,19 @@ async function main() {
const body = [
`---\ntitle: "Сводка знаний — ${SESSION}"\ntype: "knowledge-digest"\nsource_ref: "digest:${SESSION}"\n---`,
`\n# Сводка знаний — ${SESSION}\n`,
`Обработано заметок: ${summary.length}. Ниже — что узнано и как связано.\n`,
`## What This Is\n\nСводка связывает новые knowledge-note после digest-прогона и показывает, какие заметки теперь имеют человеческую справку.\n`,
`## Why It Matters\n\nЭто финальный reuse-слой: после intake знание видно не только как отдельные файлы, но и как карта применимых связей.\n`,
`## How To Use It\n\n- Открыть связанные заметки из списка ниже.\n- Взять сильные next actions в работу.\n- Проверить слабые или неподтверждённые связи перед публикацией.\n`,
`## Source\n\n- source_ref: digest:${SESSION}\n- processed_notes: ${summary.length}\n`,
`## Verification\n\nСводка построена локально из заметок vault и связей digest-этапа. Не является внешней факт-проверкой.\n`,
`## Related Notes\n\n- [[Mnemazine Protocol]]\n`,
`## Reuse\n\nОбработано заметок: ${summary.length}. Ниже — что узнано и как связано.\n`,
...summary.map(s => `## ${s.zagolovok}\n\n- Заметка: [[${s.rel.replace(/\.md$/, '')}]]\n- Связи: ${s.connections.length ? s.connections.map(c => `[[${c.replace(/\.md$/, '')}]]`).join(', ') : '—'}\n`)
].join('\n')
await fs.writeFile(path.join(dir, `Сводка-${SESSION}.md`), body, 'utf8')
}
console.log(JSON.stringify({ ok: true, provider: PROVIDER, written, summary: summary.length, graph: connByNote.size ? GRAPH : 'none' }, null, 2))
console.log(JSON.stringify({ ok: true, provider: PROVIDER, written, summary: summary.length, linked: connByNote.size }, null, 2))
}
main().catch(err => { console.error(err.message || err); process.exit(1) })
+15
View File
@@ -62,6 +62,7 @@ async function checkSyntax() {
'scripts/mnemazine-weekly-state.mjs',
'scripts/mnemazine-digest.mjs',
'scripts/mnemazine-report-quality-gate.mjs',
'scripts/mnemazine-complete-check.mjs',
'scripts/mnemazine-release-check.mjs'
]
for (const script of scripts) {
@@ -120,11 +121,25 @@ async function demoSmoke() {
const cache = await readJson(path.join(temp, '.mnemazine/cache/processed-hashes.json'))
const cacheOnly = Object.values(cache).filter(value => value && typeof value === 'object' && value.status === 'needs_manual_context')
if (cacheOnly.length !== 1) throw new Error(`demo smoke failed: expected 1 cache-only source, got ${cacheOnly.length}`)
await fs.copyFile(path.join(ROOT, 'demo/inbox/example-guide.md'), path.join(inbox, 'cached-guide.md'))
await must('demo cached-source archive smoke', process.execPath, ['scripts/mnemazine-run.mjs'], {
env: {
MNEMAZINE_ROOT: temp,
MNEMAZINE_INBOX: inbox,
MNEMAZINE_VAULT: vault
}
})
const cachedInboxFiles = await fs.readdir(inbox)
if (cachedInboxFiles.length !== 0) throw new Error(`demo cached smoke failed: inbox not empty (${cachedInboxFiles.join(', ')})`)
const archivedAfterCachedRun = await listFiles(path.join(temp, '.mnemazine/archive'))
if (archivedAfterCachedRun.length !== 3) throw new Error(`demo cached smoke failed: expected 3 archived sources, got ${archivedAfterCachedRun.length}`)
}
async function qualityAndPublicChecks() {
await must('demo vault quality', 'npm', ['run', 'quality', '--', '--vault', 'demo/vault'])
await reportQualityGateSmoke()
await must('complete gate smoke', 'npm', ['run', 'complete'])
await must('public release scan', 'npm', ['run', 'public-check'])
}
+87 -6
View File
@@ -18,6 +18,7 @@ const VIDEO_FRAMES = path.join(ROOT, '.mnemazine/cache/video-frames')
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'
// 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.
@@ -281,11 +282,89 @@ async function archiveFile(file, hash) {
const dir = path.join(ARCHIVE, month)
await ensureDir(dir)
const ext = path.extname(file)
const target = path.join(dir, `${hash}${ext}`)
let target = path.join(dir, `${hash}${ext}`)
let suffix = 1
while (existsSync(target)) {
target = path.join(dir, `${hash}-${suffix}${ext}`)
suffix += 1
}
await fs.rename(file, target)
return target
}
function runLocalNodeScript(script, args = []) {
const file = path.join(ROOT, 'scripts', script)
if (!existsSync(file)) 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,
ok: result.status === 0,
code: result.status,
stdout: compact(result.stdout, 1200),
stderr: compact(result.stderr, 1200)
}
}
async function recentNotes(limit = 8) {
const notes = []
async function walk(dir) {
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (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)
const text = await fs.readFile(file, 'utf8').catch(() => '')
const title = text.match(/^#\s+(.+)$/m)?.[1]?.trim() || path.basename(file, '.md')
const action = text.match(/Next action:\s*(.+)$/mi)?.[1]?.trim() || text.match(/- Next action:\s*(.+)$/mi)?.[1]?.trim() || ''
notes.push({ file: path.relative(VAULT, file), title, action, mtimeMs: stat.mtimeMs })
}
}
}
await walk(VAULT)
return notes.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit)
}
async function writeActionBrief(finishResult) {
const dir = path.join(ROOT, '.mnemazine/state')
await ensureDir(dir)
const notes = await recentNotes()
const lines = [
`# Mnemazine Action Brief — ${new Date().toISOString().slice(0, 10)}`,
'',
'## Status',
'',
`- Inbox: ${(await fs.readdir(INBOX).catch(() => [])).filter(name => !name.startsWith('.')).length}`,
`- Vault: ${VAULT}`,
`- Quality gate: ${finishResult.quality?.ok ? 'ok' : 'check output'}`,
`- Graph refresh: ${finishResult.graph?.ok ? 'ok' : finishResult.graph?.code === 2 ? 'partial / semantic pending' : finishResult.graph?.skipped ? 'skipped' : 'failed'}`,
`- Weekly report: ${finishResult.weekly?.ok ? 'ok' : finishResult.weekly?.skipped ? 'skipped' : 'failed'}`,
`- Report quality: ${finishResult.report_quality?.ok ? 'ok' : finishResult.report_quality?.skipped ? 'skipped' : 'failed'}`,
'',
'## Next Actions',
'',
...(notes.length
? notes.map(note => `- ${note.title}${note.action ? ` — ${note.action}` : ''} (${note.file})`)
: ['- No recent notes found.'])
]
const out = path.join(dir, 'last-action-brief.md')
await fs.writeFile(out, `${lines.join('\n')}\n`, 'utf8')
return out
}
async function finishRun() {
const result = {}
result.quality = runLocalNodeScript('mnemazine-vault-quality-gate.mjs')
result.graph = runLocalNodeScript('mnemazine-refresh-graphify.mjs', ['--vault', VAULT, '--mode', 'auto', '--json'])
result.weekly = runLocalNodeScript('mnemazine-weekly-brief-html.mjs')
const weeklyReport = result.weekly?.stdout?.match(/\/[^\s]+\.html/)?.[0]
result.report_quality = weeklyReport
? runLocalNodeScript('mnemazine-report-quality-gate.mjs', ['--report', weeklyReport])
: { skipped: true, reason: 'weekly report path missing' }
result.brief = await writeActionBrief(result)
return result
}
async function main() {
await ensureDir(INBOX)
await ensureDir(VAULT)
@@ -306,7 +385,11 @@ async function main() {
// others. Any throw here is contained — the file stays in inbox for a retry.
try {
const hash = await sha256(file)
if (cache[hash]) continue
if (cache[hash]) {
toArchive.push({ file, hash })
cachedOnly += 1
continue
}
// Local-first recognition (0 tokens): Apple Vision OCR / markitdown / whisper.
let text = await extract(file)
// Only if local produced nothing usable AND deep is on: LLM recognition.
@@ -351,15 +434,13 @@ async function main() {
if (quality.status !== 0) process.exit(quality.status || 1)
const archived = []
for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash))
if (spawnSync('graphify', ['--version'], { encoding: 'utf8' }).status === 0) {
spawnSync('graphify', ['update', VAULT], { stdio: 'inherit' })
}
// Deep + final stage: Russian humanizer digest, AFTER the graph so connections
// are real. Writes a Справка into each note + one session summary note.
if (DEEP) {
spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-digest.mjs')], { stdio: 'inherit', env: process.env })
}
console.log(JSON.stringify({ inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, vault: VAULT }, null, 2))
const finish = FINISH ? await finishRun() : { skipped: true }
console.log(JSON.stringify({ inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, finish, vault: VAULT }, null, 2))
}
main().catch(err => {
+14 -2
View File
@@ -30,6 +30,18 @@ function summaryOf(text) {
return block.replace(/[#*_`>-]/g, '').replace(/\s+/g, ' ').trim().slice(0, 520)
}
function actionOf(text) {
return text.match(/Next action:\s*(.+)$/mi)?.[1]?.trim() ||
text.match(/Следующее действие[:\s]+(.+)$/mi)?.[1]?.trim() ||
'Прочитать, решить статус и связать с ближайшим проектом.'
}
function linksOf(text) {
return [...new Set(String(text).match(/\bhttps?:\/\/[^\s)]+/g) || [])]
.map(url => url.replace(/[.,;]+$/, ''))
.slice(0, 4)
}
await fs.mkdir(REPORTS, { recursive: true })
await fs.mkdir(STATE, { recursive: true })
const files = await walk(VAULT)
@@ -39,7 +51,7 @@ for (const file of files) {
const stat = await fs.stat(file)
if (stat.mtimeMs < weekAgo) continue
const text = await fs.readFile(file, 'utf8')
cards.push({ file: path.relative(VAULT, file), title: titleOf(text, file), summary: summaryOf(text) })
cards.push({ file: path.relative(VAULT, file), title: titleOf(text, file), summary: summaryOf(text), action: actionOf(text), links: linksOf(text) })
}
const html = `<!doctype html>
@@ -63,7 +75,7 @@ main{padding:34px max(18px,6vw) 70px}.grid{display:grid;grid-template-columns:re
<body>
<header><section class="hero"><h1>Mnemazine Weekly</h1><p class="lead">Сводка знаний за последние 7 дней: что появилось, что стоит взять в работу, что можно забыть.</p><button id="export" style="margin-top:18px;border:0;background:#fff;color:var(--blue);font-weight:700;border-radius:8px;padding:11px 16px;cursor:pointer">⬇ Скачать weekly-state.json</button></section></header>
<main><section class="grid">
${cards.map((c, i) => `<article class="card" data-id="${esc(c.file)}"><div class="path">${esc(c.file)}</div><h2>${esc(c.title)}</h2><p>${esc(c.summary)}</p><div class="actions"><button data-v="read">Прочитал</button><button data-v="work">В работу</button><button data-v="forget">Забыть</button></div></article>`).join('\n') || '<article class="card"><h2>За неделю новых заметок нет</h2><p>Положите материалы в inbox и запустите Mnemazine.</p></article>'}
${cards.map((c, i) => `<article class="card" data-id="${esc(c.file)}" data-knowledge-atom="${i + 1}"><div class="path">${esc(c.file)}</div><h2>${esc(c.title)}</h2><p><strong>Синтез:</strong> ${esc(c.summary)}</p><p><strong>Расширил источниками:</strong> ${c.links.length ? c.links.map(url => `<a href="${esc(url)}">${esc(new URL(url).hostname.replace(/^www\\./, ''))}</a>`).join(' · ') : `<a href="../vault/${esc(c.file)}">локальная заметка</a>`}</p><p><strong>Где применить:</strong> В связанных проектах, skills, агентных правилах или backlog, если карточка отмечена "В работу".</p><p><strong>Проверка и риск:</strong> Проверить публичные источники перед публикацией или автоматизацией.</p><p><strong>Следующее действие:</strong> ${esc(c.action)}</p><div class="actions"><button data-v="read">Прочитал</button><button data-v="work">В работу</button><button data-v="forget">Забыть</button></div></article>`).join('\n') || '<article class="card" data-knowledge-atom="empty"><h2>За неделю новых заметок нет</h2><p>Положите материалы в inbox и запустите Mnemazine.</p></article>'}
</section></main>
<script>
const KEY='mnemazine-weekly-state';