Stabilize Mnemazine end-to-end gates

This commit is contained in:
Зарубин Филипп
2026-06-24 19:10:26 +03:00
parent a2a555cf1d
commit 17fd8fef5f
24 changed files with 1502 additions and 203 deletions
+11 -1
View File
@@ -1,6 +1,6 @@
# Mnemazine Agent Commands # Mnemazine Agent Commands
This repository has two chat commands. Treat them as commands, not as topics to discuss. This repository has three chat commands. Treat them as commands, not as topics to discuss.
## `Mnemazine` ## `Mnemazine`
@@ -22,6 +22,16 @@ npm run update
This updates code from GitHub, preserves local config, reinstalls wrappers, and syntax-checks scripts. It must not process inbox files. This updates code from GitHub, preserves local config, reinstalls wrappers, and syntax-checks scripts. It must not process inbox files.
## `Mnemazine doctor`
When the latest user message is `Mnemazine doctor`, `Мнемозина doctor`, `проверь Mnemazine`, or `проверь Мнемозину`:
```bash
npm run doctor
```
This checks the last run, live vault gates, graph markers, release smoke, and inbox state. It must not process inbox files.
## Failure Rule ## Failure Rule
If a command fails, report the failing command and the key error. Do not archive, delete, reset, or rewrite user files. If a command fails, report the failing command and the key error. Do not archive, delete, reset, or rewrite user files.
+11 -1
View File
@@ -1,6 +1,6 @@
# Mnemazine Agent Commands # Mnemazine Agent Commands
This repository has two chat commands. Treat them as commands, not as topics to discuss. This repository has three chat commands. Treat them as commands, not as topics to discuss.
## `Mnemazine` ## `Mnemazine`
@@ -22,6 +22,16 @@ npm run update
This updates code from GitHub, preserves local config, reinstalls wrappers, and syntax-checks scripts. It must not process inbox files. This updates code from GitHub, preserves local config, reinstalls wrappers, and syntax-checks scripts. It must not process inbox files.
## `Mnemazine doctor`
When the latest user message is `Mnemazine doctor`, `Мнемозина doctor`, `проверь Mnemazine`, or `проверь Мнемозину`:
```bash
npm run doctor
```
This checks the last run, live vault gates, graph markers, release smoke, and inbox state. It must not process inbox files.
## Failure Rule ## Failure Rule
If a command fails, report the failing command and the key error. Do not archive, delete, reset, or rewrite user files. If a command fails, report the failing command and the key error. Do not archive, delete, reset, or rewrite user files.
+15
View File
@@ -188,6 +188,21 @@ npm run last-run -- --require-ok
npm run complete -- --require-deep npm run complete -- --require-deep
``` ```
Agent chat health check:
```text
Mnemazine doctor
```
Terminal equivalent:
```bash
npm run doctor
```
This does not process inbox files. It checks the last run, completion gate,
human layer, release smoke, graph markers, and inbox state.
If a strict run fails before archive, that is safe: source files stay in the If a strict run fails before archive, that is safe: source files stay in the
inbox. Do not move or delete them by hand. Read inbox. Do not move or delete them by hand. Read
`npm run last-run`, fix the cause, and run again. `npm run last-run`, fix the cause, and run again.
+7 -1
View File
@@ -14,4 +14,10 @@ If the latest user message is `Mnemazine update`, run:
npm run update npm run update
``` ```
Do not use `npm run run` for live inbox work. Do not process inbox files during update. On failure, report the command and key error; do not archive, delete, reset, or rewrite user files. If the latest user message is `Mnemazine doctor`, `Мнемозина doctor`, `проверь Mnemazine`, or `проверь Мнемозину`, run:
```bash
npm run doctor
```
Do not use `npm run run` for live inbox work. Do not process inbox files during update or doctor checks. On failure, report the command and key error; do not archive, delete, reset, or rewrite user files.
+3
View File
@@ -18,6 +18,7 @@
"audit:local": "bash scripts/mnemazine-audit-local.sh", "audit:local": "bash scripts/mnemazine-audit-local.sh",
"preflight:live": "bash scripts/mnemazine-live-preflight.sh", "preflight:live": "bash scripts/mnemazine-live-preflight.sh",
"last-run": "node scripts/mnemazine-live-status.mjs", "last-run": "node scripts/mnemazine-live-status.mjs",
"doctor": "node scripts/mnemazine-doctor.mjs",
"selftest:security": "node scripts/mnemazine-verify.mjs --selftest && node scripts/mnemazine-webapp-server.mjs --selftest && node scripts/mnemazine-telegram-bot.mjs --selftest && node scripts/mnemazine-weekly-state.mjs --selftest", "selftest:security": "node scripts/mnemazine-verify.mjs --selftest && node scripts/mnemazine-webapp-server.mjs --selftest && node scripts/mnemazine-telegram-bot.mjs --selftest && node scripts/mnemazine-weekly-state.mjs --selftest",
"run": "node scripts/mnemazine-run.mjs", "run": "node scripts/mnemazine-run.mjs",
"protocol:desktop": "bash scripts/mnemazine-desktop-protocol.sh", "protocol:desktop": "bash scripts/mnemazine-desktop-protocol.sh",
@@ -37,8 +38,10 @@
"postrun": "node scripts/mnemazine-postrun-knowledge-report.mjs", "postrun": "node scripts/mnemazine-postrun-knowledge-report.mjs",
"weekly:state": "node scripts/mnemazine-weekly-state.mjs", "weekly:state": "node scripts/mnemazine-weekly-state.mjs",
"digest": "node scripts/mnemazine-digest.mjs", "digest": "node scripts/mnemazine-digest.mjs",
"tool-queue": "node scripts/mnemazine-tool-decision-queue.mjs",
"quality": "node scripts/mnemazine-vault-quality-gate.mjs", "quality": "node scripts/mnemazine-vault-quality-gate.mjs",
"report:quality": "node scripts/mnemazine-report-quality-gate.mjs", "report:quality": "node scripts/mnemazine-report-quality-gate.mjs",
"human-layer:quality": "node scripts/mnemazine-human-layer-gate.mjs",
"complete": "node scripts/mnemazine-complete-check.mjs", "complete": "node scripts/mnemazine-complete-check.mjs",
"public-check": "bash scripts/check-public-release.sh", "public-check": "bash scripts/check-public-release.sh",
"release-check": "node scripts/mnemazine-release-check.mjs" "release-check": "node scripts/mnemazine-release-check.mjs"
+39 -12
View File
@@ -3,9 +3,9 @@ import { promises as fs } from 'node:fs'
import { existsSync } from 'node:fs' import { existsSync } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { spawn } from 'node:child_process' import { spawn } from 'node:child_process'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) 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 INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports') const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state') const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
@@ -21,9 +21,9 @@ const NEEDS_UPDATE_MAX_DAYS = Number(arg('needs-update-max-days', process.env.MN
const STRICT_GRAPH = argv.includes('--strict-graph') const STRICT_GRAPH = argv.includes('--strict-graph')
const REQUIRE_DEEP = argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1' const REQUIRE_DEEP = argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
function run(command, args) { function run(command, args, env = {}) {
return new Promise(resolve => { return new Promise(resolve => {
const child = spawn(command, args, { cwd: ROOT, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] }) const child = spawn(command, args, { cwd: ROOT, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] })
let stdout = '' let stdout = ''
let stderr = '' let stderr = ''
child.stdout.on('data', chunk => { stdout += String(chunk) }) child.stdout.on('data', chunk => { stdout += String(chunk) })
@@ -55,9 +55,10 @@ async function latestReport() {
for (const item of await fs.readdir(REPORTS, { withFileTypes: true }).catch(() => [])) { for (const item of await fs.readdir(REPORTS, { withFileTypes: true }).catch(() => [])) {
if (!item.isFile() || !item.name.endsWith('.html')) continue if (!item.isFile() || !item.name.endsWith('.html')) continue
const file = path.join(REPORTS, item.name) const file = path.join(REPORTS, item.name)
reports.push({ file, mtimeMs: (await fs.stat(file)).mtimeMs }) reports.push({ file, name: item.name, mtimeMs: (await fs.stat(file)).mtimeMs })
} }
return reports.sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.file || '' const visual = reports.filter(item => item.name.includes('visual-knowledge-report'))
return (visual.length ? visual : reports).sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.file || ''
} }
async function activeInboxFiles() { async function activeInboxFiles() {
@@ -70,6 +71,16 @@ async function readJson(file, fallback = null) {
try { return JSON.parse(await fs.readFile(file, 'utf8')) } catch { return fallback } try { return JSON.parse(await fs.readFile(file, 'utf8')) } catch { return fallback }
} }
async function graphMtime(file) {
const stat = await fs.stat(file).catch(() => null)
return stat ? stat.mtimeMs : 0
}
function isGraphSemanticFile(file) {
return ['.md', '.txt', '.pdf', '.png', '.jpg', '.jpeg', '.webp', '.heic', '.tiff', '.gif', '.svg']
.includes(path.extname(file).toLowerCase())
}
function deepFailures(lastRun) { function deepFailures(lastRun) {
const failures = [] const failures = []
if (!lastRun) return ['last run state missing'] if (!lastRun) return ['last run state missing']
@@ -94,16 +105,18 @@ async function main() {
const lastRunFile = path.join(STATE, 'last-run.json') const lastRunFile = path.join(STATE, 'last-run.json')
const lastRun = await readJson(lastRunFile) const lastRun = await readJson(lastRunFile)
const VAULT = resolveVault({ cli: arg('vault'), env: process.env.MNEMAZINE_VAULT || lastRun?.vault })
const gateEnv = { MNEMAZINE_VAULT: VAULT }
const lastRunStartedMs = lastRun?.started_at ? Date.parse(lastRun.started_at) : 0 const lastRunStartedMs = lastRun?.started_at ? Date.parse(lastRun.started_at) : 0
const qualityArgs = ['scripts/mnemazine-vault-quality-gate.mjs', '--max-failures', '50'] const qualityArgs = ['scripts/mnemazine-vault-quality-gate.mjs', '--vault', VAULT, '--max-failures', '50']
if (lastRunStartedMs) qualityArgs.push('--changed-since', lastRun.started_at) if (lastRunStartedMs) qualityArgs.push('--changed-since', lastRun.started_at)
const quality = await run(process.execPath, qualityArgs) const quality = await run(process.execPath, qualityArgs, gateEnv)
if (!quality.ok) failures.push(`vault quality failed: ${quality.stderr || quality.stdout}`) if (!quality.ok) failures.push(`vault quality failed: ${quality.stderr || quality.stdout}`)
const report = await latestReport() const report = await latestReport()
if (!report) failures.push('weekly report missing') if (!report) failures.push('weekly report missing')
else { else {
const reportQuality = await run(process.execPath, ['scripts/mnemazine-report-quality-gate.mjs', '--report', report]) const reportQuality = await run(process.execPath, ['scripts/mnemazine-report-quality-gate.mjs', '--report', report], gateEnv)
if (!reportQuality.ok) failures.push(`report quality failed: ${reportQuality.stderr || reportQuality.stdout}`) if (!reportQuality.ok) failures.push(`report quality failed: ${reportQuality.stderr || reportQuality.stdout}`)
} }
@@ -115,12 +128,26 @@ async function main() {
if (!existsSync(brief)) failures.push('action brief missing') 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') else if ((await fs.stat(brief)).mtimeMs < newestNote) failures.push('action brief older than newest vault note')
const humanLayerArgs = ['scripts/mnemazine-human-layer-gate.mjs', '--vault', VAULT]
if (lastRun?.started_at) humanLayerArgs.push('--changed-since', lastRun.started_at)
if (report) humanLayerArgs.push('--report', report)
const humanLayer = await run(process.execPath, humanLayerArgs, gateEnv)
if (!humanLayer.ok) failures.push(`human layer failed: ${humanLayer.stderr || humanLayer.stdout}`)
const needsUpdate = path.join(VAULT, 'graphify-out', 'needs_update') const needsUpdate = path.join(VAULT, 'graphify-out', 'needs_update')
if (existsSync(needsUpdate)) { if (existsSync(needsUpdate)) {
const ageDays = (Date.now() - (await fs.stat(needsUpdate)).mtimeMs) / 86400000 const graphPath = path.join(VAULT, 'graphify-out', 'graph.json')
const msg = `semantic graph pending (${ageDays.toFixed(2)} days)` const graphMs = await graphMtime(graphPath)
if (STRICT_GRAPH || ageDays > NEEDS_UPDATE_MAX_DAYS) failures.push(msg) const newestSemantic = await newestChangedFileMtime(VAULT, 0, isGraphSemanticFile)
else warnings.push(msg) const staleMarker = graphMs && newestSemantic && graphMs >= newestSemantic
if (staleMarker) {
await fs.rm(needsUpdate, { force: true }).catch(() => {})
} else {
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)
}
} }
if (REQUIRE_DEEP) { if (REQUIRE_DEEP) {
+15 -14
View File
@@ -5,11 +5,12 @@
// graph. Plus one session summary note mapping all processed atoms — so the // graph. Plus one session summary note mapping all processed atoms — so the
// knowledge is trivially reusable later. // knowledge is trivially reusable later.
// node scripts/mnemazine-digest.mjs --vault <path> [--provider claude|codex] [--force] // node scripts/mnemazine-digest.mjs --vault <path> [--provider claude|codex] [--force]
// Needs an LLM (Claude primary). No-op for notes already carrying a Справка // Needs an LLM (Codex default). No-op for notes already carrying a Справка
// unless --force. Default pipeline never calls this — it is a deep/opt-in stage. // unless --force. Default pipeline never calls this — it is a deep/opt-in stage.
import { promises as fs, readFileSync, existsSync } from 'node:fs' import { promises as fs, readFileSync, existsSync } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs' import { activeProvider, llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const argv = process.argv.slice(2) const argv = process.argv.slice(2)
@@ -19,9 +20,9 @@ function arg(name, fb = '') {
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fb return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fb
} }
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault'))) const VAULT = resolveVault({ cli: arg('vault') })
const SESSION = arg('session', new Date().toISOString().slice(0, 10)) const SESSION = arg('session', new Date().toISOString().slice(0, 10))
const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || 'claude') const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || activeProvider())
const FORCE = argv.includes('--force') const FORCE = argv.includes('--force')
const DETERMINISTIC = argv.includes('--deterministic') || process.env.MNEMAZINE_DIGEST_DETERMINISTIC === '1' const DETERMINISTIC = argv.includes('--deterministic') || process.env.MNEMAZINE_DIGEST_DETERMINISTIC === '1'
const LIMIT = Number(arg('limit', '0')) // 0 = no cap const LIMIT = Number(arg('limit', '0')) // 0 = no cap
@@ -141,9 +142,9 @@ function extractSection(text, names) {
function deterministicDigest(noteText, file) { function deterministicDigest(noteText, file) {
const title = titleOf(noteText, file) const title = titleOf(noteText, file)
const what = extractSection(noteText, ['What This Is', 'Что это', 'Суть']) const what = extractSection(noteText, ['Что это', 'Суть', 'What This Is'])
const why = extractSection(noteText, ['Why It Matters', 'Почему важно']) const why = extractSection(noteText, ['Зачем это нужно', 'Почему важно', 'Why It Matters'])
const how = extractSection(noteText, ['How To Use It', 'Как использовать', 'Reuse']) const how = extractSection(noteText, ['Как использовать', 'Что добавила Mnemazine', 'Reuse', 'How To Use It'])
return { return {
zagolovok: title, zagolovok: title,
chto_eto: what || `Проверенная заметка по теме "${title}".`, chto_eto: what || `Проверенная заметка по теме "${title}".`,
@@ -207,13 +208,13 @@ async function main() {
const body = [ const body = [
`---\ntitle: "Сводка знаний — ${SESSION}"\ntype: "knowledge-digest"\nsource_ref: "digest:${SESSION}"\n---`, `---\ntitle: "Сводка знаний — ${SESSION}"\ntype: "knowledge-digest"\nsource_ref: "digest:${SESSION}"\n---`,
`\n# Сводка знаний — ${SESSION}\n`, `\n# Сводка знаний — ${SESSION}\n`,
`## What This Is\n\nСводка связывает новые knowledge-note после digest-прогона и показывает, какие заметки теперь имеют человеческую справку.\n`, `## Что это\n\nСводка связывает новые knowledge-note после digest-прогона и показывает, какие заметки теперь имеют человеческую справку.\n`,
`## Why It Matters\n\nЭто финальный reuse-слой: после intake знание видно не только как отдельные файлы, но и как карта применимых связей.\n`, `## Зачем это нужно\n\nЭто финальный reuse-слой: после intake знание видно не только как отдельные файлы, но и как карта применимых связей.\n`,
`## How To Use It\n\n- Открыть связанные заметки из списка ниже.\n- Взять сильные next actions в работу.\n- Проверить слабые или неподтверждённые связи перед публикацией.\n`, `## Как использовать\n\n- Открыть связанные заметки из списка ниже.\n- Взять сильные next actions в работу.\n- Проверить слабые или неподтверждённые связи перед публикацией.\n`,
`## Source\n\n- source_ref: digest:${SESSION}\n- processed_notes: ${summary.length}\n`, `## Источник\n\n- source_ref: digest:${SESSION}\n- processed_notes: ${summary.length}\n`,
`## Verification\n\nСводка построена локально из заметок vault и связей digest-этапа. Не является внешней факт-проверкой.\n`, `## Проверка\n\nСводка построена локально из заметок vault и связей digest-этапа. Не является внешней факт-проверкой.\n`,
`## Related Notes\n\n- [[Mnemazine Protocol]]\n`, `## Связанные заметки\n\n- [[Mnemazine Protocol]]\n`,
`## Reuse\n\nОбработано заметок: ${summary.length}. Ниже — что узнано и как связано.\n`, `## Повторное использование\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`) ...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') ].join('\n')
await fs.writeFile(path.join(dir, `Сводка-${SESSION}.md`), body, 'utf8') await fs.writeFile(path.join(dir, `Сводка-${SESSION}.md`), body, 'utf8')
+143
View File
@@ -0,0 +1,143 @@
#!/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'
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 INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
const JSON_OUT = process.argv.includes('--json')
async function readJson(file, fallback = null) {
try { return JSON.parse(await fs.readFile(file, 'utf8')) } catch { return fallback }
}
function run(name, command, args, env = {}) {
return new Promise(resolve => {
const child = spawn(command, args, {
cwd: ROOT,
env: { ...process.env, ...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({
name,
ok: code === 0,
code: code ?? 1,
stdout: stdout.trim(),
stderr: stderr.trim()
}))
child.on('error', error => resolve({
name,
ok: false,
code: 1,
stdout: stdout.trim(),
stderr: `${stderr}\n${error.message}`.trim()
}))
})
}
async function activeInboxFiles(dir) {
return (await fs.readdir(dir, { withFileTypes: true }).catch(() => []))
.filter(item => item.isFile() && !item.name.startsWith('.'))
.map(item => item.name)
}
async function latestVisualReport() {
const reports = []
for (const item of await fs.readdir(REPORTS, { withFileTypes: true }).catch(() => [])) {
if (!item.isFile() || !item.name.endsWith('.html') || !item.name.includes('visual-knowledge-report')) 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 graphMarkers(vault) {
const candidates = [
path.join(ROOT, 'vault/graphify-out/needs_update'),
path.join(vault, 'graphify-out/needs_update')
]
const out = []
for (const file of [...new Set(candidates.map(item => path.resolve(item)))]) {
out.push({
file,
exists: existsSync(file),
content: existsSync(file) ? (await fs.readFile(file, 'utf8')).trim() : ''
})
}
return out
}
function tail(text, lines = 16) {
return String(text || '').split('\n').slice(-lines).join('\n')
}
async function main() {
const lastRun = await readJson(path.join(STATE, 'last-run.json'))
const vault = resolveVault({ env: process.env.MNEMAZINE_VAULT || lastRun?.vault })
const env = { MNEMAZINE_VAULT: vault }
const report = await latestVisualReport()
const since = lastRun?.started_at || ''
const commands = [
['complete', 'npm', ['run', 'complete', '--', '--require-deep']],
...(report && since ? [['human-layer', 'npm', ['run', 'human-layer:quality', '--', '--changed-since', since, '--report', path.relative(ROOT, report)]]] : []),
['last-run', 'npm', ['run', 'last-run', '--', '--require-ok']],
['graph-smoke', 'npm', ['run', 'graph:smoke']],
['release-check', 'npm', ['run', 'release-check']]
]
const results = []
for (const [name, command, args] of commands) results.push(await run(name, command, args, env))
const inbox = await activeInboxFiles(INBOX)
const markers = await graphMarkers(vault)
const failures = [
...results.filter(item => !item.ok).map(item => `${item.name} failed`),
...(inbox.length ? [`inbox not empty: ${inbox.length}`] : []),
...markers.filter(item => item.exists).map(item => `graph marker exists: ${item.file}`)
]
const output = {
ok: failures.length === 0,
failures,
vault,
inbox: inbox.length,
report: report ? path.relative(ROOT, report) : null,
graph_markers: markers,
commands: results.map(item => ({ name: item.name, ok: item.ok, code: item.code }))
}
if (JSON_OUT) {
console.log(JSON.stringify(output, null, 2))
} else {
console.log(output.ok ? 'Mnemazine doctor: ok' : 'Mnemazine doctor: failed')
console.log(`Vault: ${vault}`)
console.log(`Inbox: ${inbox.length}`)
console.log(`Report: ${output.report || 'missing'}`)
for (const item of results) console.log(`${item.ok ? 'ok' : 'fail'} ${item.name}`)
for (const marker of markers) console.log(`${marker.exists ? 'fail' : 'ok'} marker ${marker.file}`)
if (failures.length) {
console.log('\nFailures:')
for (const failure of failures) console.log(`- ${failure}`)
const failed = results.find(item => !item.ok)
if (failed) {
console.log(`\n${failed.name} output:`)
console.log(tail(failed.stderr || failed.stdout))
}
}
}
if (!output.ok) process.exit(1)
}
main().catch(error => {
console.error(error.message || error)
process.exit(1)
})
+252
View File
@@ -0,0 +1,252 @@
#!/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 REPORTS = path.resolve(arg('reports', process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')))
const STATE = path.resolve(arg('state', process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')))
const REPORT = arg('report', '')
const BRIEF = arg('brief', path.join(STATE, 'last-action-brief.md'))
const MAX_FAILURES = Number(arg('max-failures', '50'))
const NOTES_ONLY = flag('notes-only')
const REPORTS_ONLY = flag('reports-only')
const BRIEF_ONLY = flag('brief-only')
const SOURCE_REFS = new Set(arg('source-ref', '')
.split(',')
.map(s => s.trim())
.filter(Boolean))
function lastRunStartedAt() {
try {
const state = JSON.parse(readFileSync(path.join(STATE, 'last-run.json'), 'utf8'))
return state?.started_at || ''
} catch {
return ''
}
}
function sinceMs(value) {
if (!value) return 0
if (/^\d+(?:\.\d+)?$/.test(String(value))) return Number(value)
const parsed = Date.parse(value)
return Number.isFinite(parsed) ? parsed : 0
}
const CHANGED_SINCE = arg('changed-since', lastRunStartedAt())
const CHANGED_SINCE_MS = sinceMs(CHANGED_SINCE)
async function walk(dir, include) {
const out = []
async function visit(folder) {
for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) {
if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
const file = path.join(folder, item.name)
if (item.isDirectory()) await visit(file)
else if (item.isFile() && include(file)) out.push(file)
}
}
await visit(dir)
return out
}
async function textFile(file) {
return await fs.readFile(file, 'utf8').catch(() => '')
}
function stripHtml(html) {
return String(html || '')
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/&quot;/g, '"')
.replace(/&#39;|&apos;/g, "'")
.replace(/&amp;/g, '&')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&nbsp;/g, ' ')
.replace(/\s+/g, ' ')
.trim()
}
function section(text, title) {
const re = new RegExp(`^##\\s+${title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:\\s|$)[^\\n]*\\n([\\s\\S]*?)(?=^##\\s+|(?![\\s\\S]))`, 'mi')
return text.match(re)?.[1]?.trim() || ''
}
function hasAnySection(text, titles) {
return titles.some(title => section(text, title))
}
function cyrillicCount(text) {
return (String(text || '').match(/[А-Яа-яЁё]/g) || []).length
}
function latinCount(text) {
return (String(text || '').match(/[A-Za-z]/g) || []).length
}
const rawMarkers = [
['english-section', /^##\s+(What This Is|Why It Matters|How To Use It|Source|Verification|Related Notes|Reuse)\b/gm],
['github-metadata-en', /\bGitHub metadata:/g],
['repository-freshness-en', /\bRepository freshness:/g],
['readme-signal-en', /\bREADME signal:/g],
['raw-html-attribute', /\b(?:src|href|alt|title)=["'][^"']*["']/gi],
['raw-meta-tag', /<meta\b/gi],
['raw-img-tag', /<img\b/gi],
['raw-script-marker', /window\.gtag/gi],
['raw-ocr-en', /\braw\s+ocr\b/gi],
['raw-ocr-ru', /сырой\s+ocr(?!\s+исключ[её]н)/gi],
['video-ocr-marker', /Video keyframe OCR|Video transcript from local Whisper/gi],
['empty-extract-marker', /No extractable text/gi],
['draft-marker', /\b(?:intake-draft|draft-local)\b/gi],
['media-filename', /\bIMG_\d+(?:\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4))?\b/gi],
['agent-jargon', /\b(?:candidate capability|workflow-fit|capability review queue)\b/gi],
['bad-russian-grammar', /реальным рабочий|конкретного сценария конкретный|Перед пробный|режим только чтение режим|доменов доменов|web-рабочий сценарий|черновик короткое видео/gi]
]
function markerFailures(text) {
const failures = []
for (const [name, re] of rawMarkers) {
const matches = [...String(text || '').matchAll(re)].slice(0, 5).map(m => m[0])
if (matches.length) failures.push({ rule: name, details: matches })
}
return failures
}
function noteFailures(text) {
const failures = markerFailures(text)
const type = text.match(/^type:\s*"?([^"\n]+)"?/m)?.[1]?.trim() || ''
const isDigest = type === 'knowledge-digest'
const isKnowledge = type === 'knowledge-note' || /^#\s+/.test(text)
if (!isDigest && !isKnowledge) return failures
const required = isDigest
? ['Что это', 'Как использовать', 'Проверка', 'Связанные заметки']
: ['Что это', 'Источники', 'Проверка', 'Следующее действие']
const missing = required.filter(title => !section(text, title))
if (missing.length) failures.push({ rule: 'missing-russian-sections', details: missing })
if (!isDigest && !hasAnySection(text, ['Как использовать', 'Что добавила Mnemazine', 'Зачем это нужно'])) {
failures.push({ rule: 'missing-use-section', details: ['Как использовать / Что добавила Mnemazine / Зачем это нужно'] })
}
if (cyrillicCount(text) < 120) failures.push({ rule: 'weak-russian-layer', details: `cyrillic_chars=${cyrillicCount(text)}` })
if (latinCount(text) > cyrillicCount(text) * 2.2) failures.push({ rule: 'english-dominant-layer', details: `latin=${latinCount(text)}, cyrillic=${cyrillicCount(text)}` })
return failures
}
function briefFailures(text) {
const failures = markerFailures(text)
if (!/^#\s+Короткий отч[её]т Mnemazine\b/m.test(text)) failures.push({ rule: 'brief-title-not-russian', details: ['# Короткий отчёт Mnemazine'] })
if (!section(text, 'Статус')) failures.push({ rule: 'brief-status-missing', details: ['## Статус'] })
if (!section(text, 'Следующие действия')) failures.push({ rule: 'brief-actions-missing', details: ['## Следующие действия'] })
if (/^##\s+Next Actions\b/m.test(text) || /^-\s+(Quality gate|Graph refresh|Weekly report|Report quality):/m.test(text)) {
failures.push({ rule: 'brief-english-shell', details: ['old English brief labels'] })
}
return failures
}
function reportFailures(text) {
const failures = markerFailures(text)
const required = [
['report-title', /Отч[её]т Mnemazine|Mnemazine после прогона/i],
['new-knowledge-section', /Новые и обновленн?ые знания/i],
['next-action-section', /Следующ(?:ий ход|ее действие)/i],
['verification-signal', /Проверка|риск/i]
]
for (const [name, re] of required) if (!re.test(text)) failures.push({ rule: `missing-${name}`, details: [String(re)] })
if (cyrillicCount(text) < 200) failures.push({ rule: 'weak-russian-report', details: `cyrillic_chars=${cyrillicCount(text)}` })
return failures
}
async function listNotes() {
if (!existsSync(VAULT)) return []
const files = await walk(VAULT, file => file.endsWith('.md'))
const out = []
for (const file of files) {
const stat = await fs.stat(file)
if (CHANGED_SINCE_MS && stat.mtimeMs >= CHANGED_SINCE_MS) {
out.push(file)
continue
}
if (SOURCE_REFS.size) {
const text = await textFile(file)
if ([...SOURCE_REFS].some(ref => text.includes(ref))) out.push(file)
}
}
return [...new Set(out)]
}
async function latestReport() {
const files = await walk(REPORTS, file => /\.(html|md)$/i.test(file))
const reports = []
for (const file of files) reports.push({ file, mtimeMs: (await fs.stat(file)).mtimeMs })
return reports.sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.file || ''
}
async function listReports() {
if (REPORT) return [path.resolve(REPORT)]
if (!existsSync(REPORTS)) return []
if (CHANGED_SINCE_MS) {
const files = await walk(REPORTS, file => /\.(html|md)$/i.test(file))
const recent = []
for (const file of files) if ((await fs.stat(file)).mtimeMs >= CHANGED_SINCE_MS) recent.push(file)
if (recent.length) return recent
}
const latest = await latestReport()
return latest ? [latest] : []
}
async function checkFile(file, kind) {
const raw = await textFile(file)
const text = kind === 'report' && file.endsWith('.html') ? stripHtml(raw) : raw
const failures = kind === 'note' ? noteFailures(text) : kind === 'brief' ? briefFailures(text) : reportFailures(text)
return failures.length ? { file: path.relative(ROOT, file), kind, failures } : null
}
const failures = []
if (!REPORTS_ONLY && !BRIEF_ONLY) {
for (const file of await listNotes()) {
const failure = await checkFile(file, 'note')
if (failure) failures.push(failure)
if (failures.length >= MAX_FAILURES) break
}
}
if (!NOTES_ONLY && !BRIEF_ONLY && failures.length < MAX_FAILURES) {
for (const file of await listReports()) {
const failure = await checkFile(file, 'report')
if (failure) failures.push(failure)
if (failures.length >= MAX_FAILURES) break
}
}
if (!NOTES_ONLY && !REPORTS_ONLY && failures.length < MAX_FAILURES && existsSync(BRIEF)) {
const failure = await checkFile(path.resolve(BRIEF), 'brief')
if (failure) failures.push(failure)
}
const result = {
ok: failures.length === 0,
checked_since: CHANGED_SINCE || null,
source_refs: SOURCE_REFS.size,
failures
}
console[result.ok ? 'log' : 'error'](JSON.stringify(result, null, 2))
if (!result.ok) process.exit(1)
+2 -1
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env node #!/usr/bin/env node
import { promises as fs } from 'node:fs' import { promises as fs } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')
const argv = process.argv.slice(2) const argv = process.argv.slice(2)
function arg(name, fallback = '') { function arg(name, fallback = '') {
@@ -16,6 +16,7 @@ const seed = arg('url')
const apply = argv.includes('--apply') const apply = argv.includes('--apply')
const graphify = argv.includes('--graphify') const graphify = argv.includes('--graphify')
const maxPages = Number(arg('max-pages', '40')) const maxPages = Number(arg('max-pages', '40'))
const VAULT = resolveVault({ cli: arg('vault') })
if (!seed) { if (!seed) {
console.error('Usage: node scripts/mnemazine-ingest-site.mjs --url https://example.com [--apply] [--graphify] [--max-pages 40]') console.error('Usage: node scripts/mnemazine-ingest-site.mjs --url https://example.com [--apply] [--graphify] [--max-pages 40]')
+8 -1
View File
@@ -35,9 +35,16 @@ fi
if [ "${MNEMAZINE_PREFLIGHT_SKIP_LLM:-0}" != "1" ]; then if [ "${MNEMAZINE_PREFLIGHT_SKIP_LLM:-0}" != "1" ]; then
provider_hint="${MNEMAZINE_LLM:-}" provider_hint="${MNEMAZINE_LLM:-}"
if provider="$(node --input-type=module - "$provider_hint" <<'NODE' if provider="$(node --input-type=module - "$provider_hint" <<'NODE'
import { activeProvider, llmAvailable } from './scripts/mnemazine-llm.mjs' import { activeProvider, llmAvailable, llmJson } from './scripts/mnemazine-llm.mjs'
const provider = process.argv[2] || activeProvider() const provider = process.argv[2] || activeProvider()
if (!llmAvailable(provider)) process.exit(1) if (!llmAvailable(provider)) process.exit(1)
const schema = {
type: 'object',
additionalProperties: false,
required: ['ok'],
properties: { ok: { type: 'boolean' } }
}
await llmJson('Return {"ok":true}.', schema, { provider, timeoutMs: 120000 })
console.log(provider) console.log(provider)
NODE NODE
)"; then )"; then
+54 -12
View File
@@ -1,8 +1,7 @@
#!/usr/bin/env node #!/usr/bin/env node
// Provider-abstracted LLM bridge for Mnemazine. Code-first engine is Claude // Provider-abstracted LLM bridge for Mnemazine. In Codex sessions, Codex is the
// (headless `claude -p`); Codex is kept at parity (same llmJson contract) so // default engine; Claude is only a fallback when Codex is unavailable.
// anything that works via Claude also works via Codex. // provider: MNEMAZINE_LLM = 'claude' | 'codex' (unset = Codex if present)
// provider: MNEMAZINE_LLM = 'claude' | 'codex' (unset = auto: Claude, else Codex)
// Both run as schema-instructed, web-capable headless agents. Default pipeline // Both run as schema-instructed, web-capable headless agents. Default pipeline
// never calls either — only the opt-in --deep path does. // never calls either — only the opt-in --deep path does.
import { spawnSync, spawn } from 'node:child_process' import { spawnSync, spawn } from 'node:child_process'
@@ -38,6 +37,7 @@ const HOME = os.homedir()
// in order: explicit env -> login-shell PATH (respects the user's real install) // in order: explicit env -> login-shell PATH (respects the user's real install)
// -> common absolute locations -> newest VSCode extension binary. Cached. // -> common absolute locations -> newest VSCode extension binary. Cached.
let _claudeBin let _claudeBin
let _defaultProvider
function resolveClaudeBin() { function resolveClaudeBin() {
if (_claudeBin !== undefined) return _claudeBin if (_claudeBin !== undefined) return _claudeBin
if (process.env.MNEMAZINE_CLAUDE_BIN) return (_claudeBin = process.env.MNEMAZINE_CLAUDE_BIN) if (process.env.MNEMAZINE_CLAUDE_BIN) return (_claudeBin = process.env.MNEMAZINE_CLAUDE_BIN)
@@ -74,10 +74,12 @@ function binExists(bin) {
} }
export function defaultProvider() { export function defaultProvider() {
if (_defaultProvider) return _defaultProvider
if (CONFIG_PROVIDER) return CONFIG_PROVIDER if (CONFIG_PROVIDER) return CONFIG_PROVIDER
if (binExists(resolveClaudeBin())) return 'claude' const claudeBin = resolveClaudeBin()
if (binExists(CODEX_BIN)) return 'codex' if (binExists(CODEX_BIN)) return (_defaultProvider = 'codex')
return 'claude' if (binExists(claudeBin) && claudeUsable(claudeBin)) return (_defaultProvider = 'claude')
return (_defaultProvider = 'claude')
} }
export function activeProvider(opts = {}) { export function activeProvider(opts = {}) {
@@ -119,6 +121,46 @@ function codexExecArgs(cwd, opts = {}) {
return args 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
}
function strictOutputSchema(schema) {
if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return schema
const out = { ...schema }
if (out.type === 'object' || out.properties) {
if (out.additionalProperties === undefined) out.additionalProperties = false
if (out.properties) {
out.properties = Object.fromEntries(
Object.entries(out.properties).map(([key, value]) => [key, strictOutputSchema(value)])
)
}
}
if (out.items) out.items = strictOutputSchema(out.items)
for (const key of ['anyOf', 'allOf', 'oneOf']) {
if (Array.isArray(out[key])) out[key] = out[key].map(strictOutputSchema)
}
return out
}
function procError(label, res) {
const stderr = String(res.stderr || '').trim()
if (stderr) return `${label} failed (status ${res.status}): ${stderr.slice(-400)}`
const stdout = String(res.stdout || '').trim()
if (stdout) return `${label} failed (status ${res.status}): ${stdout.slice(-400)}`
return `${label} failed (status ${res.status}): empty stderr/stdout`
}
// --- Codex backend (headless pattern: --output-schema + -o) --- // --- Codex backend (headless pattern: --output-schema + -o) ---
async function codexJsonCall(prompt, schema, opts) { async function codexJsonCall(prompt, schema, opts) {
if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`) if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
@@ -127,14 +169,14 @@ async function codexJsonCall(prompt, schema, opts) {
const schemaFile = path.join(work, 'schema.json') const schemaFile = path.join(work, 'schema.json')
const outFile = path.join(work, 'out.json') const outFile = path.join(work, 'out.json')
const promptFile = path.join(work, 'prompt.md') const promptFile = path.join(work, 'prompt.md')
await fs.writeFile(schemaFile, JSON.stringify(schema), { encoding: 'utf8', mode: 0o600 }) await fs.writeFile(schemaFile, JSON.stringify(strictOutputSchema(schema)), { encoding: 'utf8', mode: 0o600 })
await fs.writeFile(promptFile, prompt, { encoding: 'utf8', mode: 0o600 }) await fs.writeFile(promptFile, prompt, { encoding: 'utf8', mode: 0o600 })
try { try {
const res = await runProc(CODEX_BIN, [ const res = await runProc(CODEX_BIN, [
...codexExecArgs(cwd, opts), ...codexExecArgs(cwd, opts),
'--output-schema', schemaFile, '-o', outFile, '-' '--output-schema', schemaFile, '-o', outFile, '-'
], { input: await fs.readFile(promptFile, 'utf8'), timeoutMs: opts.timeoutMs || TIMEOUT_MS }) ], { input: await fs.readFile(promptFile, 'utf8'), timeoutMs: opts.timeoutMs || TIMEOUT_MS })
if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`) if (res.status !== 0) throw new Error(procError('codex exec', res))
const raw = await fs.readFile(outFile, 'utf8').catch(() => '') const raw = await fs.readFile(outFile, 'utf8').catch(() => '')
if (!raw.trim()) throw new Error('codex returned empty output') 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)}`) } try { return JSON.parse(raw) } catch (err) { throw new Error(`codex returned non-JSON: ${err.message}; head: ${raw.slice(0, 200)}`) }
@@ -157,7 +199,7 @@ async function claudeJsonCall(prompt, schema, opts) {
const args = ['-p', '--output-format', 'json'] const args = ['-p', '--output-format', 'json']
if (tools.length) args.push('--allowedTools', tools.join(',')) if (tools.length) args.push('--allowedTools', tools.join(','))
const res = await runProc(bin, args, { input: full, timeoutMs: opts.timeoutMs || TIMEOUT_MS }) const res = await runProc(bin, args, { input: full, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
if (res.status !== 0) throw new Error(`claude -p failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`) if (res.status !== 0) throw new Error(procError('claude -p', res))
// --output-format json wraps the turn: { type:'result', result:'<text>', ... } // --output-format json wraps the turn: { type:'result', result:'<text>', ... }
let envelope let envelope
try { envelope = JSON.parse(res.stdout) } catch { envelope = null } try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
@@ -183,7 +225,7 @@ export async function llmText(prompt, opts = {}) {
const res = await runProc(CODEX_BIN, [ const res = await runProc(CODEX_BIN, [
...codexExecArgs(opts.cwd || process.cwd(), opts), '-' ...codexExecArgs(opts.cwd || process.cwd(), opts), '-'
], { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS }) ], { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`) if (res.status !== 0) throw new Error(procError('codex exec', res))
return String(res.stdout || '').trim() return String(res.stdout || '').trim()
} }
const bin = resolveClaudeBin() const bin = resolveClaudeBin()
@@ -191,7 +233,7 @@ export async function llmText(prompt, opts = {}) {
const args = ['-p', '--output-format', 'json'] const args = ['-p', '--output-format', 'json']
if (opts.tools?.length) args.push('--allowedTools', opts.tools.join(',')) if (opts.tools?.length) args.push('--allowedTools', opts.tools.join(','))
const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS }) const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
if (res.status !== 0) throw new Error(`claude -p failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`) if (res.status !== 0) throw new Error(procError('claude -p', res))
let envelope let envelope
try { envelope = JSON.parse(res.stdout) } catch { envelope = null } try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
return (envelope && typeof envelope.result === 'string' ? envelope.result : res.stdout).trim() return (envelope && typeof envelope.result === 'string' ? envelope.result : res.stdout).trim()
+2 -1
View File
@@ -3,6 +3,7 @@ import { promises as fs } from 'node:fs'
import { existsSync } from 'node:fs' import { existsSync } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { readGraph, writeGraph, mergeGraphObjects, graphStats } from './mnemazine-graph-utils.mjs' import { readGraph, writeGraph, mergeGraphObjects, graphStats } from './mnemazine-graph-utils.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
const argv = process.argv.slice(2) const argv = process.argv.slice(2)
@@ -46,7 +47,7 @@ function withoutSourceFiles(graph, files) {
} }
async function main() { async function main() {
const vault = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(process.cwd(), 'vault'))) const vault = resolveVault({ cli: arg('vault') })
const graphPath = path.resolve(arg('graph', path.join(vault, 'graphify-out/graph.json'))) 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', path.join(vault, '.mnemazine/semantic-shards')))
const manifestPath = arg('manifest', '') const manifestPath = arg('manifest', '')
+71 -21
View File
@@ -17,17 +17,31 @@ function flag(name) {
return argv.includes(`--${name}`) return argv.includes(`--${name}`)
} }
const REPO_VAULT = path.join(ROOT, 'vault') function lastRunVault() {
const file = path.join(ROOT, '.mnemazine/state/last-run.json')
try {
const state = JSON.parse(fsSync.readFileSync(file, 'utf8'))
return state?.vault || ''
} catch {
return ''
}
}
const VAULT = resolveVault({ const VAULT = resolveVault({
cli: arg('vault', process.env.MNEMAZINE_VAULT || (fsSync.existsSync(REPO_VAULT) ? REPO_VAULT : '')), cli: arg('vault', process.env.MNEMAZINE_VAULT || lastRunVault()),
}) })
const REPORTS = path.resolve(arg('reports', process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports'))) 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)) const RUN_ID = arg('run-id', new Date().toISOString().slice(0, 10))
const TITLE = arg('title', 'Mnemazine knowledge brief') const TITLE = arg('title', 'Отчёт Mnemazine по знаниям')
const LOGS = arg('logs', '') const LOGS = arg('logs', '')
const RESULTS_JSON = arg('results-json', '') const RESULTS_JSON = arg('results-json', '')
const FINAL_FILES_JSON = arg('final-files-json', '') const FINAL_FILES_JSON = arg('final-files-json', '')
const SINCE_DAYS = Number(arg('since-days', process.env.MNEMAZINE_POSTRUN_SINCE_DAYS || '7')) const SINCE_DAYS = Number(arg('since-days', process.env.MNEMAZINE_POSTRUN_SINCE_DAYS || '7'))
function lastRunState() {
const file = path.join(ROOT, '.mnemazine/state/last-run.json')
try { return JSON.parse(fsSync.readFileSync(file, 'utf8')) } catch { return null }
}
const LAST_RUN = lastRunState()
const CHANGED_SINCE = arg('changed-since', LAST_RUN?.started_at || '')
const DEFAULT_LOGS = (process.env.MNEMAZINE_POSTRUN_LOGS || '') const DEFAULT_LOGS = (process.env.MNEMAZINE_POSTRUN_LOGS || '')
.split(',') .split(',')
@@ -56,9 +70,37 @@ function clean(text) {
function present(text) { function present(text) {
return String(text || '') return String(text || '')
.replace(/\bcandidate capability\b/gi, 'кандидат в рабочие возможности')
.replace(/\bcapability review queue\b/gi, 'очередь разбора возможностей')
.replace(/\bworkflow-fit\b/gi, 'пригодность для конкретного сценария')
.replace(/\bworkflow\b/gi, 'рабочий сценарий')
.replace(/с одним реальным рабочий сценарий/gi, 'с одним реальным рабочим сценарием')
.replace(/если пригодность для конкретного сценария конкретный/gi, 'если есть понятная пригодность для конкретного сценария')
.replace(/с одним критерием принять\/отклонить/gi, 'с одним критерием: принять или отклонить')
.replace(/Перед пробный запуск проверить/gi, 'Перед пробным запуском проверить')
.replace(/режим только чтение режим/gi, 'режим только чтения')
.replace(/список разрешённых доменов доменов/gi, 'список разрешённых доменов')
.replace(/web-рабочий сценарий/gi, 'браузерный сценарий')
.replace(/черновик короткое видео/gi, 'черновик короткого видео')
.replace(/\bfit под конкретный рабочий сценарий\b/gi, 'пригодность к конкретному рабочему сценарию')
.replace(/\blocal trial\b/gi, 'локальный пробный запуск')
.replace(/\btrial\b/gi, 'пробный запуск')
.replace(/\breview diff\b/gi, 'проверку изменений кода')
.replace(/\bweb-workflow\b/gi, 'браузерный сценарий')
.replace(/\bshort-form video\b/gi, 'короткое видео')
.replace(/\bhook\/CTA\b/gi, 'крючок и призыв к действию')
.replace(/\bread-only\b/gi, 'режим только чтение')
.replace(/\ballowlist\b/gi, 'список разрешённых доменов')
.replace(/\bregistry\/ledger\b/gi, 'реестр и журнал')
.replace(/\s+(?:src|href|alt|title)=["'][^"']*["']/gi, '')
.replace(/\b(?:src|href|alt|title)=["'][^"']*["']/gi, '')
.replace(/<[^>]+>/g, ' ')
.replace(/\bIMG_\d+(?:\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4))?\b/gi, 'локальный визуальный источник') .replace(/\bIMG_\d+(?:\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4))?\b/gi, 'локальный визуальный источник')
.replace(/\btemp_image[_-][\w.-]+/gi, 'локальный визуальный источник') .replace(/\btemp_image[_-][\w.-]+/gi, 'локальный визуальный источник')
.replace(/\b[\w.-]+\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4)\b/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(/\s+/g, ' ')
.trim() .trim()
} }
@@ -75,7 +117,7 @@ function titleOf(text, file) {
function extractSection(text, names) { function extractSection(text, names) {
for (const name of names) { for (const name of names) {
const re = new RegExp(`^##\\s+${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:\\s|$)[^\\n]*\\n([\\s\\S]*?)(?=^##\\s+|\\z)`, 'mi') const re = new RegExp(`^##\\s+${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:\\s|$)[^\\n]*\\n([\\s\\S]*?)(?=^##\\s+|(?![\\s\\S]))`, 'mi')
const hit = text.match(re) const hit = text.match(re)
if (hit) return clean(hit[1]) if (hit) return clean(hit[1])
} }
@@ -137,15 +179,22 @@ async function loadResults() {
if (obj) rows.push(obj) if (obj) rows.push(obj)
} }
} }
if (!rows.length) rows.push(...await loadRecentVaultResults(SINCE_DAYS)) if (!rows.length) rows.push(...await loadRecentVaultResults(SINCE_DAYS, CHANGED_SINCE))
const byGroup = new Map() const byGroup = new Map()
for (const row of rows) byGroup.set(row.group_id, row) for (const row of rows) byGroup.set(row.group_id, row)
return [...byGroup.values()] return [...byGroup.values()]
} }
async function loadRecentVaultResults(days) { function sinceMs(value) {
if (!value) return 0
if (/^\d+(?:\.\d+)?$/.test(String(value))) return Number(value)
const parsed = Date.parse(value)
return Number.isFinite(parsed) ? parsed : 0
}
async function loadRecentVaultResults(days, changedSince = '') {
const files = await walk(VAULT) const files = await walk(VAULT)
const cutoff = Date.now() - Math.max(1, Number(days) || 7) * 24 * 60 * 60 * 1000 const cutoff = sinceMs(changedSince) || (Date.now() - Math.max(1, Number(days) || 7) * 24 * 60 * 60 * 1000)
const rows = [] const rows = []
for (const file of files) { for (const file of files) {
const stat = await fs.stat(file).catch(() => null) const stat = await fs.stat(file).catch(() => null)
@@ -213,8 +262,8 @@ function clusterOf(record) {
if (text.includes('investor') || text.includes('cap table') || text.includes('esop') || text.includes('founder') || text.includes('shareholder')) return 'Investor-ready startup' if (text.includes('investor') || text.includes('cap table') || text.includes('esop') || text.includes('founder') || text.includes('shareholder')) return 'Investor-ready startup'
if (text.includes('agent') || text.includes('codex') || text.includes('claude') || text.includes('mnemazine') || text.includes('graph')) return 'Agent OS' if (text.includes('agent') || text.includes('codex') || text.includes('claude') || text.includes('mnemazine') || text.includes('graph')) return 'Agent OS'
if (text.includes('quick wins') || text.includes('support') || text.includes('sales') || text.includes('onboarding')) return 'AI business offers' if (text.includes('quick wins') || text.includes('support') || text.includes('sales') || text.includes('onboarding')) return 'AI business offers'
if (text.includes('prompt') || text.includes('промпт') || text.includes('slash')) return 'Prompts / commands' if (text.includes('prompt') || text.includes('промпт') || text.includes('slash')) return 'Промпты и команды'
return 'Other useful knowledge' return 'Прочие полезные знания'
} }
async function buildRecords(results) { async function buildRecords(results) {
@@ -246,9 +295,9 @@ async function buildRecords(results) {
const text = await fs.readFile(noteFile, 'utf8') const text = await fs.readFile(noteFile, 'utf8')
record.title ||= titleOf(text, noteFile) record.title ||= titleOf(text, noteFile)
record.section ||= sectionOf(noteFile) record.section ||= sectionOf(noteFile)
record.summary ||= firstPara(extractSection(text, ['Короткий ответ', 'Что это и зачем', 'Что это', 'Суть', 'Полное объяснение', 'What This Is']), 430) record.summary ||= firstPara(extractSection(text, ['Короткий ответ', 'Что это и зачем', 'Что это', 'Что обещает README', 'Риск', 'Решение', 'Суть', 'Полное объяснение', 'What This Is']), 430)
record.helps ||= firstPara(extractSection(text, ['Как поможет мне', '🎯 Как поможет мне', 'Как это поможет мне', 'Зачем мне']), 340) record.helps ||= firstPara(extractSection(text, ['Как использовать', 'Как поможет мне', '🎯 Как поможет мне', 'Как это поможет мне', 'Зачем мне', 'Что добавила Mnemazine']), 340)
record.next ||= firstPara(extractSection(text, ['Следующий ход', 'Следующее действие', 'Next Action']), 260) record.next ||= firstPara(extractSection(text, ['Следующий ход', 'Следующее действие', 'Next Action']), 260).replace(/^[-*]\s*/, '')
record.atoms = record.atoms.length ? record.atoms : splitAtoms(text) record.atoms = record.atoms.length ? record.atoms : splitAtoms(text)
} else { } else {
record.title ||= raw ? firstPara(raw, 100) : result.group_id record.title ||= raw ? firstPara(raw, 100) : result.group_id
@@ -270,12 +319,13 @@ async function buildRecords(results) {
} }
function outcomeLabel(record) { function outcomeLabel(record) {
return Object.entries(record.outcomes).map(([k, v]) => `${k}:${v}`).join(', ') const names = { note: 'заметка', atoms: 'атомы', dup: 'дубль' }
return Object.entries(record.outcomes).map(([k, v]) => `${names[k] || k}:${v}`).join(', ')
} }
function noteLink(record) { function noteLink(record) {
if (!record.file) return '—' if (!record.file) return '—'
return `[${present(path.basename(record.file, '.md')) || 'Локальное знание'}](${record.file})` return `[${present(record.title) || 'Локальное знание'}](${record.file})`
} }
function top20(records) { function top20(records) {
@@ -351,7 +401,7 @@ function graphSvg(modules) {
function mermaid(records) { function mermaid(records) {
const clusters = groupByCluster(records.filter(r => r.outcomes.note || r.outcomes.atoms)) const clusters = groupByCluster(records.filter(r => r.outcomes.note || r.outcomes.atoms))
const lines = ['mindmap', ' root((Mnemazine batch))'] const lines = ['mindmap', ' root((Прогон Mnemazine))']
for (const [cluster, items] of clusters) { for (const [cluster, items] of clusters) {
lines.push(` ${cluster.replace(/[()]/g, '')}`) lines.push(` ${cluster.replace(/[()]/g, '')}`)
for (const item of items.slice(0, 8)) { for (const item of items.slice(0, 8)) {
@@ -373,9 +423,9 @@ function markdown({ records, results, mdPath, htmlPath }) {
const dupRows = dup const dupRows = dup
.sort((a, b) => b.files - a.files) .sort((a, b) => b.files - a.files)
.map(r => `| ${mdEsc(r.cluster)} | ${r.files} | ${noteLink(r)} | ${mdEsc(r.summary || r.title)} |`) .map(r => `| ${mdEsc(r.cluster)} | ${r.files} | ${noteLink(r)} | ${mdEsc(r.summary || r.title)} |`)
return `# Mnemazine visual knowledge report return `# Отчёт Mnemazine по знаниям
Run: ${RUN_ID} Прогон: ${RUN_ID}
HTML: ${htmlPath} HTML: ${htmlPath}
## Сводка ## Сводка
@@ -450,7 +500,7 @@ main{padding:20px max(16px,4.5vw) 64px}.minute{display:grid;grid-template-column
<body> <body>
<header class="hero"> <header class="hero">
<div> <div>
<div class="eyebrow">Mnemazine post-run knowledge report</div> <div class="eyebrow">Отчёт Mnemazine после прогона</div>
<h1>Минутная карта знаний</h1> <h1>Минутная карта знаний</h1>
<p class="lead">Сначала модули и атомы, потом действия. Подробный текст спрятан ниже, чтобы быстро понять, что появилось и зачем это нужно.</p> <p class="lead">Сначала модули и атомы, потом действия. Подробный текст спрятан ниже, чтобы быстро понять, что появилось и зачем это нужно.</p>
<div class="stats"> <div class="stats">
@@ -466,7 +516,7 @@ main{padding:20px max(16px,4.5vw) 64px}.minute{display:grid;grid-template-column
<div class="panel"> <div class="panel">
<h2>Блок-схема</h2> <h2>Блок-схема</h2>
${graphSvg(topModules)} ${graphSvg(topModules)}
<p>Синтез: источники и проверка сведены в модули. Применение видно через действия, риск — через дубли, неизвестные и слабые извлечения.</p> <p>Синтез: источники и проверка сведены в модули. Применение видно через действия, риск - через дубли, неизвестные и слабые извлечения.</p>
<p><a href="#modules">Источники</a> · <a href="#actions">Где применить</a> · <a href="#details">Проверка и риск</a></p> <p><a href="#modules">Источники</a> · <a href="#actions">Где применить</a> · <a href="#details">Проверка и риск</a></p>
</div> </div>
<div class="panel" id="actions"> <div class="panel" id="actions">
@@ -482,9 +532,9 @@ main{padding:20px max(16px,4.5vw) 64px}.minute{display:grid;grid-template-column
<section class="section-title"><h2>Топ-20 к действию</h2><p>Полный рекомендуемый порядок.</p></section> <section class="section-title"><h2>Топ-20 к действию</h2><p>Полный рекомендуемый порядок.</p></section>
<section class="cards">${actions.map((item, i) => `<article class="card"><div class="meta"><span class="tag">#${i + 1}</span><span class="tag">${esc(item.cluster)}</span></div><h3>${esc(item.title)}</h3><p>${esc(item.next)}</p></article>`).join('')}</section> <section class="cards">${actions.map((item, i) => `<article class="card"><div class="meta"><span class="tag">#${i + 1}</span><span class="tag">${esc(item.cluster)}</span></div><h3>${esc(item.title)}</h3><p>${esc(item.next)}</p></article>`).join('')}</section>
<section class="section-title"><h2>Новые и обновленные знания</h2><p>Архивная часть отчёта.</p></section> <section class="section-title"><h2>Новые и обновленные знания</h2><p>Архивная часть отчёта.</p></section>
<section class="cards">${fresh.sort((a, b) => b.score - a.score).map(item => `<article class="card"><div class="meta"><span class="tag">${esc(item.cluster)}</span><span class="tag">${esc(outcomeLabel(item))}</span><span class="tag">${item.files} files</span></div><h3>${item.file ? `<a href="file://${esc(item.file)}">${esc(item.title)}</a>` : esc(item.title)}</h3><p>${esc(brief(item.summary || 'Описание не найдено, смотри ноту.', 180))}</p><p><strong>Как полезно:</strong> ${esc(brief(item.helps || 'Привязать к ближайшему проекту.', 160))}</p></article>`).join('')}</section> <section class="cards">${fresh.sort((a, b) => b.score - a.score).map(item => `<article class="card"><div class="meta"><span class="tag">${esc(item.cluster)}</span><span class="tag">${esc(outcomeLabel(item))}</span><span class="tag">${item.files} файлов</span></div><h3>${item.file ? `<a href="file://${esc(item.file)}">${esc(item.title)}</a>` : esc(item.title)}</h3><p>${esc(brief(item.summary || 'Описание не найдено, смотри ноту.', 180))}</p><p><strong>Как полезно:</strong> ${esc(brief(item.helps || 'Привязать к ближайшему проекту.', 160))}</p></article>`).join('')}</section>
<section class="section-title"><h2>Дубли без потерь</h2><p>Материалы, которые подтвердили уже существующие знания.</p></section> <section class="section-title"><h2>Дубли без потерь</h2><p>Материалы, которые подтвердили уже существующие знания.</p></section>
<section class="dups">${dup.sort((a, b) => b.files - a.files).map(item => `<article class="dup"><b>${esc(item.title)}</b><span>${esc(item.cluster)} · ${item.files} files · ${esc(outcomeLabel(item))}</span></article>`).join('')}</section> <section class="dups">${dup.sort((a, b) => b.files - a.files).map(item => `<article class="dup"><b>${esc(item.title)}</b><span>${esc(item.cluster)} · ${item.files} файлов · ${esc(outcomeLabel(item))}</span></article>`).join('')}</section>
</div> </div>
</details> </details>
</main> </main>
+2 -1
View File
@@ -5,6 +5,7 @@ import path from 'node:path'
import os from 'node:os' import os from 'node:os'
import { spawn } from 'node:child_process' import { spawn } from 'node:child_process'
import { graphStats as normalizedGraphStats, mergeGraphObjects, readGraph, writeGraph } from './mnemazine-graph-utils.mjs' import { graphStats as normalizedGraphStats, mergeGraphObjects, readGraph, writeGraph } from './mnemazine-graph-utils.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
const argv = process.argv.slice(2) const argv = process.argv.slice(2)
@@ -23,7 +24,7 @@ const CONFIG_PATH = path.join(ROOT, 'config', 'graphify-refresh.json')
const CONFIG = existsSync(CONFIG_PATH) const CONFIG = existsSync(CONFIG_PATH)
? JSON.parse(readFileSync(CONFIG_PATH, 'utf8')) ? JSON.parse(readFileSync(CONFIG_PATH, 'utf8'))
: {} : {}
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault'))) const VAULT = resolveVault({ cli: arg('vault') })
const MODE = arg('mode', 'auto') const MODE = arg('mode', 'auto')
const BACKEND = arg('backend', process.env.MNEMAZINE_GRAPHIFY_BACKEND || CONFIG.backend || 'ollama') const BACKEND = arg('backend', process.env.MNEMAZINE_GRAPHIFY_BACKEND || CONFIG.backend || 'ollama')
const CONFIG_BACKEND = CONFIG.backend || 'ollama' const CONFIG_BACKEND = CONFIG.backend || 'ollama'
+191 -8
View File
@@ -53,6 +53,8 @@ async function listFiles(dir) {
async function checkSyntax() { async function checkSyntax() {
const scripts = [ const scripts = [
'scripts/mnemazine-run.mjs', 'scripts/mnemazine-run.mjs',
'scripts/mnemazine-paths.mjs',
'scripts/mnemazine-doctor.mjs',
'scripts/mnemazine-vault-quality-gate.mjs', 'scripts/mnemazine-vault-quality-gate.mjs',
'scripts/mnemazine-refresh-graphify.mjs', 'scripts/mnemazine-refresh-graphify.mjs',
'scripts/mnemazine-refresh-graphify-smoke.mjs', 'scripts/mnemazine-refresh-graphify-smoke.mjs',
@@ -69,7 +71,9 @@ async function checkSyntax() {
'scripts/mnemazine-weekly-state.mjs', 'scripts/mnemazine-weekly-state.mjs',
'scripts/mnemazine-postrun-knowledge-report.mjs', 'scripts/mnemazine-postrun-knowledge-report.mjs',
'scripts/mnemazine-digest.mjs', 'scripts/mnemazine-digest.mjs',
'scripts/mnemazine-tool-decision-queue.mjs',
'scripts/mnemazine-report-quality-gate.mjs', 'scripts/mnemazine-report-quality-gate.mjs',
'scripts/mnemazine-human-layer-gate.mjs',
'scripts/mnemazine-complete-check.mjs', 'scripts/mnemazine-complete-check.mjs',
'scripts/mnemazine-live-status.mjs', 'scripts/mnemazine-live-status.mjs',
'scripts/mnemazine-release-check.mjs' 'scripts/mnemazine-release-check.mjs'
@@ -164,6 +168,7 @@ async function demoSmoke() {
await fs.mkdir(scripts, { recursive: true }) await fs.mkdir(scripts, { recursive: true })
await fs.copyFile(path.join(ROOT, 'demo/inbox/example-guide.md'), path.join(inbox, 'example-guide.md')) 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.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-vault-quality-gate.mjs'), path.join(scripts, 'mnemazine-vault-quality-gate.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-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-llm.mjs'), path.join(scripts, 'mnemazine-llm.mjs'))
@@ -231,7 +236,12 @@ async function strictArchiveGateSmoke() {
await fs.mkdir(path.join(vault, '01 Concepts'), { recursive: true }) await fs.mkdir(path.join(vault, '01 Concepts'), { recursive: true })
await fs.mkdir(scripts, { recursive: true }) await fs.mkdir(scripts, { recursive: true })
await fs.mkdir(extracts, { 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-vault-quality-gate.mjs'), path.join(scripts, 'mnemazine-vault-quality-gate.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-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-codex.mjs'), path.join(scripts, 'mnemazine-codex.mjs'))
const source = 'MarkItDown converts Office/PDF/image inputs into Markdown for LLM pipelines. This cached source has enough text for synthesis.' const source = 'MarkItDown converts Office/PDF/image inputs into Markdown for LLM pipelines. This cached source has enough text for synthesis.'
const hash = sha256Text(source) const hash = sha256Text(source)
@@ -295,13 +305,19 @@ status: "final"
enrichment: "external-research" enrichment: "external-research"
--- ---
# Verified enriched cached note # Проверенная cached note
## What This Is ## Что это
MarkItDown is verified here as reusable knowledge, not raw OCR. MarkItDown здесь зафиксирован как проверенное переиспользуемое знание, а не голый распознанный текст.
## Source ## Как использовать
- Держать source refs как доказательство происхождения.
- Проверять публичный репозиторий перед рекомендацией.
- Архивировать исходник только после verified final note.
## Источники
Local source refs: Local source refs:
- ${ref} - ${ref}
@@ -309,11 +325,20 @@ Local source refs:
Public/source expansion: Public/source expansion:
- Microsoft MarkItDown: https://github.com/microsoft/markitdown - Microsoft MarkItDown: https://github.com/microsoft/markitdown
## Enrichment ## Расширение знания
External facts added before atomization: External facts added before atomization:
- Microsoft maintains MarkItDown as an open-source file-to-Markdown converter. - Microsoft maintains MarkItDown as an open-source file-to-Markdown converter.
- The public repository documents optional extras for additional input formats. - The public repository documents optional extras for additional input formats.
## Проверка
- Статус: verified.
- Источник сверяется с публичным GitHub URL.
## Следующее действие
- Держать эту ноту как smoke fixture для strict archive gate.
`) `)
await must('strict archive gate smoke:good', process.execPath, ['scripts/mnemazine-run.mjs'], { await must('strict archive gate smoke:good', process.execPath, ['scripts/mnemazine-run.mjs'], {
env: { env: {
@@ -336,11 +361,62 @@ async function qualityAndPublicChecks() {
await must('weekly state selftest', process.execPath, ['scripts/mnemazine-weekly-state.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('live status selftest', process.execPath, ['scripts/mnemazine-live-status.mjs', '--selftest'])
await must('demo vault quality', 'npm', ['run', 'quality', '--', '--vault', 'demo/vault']) await must('demo vault quality', 'npm', ['run', 'quality', '--', '--vault', 'demo/vault'])
await toolDecisionQueueSmoke()
await reportQualityGateSmoke() await reportQualityGateSmoke()
await humanLayerGateSmoke()
await completeGateSmoke() await completeGateSmoke()
await must('public release scan', 'npm', ['run', 'public-check']) await must('public release scan', 'npm', ['run', 'public-check'])
} }
async function toolDecisionQueueSmoke() {
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-tool-queue-'))
const vault = path.join(temp, 'vault')
const concepts = path.join(vault, '01 Concepts')
await fs.mkdir(concepts, { recursive: true })
const started = new Date(Date.now() - 1000).toISOString()
await fs.writeFile(path.join(concepts, 'aider.md'), `---
title: "Aider-AI/aider: решение для Mnemazine"
type: "knowledge-note"
verified: true
verification_status: "verified"
status: "final"
---
# Aider-AI/aider: решение для Mnemazine
## Что это
CLI-инструмент для разработки с LLM внутри локального git-репозитория.
## Решение
Хранить как кандидата в рабочие возможности, не устанавливать автоматически.
## Что добавила Mnemazine
- Метаданные GitHub: 1 звезда, 1 форк, 1 issue, MIT, основной язык Python.
- Свежесть репозитория: основная ветка main, последний push 2026-06-24, последний release v1.
## Источники
- https://github.com/Aider-AI/aider
## Проверка
- Статус: verified.
## Следующее действие
- Добавить в очередь разбора возможностей.
`, 'utf8')
await must('tool decision queue smoke', process.execPath, ['scripts/mnemazine-tool-decision-queue.mjs', '--vault', vault, '--changed-since', started])
const out = path.join(vault, '08 AI и Инструменты/Tools/Очередь разбора инструментов.md')
const body = await fs.readFile(out, 'utf8')
for (const token of ['# Очередь разбора инструментов', 'Aider', 'Пробный запуск', 'берём, откладываем, забываем']) {
if (!body.includes(token)) throw new Error(`tool queue smoke failed: missing ${token}`)
}
}
async function completeGateSmoke() { async function completeGateSmoke() {
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-complete-gate-')) const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-complete-gate-'))
const inbox = path.join(temp, 'inbox') const inbox = path.join(temp, 'inbox')
@@ -352,8 +428,9 @@ async function completeGateSmoke() {
await fs.writeFile(path.join(reports, 'complete-smoke.html'), [ await fs.writeFile(path.join(reports, 'complete-smoke.html'), [
'<!doctype html><html><body>', '<!doctype html><html><body>',
'<main data-knowledge-atom="complete-smoke">', '<main data-knowledge-atom="complete-smoke">',
'<h1>Синтезированные знания</h1>', '<h1>Отчёт Mnemazine после прогона</h1>',
'<section><h2>Синтез</h2><p>Проверенная идея после обработки.</p></section>', '<section><h2>Новые и обновленные знания</h2><p>Свежий слой знаний на русском языке: понятно, что обработано, что проверено и какой следующий шаг нужен человеку.</p></section>',
'<section><h2>Синтез</h2><p>Проверенная идея после обработки превращена в короткий вывод, а не оставлена как сырой захват.</p></section>',
'<section><h2>Источники</h2>', '<section><h2>Источники</h2>',
'<a href="https://example.com/source-a">source a</a>', '<a href="https://example.com/source-a">source a</a>',
'<a href="https://example.com/source-b">source b</a>', '<a href="https://example.com/source-b">source b</a>',
@@ -363,7 +440,25 @@ async function completeGateSmoke() {
'<section><h2>Следующее действие</h2><p>Запустить gate.</p></section>', '<section><h2>Следующее действие</h2><p>Запустить gate.</p></section>',
'</main></body></html>' '</main></body></html>'
].join(''), 'utf8') ].join(''), 'utf8')
await fs.writeFile(path.join(state, 'last-action-brief.md'), '# Complete Gate Smoke\n\n- Next action: keep release gate green.\n', 'utf8') await fs.writeFile(path.join(state, 'last-action-brief.md'), [
'# Короткий отчёт Mnemazine — smoke',
'',
'## Статус',
'',
'- Inbox: 0',
'- Гейт качества: ok',
'',
'## Следующие действия',
'',
'- Держать release gate зелёным.'
].join('\n'), 'utf8')
await fs.writeFile(path.join(state, 'last-run.json'), JSON.stringify({
ok: true,
started_at: new Date().toISOString(),
deep: false,
processed: 0,
synthesize: { skipped: true }
}, null, 2), 'utf8')
await must('complete gate smoke', process.execPath, ['scripts/mnemazine-complete-check.mjs'], { await must('complete gate smoke', process.execPath, ['scripts/mnemazine-complete-check.mjs'], {
env: { env: {
MNEMAZINE_VAULT: path.join(ROOT, 'demo/vault'), MNEMAZINE_VAULT: path.join(ROOT, 'demo/vault'),
@@ -404,6 +499,94 @@ async function reportQualityGateSmoke() {
await must('report quality gate smoke:good', process.execPath, ['scripts/mnemazine-report-quality-gate.mjs', '--report', good]) await must('report quality gate smoke:good', process.execPath, ['scripts/mnemazine-report-quality-gate.mjs', '--report', good])
} }
async function humanLayerGateSmoke() {
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-human-layer-'))
const vault = path.join(temp, 'vault')
const reports = path.join(temp, 'reports')
const state = path.join(temp, 'state')
const concepts = path.join(vault, '01 Concepts')
await fs.mkdir(concepts, { 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"
status: "final"
verified: true
verification_status: "verified"
---
# Хорошая русская заметка
## Что это
Это проверенное знание: оно объясняет смысл, применение, источник и следующий шаг обычным русским языком.
## Как использовать
- Читать вывод, а не сырой захват.
- Проверять источник перед применением.
- Превращать вывод в маленькое действие.
## Источники
- local-media:humanlayersmoke
- https://example.com/source
## Проверка
- Статус: verified.
- Сырой HTML исключён из финального слоя.
## Следующее действие
- Оставить human-layer gate в release-check.
`, 'utf8')
const report = path.join(reports, 'good.html')
await fs.writeFile(report, [
'<!doctype html><html><body>',
'<h1>Отчёт Mnemazine после прогона</h1>',
'<section><h2>Новые и обновленные знания</h2><p>Понятная сводка объясняет, что появилось, зачем это нужно, где источник и какое действие взять следующим шагом.</p></section>',
'<section><h2>Проверка и риск</h2><p>Сырой HTML исключён из пользовательского текста, а непроверенные утверждения остаются помеченными до ручной проверки.</p></section>',
'<section><h2>Следующее действие</h2><p>Запустить gate и убедиться, что отчёт читается человеком без знания внутреннего пайплайна.</p></section>',
'</body></html>'
].join(''), 'utf8')
await fs.writeFile(path.join(state, 'last-action-brief.md'), [
'# Короткий отчёт Mnemazine — smoke',
'',
'## Статус',
'',
'- Inbox: 0',
'',
'## Следующие действия',
'',
'- Проверить human-layer gate.'
].join('\n'), 'utf8')
await must('human layer gate smoke:good', process.execPath, ['scripts/mnemazine-human-layer-gate.mjs', '--changed-since', started, '--report', report], {
env: {
MNEMAZINE_VAULT: vault,
MNEMAZINE_REPORTS: reports,
MNEMAZINE_STATE: state
}
})
await fs.writeFile(path.join(concepts, 'bad.md'), `# Bad note
## What This Is
README signal: src="https://example.com/badge.svg"
`, 'utf8')
const bad = await run(process.execPath, ['scripts/mnemazine-human-layer-gate.mjs', '--changed-since', started, '--report', report], {
env: {
MNEMAZINE_VAULT: vault,
MNEMAZINE_REPORTS: reports,
MNEMAZINE_STATE: state
}
})
if (bad.code === 0) throw new Error('human layer gate smoke failed: bad note passed')
}
async function searchEvalSmoke() { async function searchEvalSmoke() {
// Tier A only (0 tokens): recall/anti-noise of the KB search skill. Tier B // Tier A only (0 tokens): recall/anti-noise of the KB search skill. Tier B
// (LLM judge) is opt-in via `npm run search:eval -- --deep`, not in the gate. // (LLM judge) is opt-in via `npm run search:eval -- --deep`, not in the gate.
+108 -17
View File
@@ -5,10 +5,11 @@ import path from 'node:path'
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { spawnSync } from 'node:child_process' import { spawnSync } from 'node:child_process'
import { llmAvailable, llmText } from './mnemazine-llm.mjs' import { llmAvailable, llmText } from './mnemazine-llm.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox') const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault') const VAULT = resolveVault()
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports') const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state') const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
const CACHE = process.env.MNEMAZINE_CACHE || path.join(ROOT, '.mnemazine/cache/processed-hashes.json') const CACHE = process.env.MNEMAZINE_CACHE || path.join(ROOT, '.mnemazine/cache/processed-hashes.json')
@@ -378,6 +379,25 @@ function parseJsonOutput(text) {
try { return JSON.parse(raw.slice(start, end + 1)) } catch { return null } try { return JSON.parse(raw.slice(start, end + 1)) } catch { return null }
} }
function failRunState(payload, code = 1) {
return writeRunState({
ok: false,
inbox: payload.inbox,
processed: payload.processed,
cached_only: payload.cached_only,
failed: payload.failed,
deep: DEEP,
deep_required: REQUIRE_DEEP,
enrich_required: ENRICH_REQUIRED,
strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE,
synthesize: payload.synthesize,
vault: VAULT,
started_at: payload.started_at,
finished_at: new Date().toISOString(),
...payload.extra
}).then(() => process.exit(code))
}
async function writeRunState(state) { async function writeRunState(state) {
await ensureDir(STATE) await ensureDir(STATE)
await fs.writeFile(path.join(STATE, 'last-run.json'), `${JSON.stringify(state, null, 2)}\n`, 'utf8') await fs.writeFile(path.join(STATE, 'last-run.json'), `${JSON.stringify(state, null, 2)}\n`, 'utf8')
@@ -396,6 +416,42 @@ function validateDeepRun({ synthesize, processed }) {
async function recentNotes(limit = 8) { async function recentNotes(limit = 8) {
const notes = [] const notes = []
function cleanAction(text) {
return String(text || '')
.split(/\n\s*\n/)[0]
.replace(/^[-*]\s*/, '')
.replace(/\s+/g, ' ')
.trim()
}
function section(text, names) {
for (const name of names) {
const re = new RegExp(`^##\\s+${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:\\s|$)[^\\n]*\\n([\\s\\S]*?)(?=^##\\s+|(?![\\s\\S]))`, 'mi')
const hit = text.match(re)
if (hit) return cleanAction(hit[1])
}
return ''
}
function present(text) {
return String(text || '')
.replace(/Security, review, and trust boundaries: source-backed operating pattern/g, 'Безопасность, ревью и границы доверия: проверенный рабочий паттерн')
.replace(/Miscellaneous knowledge signals: source-backed operating pattern/g, 'Прочие сигналы знаний: проверенный рабочий паттерн')
.replace(/Knowledge memory, vaults, and synthesis loops: source-backed operating pattern/g, 'Память знаний, vault и циклы синтеза: проверенный рабочий паттерн')
.replace(/Design systems and frontend quality: source-backed operating pattern/g, 'Дизайн-системы и качество фронтенда: проверенный рабочий паттерн')
.replace(/Mnemazine routing decision/g, 'решение для Mnemazine')
.replace(/operational risk and maintenance check/g, 'риск эксплуатации и поддержки')
.replace(/README-backed capability summary/g, 'что реально обещает README')
.replace(/Add a unified publish gate: vault quality, report quality, secret scan, diff review\./g, 'Собрать единый publish gate: качество vault, качество отчёта, поиск секретов и ревью изменений.')
.replace(/Manually review miscellaneous signals and either promote or forget them\./g, 'Вручную разобрать misc-сигналы: повысить до знания или забыть.')
.replace(/Automate nightly connection finding and weekly synthesis from final atoms\./g, 'Автоматизировать ночной поиск связей и weekly synthesis по финальным атомам.')
.replace(/Create browser smoke for generated HTML reports\./g, 'Сделать browser-smoke для сгенерированных HTML-отчётов.')
.replace(/Add ([^ ]+\/[^ ]+) to the capability review queue with one accept\/reject criterion\./g, 'Добавить $1 в очередь разбора возможностей с одним критерием: принять или отклонить.')
.replace(/Run a small local trial for ([^ ]+) only if the workflow fit is concrete\./g, 'Запустить маленький локальный пробный запуск для $1 только если понятна пригодность к рабочему сценарию.')
.replace(/Map ([^ ]+) README features to one concrete local workflow before installing\./g, 'Связать возможности README $1 с одним конкретным рабочим сценарием до установки.')
.replace(/с одним реальным рабочий сценарий/gi, 'с одним реальным рабочим сценарием')
.replace(/если пригодность для конкретного сценария конкретный/gi, 'если есть понятная пригодность для конкретного сценария')
.replace(/с одним критерием принять\/отклонить/gi, 'с одним критерием: принять или отклонить')
.trim()
}
async function walk(dir) { async function walk(dir) {
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) { for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (item.name.startsWith('graphify-out')) continue if (item.name.startsWith('graphify-out')) continue
@@ -404,8 +460,8 @@ async function recentNotes(limit = 8) {
else if (item.isFile() && item.name.endsWith('.md')) { else if (item.isFile() && item.name.endsWith('.md')) {
const stat = await fs.stat(file) const stat = await fs.stat(file)
const text = await fs.readFile(file, 'utf8').catch(() => '') const text = await fs.readFile(file, 'utf8').catch(() => '')
const title = text.match(/^#\s+(.+)$/m)?.[1]?.trim() || path.basename(file, '.md') const title = present(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() || '' const action = present(section(text, ['Следующее действие', 'Next 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 }) notes.push({ file: path.relative(VAULT, file), title, action, mtimeMs: stat.mtimeMs })
} }
} }
@@ -421,22 +477,22 @@ async function writeActionBrief(finishResult) {
const inboxEntries = await fs.readdir(INBOX, { withFileTypes: true }).catch(() => []) const inboxEntries = await fs.readdir(INBOX, { withFileTypes: true }).catch(() => [])
const activeInboxCount = inboxEntries.filter(entry => entry.isFile() && !entry.name.startsWith('.')).length const activeInboxCount = inboxEntries.filter(entry => entry.isFile() && !entry.name.startsWith('.')).length
const lines = [ const lines = [
`# Mnemazine Action Brief — ${new Date().toISOString().slice(0, 10)}`, `# Короткий отчёт Mnemazine — ${new Date().toISOString().slice(0, 10)}`,
'', '',
'## Status', '## Статус',
'', '',
`- Inbox: ${activeInboxCount}`, `- Inbox: ${activeInboxCount}`,
`- Vault: ${VAULT}`, `- Vault: ${VAULT}`,
`- Quality gate: ${finishResult.quality?.ok ? 'ok' : 'check output'}`, `- Гейт качества: ${finishResult.quality?.ok ? 'ok' : 'проверь вывод'}`,
`- Graph refresh: ${finishResult.graph?.ok ? 'ok' : finishResult.graph?.code === 2 ? 'partial / semantic pending' : finishResult.graph?.skipped ? 'skipped' : 'failed'}`, `- Обновление графа: ${finishResult.graph?.ok ? 'ok' : finishResult.graph?.code === 2 ? 'частично / semantic pending' : finishResult.graph?.skipped ? 'пропущено' : 'failed'}`,
`- Weekly report: ${finishResult.weekly?.ok ? 'ok' : finishResult.weekly?.skipped ? 'skipped' : 'failed'}`, `- Недельный отчёт: ${finishResult.weekly?.ok ? 'ok' : finishResult.weekly?.skipped ? 'пропущен' : 'failed'}`,
`- Report quality: ${finishResult.report_quality?.ok ? 'ok' : finishResult.report_quality?.skipped ? 'skipped' : 'failed'}`, `- Качество отчёта: ${finishResult.report_quality?.ok ? 'ok' : finishResult.report_quality?.skipped ? 'пропущено' : 'failed'}`,
'', '',
'## Next Actions', '## Следующие действия',
'', '',
...(notes.length ...(notes.length
? notes.map(note => `- ${note.title}${note.action ? ` — ${note.action}` : ''} (${note.file})`) ? notes.map(note => `- ${note.title}${note.action ? ` — ${note.action}` : ''} (${note.file})`)
: ['- No recent notes found.']) : ['- Свежие заметки не найдены.'])
] ]
const out = path.join(dir, 'last-action-brief.md') const out = path.join(dir, 'last-action-brief.md')
await fs.writeFile(out, `${lines.join('\n')}\n`, 'utf8') await fs.writeFile(out, `${lines.join('\n')}\n`, 'utf8')
@@ -445,6 +501,7 @@ async function writeActionBrief(finishResult) {
async function finishRun(runStartedAt) { async function finishRun(runStartedAt) {
const result = {} 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.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', 'auto', '--json'])
result.weekly = runLocalNodeScript('mnemazine-weekly-brief-html.mjs') result.weekly = runLocalNodeScript('mnemazine-weekly-brief-html.mjs')
@@ -453,7 +510,13 @@ async function finishRun(runStartedAt) {
? runLocalNodeScript('mnemazine-report-quality-gate.mjs', ['--report', weeklyReport]) ? runLocalNodeScript('mnemazine-report-quality-gate.mjs', ['--report', weeklyReport])
: { skipped: true, reason: 'weekly report path missing' } : { skipped: true, reason: 'weekly report path missing' }
result.brief = await writeActionBrief(result) result.brief = await writeActionBrief(result)
result.visual_report = runLocalNodeScript('mnemazine-postrun-knowledge-report.mjs', ['--run-id', `local-${new Date().toISOString().slice(0, 10)}`, '--since-days', '14']) result.visual_report = runLocalNodeScript('mnemazine-postrun-knowledge-report.mjs', ['--run-id', `local-${new Date().toISOString().slice(0, 10)}`, '--changed-since', runStartedAt])
const visualReport = result.visual_report?.stdout?.match(/"html":\s*"([^"]+)"/)?.[1] || ''
result.human_layer = runLocalNodeScript('mnemazine-human-layer-gate.mjs', [
'--changed-since',
runStartedAt,
...(visualReport ? ['--report', visualReport] : [])
])
return result return result
} }
@@ -568,13 +631,41 @@ async function main() {
console.error(JSON.stringify({ ok: false, failure, missing_final_notes: missingFinalNotes }, null, 2)) console.error(JSON.stringify({ ok: false, failure, missing_final_notes: missingFinalNotes }, null, 2))
process.exit(1) process.exit(1)
} }
// Deep + final stage before archive: Russian humanizer digest + human-layer
// gate. If this fails, sources stay in inbox for a safe retry.
if (DEEP) {
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({
inbox: entries.length,
processed,
cached_only: cachedOnly,
failed,
synthesize,
started_at: runStartedAt,
extra: { failure: 'digest failed before archive' }
}, digest.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(','))
const human = spawnSync(process.execPath, humanArgs, { encoding: 'utf8', env: process.env })
if (human.stdout) process.stdout.write(human.stdout)
if (human.stderr) process.stderr.write(human.stderr)
if (human.status !== 0) {
await failRunState({
inbox: entries.length,
processed,
cached_only: cachedOnly,
failed,
synthesize,
started_at: runStartedAt,
extra: { failure: 'human layer gate failed before archive' }
}, human.status || 1)
}
}
const archived = [] const archived = []
for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash)) for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash))
// Deep + final stage: Russian humanizer digest, AFTER the graph so connections
// are real. Writes a Справка into each note + one session summary note.
if (DEEP) {
spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-digest.mjs'), '--changed-since', runStartedAt], { stdio: 'inherit', env: process.env })
}
const finish = FINISH ? await finishRun(runStartedAt) : { skipped: true } 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: 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() }
await writeRunState(result) await writeRunState(result)
+2 -1
View File
@@ -5,6 +5,7 @@ import path from 'node:path'
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { spawn } from 'node:child_process' import { spawn } from 'node:child_process'
import { readGraph, writeGraph, mergeGraphObjects, graphStats } from './mnemazine-graph-utils.mjs' import { readGraph, writeGraph, mergeGraphObjects, graphStats } from './mnemazine-graph-utils.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const CONFIG_PATH = path.join(ROOT, 'config', 'graphify-refresh.json') const CONFIG_PATH = path.join(ROOT, 'config', 'graphify-refresh.json')
@@ -21,7 +22,7 @@ function flag(name) {
return argv.includes(`--${name}`) return argv.includes(`--${name}`)
} }
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault'))) const VAULT = resolveVault({ cli: arg('vault') })
const GRAPH = path.resolve(arg('graph', path.join(VAULT, 'graphify-out/graph.json'))) const GRAPH = path.resolve(arg('graph', path.join(VAULT, 'graphify-out/graph.json')))
const BACKEND = arg('backend', process.env.MNEMAZINE_GRAPHIFY_BACKEND || CONFIG.backend || 'ollama') const BACKEND = arg('backend', process.env.MNEMAZINE_GRAPHIFY_BACKEND || CONFIG.backend || 'ollama')
const MODEL = arg('model', process.env.MNEMAZINE_GRAPHIFY_MODEL || CONFIG.model || 'qwen2.5-coder:7b') const MODEL = arg('model', process.env.MNEMAZINE_GRAPHIFY_MODEL || CONFIG.model || 'qwen2.5-coder:7b')
+2 -1
View File
@@ -3,6 +3,7 @@ import { promises as fs } from 'node:fs'
import { spawn } from 'node:child_process' import { spawn } from 'node:child_process'
import os from 'node:os' import os from 'node:os'
import path from 'node:path' import path from 'node:path'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const argv = process.argv.slice(2) const argv = process.argv.slice(2)
@@ -66,7 +67,7 @@ function runWorker(job) {
} }
async function main() { async function main() {
const vault = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault'))) const vault = resolveVault({ cli: arg('vault') })
const graph = path.resolve(arg('graph', path.join(vault, 'graphify-out/graph.json'))) 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', path.join(vault, `.mnemazine/semantic-shards/${RUN_ID}`)))
const logsDir = path.resolve(arg('logs-dir', path.join(shardsDir, 'logs'))) const logsDir = path.resolve(arg('logs-dir', path.join(shardsDir, 'logs')))
+264 -107
View File
@@ -4,6 +4,7 @@ import path from 'node:path'
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs' import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
import { verifyLocal, verifyDeep, isPublicHttpUrl } from './mnemazine-verify.mjs' import { verifyLocal, verifyDeep, isPublicHttpUrl } from './mnemazine-verify.mjs'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const argv = process.argv.slice(2) const argv = process.argv.slice(2)
@@ -14,7 +15,7 @@ function arg(name, fallback = '') {
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
} }
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault'))) const VAULT = resolveVault({ cli: arg('vault') })
const EXTRACTS = path.resolve(arg('extracts', process.env.MNEMAZINE_EXTRACTS || path.join(ROOT, '.mnemazine/cache/extracted'))) const EXTRACTS = path.resolve(arg('extracts', process.env.MNEMAZINE_EXTRACTS || path.join(ROOT, '.mnemazine/cache/extracted')))
const SESSION = arg('session', new Date().toISOString().slice(0, 10)) const SESSION = arg('session', new Date().toISOString().slice(0, 10))
const MIN_CLUSTER_CHARS = Number(arg('min-cluster-chars', '80')) const MIN_CLUSTER_CHARS = Number(arg('min-cluster-chars', '80'))
@@ -69,55 +70,112 @@ const topicTemplates = {
what: 'Agent systems are reusable operating capabilities: skills, MCP connections, memory, review roles, and harness rules that make an AI assistant behave consistently across tasks.', what: 'Agent systems are reusable operating capabilities: skills, MCP connections, memory, review roles, and harness rules that make an AI assistant behave consistently across tasks.',
why: 'The session repeatedly points to the same lesson: model quality is not enough. Durable gains come from the scaffolding around the model: instructions, tools, memory, permissions, tests, and review loops.', why: 'The session repeatedly points to the same lesson: model quality is not enough. Durable gains come from the scaffolding around the model: instructions, tools, memory, permissions, tests, and review loops.',
how: '- Convert repeated procedures into Skills.\n- Keep tool access behind explicit permission boundaries.\n- Store memory as linked knowledge and decisions, not chat residue.\n- Add gates before publication or irreversible actions.', how: '- Convert repeated procedures into Skills.\n- Keep tool access behind explicit permission boundaries.\n- Store memory as linked knowledge and decisions, not chat residue.\n- Add gates before publication or irreversible actions.',
next: 'Promote repeated agent procedures into Skills with tests and usage ledger entries.' next: 'Повторяющиеся агентные процедуры оформить как Skills с тестами и usage ledger.'
}, },
'knowledge-memory': { 'knowledge-memory': {
what: 'Knowledge memory is an active vault: captures are processed into atoms, atoms are linked to projects and decisions, and weekly synthesis turns memory into action.', what: 'Knowledge memory is an active vault: captures are processed into atoms, atoms are linked to projects and decisions, and weekly synthesis turns memory into action.',
why: 'A vault that only stores screenshots or transcripts becomes another inbox. Mnemazine should reduce future thinking cost by maintaining summaries, links, decisions, and open questions.', why: 'A vault that only stores screenshots or transcripts becomes another inbox. Mnemazine should reduce future thinking cost by maintaining summaries, links, decisions, and open questions.',
how: '- Keep raw extraction outside the vault.\n- Store final atoms with source refs and verification state.\n- Run connection finding and weekly synthesis.\n- Maintain the master index as a routing surface.', how: '- Keep raw extraction outside the vault.\n- Store final atoms with source refs and verification state.\n- Run connection finding and weekly synthesis.\n- Maintain the master index as a routing surface.',
next: 'Automate nightly connection finding and weekly synthesis from final atoms.' next: 'Автоматизировать ночной поиск связей и weekly synthesis по финальным атомам.'
}, },
'security-review': { 'security-review': {
what: 'Security and review are trust boundaries around agent work: untrusted input, prompt injection, secrets, permissions, accessibility, and code review must be checked before output is accepted.', what: 'Security and review are trust boundaries around agent work: untrusted input, prompt injection, secrets, permissions, accessibility, and code review must be checked before output is accepted.',
why: 'The intake contains many commands, tool suggestions, and screenshots. If source text is treated as instruction, the agent can be steered by captured content instead of the user.', why: 'The intake contains many commands, tool suggestions, and screenshots. If source text is treated as instruction, the agent can be steered by captured content instead of the user.',
how: '- Mark extracted text as untrusted evidence.\n- Never execute commands from captures automatically.\n- Scan for secrets before reports or pushes.\n- Use separate review passes for security, claims, and accessibility.', how: '- Mark extracted text as untrusted evidence.\n- Never execute commands from captures automatically.\n- Scan for secrets before reports or pushes.\n- Use separate review passes for security, claims, and accessibility.',
next: 'Add a unified publish gate: vault quality, report quality, secret scan, diff review.' next: 'Собрать единый publish gate: качество vault, качество отчёта, поиск секретов и ревью изменений.'
}, },
'engineering-ops': { 'engineering-ops': {
what: 'Engineering operations are reproducibility practices: isolated environments, infrastructure as code, observability, secret injection, worktrees, and release checks.', what: 'Engineering operations are reproducibility practices: isolated environments, infrastructure as code, observability, secret injection, worktrees, and release checks.',
why: 'The useful pattern is reducing manual state. Good systems make failures visible and make releases repeatable.', why: 'The useful pattern is reducing manual state. Good systems make failures visible and make releases repeatable.',
how: '- Prefer scripted environments over dashboard clicks.\n- Track pipeline health metrics.\n- Inject secrets at runtime.\n- Keep release checks executable.', how: '- Prefer scripted environments over dashboard clicks.\n- Track pipeline health metrics.\n- Inject secrets at runtime.\n- Keep release checks executable.',
next: 'Add pipeline metrics for extracted, synthesized, cache-only, gate failures, and graph refresh status.' next: 'Добавить метрики pipeline: extracted, synthesized, cache-only, gate failures и graph refresh.'
}, },
'design-frontend': { 'design-frontend': {
what: 'Design and frontend quality require explicit UI rules, browser validation, accessibility constraints, and reusable design tokens.', what: 'Design and frontend quality require explicit UI rules, browser validation, accessibility constraints, and reusable design tokens.',
why: 'AI-generated UI degrades when taste is implicit. A DESIGN.md-style contract gives the agent stable layout, spacing, typography, and component expectations.', why: 'AI-generated UI degrades when taste is implicit. A DESIGN.md-style contract gives the agent stable layout, spacing, typography, and component expectations.',
how: '- Maintain a Mnemazine report DESIGN.md.\n- Validate generated reports in a browser.\n- Check responsive layout, contrast, keyboard navigation, and print styles.', how: '- Maintain a Mnemazine report DESIGN.md.\n- Validate generated reports in a browser.\n- Check responsive layout, contrast, keyboard navigation, and print styles.',
next: 'Create browser smoke for generated HTML reports.' next: 'Сделать browser-smoke для сгенерированных HTML-отчётов.'
}, },
'tool-radar': { 'tool-radar': {
what: 'Tool radar is a decision system for open-source tools, not a list of exciting repositories.', what: 'Tool radar is a decision system for open-source tools, not a list of exciting repositories.',
why: 'Screenshots with GitHub stars are weak evidence. Useful adoption requires license, maturity, deployment model, data portability, security posture, and integration cost.', why: 'Screenshots with GitHub stars are weak evidence. Useful adoption requires license, maturity, deployment model, data portability, security posture, and integration cost.',
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.', 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: 'Create a tool-radar schema and populate it from extracted GitHub links.' next: 'Сделать schema для tool-radar и заполнять её из извлечённых GitHub-ссылок.'
}, },
'content-growth': { 'content-growth': {
what: 'Content growth loops treat ads, hooks, CTAs, short-form scripts, and publishing as experiments with feedback.', 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.', why: 'One generated video or ad is not learning. Learning appears when variants, metric, result, and next control are stored.',
how: '- Store hypothesis, channel, variant, metric, result, and decision.\n- Keep winners as controls.\n- Discard weak variants without preserving noise as knowledge.', how: '- Store hypothesis, channel, variant, metric, result, and decision.\n- Keep winners as controls.\n- Discard weak variants without preserving noise as knowledge.',
next: 'Add a Content Experiment note template.' next: 'Добавить шаблон заметки для Content Experiment.'
}, },
'research-workflow': { 'research-workflow': {
what: 'Research workflow means claims are sourced before they become operational knowledge.', what: 'Research workflow means claims are sourced before they become operational knowledge.',
why: 'A source link is not decoration. It should confirm, correct, or constrain the conclusion.', why: 'A source link is not decoration. It should confirm, correct, or constrain the conclusion.',
how: '- Separate extracted claim from verified conclusion.\n- Prefer official docs and primary repositories.\n- Record confidence and what the source changed.', how: '- Separate extracted claim from verified conclusion.\n- Prefer official docs and primary repositories.\n- Record confidence and what the source changed.',
next: 'Add `source_changed_what` to final atom schema.' next: 'Добавить `source_changed_what` в schema финального атома.'
}, },
misc: { misc: {
what: 'Miscellaneous signals are captured items that do not yet form a strong enough reusable cluster.', what: 'Miscellaneous signals are captured items that do not yet form a strong enough reusable cluster.',
why: 'Keeping them separate prevents weak or noisy items from polluting stronger knowledge atoms.', why: 'Keeping them separate prevents weak or noisy items from polluting stronger knowledge atoms.',
how: '- Review manually.\n- Promote only recurring or high-value ideas.\n- Move low-signal material to forget/archive.', how: '- Review manually.\n- Promote only recurring or high-value ideas.\n- Move low-signal material to forget/archive.',
next: 'Manually review miscellaneous signals and either promote or forget them.' next: 'Вручную разобрать misc-сигналы: повысить до знания или забыть.'
}
}
const topicTemplatesRu = {
'agent-systems': {
what: 'Агентная система - это набор повторяемых возможностей вокруг модели: skills, MCP, память, роли ревью, правила harness и release gates.',
why: 'Качество даёт не только модель. Стабильность появляется, когда вокруг неё есть инструменты, память, разрешения, тесты и ревью.',
how: ['Повторяющиеся процедуры превращать в Skills.', 'Доступ к инструментам держать за явными границами разрешений.', 'Память хранить как связанные знания и решения.', 'Перед публикацией держать gate.'],
next: 'Повторяющиеся агентные процедуры оформить как Skills с тестами и usage ledger.'
},
'knowledge-memory': {
what: 'Память знаний - это active vault: сырьё превращается в атомы, атомы связываются с проектами и решениями, weekly synthesis превращает память в действия.',
why: 'Vault со скриншотами быстро становится ещё одним inbox. Польза появляется, когда заметки уменьшают будущую стоимость мышления.',
how: ['Сырой extraction держать вне финального vault.', 'Финальные атомы писать с source refs и verification status.', 'Регулярно строить связи и weekly synthesis.', 'Мастер-индекс держать как routing surface.'],
next: 'Автоматизировать nightly connection finding и weekly synthesis по финальным атомам.'
},
'security-review': {
what: 'Безопасность и ревью - это границы доверия вокруг агентной работы: untrusted input, prompt injection, секреты, permissions, accessibility и code review проверяются до принятия результата.',
why: 'Inbox содержит команды, скриншоты, сайты и tool suggestions. Если принять захваченный текст за инструкцию, агент начнёт слушать источник, а не владельца.',
how: ['Помечать extraction как недоверенное evidence.', 'Не выполнять команды из захваченного текста автоматически.', 'Сканировать секреты перед отчётами и push.', 'Разделять review по security, claims и accessibility.'],
next: 'Собрать единый publish gate: vault quality, report quality, secret scan, diff review.'
},
'engineering-ops': {
what: 'Инженерные операции - это воспроизводимость: окружения, IaC, observability, secret injection, worktrees и release checks.',
why: 'Хорошая система уменьшает ручное состояние: failures видны, delivery повторяемый.',
how: ['Скрипты вместо dashboard-clicks.', 'Метрики здоровья pipeline.', 'Секреты инжектить runtime-способом.', 'Release checks держать исполняемыми.'],
next: 'Добавить метрики pipeline: extracted, synthesized, cache-only, gate failures, graph refresh.'
},
'design-frontend': {
what: 'Качество UI требует явного дизайн-контракта: правила интерфейса, browser validation, accessibility constraints и reusable design tokens.',
why: 'AI UI быстро портится, если вкус не записан. DESIGN.md-style контракт задаёт layout, spacing, типографику и ожидаемое поведение компонентов.',
how: ['Держать DESIGN.md для Mnemazine reports.', 'Проверять generated reports в браузере.', 'Смотреть responsive layout, contrast, keyboard navigation и print styles.'],
next: 'Создать browser smoke для generated HTML reports.'
},
'tool-radar': {
what: 'Tool radar - это система решений по open-source, а не список красивых репозиториев.',
why: 'Скриншот со stars - слабое evidence. Нужны license, maturity, deployment model, data portability, security posture и integration cost.',
how: ['Оценивать fit, maturity, license, API, self-hosting и operational burden.', 'Связывать инструмент с конкретным проектом.', 'Перед adoption перепроверять primary source.'],
next: 'Сделать schema для tool-radar и заполнять её из GitHub links.'
},
'content-growth': {
what: 'Контентные петли роста рассматривают ads, hooks, CTA, scripts и публикации как эксперименты с обратной связью.',
why: 'Один ролик или объявление ещё не обучение. Обучение появляется, когда есть variant, metric, result и next control.',
how: ['Хранить hypothesis, channel, variant, metric, result и decision.', 'Победителей держать как controls.', 'Слабые варианты удалять без превращения шума в знания.'],
next: 'Добавить template для Content Experiment note.'
},
'research-workflow': {
what: 'Research workflow значит: claims получают источники до того, как становятся рабочим знанием.',
why: 'Ссылка должна подтверждать, исправлять или ограничивать вывод. Иначе это декорация.',
how: ['Отделять extracted claim от verified conclusion.', 'Предпочитать official docs и primary repositories.', 'Писать, что именно источник изменил в выводе.'],
next: 'Добавить поле `source_changed_what` в final atom schema.'
},
misc: {
what: 'Прочие сигналы - материалы, которые пока не сложились в сильный reusable cluster.',
why: 'Отдельный misc-кластер защищает сильные знания от слабого шума.',
how: ['Проверить вручную.', 'Повышать до знания только повторяющиеся или ценные идеи.', 'Низкий сигнал отправлять в forget/archive.'],
next: 'Вручную разобрать misc-сигналы: promote или forget.'
} }
} }
@@ -188,6 +246,21 @@ function clusterTitle(id) {
return clusterRules.find(rule => rule.id === id)?.title || 'Miscellaneous knowledge signals' return clusterRules.find(rule => rule.id === id)?.title || 'Miscellaneous knowledge signals'
} }
function clusterTitleRu(id) {
const map = {
'agent-systems': 'Агентные системы и переиспользуемые возможности',
'knowledge-memory': 'Память знаний, vault и циклы синтеза',
'security-review': 'Безопасность, ревью и границы доверия',
'engineering-ops': 'Инженерные операции и воспроизводимая доставка',
'design-frontend': 'Дизайн-системы и качество фронтенда',
'tool-radar': 'Радар инструментов и выбор open-source',
'content-growth': 'Контентные эксперименты и петли роста',
'research-workflow': 'Исследовательский workflow и проверка источников',
misc: 'Прочие сигналы знаний'
}
return map[id] || map.misc
}
function publicSources(text) { function publicSources(text) {
const explicit = extractUrls(text).map(url => ({ name: url.includes('github.com') ? 'GitHub source' : 'Source link', url })) const explicit = extractUrls(text).map(url => ({ name: url.includes('github.com') ? 'GitHub source' : 'Source link', url }))
const hinted = sourceHints const hinted = sourceHints
@@ -234,11 +307,14 @@ async function fetchText(url, limit = 40000) {
function readmePoints(readme, max = 6) { function readmePoints(readme, max = 6) {
const points = [] const points = []
for (const line of String(readme || '').split('\n')) { for (const line of stripHtmlText(readme).split('\n')) {
const clean = compact(line.replace(/^#+\s*/, '').replace(/^[-*]\s+/, ''), 220) const clean = compact(line.replace(/^#+\s*/, '').replace(/^[-*]\s+/, ''), 220)
if (clean.length < 32) continue if (clean.length < 32) continue
if (/^(install|usage|license|contributing|table of contents|badges?)$/i.test(clean)) continue if (/^(install|usage|license|contributing|table of contents|badges?)$/i.test(clean)) continue
if (/^!\[|^<img|^\[!?\[/.test(line.trim())) continue if (/^!\[|^<img|^\[!?\[|^window\.|^document\.|^function\s/i.test(line.trim())) continue
if (/\b(src|href|alt|title)=["'][^"']*["']/i.test(clean)) continue
if (/https?:\/\/\S+\.(?:svg|png|jpe?g|gif|webp)(?:\?\S*)?$/i.test(clean)) continue
if (/<[a-z][\s\S]*>/i.test(clean)) continue
points.push(clean) points.push(clean)
if (points.length >= max) break if (points.length >= max) break
} }
@@ -249,7 +325,28 @@ function htmlDescription(html) {
const raw = String(html || '') const raw = String(html || '')
const hit = raw.match(/<meta\s+name="description"\s+content="([^"]+)"/i) || const hit = raw.match(/<meta\s+name="description"\s+content="([^"]+)"/i) ||
raw.match(/<meta\s+property="og:description"\s+content="([^"]+)"/i) raw.match(/<meta\s+property="og:description"\s+content="([^"]+)"/i)
return hit ? compact(hit[1].replace(/&quot;/g, '"').replace(/&amp;/g, '&'), 260) : '' return hit ? compact(decodeEntities(hit[1]), 260) : ''
}
function decodeEntities(text) {
return String(text || '')
.replace(/&quot;/g, '"')
.replace(/&#39;|&apos;/g, "'")
.replace(/&amp;/g, '&')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&nbsp;/g, ' ')
}
function stripHtmlText(text) {
return decodeEntities(String(text || '')
.replace(/<script[\s\S]*?<\/script>/gi, '\n')
.replace(/<style[\s\S]*?<\/style>/gi, '\n')
.replace(/<!--[\s\S]*?-->/g, '\n')
.replace(/<[^>]+>/g, '\n'))
.replace(/\n{3,}/g, '\n\n')
.replace(/[ \t]+/g, ' ')
.trim()
} }
async function fetchRawReadme(repoRef, preferredBranch = '') { async function fetchRawReadme(repoRef, preferredBranch = '') {
@@ -279,7 +376,7 @@ async function enrichClusterFromGithub(cluster, sources) {
api = { api = {
full_name: `${repoRef.owner}/${repoRef.repo}`, full_name: `${repoRef.owner}/${repoRef.repo}`,
html_url: repoRef.url, html_url: repoRef.url,
description: htmlDescription(repoHtml) || readmePoints(rawReadme.text, 1)[0] || 'official GitHub repository', description: htmlDescription(repoHtml) || readmePoints(rawReadme.text, 1)[0] || 'официальный GitHub-репозиторий',
stargazers_count: 'unknown', stargazers_count: 'unknown',
forks_count: 'unknown', forks_count: 'unknown',
open_issues_count: 'unknown', open_issues_count: 'unknown',
@@ -293,14 +390,14 @@ async function enrichClusterFromGithub(cluster, sources) {
const readme = rawReadme.text const readme = rawReadme.text
const release = await fetchJson(`https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}/releases/latest`) const release = await fetchJson(`https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}/releases/latest`)
const points = readmePoints(readme) const points = readmePoints(readme)
const license = api.license?.spdx_id || api.license?.name || 'unknown license' const license = api.license?.spdx_id || api.license?.name || 'лицензия неизвестна'
const pushed = api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown' 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) || 'date unknown'})` : 'no latest release returned by GitHub API' const releaseLine = release?.tag_name ? `${release.tag_name} (${String(release.published_at || '').slice(0, 10) || 'дата неизвестна'})` : 'GitHub API не вернул latest release'
const addedFacts = [ const addedFacts = [
`${api.full_name}: ${api.description || 'official GitHub repository'}.`, `${api.full_name}: ${api.description || 'официальный GitHub-репозиторий'}.`,
`GitHub metadata: ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, ${license}, primary language ${api.language || 'unknown'}.`, `Метаданные GitHub: ${api.stargazers_count} звёзд, ${api.forks_count} форков, ${api.open_issues_count} открытых issues, лицензия ${license}, основной язык ${api.language || 'unknown'}.`,
`Repository freshness: default branch ${api.default_branch || 'unknown'}, last push ${pushed}, latest release ${releaseLine}.`, `Свежесть репозитория: основная ветка ${api.default_branch || 'unknown'}, последний push ${pushed}, последний release ${releaseLine}.`,
...points.slice(0, 5).map(point => `README signal: ${point}`) ...points.slice(0, 5).map(point => `Сигнал README: ${point}`)
] ]
const addedSources = [ const addedSources = [
api.html_url, api.html_url,
@@ -308,16 +405,45 @@ async function enrichClusterFromGithub(cluster, sources) {
release?.html_url release?.html_url
].filter(Boolean) ].filter(Boolean)
const enriched = [ const enriched = [
`Official GitHub enrichment for ${api.full_name}.`, `Расширение по официальному GitHub для ${api.full_name}.`,
`Description: ${api.description || 'No GitHub description provided.'}`, `Описание: ${api.description || 'GitHub не дал описание.'}`,
`Metadata: ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, ${license}, ${api.language || 'unknown'} language, pushed ${pushed}.`, `Метаданные: ${api.stargazers_count} звёзд, ${api.forks_count} форков, ${api.open_issues_count} открытых issues, ${license}, язык ${api.language || 'unknown'}, последний push ${pushed}.`,
`Latest release: ${releaseLine}.`, `Последний release: ${releaseLine}.`,
points.length ? `README extracted signals:\n${points.map(point => `- ${point}`).join('\n')}` : 'README extraction returned no stable feature bullets.', points.length ? `Из README извлечены стабильные сигналы:\n${points.map(point => `- ${point}`).join('\n')}` : 'README не дал устойчивых feature-пунктов без ручной проверки.',
`Local seed refs: ${cluster.records.map(r => r.source_ref).join(', ')}.` `Локальные source refs: ${cluster.records.map(r => r.source_ref).join(', ')}.`
].join('\n\n') ].join('\n\n')
return { enriched, addedSources, addedFacts, github: { api, readmeUrl, release, points } } return { enriched, addedSources, addedFacts, github: { api, readmeUrl, release, points } }
} }
async function enrichClusterFromSources(cluster, sources) {
const picked = sources.filter(source => isPublicHttpUrl(source.url)).slice(0, 4)
if (!picked.length) return null
const addedSources = []
const addedFacts = []
const sections = []
for (const source of picked) {
const text = await fetchText(source.url, 40000)
if (!text) continue
const desc = htmlDescription(text) || readmePoints(text, 1)[0] || `${source.name} is reachable at ${source.url}.`
const points = readmePoints(text, 3)
addedSources.push(source.url)
addedFacts.push(`${source.name}: ${desc}`)
for (const point of points) addedFacts.push(`${source.name}: сигнал источника - ${point}`)
sections.push(`${source.name} (${source.url})\n${[desc, ...points].filter(Boolean).map(p => `- ${p}`).join('\n')}`)
if (addedFacts.length >= 6) break
}
if (!addedSources.length || addedFacts.length < MIN_ADDED_FACTS) return null
const template = topicTemplates[cluster.id] || topicTemplates.misc
const enriched = [
`Детерминированное расширение источниками для ${clusterTitleRu(cluster.id)}.`,
template.what,
template.why,
sections.join('\n\n'),
`Локальные source refs: ${cluster.records.map(r => r.source_ref).join(', ')}.`
].join('\n\n')
return { enriched, addedSources, addedFacts, sourceFacts: { sources: addedSources, facts: addedFacts } }
}
function atomsFromGithub(part, sources) { function atomsFromGithub(part, sources) {
const github = part.enrichment?.github const github = part.enrichment?.github
if (!github?.api) return [] if (!github?.api) return []
@@ -329,40 +455,62 @@ function atomsFromGithub(part, sources) {
const releaseLine = github.release?.tag_name || 'no latest release returned' const releaseLine = github.release?.tag_name || 'no latest release returned'
return [ return [
{ {
title: `${repo}: verified tool identity and adoption signal`, title: `${repo}: проверенная карточка инструмента`,
what: `${repo} is the official GitHub repository for ${api.description || 'the tool captured in the local source'}. GitHub reports ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, ${license}, primary language ${api.language || 'unknown'}, and last push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}.`, 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'}.`,
why: 'This turns a screenshot/star-count capture into a checked adoption signal with a primary source, not unchecked extraction.', why: 'Это превращает скриншот или карточку со звёздами в проверяемую запись: есть primary source, дата свежести, лицензия и базовый риск.',
how: ['Use the repo metadata as the first pass: license, freshness, stars, forks, issues.', 'Open the README before adopting; treat social-card claims as hints until repo/docs confirm them.', 'Record adoption decision separately: install now, trial later, or ignore.'], how: ['Сначала смотреть метаданные: лицензия, свежесть, stars, forks, issues.', 'Перед установкой открыть README и issues, скриншот считать только подсказкой.', 'Решение фиксировать отдельно: установить сейчас, протестировать позже или забыть.'],
sources: sourceUrls, sources: sourceUrls,
next: `Review ${repo} README and decide whether it belongs in the agent capability registry.` next: `Прочитать README ${repo} и решить, нужен ли он в реестре возможностей.`
}, },
{ {
title: `${repo}: README-backed capability summary`, title: `${repo}: что реально обещает README`,
what: points.length ? points.slice(0, 4).join(' ') : `${repo} has an official README, but Mnemazine could not extract stable feature bullets from it.`, what: points.length ? points.slice(0, 4).join(' ') : `${repo} имеет официальный README, но Mnemazine не нашла в нём устойчивые продуктовые тезисы без ручной проверки.`,
why: 'README text is closer to operational truth than a screenshot caption. It tells what the maintainer actually ships and documents.', why: 'README ближе к рабочей правде, чем подпись на скриншоте. Он показывает, что авторы реально поддерживают и документируют.',
how: points.slice(0, 5).map(point => `Check: ${point}`), how: points.slice(0, 5).map(point => `Проверить по README: ${point}`),
sources: sourceUrls, sources: sourceUrls,
next: `Map ${repo} README features to one concrete local workflow before installing.` next: `Связать возможности ${repo} с одним конкретным рабочим сценарием до установки.`
}, },
{ {
title: `${repo}: operational risk and maintenance check`, title: `${repo}: риск эксплуатации и поддержки`,
what: `Risk surface: ${api.open_issues_count} open issues, latest release ${releaseLine}, last push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}, license ${license}.`, what: `Поверхность риска: ${api.open_issues_count} open issues, последний release ${releaseLine}, последний push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}, лицензия ${license}.`,
why: 'A popular repo can still be a bad dependency if release cadence, license, or issue volume do not fit the workflow.', why: 'Популярный репозиторий всё равно может быть плохой зависимостью, если релизы, лицензия или issue-профиль не подходят под workflow.',
how: ['Check open issues for security, data-loss, and install failures.', 'Prefer trial in a disposable workspace before adding it to global agent rules.', 'If it becomes a Skill/MCP/plugin, register usage and source ledgers.'], how: ['Проверить issues на security, потерю данных и ошибки установки.', 'Сначала гонять в одноразовом workspace, не добавлять сразу в глобальные правила агента.', 'Если это станет Skill/MCP/plugin, записать source ledger и usage ledger.'],
sources: sourceUrls, sources: sourceUrls,
next: `Run a small local trial for ${repo} only if the workflow fit is concrete.` next: `Запустить маленький локальный пробный запуск для ${repo} только при понятной пригодности к рабочему сценарию.`
}, },
{ {
title: `${repo}: Mnemazine routing decision`, title: `${repo}: решение для Mnemazine`,
what: `This atom links the local capture (${part.records.map(record => record.source_ref).join(', ')}) to primary GitHub evidence for ${repo}.`, what: `Этот атом связывает локальный захват с primary GitHub evidence по ${repo}. Это не команда установить, а кандидат на разбор.`,
why: 'The useful memory is not "saw a repo". The useful memory is the routing decision: what the repo does, whether it fits, what risk remains, and what action follows.', why: 'Полезная память - не "увидел репозиторий", а решение: что инструмент делает, подходит ли он, какой риск остаётся и что делать дальше.',
how: ['Store the repo as a candidate capability, not an instruction to install.', 'If adopted, mirror docs/skill metadata and log usage.', 'If rejected, record the reason so the same shiny repo does not return as noise.'], how: ['Хранить репозиторий как кандидата в рабочие возможности, не как инструкцию к установке.', 'Если принять, зеркалировать docs/skill metadata и логировать usage.', 'Если отклонить, записать причину, чтобы репозиторий не возвращался шумом.'],
sources: sourceUrls, sources: sourceUrls,
next: `Add ${repo} to the capability review queue with one accept/reject criterion.` next: `Добавить ${repo} в очередь разбора возможностей с одним критерием: принять или отклонить.`
} }
] ]
} }
function atomsFromSources(part, sources) {
const template = topicTemplatesRu[part.id] || topicTemplatesRu.misc
const facts = part.enrichment?.addedFacts || []
const sourceUrls = sources.map(source => source.url).filter(isPublicHttpUrl)
const how = Array.isArray(template.how) ? template.how : String(template.how || '').split('\n').map(line => line.replace(/^-\s*/, '').trim()).filter(Boolean)
return [
{
title: `${clusterTitleRu(part.id)}: проверенный рабочий паттерн`,
what: `${template.what} Источники добавили проверяемые опорные факты: ${facts.slice(0, 2).join(' ')}`,
why: template.why,
how: [...how, ...facts.slice(2, 4).map(fact => `Проверить по источнику: ${fact}`)].slice(0, 5),
sources: sourceUrls,
next: template.next
}
]
}
function atomsFromDeterministic(part, sources) {
if (part.enrichment?.kind === 'github') return atomsFromGithub(part, sources)
return atomsFromSources(part, sources)
}
function recordTitle(record) { function recordTitle(record) {
const url = extractUrls(record.text)[0] const url = extractUrls(record.text)[0]
if (url) return url.replace(/^https?:\/\//, '').replace(/[?#].*$/, '').slice(0, 90) if (url) return url.replace(/^https?:\/\//, '').replace(/[?#].*$/, '').slice(0, 90)
@@ -379,17 +527,17 @@ function hostOf(url) {
function topicSignals(cluster, sources) { function topicSignals(cluster, sources) {
const hosts = uniq(sources.map(source => hostOf(source.url)).filter(Boolean)).slice(0, 6) const hosts = uniq(sources.map(source => hostOf(source.url)).filter(Boolean)).slice(0, 6)
const sourceLine = hosts.length ? `Detected public sources: ${hosts.join(', ')}.` : 'No stable public URL detected in this cluster.' const sourceLine = hosts.length ? `Найдены публичные источники: ${hosts.join(', ')}.` : 'Стабильный публичный URL в кластере не найден.'
const map = { const map = {
'agent-systems': ['Repeated agent capability signals: Skills, MCP, memory, browser tools, review roles, and harness rules.', sourceLine], 'agent-systems': ['Повторяются агентные сигналы: Skills, MCP, память, browser tools, роли ревью и harness rules.', sourceLine],
'knowledge-memory': ['Repeated memory signals: vault structure, connection finding, weekly synthesis, decisions, beliefs, and active indexes.', sourceLine], 'knowledge-memory': ['Повторяются сигналы памяти: структура vault, поиск связей, weekly synthesis, decisions, beliefs и active indexes.', sourceLine],
'security-review': ['Repeated trust signals: prompt injection risk, secret handling, permissions, review gates, and accessibility checks.', sourceLine], 'security-review': ['Повторяются сигналы доверия: prompt injection, секреты, permissions, review gates и accessibility checks.', sourceLine],
'engineering-ops': ['Repeated engineering signals: reproducible environments, IaC, worktrees, observability, release checks, and secret injection.', sourceLine], 'engineering-ops': ['Повторяются инженерные сигналы: воспроизводимые окружения, IaC, worktrees, observability, release checks и secret injection.', sourceLine],
'design-frontend': ['Repeated UI signals: DESIGN.md, taste rules, frontend structure, Playwright/browser checks, and WCAG constraints.', sourceLine], 'design-frontend': ['Повторяются UI-сигналы: DESIGN.md, taste rules, frontend structure, Playwright/browser checks и WCAG constraints.', sourceLine],
'tool-radar': ['Repeated tool-radar signals: GitHub repositories, self-hosting options, AI tools, and open-source alternatives.', sourceLine], 'tool-radar': ['Повторяются tool-radar сигналы: GitHub repos, self-hosting, AI tools и open-source alternatives.', sourceLine],
'content-growth': ['Repeated growth signals: ad variants, hooks, CTAs, short-form generation, metrics, and winner/loser loops.', sourceLine], 'content-growth': ['Повторяются growth-сигналы: ad variants, hooks, CTA, short-form generation, metrics и winner/loser loops.', sourceLine],
'research-workflow': ['Repeated research signals: source gathering, claim review, evidence checking, drafting, and revision.', sourceLine], 'research-workflow': ['Повторяются research-сигналы: сбор источников, проверка claims, evidence, drafting и revision.', sourceLine],
misc: ['Low-confidence miscellaneous signals kept separate from stronger clusters.', sourceLine] misc: ['Слабые misc-сигналы отделены от сильных knowledge atoms.', sourceLine]
} }
return map[cluster.id] || map.misc return map[cluster.id] || map.misc
} }
@@ -424,20 +572,21 @@ function chunks(values, size) {
function makeNote(cluster) { function makeNote(cluster) {
const text = cluster.records.map(record => record.text).join('\n\n') const text = cluster.records.map(record => record.text).join('\n\n')
const baseTitle = clusterTitle(cluster.id) const baseTitle = clusterTitleRu(cluster.id)
const title = cluster.partCount > 1 ? `${baseTitle} ${cluster.part}/${cluster.partCount}` : baseTitle const title = cluster.partCount > 1 ? `${baseTitle} ${cluster.part}/${cluster.partCount}` : baseTitle
const template = topicTemplates[cluster.id] || topicTemplates.misc const template = topicTemplatesRu[cluster.id] || topicTemplatesRu.misc
const sources = publicSources(text) const sources = publicSources(text)
const signals = topicSignals(cluster, sources) const signals = topicSignals(cluster, sources)
const sourceRefs = cluster.records.map(record => `- ${record.source_ref}`) const sourceRefs = cluster.records.map(record => `- ${record.source_ref}`)
const sourceLines = sources.length const sourceLines = sources.length
? sources.map(source => `- ${source.name}: ${source.url}`) ? sources.map(source => `- ${source.name}: ${source.url}`)
: ['- No public source detected in extraction; external verification required before operational adoption.'] : ['- Публичный источник не найден в extraction; перед применением нужна внешняя проверка.']
const sourceStatus = sources.length ? 'local synthesis with public source expansion' : 'local synthesis; external verification required' const sourceStatus = sources.length ? 'local synthesis with public source expansion' : 'local synthesis; external verification required'
const localVerdict = verifyLocal(sources.map(s => s.url)) const localVerdict = verifyLocal(sources.map(s => s.url))
const how = Array.isArray(template.how) ? template.how.map(item => `- ${item}`).join('\n') : template.how
const risk = sources.length const risk = sources.length
? 'Public links were detected or added by topic hints, but claims still need project-specific validation before adoption.' ? 'Публичные ссылки найдены или добавлены по source hints, но перед adoption claims всё равно надо проверить под конкретный проект.'
: 'No public source was available in extracted text; treat this as a local memory atom, not an externally verified claim.' : 'Публичного источника в extraction не было; это локальный memory atom, а не внешне подтверждённый claim.'
return `--- return `---
title: "${title.replace(/"/g, '\\"')}" title: "${title.replace(/"/g, '\\"')}"
type: "knowledge-note" type: "knowledge-note"
@@ -453,47 +602,47 @@ cluster_fingerprint: "${fingerprint(cluster)}"
# ${title} # ${title}
## What This Is ## Что это
${template.what} ${template.what}
Key session signals: Ключевые сигналы сессии:
${signals.map(signal => `- ${signal}`).join('\n')} ${signals.map(signal => `- ${signal}`).join('\n')}
## Why It Matters ## Зачем это нужно
${template.why} ${template.why}
This note condenses ${cluster.records.length} extracted source item${cluster.records.length === 1 ? '' : 's'} into reusable knowledge. Source-level extraction stays in \`.mnemazine/cache/extracted\`. Заметка сжимает ${cluster.records.length} исходных элементов в переиспользуемое знание. Source-level extraction остаётся в \`.mnemazine/cache/extracted\`.
## How To Use It ## Как использовать
${template.how} ${how}
## Source ## Источники
Local source refs: Локальные source refs:
${sourceRefs.slice(0, 30).join('\n')} ${sourceRefs.slice(0, 30).join('\n')}
${sourceRefs.length > 30 ? `- ... ${sourceRefs.length - 30} more source refs kept in extraction cache` : ''} ${sourceRefs.length > 30 ? `- ... ещё ${sourceRefs.length - 30} source refs сохранены в extraction cache` : ''}
Public/source expansion: Публичные источники:
${sourceLines.join('\n')} ${sourceLines.join('\n')}
## Verification ## Проверка
- **No automated fact-check ran.** This note is an unverified synthesis cluster (\`status: draft\`). Source URLs are detected from extracted text or added by topic hints — they are pointers, not confirmation that any specific claim is true. - **Автоматический fact-check не запускался.** Это unverified synthesis cluster (\`status: draft\`). URL из extraction или topic hints - указатели, не подтверждение конкретного claim.
- Promote to \`status: final\` only after a human or the verify gate checks claims against the listed primary sources. - Повышать до \`status: final\` только после проверки человеком или verify gate по primary sources.
- Confidence: low until verified — treat dates, prices, stars, security claims, and release status as unconfirmed. - Уверенность: низкая до проверки. Даты, цены, stars, security claims и release status считать неподтверждёнными.
- Risk: ${risk} - Риск: ${risk}
## Related Notes ## Связанные заметки
- [[Mnemazine Protocol]] - [[Mnemazine Protocol]]
- [[${clusterTitle(cluster.id)}]] - [[${clusterTitle(cluster.id)}]]
## Reuse ## Следующее действие
- Next action: ${template.next} - ${template.next}
` `
} }
@@ -529,7 +678,7 @@ function atomPrompt(cluster, sources, materialOverride) {
const urls = sources.map(s => s.url).join(', ') || 'none detected' 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). 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).
Return ONLY JSON matching the schema. Пиши значения JSON на русском языке. Return ONLY JSON matching the schema.
${fenceUntrusted('MATERIAL', text)}` ${fenceUntrusted('MATERIAL', text)}`
} }
@@ -562,7 +711,7 @@ function enrichPrompt(text, sources) {
Known source hints: ${urls}. Known source hints: ${urls}.
Produce: "enriched" = the expanded knowledge as clean prose (English ok; the human-readable Russian digest is a later stage), "sources" = all source URLs used, "added_facts" = short bullet list of what you added beyond the seed. Produce: "enriched" = the expanded knowledge as clean Russian prose, "sources" = all source URLs used, "added_facts" = short Russian bullet list of what you added beyond the seed.
${fenceUntrusted('MATERIAL', text)}` ${fenceUntrusted('MATERIAL', text)}`
} }
@@ -587,13 +736,13 @@ function atomFingerprint(atom, clusterId = '') {
} }
function makeAtomNote(cluster, atom, verdict) { function makeAtomNote(cluster, atom, verdict) {
const how = (atom.how || []).filter(Boolean).map(h => `- ${compact(h, 240)}`).join('\n') || '- Review and apply in context.' 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 sourceRefs = cluster.records.map(record => `- ${record.source_ref}`).join('\n')
const addedFacts = (cluster.enrichment?.addedFacts || []).map(f => `- ${compact(f, 300)}`).join('\n') || '- No external enrichment facts recorded.' const addedFacts = (cluster.enrichment?.addedFacts || []).map(f => `- ${compact(f, 300)}`).join('\n') || '- Внешние факты не записаны.'
const srcs = (atom.sources || []).filter(isPublicHttpUrl) const srcs = (atom.sources || []).filter(isPublicHttpUrl)
const sourceLines = srcs.length const sourceLines = srcs.length
? srcs.map(u => `- ${hostOf(u) || 'Source'}: ${u}`).join('\n') ? srcs.map(u => `- ${hostOf(u) || 'Источник'}: ${u}`).join('\n')
: '- No public source detected; external verification required before operational adoption.' : '- Публичный источник не найден; перед применением нужна внешняя проверка.'
const fp = atomFingerprint(atom, cluster.id) const fp = atomFingerprint(atom, cluster.id)
const v = verdict || { status: 'unknown', note: '' } const v = verdict || { status: 'unknown', note: '' }
const isVerified = v.status === 'verified' const isVerified = v.status === 'verified'
@@ -613,47 +762,47 @@ cluster_fingerprint: "${fp}"
# ${compact(atom.title, 120)} # ${compact(atom.title, 120)}
## What This Is ## Что это
${compact(atom.what, 1200)} ${compact(atom.what, 1200)}
## Why It Matters ## Зачем это нужно
${compact(atom.why, 1200)} ${compact(atom.why, 1200)}
## How To Use It ## Как использовать
${how} ${how}
## Source ## Источники
Local source refs: Локальные source refs:
${sourceRefs} ${sourceRefs}
Public/source expansion: Публичные источники:
${sourceLines} ${sourceLines}
## Enrichment ## Расширение знания
External facts added before atomization: Факты, добавленные до атомизации:
${addedFacts} ${addedFacts}
## Verification ## Проверка
- Verification status: **${v.status}**${v.note ? ` (${v.note})` : ''}. - Статус проверки: **${v.status}**${v.note ? ` (${v.note})` : ''}.
${isVerified ${isVerified
? `- A deep verify pass cross-checked the claim against the listed sources.${v.evidence ? ` Evidence: ${compact(v.evidence, 300)}` : ''}` ? `- Утверждение сверено с указанными источниками.${v.evidence ? ` Подтверждение: ${compact(v.evidence, 300)}` : ''}`
: '- **No claim-level fact-check confirmed this.** Source URLs are pointers, not confirmation. Promote to `verified` only after the deep verify gate (`--deep`) checks claims against the listed sources.'} : '- **Claim-level fact-check не подтвердил это.** URL - указатели, не доказательство. Статус `verified` допустим только после deep verify.'}
- ${v.status === 'unknown' ? 'No source URL was anchored — treat as a local memory atom, not an externally verified claim.' : 'Confidence: medium until a human or deep verify confirms.'} - ${v.status === 'unknown' ? 'Нет source URL: это локальный memory atom, а не внешне подтверждённый claim.' : 'Уверенность: средняя, пока человек или deep verify не подтвердит вывод.'}
## Related Notes ## Связанные заметки
- [[Mnemazine Protocol]] - [[Mnemazine Protocol]]
- [[${clusterTitle(cluster.id)}]] - [[${clusterTitleRu(cluster.id)}]]
## Reuse ## Следующее действие
- Next action: ${compact(atom.next, 240) || 'Review and apply.'} - ${compact(atom.next, 240) || 'Проверить и применить по контексту.'}
` `
} }
@@ -698,12 +847,20 @@ async function processPart(part, parts, index) {
let material let material
if (ENRICH) { if (ENRICH) {
try { try {
const github = await enrichClusterFromGithub(part, sources) const deterministic = await enrichClusterFromGithub(part, sources) || await enrichClusterFromSources(part, sources)
const { enriched, addedSources, addedFacts } = github || await enrichCluster(part, sources) const { enriched, addedSources, addedFacts } = deterministic || await enrichCluster(part, sources)
if (enriched && enriched.length > 200) { if (enriched && enriched.length > 200) {
material = enriched material = enriched
for (const u of addedSources) if (!sources.some(s => s.url === u)) sources.push({ name: hostOf(u) || 'Source', url: u }) for (const u of addedSources) if (!sources.some(s => s.url === u)) sources.push({ name: hostOf(u) || 'Source', url: u })
part.enrichment = { ok: true, addedFacts, addedSources, deterministic: Boolean(github), github: github?.github || null } part.enrichment = {
ok: true,
addedFacts,
addedSources,
deterministic: Boolean(deterministic),
kind: deterministic?.github ? 'github' : deterministic ? 'sources' : 'llm',
github: deterministic?.github || null,
sourceFacts: deterministic?.sourceFacts || null
}
enriched_clusters += 1 enriched_clusters += 1
} }
} catch (err) { } catch (err) {
@@ -714,7 +871,7 @@ async function processPart(part, parts, index) {
throw new Error(`strict enrichment failed for cluster ${part.id}: no expanded material with external facts/sources`) throw new Error(`strict enrichment failed for cluster ${part.id}: no expanded material with external facts/sources`)
} }
const atoms = part.enrichment?.deterministic const atoms = part.enrichment?.deterministic
? atomsFromGithub(part, sources) ? atomsFromDeterministic(part, sources)
: await atomizeCluster(part, sources, material) : await atomizeCluster(part, sources, material)
let wroteAtom = false let wroteAtom = false
const allowedSourceUrls = new Set(sources.map(source => source.url).filter(isPublicHttpUrl)) const allowedSourceUrls = new Set(sources.map(source => source.url).filter(isPublicHttpUrl))
@@ -723,7 +880,7 @@ async function processPart(part, parts, index) {
const out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(atom.title)}-${atomFingerprint(atom, part.id)}.md`) 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 } if (await fs.access(out).then(() => true).catch(() => false)) { skipped += 1; continue }
const verdict = part.enrichment?.deterministic const verdict = part.enrichment?.deterministic
? { status: 'verified', checked: atom.sources || [], evidence: 'Fetched GitHub API/README/release for primary-source enrichment.', note: 'deterministic GitHub source check' } ? { 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` }
: DEEP : DEEP
? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources) ? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources)
: verifyLocal(atom.sources) : verifyLocal(atom.sources)
+294
View File
@@ -0,0 +1,294 @@
#!/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 lastRun() {
try { return JSON.parse(readFileSync(path.join(ROOT, '.mnemazine/state/last-run.json'), 'utf8')) } catch { return null }
}
const LAST_RUN = lastRun()
const VAULT = resolveVault({ cli: arg('vault'), env: process.env.MNEMAZINE_VAULT || LAST_RUN?.vault })
const SINCE = arg('changed-since', LAST_RUN?.started_at || '')
const SINCE_MS = Number.isFinite(Date.parse(SINCE)) ? Date.parse(SINCE) : 0
const OUT = path.resolve(arg('out', path.join(VAULT, '08 AI и Инструменты/Tools/Очередь разбора инструментов.md')))
const SESSION = arg('session', new Date().toISOString().slice(0, 10))
function escMd(value) {
return String(value || '').replace(/\|/g, '\\|').replace(/\n+/g, ' ').trim()
}
function clean(value, max = 500) {
const text = String(value || '')
.replace(/```[\s\S]*?```/g, '')
.replace(/^[-*]\s+/gm, '')
.replace(/\bprimary source\b/gi, 'первичным источникам')
.replace(/\bGitHub repo\b/gi, 'GitHub-репозиторий')
.replace(/\bREADME\/release\b/gi, 'README и release')
.replace(/README и release и метаданные/gi, 'README, release и метаданные')
.replace(/\bknowledge notes\b/gi, 'заметки знаний')
.replace(/\bevidence\b/gi, 'доказательства')
.replace(/\bworkflow\b/gi, 'рабочий сценарий')
.replace(/\bsandbox\b/gi, 'песочница')
.replace(/\bdraft\b/gi, 'черновик')
.replace(/\s+/g, ' ')
.replace(/ \./g, '.')
.replace(/\.\./g, '.')
.trim()
return text.length > max ? `${text.slice(0, max - 1).trim()}...` : text
}
function section(text, names) {
for (const name of names) {
const re = new RegExp(`^##\\s+${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:\\s|$)[^\\n]*\\n([\\s\\S]*?)(?=^##\\s+|(?![\\s\\S]))`, 'mi')
const hit = text.match(re)
if (hit) return hit[1].trim()
}
return ''
}
function titleOf(text, file) {
return text.match(/^title:\s*"([^"]+)"/m)?.[1]?.trim() ||
text.match(/^#\s+(.+)$/m)?.[1]?.trim() ||
path.basename(file, '.md')
}
async function walk(dir) {
const out = []
async function visit(folder) {
for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) {
if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
const file = path.join(folder, item.name)
if (item.isDirectory()) await visit(file)
else if (item.isFile() && item.name.endsWith('.md')) out.push(file)
}
}
await visit(dir)
return out
}
function reposFrom(text) {
const repos = []
for (const hit of String(text || '').matchAll(/https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)/g)) {
const owner = hit[1]
const repo = hit[2].replace(/\.git$/i, '')
if (!owner || !repo || repo === 'releases' || repo === 'blob') continue
repos.push(`${owner}/${repo}`)
}
return [...new Set(repos)]
}
function classifyNote(title) {
const low = title.toLowerCase()
if (low.includes('решение')) return 'decision'
if (low.includes('риск')) return 'risk'
if (low.includes('readme')) return 'readme'
if (low.includes('карточка')) return 'identity'
return 'note'
}
function humanRepoName(repo) {
if (/aider/i.test(repo)) return 'Aider'
if (/browser-use/i.test(repo)) return 'browser-use'
if (/moneyprinter/i.test(repo)) return 'MoneyPrinterTurbo'
return repo
}
function defaultCard(repo, merged) {
const name = humanRepoName(repo)
const lower = repo.toLowerCase()
if (lower.includes('aider')) {
return {
status: 'Пробовать только точечно',
decision: 'тестировать первым, если нужен независимый пробный запуск coding-агента; основной стек не менять',
scenario: 'маленькая правка или рефакторинг в отдельном git worktree',
trial: 'создать одноразовый worktree, дать Aider одну задачу, принять результат только после `git diff` и ручного ревью',
gate: 'не давать широкий доступ к основному рабочему дереву; не принимать изменения без ревью diff',
accept: 'ускоряет маленькие кодовые правки без роста риска',
reject: 'лезет слишком широко, шумит в diff или требует ручной чистки',
}
}
if (lower.includes('browser-use')) {
return {
status: 'Отложить до задачи, где Playwright мало',
decision: 'не брать сейчас в постоянный стек; сначала использовать обычную браузерную smoke-проверку, browser-use проверять только для агентных UI-сценариев',
scenario: 'проверка браузера в режиме чтения, сбор доказательств, воспроизведение UI-сценария',
trial: 'запустить на тестовом профиле и списке разрешённых доменов; без отправки форм, оплат, публикаций и действий в живых аккаунтах',
gate: 'тестовый профиль, список разрешённых доменов, явное подтверждение перед любой внешней мутацией',
accept: 'надёжно воспроизводит сценарий и даёт проверяемые доказательства',
reject: 'пытается действовать в живом аккаунте или требует слишком много присмотра',
}
}
if (lower.includes('moneyprinterturbo')) {
return {
status: 'Отложить до контент-эксперимента',
decision: 'не ставить сейчас; возвращаться только когда есть конкретный ролик, канал и критерий качества',
scenario: 'один черновик короткого видео для проверки крючка и призыва к действию',
trial: 'собрать один черновик без автопубликации, проверить права на ассеты, голос, качество сценария и итоговый монтаж',
gate: 'никакой автопубликации; проверка прав на контент и стоковые материалы; ручная проверка качества',
accept: 'быстро даёт пригодный черновик, который можно довести руками',
reject: 'получается фабрика однотипного контента или юридический риск',
}
}
return {
status: 'Проверить на одном сценарии',
decision: 'не добавлять в постоянный стек автоматически',
scenario: clean(merged.decision || merged.what || 'один конкретный рабочий сценарий', 140),
trial: `сделать маленький пробный запуск ${name} без установки в постоянный стек`,
gate: 'проверить README, лицензию, issues, свежесть релизов и риск для данных',
accept: 'есть понятная польза в одном рабочем сценарии',
reject: 'нет сценария, высокий риск или слабая поддержка',
}
}
async function collectTools() {
const groups = new Map()
for (const file of await walk(VAULT)) {
if (file === OUT) continue
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 (!/github\.com\//i.test(text)) continue
if (!/verified:\s*true/.test(text)) continue
const repos = reposFrom(text)
if (!repos.length) continue
const title = titleOf(text, file)
const noteType = classifyNote(title)
for (const repo of repos) {
const group = groups.get(repo) || {
repo,
notes: [],
sources: new Set(),
metadata: '',
freshness: '',
what: '',
decision: '',
risk: '',
readme: '',
next: '',
}
group.notes.push({ file, title, type: noteType })
for (const url of [...text.matchAll(/https?:\/\/[^\s)]+/g)].map(m => m[0].replace(/[.,;]+$/, ''))) {
if (url.includes(repo)) group.sources.add(url)
}
group.metadata ||= text.match(/Метаданные GitHub:\s*([^\n]+)/)?.[1]?.trim() || ''
group.freshness ||= text.match(/Свежесть репозитория:\s*([^\n]+)/)?.[1]?.trim() || ''
if (noteType === 'identity') group.what ||= section(text, ['Что это'])
if (noteType === 'decision') group.decision ||= section(text, ['Решение', 'Что это'])
if (noteType === 'risk') group.risk ||= section(text, ['Что это'])
if (noteType === 'readme') group.readme ||= section(text, ['Что обещает README', 'Что это'])
group.next ||= clean(section(text, ['Следующее действие']), 180)
groups.set(repo, group)
}
}
return [...groups.values()].sort((a, b) => humanRepoName(a.repo).localeCompare(humanRepoName(b.repo), 'ru'))
}
function renderCard(group) {
const card = defaultCard(group.repo, group)
const noteLinks = group.notes
.sort((a, b) => a.type.localeCompare(b.type))
.map(note => `- [[${path.relative(VAULT, note.file).replace(/\.md$/, '')}|${note.title}]]`)
.join('\n')
const sources = [...group.sources].slice(0, 6).map(url => `- ${url}`).join('\n') || '- источник не найден'
return `### ${humanRepoName(group.repo)} (${group.repo})
**Статус:** ${card.status}
**Что это:** ${clean(group.what || group.readme || group.decision, 360)}
**Решение сейчас:** ${card.decision}. Сначала один маленький пробный запуск, потом явное решение: берём, откладываем или забываем.
**Где проверять:** ${card.scenario}.
**Пробный запуск:** ${card.trial}.
**Гейт риска:** ${card.gate}.
**Принять, если:** ${card.accept}.
**Отклонить, если:** ${card.reject}.
**Метаданные:** ${clean([group.metadata, group.freshness].filter(Boolean).join(' '), 360)}
**Источники:**
${sources}
**Связанные ноты:**
${noteLinks}
`
}
function renderQueue(groups) {
const rows = groups.map(group => {
const card = defaultCard(group.repo, group)
return `| ${escMd(humanRepoName(group.repo))} | ${escMd(card.status)} | ${escMd(card.scenario)} | ${escMd(card.gate)} | ${escMd(card.trial)} |`
})
return `---
title: "Очередь разбора инструментов"
type: "tool-decision-queue"
status: "active"
source_ref: "mnemazine-tool-decision-queue:${SESSION}"
generated_at: "${new Date().toISOString()}"
---
# Очередь разбора инструментов
## Что это
Это рабочая очередь решений по инструментам из Mnemazine. Она не заменяет исходные заметки знаний: она сжимает их в одно место, где видно, что тестировать, чем рискуем и по какому критерию принять или отклонить инструмент.
## Правило
- Скриншот, звёзды GitHub и красивый README не являются решением.
- Один инструмент проверяется только на одном понятном рабочем сценарии.
- До принятия в стек нужен маленький пробный запуск в безопасной среде.
- Решение всегда одно из трёх: берём, откладываем, забываем.
## Очередь
| Инструмент | Статус | Где проверять | Гейт риска | Пробный запуск |
|---|---|---|---|---|
${rows.join('\n')}
## Карточки
${groups.map(renderCard).join('\n')}
## Источники
- Сгенерировано из verified Mnemazine notes после ${SINCE || 'последнего прогона'}.
- Исходные заметки остаются в vault как доказательства и подробности.
## Проверка
- Очередь не устанавливает инструменты и не выполняет внешние действия.
- Перед установкой проверять README, лицензию, issues, свежесть релизов, доступ к данным и границы песочницы.
- Любой пробный запуск делать отдельно от боевого рабочего дерева или живых аккаунтов.
## Следующее действие
- Выбрать один инструмент из очереди и провести один маленький пробный запуск с критерием “берём / откладываем / забываем”.
`
}
const groups = await collectTools()
if (!groups.length) {
console.log(JSON.stringify({ ok: true, written: false, tools: 0 }, null, 2))
process.exit(0)
}
await fs.mkdir(path.dirname(OUT), { recursive: true })
await fs.writeFile(OUT, renderQueue(groups), 'utf8')
console.log(JSON.stringify({ ok: true, written: true, tools: groups.length, out: OUT }, null, 2))
+2 -1
View File
@@ -2,6 +2,7 @@
import { promises as fs } from 'node:fs' import { promises as fs } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import os from 'node:os' import os from 'node:os'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const argv = process.argv.slice(2) const argv = process.argv.slice(2)
@@ -12,7 +13,7 @@ function arg(name, fallback = '') {
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
} }
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault'))) const VAULT = resolveVault({ cli: arg('vault') })
const REQUIRE_DOSSIER = argv.includes('--require-dossier') const REQUIRE_DOSSIER = argv.includes('--require-dossier')
const CHANGED_SINCE = arg('changed-since', '') const CHANGED_SINCE = arg('changed-since', '')
const MAX_FAILURES = Number(arg('max-failures', process.env.MNEMAZINE_QUALITY_MAX_FAILURES || '0')) const MAX_FAILURES = Number(arg('max-failures', process.env.MNEMAZINE_QUALITY_MAX_FAILURES || '0'))
+2 -1
View File
@@ -1,9 +1,10 @@
#!/usr/bin/env node #!/usr/bin/env node
import { promises as fs } from 'node:fs' import { promises as fs } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault') const VAULT = resolveVault()
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports') const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state') const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
+2 -1
View File
@@ -11,6 +11,7 @@ import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
import path from 'node:path' import path from 'node:path'
import os from 'node:os' import os from 'node:os'
import { resolveVault } from './mnemazine-paths.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const argv = process.argv.slice(2) const argv = process.argv.slice(2)
@@ -21,7 +22,7 @@ function arg(name, fallback = '') {
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
} }
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault'))) const VAULT = resolveVault({ cli: arg('vault') })
// Default state dir matches README:224 (~/Desktop/Mnemazine/.mnemazine/state), // Default state dir matches README:224 (~/Desktop/Mnemazine/.mnemazine/state),
// the canonical pickup for the weekly-brief export. Override with MNEMAZINE_STATE // the canonical pickup for the weekly-brief export. Override with MNEMAZINE_STATE
// / --state-dir, or point --state straight at the downloaded file. // / --state-dir, or point --state straight at the downloaded file.