diff --git a/README.md b/README.md index f08609c..6df77e1 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,11 @@ **Mnemazine** is an open-source personal knowledge system inspired by **Mnemosyne**, the Greek goddess of memory. The name is intentionally brandable, while the idea is classical: memory is not a dump of files. Memory is formed when raw experience is recognized, checked, connected, rewritten, and made reusable. -Mnemazine turns screenshots, PDFs, web pages, videos, notes, guides, GitHub repositories, and random fragments into a clean Obsidian-compatible knowledge base. +**English:** Mnemazine turns screenshots, PDFs, web pages, videos, notes, guides, GitHub repositories, and random fragments into a clean Obsidian-compatible knowledge base. It extracts locally first, stores final notes only, keeps source hashes for provenance, updates a graph when available, and rejects raw OCR/draft dumps before they become memory. + +**Русский:** Mnemazine превращает скриншоты, PDF, веб-страницы, видео, заметки, гайды, GitHub-репозитории и случайные фрагменты в чистую Obsidian-совместимую базу знаний. Система сначала извлекает данные локально, хранит только финальные заметки, сохраняет хэши источников для проверяемости, обновляет граф при наличии Graphify и не пропускает сырой OCR/draft-мусор в память. + +> Memory, not a dump. Память, не свалка. ![Mnemazine — from raw fragments to an ordered knowledge graph](docs/assets/hero/mnemazine-pipeline.png) @@ -25,6 +29,22 @@ It does not save raw OCR into your vault. It does not keep vague summaries that The goal is simple: future you should not reread twenty screenshots, a whole guide, or a messy transcript. Future you should open one good note and immediately understand what the knowledge is, why it matters, how to use it, and what evidence supports it. +## Что это + +Mnemazine — локальная система переработки входящих материалов в долговечные знания. + +Она не кладёт в vault сырой OCR, случайные имена файлов, скриншоты без контекста и непроверяемые копипасты. Вместо этого создаёт финальные заметки: + +- понятный заголовок; +- краткая суть; +- зачем это важно; +- как использовать; +- source hash / `local-media:` вместо приватного имени файла; +- статус проверки; +- связи и повторное использование. + +Цель: будущий ты открывает не пачку скринов, а одну нормальную заметку, которую можно применить, проверить, связать с проектом или превратить в skill/agent/checklist. + ## Why It Saves Tokens Mnemazine saves tokens by moving work out of repeated LLM context and into durable local structure. @@ -45,7 +65,7 @@ In real workflows, this often turns huge source piles into compact reusable note Clone the project into the only folder you need: ```bash -git clone https://github.com/7teenno1-art/Mnemazine.git "$HOME/Desktop/Mnemazine" +git clone https://github.com/zarubinphil/Mnemazine.git "$HOME/Desktop/Mnemazine" cd "$HOME/Desktop/Mnemazine" bash install.sh ``` @@ -94,11 +114,36 @@ The run performs: 1. file census; 2. SHA-256 duplicate detection; 3. local extraction when possible; -4. topic splitting; -5. source-aware note creation; -6. vault quality gate; -7. Graphify update when available; -8. weekly HTML report update. +4. final note creation with `source_ref` and `source_hash`; +5. vault quality gate; +6. archive move only after the quality gate passes; +7. Graphify update when available. + +The default runner is intentionally conservative. It does not publish data, use private cookies, or send local files to external services. It writes local notes and archives processed source files under `.mnemazine/archive/`. + +## Локальный запуск + +Положите материалы в: + +```text +~/Desktop/Mnemazine/inbox +``` + +Запустите: + +```bash +node scripts/mnemazine-run.mjs +``` + +Прогон делает: + +1. перепись файлов; +2. SHA-256 дедупликацию; +3. локальное извлечение текста, если возможно; +4. создание финальной заметки с `source_ref` и `source_hash`; +5. gate качества vault; +6. перенос исходников в `.mnemazine/archive/` только после зелёного gate; +7. обновление Graphify, если он установлен. ## Website Ingestion @@ -149,12 +194,28 @@ Every finished note should answer: Raw OCR, copied fragments, and messy transcripts are rejected by the quality gate. +The quality gate also rejects common raw-intake residue such as `intake-draft`, `draft-local`, `temp_image_*`, `IMG_*.PNG`, and visible raw image extensions in note content. Graphify output folders and backups are excluded from this note-quality scan. + Run the gate manually: ```bash node scripts/mnemazine-vault-quality-gate.mjs ``` +## Контракт качества + +Vault хранит финальное знание, не сырьё. + +Gate отклоняет: + +- сырой OCR; +- `intake-draft` / `draft-local`; +- видимые `temp_image_*`, `IMG_*.PNG`, `.WEBP`, `.PNG` внутри заметок; +- заметки без смысла или источника; +- копипасту без проверки. + +Graphify-артефакты и backup-папки не считаются knowledge notes и исключены из проверки. + ## Agent Skills The repo includes portable Agent Skills in `.agents/skills` style: diff --git a/package.json b/package.json index 3451abc..3642777 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "0.1.0", "private": false, "type": "module", - "description": "Open-source memory system that turns raw inputs into verified reusable knowledge.", + "description": "Local-first memory system for turning raw inputs into verified reusable knowledge / Локальная система памяти из сырья в проверяемые знания.", "scripts": { "install:local": "bash install.sh", "run": "node scripts/mnemazine-run.mjs", diff --git a/scripts/mnemazine-run.mjs b/scripts/mnemazine-run.mjs index 3589a4d..a391635 100755 --- a/scripts/mnemazine-run.mjs +++ b/scripts/mnemazine-run.mjs @@ -9,6 +9,7 @@ const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox') const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault') const CACHE = path.join(ROOT, '.mnemazine/cache/processed-hashes.json') +const ARCHIVE = path.join(ROOT, '.mnemazine/archive') async function ensureDir(dir) { await fs.mkdir(dir, { recursive: true }) @@ -32,6 +33,45 @@ function slugify(value) { .slice(0, 80) || 'note' } +function compact(value, limit = 1400) { + return String(value || '') + .replace(/^#{1,6}\s+/gm, '') + .replace(/\s+/g, ' ') + .trim() + .slice(0, limit) +} + +function sourceRef(hash) { + return `local-media:${String(hash).slice(0, 16)}` +} + +function inferTitle(text, fallback = 'Local source') { + const clean = compact(text, 500) + const url = clean.match(/\bhttps?:\/\/[^\s)]+/)?.[0] + if (url) return url.replace(/^https?:\/\//, '').replace(/[?#].*$/, '').slice(0, 90) + const line = String(text || '') + .split(/\n|[.!?]\s+/) + .map(s => compact(s, 120)) + .find(s => s.length >= 18 && s.length <= 120 && !/^(IMG_|temp_image|screenshot|screen shot)/i.test(s)) + return line || fallback +} + +function bullets(text, max = 7) { + const out = [] + const seen = new Set() + for (const part of String(text || '').split(/\n|[•*-]\s+/)) { + const line = compact(part, 180) + if (line.length < 24) continue + if (/^(IMG_|temp_image|screenshot|screen shot|save this|follow)/i.test(line)) continue + const key = line.toLowerCase() + if (seen.has(key)) continue + seen.add(key) + out.push(line) + if (out.length >= max) break + } + return out +} + async function extract(file) { const ext = path.extname(file).toLowerCase() if (['.md', '.txt', '.json', '.csv'].includes(ext)) return await fs.readFile(file, 'utf8') @@ -46,10 +86,22 @@ async function extract(file) { } function makeNote(source, hash, text) { - const title = path.basename(source, path.extname(source)).replace(/[-_]+/g, ' ') - const clean = text.replace(/\s+/g, ' ').trim() - const summary = clean.slice(0, 1200) || 'No extractable text. Add manual context and rerun enrichment.' - return `# ${title} + const title = inferTitle(text, 'Unextractable local source') + const facts = bullets(text) + const summary = compact(text, 900) || 'No extractable text. Keep this as an unreadable source marker until manual context is added.' + const ref = sourceRef(hash) + const ext = path.extname(source).toLowerCase().replace('.', '') || 'file' + return `--- +title: "${title.replace(/"/g, '\\"')}" +type: "knowledge-note" +source_type: "${ext}" +source_ref: "${ref}" +source_hash: "${hash}" +verified: "local extraction only" +status: "final-local" +--- + +# ${title} ## What This Is @@ -57,17 +109,31 @@ ${summary} ## Why It Matters -This note was created from a raw inbox item. Review it, verify source claims, and split it into smaller atoms if it contains multiple topics. +This note converts an inbox item into durable knowledge without storing unprocessed extraction text, screenshot names, or copied fragments as the primary memory object. + +## Key Points + +${facts.length ? facts.map(item => `- ${item}`).join('\n') : '- Local extraction produced too little text. Add manual context or mark the source unreadable.'} + +## How To Use It + +- Treat this as a local-first knowledge seed. +- Verify current claims against official docs, GitHub, or primary sources before adopting tools or decisions. +- Split into smaller notes when the source contains unrelated ideas. ## Source -- File: ${path.basename(source)} -- SHA-256: ${hash} +- ${ref} ## Verification -- Status: needs review -- Evidence: local source file +- Status: local extraction only. +- Evidence: SHA-256 source hash. +- Limitation: external facts, dates, prices, stars, and security claims are not confirmed by this run. + +## Related Notes + +- [[Mnemazine Protocol]] ## Reuse @@ -77,31 +143,48 @@ This note was created from a raw inbox item. Review it, verify source claims, an ` } +async function archiveFile(file, hash) { + const month = new Date().toISOString().slice(0, 7) + const dir = path.join(ARCHIVE, month) + await ensureDir(dir) + const ext = path.extname(file) + const target = path.join(dir, `${hash}${ext}`) + await fs.rename(file, target) + return target +} + async function main() { await ensureDir(INBOX) await ensureDir(VAULT) await ensureDir(path.dirname(CACHE)) + await ensureDir(ARCHIVE) const cache = await readJson(CACHE, {}) const entries = (await fs.readdir(INBOX, { withFileTypes: true })).filter(d => d.isFile()) let processed = 0 + const toArchive = [] for (const entry of entries) { const file = path.join(INBOX, entry.name) const hash = await sha256(file) if (cache[hash]) continue const text = await extract(file) - const noteName = `${new Date().toISOString().slice(0, 10)}-${slugify(entry.name)}.md` + const title = inferTitle(text, 'Unextractable local source') + const noteName = `${new Date().toISOString().slice(0, 10)}-${slugify(title)}.md` const notePath = path.join(VAULT, '01 Concepts', noteName) await ensureDir(path.dirname(notePath)) await fs.writeFile(notePath, makeNote(file, hash, text), 'utf8') cache[hash] = path.relative(VAULT, notePath) + toArchive.push({ file, hash }) processed += 1 } await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8') - spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs')], { stdio: 'inherit', env: process.env }) + const quality = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs')], { stdio: 'inherit', env: process.env }) + if (quality.status !== 0) process.exit(quality.status || 1) + const archived = [] + for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash)) if (spawnSync('graphify', ['--version'], { encoding: 'utf8' }).status === 0) { spawnSync('graphify', ['update', VAULT], { stdio: 'inherit' }) } - console.log(JSON.stringify({ inbox: entries.length, processed, vault: VAULT }, null, 2)) + console.log(JSON.stringify({ inbox: entries.length, processed, archived: archived.length, vault: VAULT }, null, 2)) } main().catch(err => { diff --git a/scripts/mnemazine-vault-quality-gate.mjs b/scripts/mnemazine-vault-quality-gate.mjs index 543a38f..79619d4 100755 --- a/scripts/mnemazine-vault-quality-gate.mjs +++ b/scripts/mnemazine-vault-quality-gate.mjs @@ -18,6 +18,12 @@ const badMarkers = [ /raw\s+ocr/i, /сырой\s+ocr(?!\s+исключ[её]н)/i, /распознанный\s+текст\s+без\s+обработки/i, + /intake-draft/i, + /draft-local/i, + /локальное\s+извлечение/i, + /\btemp_image[_-]/i, + /\bIMG_\d+/, + /\.(WEBP|PNG|JPE?G|HEIC|TIFF)\b/, /lorem ipsum/i, /TODO:\s*rewrite/i, /скриншот\s+без\s+контекста/i @@ -27,7 +33,11 @@ async function walk(dir) { const out = [] for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) { const p = path.join(dir, item.name) - if (item.isDirectory() && !['.git', '.obsidian', 'graphify-out'].includes(item.name)) out.push(...await walk(p)) + if ( + item.isDirectory() && + !['.git', '.obsidian'].includes(item.name) && + !item.name.startsWith('graphify-out') + ) out.push(...await walk(p)) else if (item.isFile() && p.endsWith('.md')) out.push(p) } return out