Initial open source release

This commit is contained in:
tv5171621-source
2026-06-15 02:47:14 +03:00
commit 5c59152c06
44 changed files with 1640 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
MNEMAZINE_ROOT="$HOME/Desktop/Mnemazine"
MNEMAZINE_INBOX="$HOME/Desktop/Mnemazine/inbox"
MNEMAZINE_VAULT="$HOME/Desktop/Mnemazine/vault"
MNEMAZINE_REPORTS="$HOME/Desktop/Mnemazine/reports"
MNEMAZINE_STATE="$HOME/Desktop/Mnemazine/.mnemazine/state"
MNEMAZINE_LANG="ru"
MNEMAZINE_WHISPER_MODEL="small"
+18
View File
@@ -0,0 +1,18 @@
.DS_Store
node_modules/
.venv/
__pycache__/
*.pyc
.env
.mnemazine/cache/
.mnemazine/tmp/
.mnemazine/bin/
.mnemazine/state/*.lock
inbox/*
!inbox/.gitkeep
vault/*
!vault/.gitkeep
reports/*
!reports/.gitkeep
graphify-out/
*.log
+22
View File
@@ -0,0 +1,22 @@
# Contributing
Mnemazine accepts contributions that make the system more portable, safer, and easier to use.
Good contributions:
- improve extraction quality;
- add source parsers;
- improve vault quality gates;
- add agent skills;
- improve Graphify integration;
- improve local-first installation;
- remove assumptions about one user or one machine.
Before opening a pull request:
```bash
bash scripts/check-public-release.sh
node scripts/mnemazine-vault-quality-gate.mjs --vault demo/vault
```
Do not commit secrets, private vaults, raw personal screenshots, cookies, tokens, or machine-specific paths.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Mnemazine contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+230
View File
@@ -0,0 +1,230 @@
# Mnemazine
**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.
![Mnemazine pipeline](docs/assets/screenshots/01-inbox-to-knowledge.svg)
## What It Is
Mnemazine is a local-first knowledge refinery.
It does not save raw OCR into your vault. It does not keep vague summaries that are impossible to reuse. It tries to produce finished knowledge:
- clear notes with understandable titles;
- source links and verification status;
- topic-based atomization when one source contains many ideas;
- reusable skill descriptions, agent instructions, implementation notes, and project actions;
- Graphify maps for semantic navigation;
- weekly HTML briefings with local state: `read`, `work on it`, `forget`.
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.
## Why It Saves Tokens
Mnemazine saves tokens by moving work out of repeated LLM context and into durable local structure.
Typical savings come from:
- **Local extraction first:** Apple Vision OCR, PDF parsing, transcription, hashing, and file census happen locally when possible.
- **Hash cache:** repeated files are detected before LLM processing. A duplicate costs zero model tokens.
- **Atomization:** one long guide can become twenty focused notes, so future prompts pull only the relevant atom.
- **Graphify context:** the agent can query a graph instead of dumping the whole vault into context.
- **Final notes only:** raw OCR and noisy transcripts stay outside the vault. The vault stores condensed, verified, human-readable knowledge.
- **Weekly briefs:** the system surfaces what changed and what deserves action, so the user does not ask the model to rediscover the week.
In real workflows, this often turns huge source piles into compact reusable notes. The exact savings depend on source size, but the operating principle is reliable: parse locally, cache aggressively, store refined atoms, retrieve narrowly.
## Install
Clone the project into the only folder you need:
```bash
git clone https://github.com/7teenno1-art/Mnemazine.git "$HOME/Desktop/Mnemazine"
cd "$HOME/Desktop/Mnemazine"
bash install.sh
```
After installation, open this folder as an Obsidian vault:
```text
~/Desktop/Mnemazine/vault
```
Everything lives under `~/Desktop/Mnemazine` by default:
- `inbox/` for raw inputs;
- `vault/` for finished knowledge;
- `reports/` for HTML weekly briefings;
- `.mnemazine/` for caches, binaries, and local state;
- `skills/`, `agents/`, `workflows/`, and `scripts/` for the agent system.
## Requirements
- macOS is recommended for Apple Vision OCR.
- Linux works for site parsing, markdown processing, Graphify, and vault operations, but Apple Vision OCR is skipped.
- Node.js 20+.
- Python 3.11+.
- Git.
- Optional: Obsidian, Claude Code, Codex, Cursor, OpenCode, Gemini CLI.
The installer checks what exists and installs what it can safely install locally. It does not require private credentials.
## One-Command Local Run
Put files into:
```text
~/Desktop/Mnemazine/inbox
```
Then run:
```bash
node scripts/mnemazine-run.mjs
```
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.
## Website Ingestion
Mnemazine can ingest a website and convert its useful pages into structured notes:
```bash
node scripts/mnemazine-ingest-site.mjs --url https://example.com --apply --graphify --max-pages 40
```
The parser looks for:
- `robots.txt` sitemap hints;
- `sitemap.xml`;
- same-origin links;
- page titles, descriptions, headings, and main text;
- JSON-LD blocks;
- public API hints inside same-origin JavaScript;
- GitHub links and documentation links.
It does not use private cookies or browser sessions by default. If a site needs authentication, export the data yourself and place it in `inbox/`.
![Site ingestion](docs/assets/screenshots/04-site-ingestion.svg)
## Knowledge Quality Contract
The vault must contain final knowledge, not raw material.
Every finished note should answer:
- What is this?
- Why does it matter?
- How can it be used?
- What are the source links?
- What is verified, assumed, or still unknown?
- Which skills, agents, scripts, or projects can reuse it?
Raw OCR, copied fragments, and messy transcripts are rejected by the quality gate.
Run the gate manually:
```bash
node scripts/mnemazine-vault-quality-gate.mjs
```
## Agent Skills
The repo includes portable Agent Skills in `.agents/skills` style:
- `skills/mnemazine` — the main knowledge refinery skill;
- `skills/local-doc-ops` — local document/PDF helpers.
The installer can copy them into common agent locations when those tools exist:
- `~/.codex/skills`;
- `~/.claude/skills`;
- project `.agents/skills`.
The skills are public-safe: no personal paths, no private repositories, no account names, no secrets.
## Graphify
Graphify turns the vault into a navigable relationship graph. Mnemazine uses it for:
- related-note discovery;
- graph-assisted retrieval;
- weekly change maps;
- finding duplicate or near-duplicate ideas;
- showing how a source affects multiple knowledge areas.
![Graphify map](docs/assets/screenshots/03-graphify-map.svg)
## Weekly HTML Brief
The weekly report is a local HTML presentation in Russian by default. It is meant to be pleasant to read, not a raw log.
Each card can be marked locally:
- `read` — keep in vault;
- `work` — move to action backlog;
- `forget` — remove or quarantine from the active vault.
State is stored in:
```text
~/Desktop/Mnemazine/.mnemazine/state/weekly-state.json
```
![Weekly HTML report](docs/assets/screenshots/02-weekly-html-report.svg)
## Repository Philosophy
Mnemazine is not a second brain as a storage slogan. It is a memory system as a pipeline:
```text
raw input -> extraction -> understanding -> research -> verification -> atomization -> vault -> graph -> reuse
```
That matters because a real memory must be reproducible. A note should be able to become:
- a skill;
- an agent instruction;
- a script;
- a product decision;
- a checklist;
- a weekly action;
- a future prompt with much less context.
## Documentation
- [Installation](docs/installation.md)
- [Architecture](docs/architecture.md)
- [Token Economics](docs/token-economics.md)
- [Website Ingestion](docs/site-ingestion.md)
- [Obsidian Vault](docs/obsidian.md)
- [Apple Vision OCR](docs/apple-vision.md)
- [Graphify](docs/graphify.md)
- [Weekly HTML Brief](docs/weekly-html.md)
## Safety
This public repository intentionally excludes:
- private vault contents;
- screenshots with personal data;
- API keys;
- SSH hosts;
- account names;
- private project names;
- local absolute paths from the original development machine.
## License
MIT.
+22
View File
@@ -0,0 +1,22 @@
# Security
Mnemazine is local-first. It should not require secrets for the default workflow.
Please report security issues privately through GitHub security advisories when available.
Never publish:
- API keys;
- OAuth tokens;
- SSH keys;
- browser cookies;
- private vault content;
- private screenshots;
- internal hostnames;
- personal absolute paths.
The public release check is:
```bash
bash scripts/check-public-release.sh
```
+17
View File
@@ -0,0 +1,17 @@
# KB Coordinator
Coordinates a Mnemazine run.
Responsibilities:
- protect the vault from raw dumps;
- route files to extraction, verification, atomization, and storage;
- ensure every inbox item has an outcome;
- update Graphify when available;
- create a short weekly or session brief.
Default folders:
- inbox: `MNEMAZINE_INBOX` or `~/Desktop/Mnemazine/inbox`;
- vault: `MNEMAZINE_VAULT` or `~/Desktop/Mnemazine/vault`;
- reports: `MNEMAZINE_REPORTS` or `~/Desktop/Mnemazine/reports`.
+12
View File
@@ -0,0 +1,12 @@
# KB Extract
Extracts raw content without interpretation.
Use:
- text read for `.md`, `.txt`, `.json`, `.csv`;
- `markitdown` for common documents;
- Apple Vision OCR for images on macOS;
- Whisper for audio and video when installed.
Output goes to cache, not directly to the vault.
+11
View File
@@ -0,0 +1,11 @@
# KB Guard
Protects the run.
Checks:
- no raw OCR in vault;
- no private paths in public artifacts;
- every note has source and meaning sections;
- duplicate files are skipped through hash cache;
- forgotten items are quarantined or removed only after explicit local state marks them.
+9
View File
@@ -0,0 +1,9 @@
# KB Refine
Turns extracted material into clear reusable notes.
The note must be understandable to a reader who has never seen the original file name or screenshot.
Avoid literal translation. Explain the idea in natural language.
If one source contains many topics, split it into many notes.
+11
View File
@@ -0,0 +1,11 @@
# KB Verify
Checks claims before they become durable knowledge.
Rules:
- prefer primary sources;
- include GitHub repository links when a tool or project is discussed;
- separate verified facts from assumptions;
- mark unknowns explicitly;
- do not invent installation steps.
+9
View File
@@ -0,0 +1,9 @@
# Example Raw Guide
This is a fake source file for a public demo.
It mentions three unrelated ideas:
1. Use local OCR before asking a model to read screenshots.
2. Split long guides into atomic notes.
3. Update a graph after changing a knowledge vault.
+30
View File
@@ -0,0 +1,30 @@
# Local OCR Before Model Vision
## What This Is
Local OCR extracts readable text from screenshots before an LLM is asked to interpret meaning.
## Why It Matters
OCR is cheaper, faster, and repeatable. It also creates a stable artifact that can be cached.
## How To Use It
Run Apple Vision OCR on macOS for images. Store the raw text in cache, then refine it into a note.
## Source
- Demo source: `demo/inbox/example-guide.md`
## Verification
- Status: demo
## Related Notes
- Graphify memory map
- Screenshot ingestion
## Reuse
- Add this as a step in screenshot ingestion skills.
+17
View File
@@ -0,0 +1,17 @@
# Apple Vision OCR
On macOS, Mnemazine can use Apple's Vision framework for local OCR.
Compile:
```bash
swiftc -O skills/mnemazine/vision-ocr.swift -o .mnemazine/bin/vision-ocr
```
Run:
```bash
.mnemazine/bin/vision-ocr path/to/image.png
```
The OCR output is raw material. It should be refined before entering the vault.
+45
View File
@@ -0,0 +1,45 @@
# Architecture
Mnemazine has five layers.
## 1. Inbox
Raw files enter through `inbox/`.
Examples:
- screenshots;
- PDFs;
- exported web pages;
- markdown notes;
- transcripts;
- links saved as `.md` files.
## 2. Extraction
Extraction is local-first:
- direct text read;
- MarkItDown;
- Apple Vision OCR;
- Whisper;
- custom parsers.
Extraction is not knowledge yet.
## 3. Refinement
The agent or workflow decides:
- what the source is about;
- whether it contains one topic or many;
- which claims need external verification;
- which notes already exist and should be updated.
## 4. Vault
The vault contains finished knowledge. It is Obsidian-compatible markdown.
## 5. Graph And Reports
Graphify builds relationship maps. Weekly HTML reports make the memory readable and actionable.
@@ -0,0 +1,32 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720">
<rect width="1280" height="720" fill="#f8fafc"/>
<rect x="72" y="72" width="1136" height="576" rx="28" fill="#fff" stroke="#e5e7eb"/>
<text x="104" y="132" font-family="-apple-system,Segoe UI,sans-serif" font-size="42" font-weight="700" fill="#111827">Mnemazine: from raw input to memory</text>
<g font-family="-apple-system,Segoe UI,sans-serif">
<rect x="104" y="198" width="190" height="130" rx="14" fill="#ffffff" stroke="#d0d5dd"/>
<text x="128" y="246" font-size="24" font-weight="700" fill="#0039a6">Inbox</text>
<text x="128" y="282" font-size="17" fill="#475467">screenshots, PDFs,</text>
<text x="128" y="306" font-size="17" fill="#475467">links, transcripts</text>
<path d="M304 263h92" stroke="#0039a6" stroke-width="5" stroke-linecap="round"/>
<path d="M388 250l18 13-18 13" fill="none" stroke="#0039a6" stroke-width="5"/>
<rect x="416" y="198" width="190" height="130" rx="14" fill="#ffffff" stroke="#d0d5dd"/>
<text x="440" y="246" font-size="24" font-weight="700" fill="#0039a6">Extract</text>
<text x="440" y="282" font-size="17" fill="#475467">local OCR, parsers,</text>
<text x="440" y="306" font-size="17" fill="#475467">hash cache</text>
<path d="M616 263h92" stroke="#d52b1e" stroke-width="5" stroke-linecap="round"/>
<path d="M700 250l18 13-18 13" fill="none" stroke="#d52b1e" stroke-width="5"/>
<rect x="728" y="198" width="190" height="130" rx="14" fill="#ffffff" stroke="#d0d5dd"/>
<text x="752" y="246" font-size="24" font-weight="700" fill="#d52b1e">Verify</text>
<text x="752" y="282" font-size="17" fill="#475467">sources, GitHub,</text>
<text x="752" y="306" font-size="17" fill="#475467">official docs</text>
<path d="M928 263h92" stroke="#0039a6" stroke-width="5" stroke-linecap="round"/>
<path d="M1012 250l18 13-18 13" fill="none" stroke="#0039a6" stroke-width="5"/>
<rect x="1040" y="198" width="120" height="130" rx="14" fill="#ffffff" stroke="#d0d5dd"/>
<text x="1064" y="246" font-size="24" font-weight="700" fill="#111827">Vault</text>
<text x="1064" y="282" font-size="17" fill="#475467">final</text>
<text x="1064" y="306" font-size="17" fill="#475467">notes</text>
<rect x="162" y="420" width="956" height="96" rx="16" fill="#f9fafb" stroke="#e5e7eb"/>
<text x="196" y="462" font-size="23" font-weight="700" fill="#111827">Rule</text>
<text x="196" y="496" font-size="21" fill="#344054">Raw OCR never becomes memory until it is understood, checked, and rewritten.</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720">
<rect width="1280" height="720" fill="#f8fafc"/>
<rect x="0" y="0" width="1280" height="160" fill="#fff"/>
<rect x="0" y="160" width="1280" height="150" fill="#0039a6"/>
<rect x="0" y="310" width="1280" height="110" fill="#d52b1e"/>
<text x="72" y="118" font-family="-apple-system,Segoe UI,sans-serif" font-size="64" font-weight="800" fill="#111827">Mnemazine Weekly</text>
<text x="76" y="230" font-family="-apple-system,Segoe UI,sans-serif" font-size="28" fill="#ffffff">Readable weekly memory, not a raw changelog</text>
<g font-family="-apple-system,Segoe UI,sans-serif">
<rect x="72" y="470" width="340" height="172" rx="12" fill="#fff" stroke="#e5e7eb"/>
<text x="96" y="510" font-size="22" font-weight="700" fill="#111827">Local OCR before vision</text>
<text x="96" y="548" font-size="17" fill="#475467">Cheaper extraction. Stable cache.</text>
<rect x="96" y="590" width="82" height="34" rx="7" fill="#fff" stroke="#0039a6"/><text x="114" y="612" font-size="14" fill="#0039a6">Read</text>
<rect x="190" y="590" width="82" height="34" rx="7" fill="#fff" stroke="#d52b1e"/><text x="208" y="612" font-size="14" fill="#d52b1e">Work</text>
<rect x="284" y="590" width="82" height="34" rx="7" fill="#fff" stroke="#98a2b3"/><text x="302" y="612" font-size="14" fill="#475467">Forget</text>
<rect x="470" y="470" width="340" height="172" rx="12" fill="#fff" stroke="#e5e7eb"/>
<text x="494" y="510" font-size="22" font-weight="700" fill="#111827">Graph after ingest</text>
<text x="494" y="548" font-size="17" fill="#475467">New notes become navigable context.</text>
<rect x="494" y="590" width="82" height="34" rx="7" fill="#111827"/><text x="512" y="612" font-size="14" fill="#fff">Read</text>
<rect x="868" y="470" width="340" height="172" rx="12" fill="#fff" stroke="#e5e7eb"/>
<text x="892" y="510" font-size="22" font-weight="700" fill="#111827">Split long guides</text>
<text x="892" y="548" font-size="17" fill="#475467">One source can become many notes.</text>
<rect x="892" y="590" width="82" height="34" rx="7" fill="#fff" stroke="#0039a6"/><text x="910" y="612" font-size="14" fill="#0039a6">Read</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720">
<rect width="1280" height="720" fill="#ffffff"/>
<text x="72" y="98" font-family="-apple-system,Segoe UI,sans-serif" font-size="46" font-weight="800" fill="#111827">Graphify memory map</text>
<g stroke-width="3" stroke="#d0d5dd">
<line x1="318" y1="310" x2="528" y2="220"/><line x1="318" y1="310" x2="560" y2="430"/><line x1="528" y1="220" x2="780" y2="262"/><line x1="560" y1="430" x2="818" y2="450"/><line x1="780" y1="262" x2="818" y2="450"/><line x1="780" y1="262" x2="970" y2="330"/>
</g>
<g font-family="-apple-system,Segoe UI,sans-serif" font-size="18" font-weight="700">
<circle cx="318" cy="310" r="70" fill="#0039a6"/><text x="274" y="316" fill="#fff">OCR</text>
<circle cx="528" cy="220" r="82" fill="#f8fafc" stroke="#0039a6" stroke-width="4"/><text x="474" y="226" fill="#111827">Extraction</text>
<circle cx="560" cy="430" r="86" fill="#f8fafc" stroke="#d52b1e" stroke-width="4"/><text x="506" y="436" fill="#111827">Atomization</text>
<circle cx="780" cy="262" r="74" fill="#d52b1e"/><text x="742" y="268" fill="#fff">Sources</text>
<circle cx="818" cy="450" r="78" fill="#f8fafc" stroke="#0039a6" stroke-width="4"/><text x="772" y="456" fill="#111827">Skills</text>
<circle cx="970" cy="330" r="84" fill="#111827"/><text x="918" y="336" fill="#fff">Agents</text>
</g>
<text x="72" y="650" font-family="-apple-system,Segoe UI,sans-serif" font-size="24" fill="#475467">Graph context lets agents retrieve related knowledge without reading the whole vault.</text>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

@@ -0,0 +1,27 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720">
<rect width="1280" height="720" fill="#f8fafc"/>
<text x="72" y="96" font-family="-apple-system,Segoe UI,sans-serif" font-size="48" font-weight="800" fill="#111827">Website ingestion</text>
<g font-family="-apple-system,Segoe UI,sans-serif">
<rect x="72" y="150" width="260" height="380" rx="14" fill="#fff" stroke="#e5e7eb"/>
<text x="104" y="205" font-size="28" font-weight="700" fill="#0039a6">Discover</text>
<text x="104" y="252" font-size="20" fill="#475467">robots.txt</text>
<text x="104" y="292" font-size="20" fill="#475467">sitemap.xml</text>
<text x="104" y="332" font-size="20" fill="#475467">same-origin links</text>
<rect x="394" y="150" width="260" height="380" rx="14" fill="#fff" stroke="#e5e7eb"/>
<text x="426" y="205" font-size="28" font-weight="700" fill="#d52b1e">Extract</text>
<text x="426" y="252" font-size="20" fill="#475467">title</text>
<text x="426" y="292" font-size="20" fill="#475467">headings</text>
<text x="426" y="332" font-size="20" fill="#475467">visible text</text>
<text x="426" y="372" font-size="20" fill="#475467">GitHub links</text>
<rect x="716" y="150" width="260" height="380" rx="14" fill="#fff" stroke="#e5e7eb"/>
<text x="748" y="205" font-size="28" font-weight="700" fill="#0039a6">Refine</text>
<text x="748" y="252" font-size="20" fill="#475467">meaning</text>
<text x="748" y="292" font-size="20" fill="#475467">verification</text>
<text x="748" y="332" font-size="20" fill="#475467">atom notes</text>
<rect x="1038" y="150" width="170" height="380" rx="14" fill="#111827"/>
<text x="1070" y="205" font-size="28" font-weight="700" fill="#fff">Vault</text>
<text x="1070" y="252" font-size="20" fill="#fff">final</text>
<text x="1070" y="292" font-size="20" fill="#fff">knowledge</text>
<path d="M342 340h40" stroke="#0039a6" stroke-width="5"/><path d="M664 340h40" stroke="#d52b1e" stroke-width="5"/><path d="M986 340h40" stroke="#0039a6" stroke-width="5"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

+20
View File
@@ -0,0 +1,20 @@
# Graphify
Install:
```bash
python3 -m pip install graphifyy
```
Update graph:
```bash
graphify update ~/Desktop/Mnemazine/vault
```
Graphify helps Mnemazine:
- find related notes;
- detect clusters;
- avoid duplicate concepts;
- build graph-aware context for agents.
+42
View File
@@ -0,0 +1,42 @@
# Installation
Install into one folder:
```bash
git clone https://github.com/7teenno1-art/Mnemazine.git "$HOME/Desktop/Mnemazine"
cd "$HOME/Desktop/Mnemazine"
bash install.sh
```
The installer creates:
- `inbox/`;
- `vault/`;
- `reports/`;
- `.mnemazine/cache/`;
- `.mnemazine/state/`;
- `.mnemazine/bin/`.
Open `vault/` in Obsidian.
## macOS
On macOS, the installer tries to compile Apple Vision OCR:
```bash
swiftc -O skills/mnemazine/vision-ocr.swift -o .mnemazine/bin/vision-ocr
```
If this fails, install Xcode Command Line Tools:
```bash
xcode-select --install
```
## Python
Python dependencies are installed into `.venv/`. This keeps the system local to the Mnemazine folder.
## Agent Skills
If Codex or Claude skill folders exist, the installer copies portable skills there. If they do not exist, nothing breaks.
+18
View File
@@ -0,0 +1,18 @@
# Obsidian
Open this folder as an Obsidian vault:
```text
~/Desktop/Mnemazine/vault
```
Recommended folders:
- `00 System`;
- `01 Concepts`;
- `02 Tools`;
- `03 Agents`;
- `04 Projects`;
- `99 Archive`.
Mnemazine notes are plain markdown. Obsidian is optional, but useful for backlinks, search, and manual editing.
+26
View File
@@ -0,0 +1,26 @@
# Website Ingestion
Run:
```bash
node scripts/mnemazine-ingest-site.mjs --url https://example.com --apply --graphify --max-pages 40
```
The parser discovers pages through:
- `robots.txt`;
- sitemap links;
- `sitemap.xml`;
- same-origin links on the seed page.
For every page it extracts:
- title;
- headings;
- visible text;
- GitHub links;
- source URL.
The output is a markdown note with verification status. The note is not considered perfect final knowledge until it is reviewed and split if needed.
Authentication is intentionally excluded from the default parser. Public open-source users should not leak browser sessions, cookies, or private dashboards into a knowledge pipeline.
+41
View File
@@ -0,0 +1,41 @@
# Token Economics
Mnemazine reduces token use by keeping repeated, mechanical, and already-known work outside the model context.
## Local Work Costs Zero Model Tokens
These operations can happen without LLM calls:
- file listing;
- hashing;
- duplicate detection;
- OCR;
- PDF extraction;
- transcription;
- graph update;
- quality gate checks.
## Hash Cache
Every inbox file receives a SHA-256 hash. If the same file appears again, Mnemazine can skip it.
## Atomization
A long guide often contains many unrelated ideas. Storing it as one giant note forces future prompts to read too much. Splitting it into atoms lets an agent retrieve only the relevant part.
## Graphify Retrieval
Graphify helps retrieve related context through graph structure. That is cheaper than placing a whole vault into a prompt.
## Final Notes
Final notes are smaller than raw OCR because they remove:
- duplicate text;
- navigation;
- boilerplate;
- broken OCR;
- irrelevant screenshots;
- repeated introductions.
The result is a vault that becomes cheaper to query over time.
+23
View File
@@ -0,0 +1,23 @@
# Weekly HTML Brief
Generate:
```bash
node scripts/mnemazine-weekly-brief-html.mjs
```
The report appears in:
```text
~/Desktop/Mnemazine/reports
```
The default report language is Russian because the first public release was designed around Russian reading flow. The template can be localized.
Card states:
- `Прочитал` means keep the note;
- `В работу` means convert the note into an action;
- `Забыть` means remove or archive it.
The browser stores state locally.
+27
View File
@@ -0,0 +1,27 @@
# Agent Browser Control
## What This Is
Agent browser control is a pattern where an AI assistant operates a browser to inspect pages, click through flows, collect evidence, and verify that a local web interface works as expected.
## Why It Matters
It reduces blind coding. Instead of assuming a UI works, the agent can open it, inspect screenshots, and check actual rendered state.
## How To Use It
Use browser control after frontend changes, during local app verification, or when a website needs structured inspection.
## Source
- Example source: public documentation or local browser plugin docs.
## Verification
- Status: example note
- Evidence: not tied to a private source
## Reuse
- Can become a testing skill.
- Can become a frontend verification checklist.
+1
View File
@@ -0,0 +1 @@
Executable
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${MNEMAZINE_ROOT:-$HOME/Desktop/Mnemazine}"
INBOX="${MNEMAZINE_INBOX:-$ROOT/inbox}"
VAULT="${MNEMAZINE_VAULT:-$ROOT/vault}"
REPORTS="${MNEMAZINE_REPORTS:-$ROOT/reports}"
STATE="${MNEMAZINE_STATE:-$ROOT/.mnemazine/state}"
BIN="$ROOT/.mnemazine/bin"
mkdir -p "$INBOX" "$VAULT" "$REPORTS" "$STATE" "$BIN" "$ROOT/.mnemazine/cache"
mkdir -p "$VAULT/00 System" "$VAULT/01 Concepts" "$VAULT/02 Tools" "$VAULT/03 Agents" "$VAULT/04 Projects" "$VAULT/99 Archive"
if command -v python3 >/dev/null 2>&1; then
python3 -m venv "$ROOT/.venv" || true
"$ROOT/.venv/bin/python" -m pip install --upgrade pip
"$ROOT/.venv/bin/python" -m pip install -r "$ROOT/requirements.txt" || true
fi
if command -v swiftc >/dev/null 2>&1 && [ -f "$ROOT/skills/mnemazine/vision-ocr.swift" ]; then
swiftc -O "$ROOT/skills/mnemazine/vision-ocr.swift" -o "$BIN/vision-ocr" || true
fi
if [ -d "$HOME/.codex/skills" ]; then
mkdir -p "$HOME/.codex/skills"
cp -R "$ROOT/skills/mnemazine" "$HOME/.codex/skills/" 2>/dev/null || true
cp -R "$ROOT/skills/local-doc-ops" "$HOME/.codex/skills/" 2>/dev/null || true
fi
if [ -d "$HOME/.claude/skills" ]; then
mkdir -p "$HOME/.claude/skills"
cp -R "$ROOT/skills/mnemazine" "$HOME/.claude/skills/" 2>/dev/null || true
cp -R "$ROOT/skills/local-doc-ops" "$HOME/.claude/skills/" 2>/dev/null || true
fi
cat > "$VAULT/00 System/Mnemazine Protocol.md" <<'EOF'
# Mnemazine Protocol
The vault contains finished knowledge only.
Raw OCR, copied fragments, transcripts, screenshots, and unverified dumps stay in `inbox/`, `.mnemazine/cache/`, or `99 Archive/`.
Every durable note should contain:
- clear title;
- short explanation;
- source links;
- verified facts;
- open questions;
- practical use;
- related notes.
EOF
cat > "$ROOT/.mnemazine/config.json" <<EOF
{
"root": "$ROOT",
"inbox": "$INBOX",
"vault": "$VAULT",
"reports": "$REPORTS",
"state": "$STATE",
"ocr": "$BIN/vision-ocr"
}
EOF
echo "Mnemazine installed."
echo "Root: $ROOT"
echo "Inbox: $INBOX"
echo "Vault: $VAULT"
echo "Open the vault folder in Obsidian."
+27
View File
@@ -0,0 +1,27 @@
{
"name": "mnemazine",
"version": "0.1.0",
"private": false,
"type": "module",
"description": "Open-source memory system that turns raw inputs into verified reusable knowledge.",
"scripts": {
"install:local": "bash install.sh",
"run": "node scripts/mnemazine-run.mjs",
"ingest:site": "node scripts/mnemazine-ingest-site.mjs",
"weekly": "node scripts/mnemazine-weekly-brief-html.mjs",
"quality": "node scripts/mnemazine-vault-quality-gate.mjs",
"public-check": "bash scripts/check-public-release.sh"
},
"keywords": [
"knowledge-base",
"obsidian",
"agent-skills",
"ocr",
"graphify",
"personal-knowledge-management"
],
"license": "MIT",
"engines": {
"node": ">=20"
}
}
+18
View File
@@ -0,0 +1,18 @@
# Mnemazine Protocol
Mnemazine is a memory system, not a file dump.
## Rules
1. Raw material starts in `inbox/`.
2. Extracted text can live in `.mnemazine/cache/`.
3. The vault stores final knowledge only.
4. One source may become many notes.
5. Every note needs source links and verification state.
6. Public tools should include GitHub or official documentation links when available.
7. Graphify updates after meaningful vault changes.
8. Weekly briefs turn new knowledge into decisions.
## Forgetting
If an item is marked `forget`, remove it from the active vault or move it to archive. Forgetting is part of memory hygiene.
+1
View File
@@ -0,0 +1 @@
+8
View File
@@ -0,0 +1,8 @@
markitdown
fastembed
pymupdf
pypdf
reportlab
pillow
openai-whisper
graphifyy
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}"
if rg -n '/Users/fil|72\.56|root@|Полезные знания|_ВХОДЯЩИЕ|TODOCUPS|ПКК|legal-practice|Adventure Book|AthenaOS|Филипп' "$ROOT" -g '!node_modules/**' -g '!.git/**' -g '!scripts/check-public-release.sh'; then
echo "Public release check failed: private marker found." >&2
exit 1
fi
if rg -n 'gho_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[baprs]-[A-Za-z0-9-]+' "$ROOT" -g '!node_modules/**' -g '!.git/**' -g '!scripts/check-public-release.sh'; then
echo "Public release check failed: token-like value found." >&2
exit 1
fi
echo "Public release check passed."
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import path from 'node:path'
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)
function arg(name, fallback = '') {
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
if (!hit) return fallback
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
}
const seed = arg('url')
const apply = argv.includes('--apply')
const graphify = argv.includes('--graphify')
const maxPages = Number(arg('max-pages', '40'))
if (!seed) {
console.error('Usage: node scripts/mnemazine-ingest-site.mjs --url https://example.com [--apply] [--graphify] [--max-pages 40]')
process.exit(2)
}
function escMd(s) {
return String(s || '').replace(/\r/g, '').trim()
}
function stripHtml(html) {
return String(html)
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<\/(h[1-4]|p|li|section|article|div)>/gi, '\n')
.replace(/<h([1-4])[^>]*>/gi, '\n### ')
.replace(/<[^>]+>/g, ' ')
.replace(/&nbsp;/g, ' ')
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.replace(/&#39;|&#x27;/g, "'")
.replace(/\s+\n/g, '\n')
.replace(/[ \t]{2,}/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
function slug(value) {
return String(value || 'site')
.toLowerCase()
.replace(/^https?:\/\//, '')
.replace(/[^a-z0-9а-я]+/gi, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 90) || 'site'
}
async function fetchText(url, optional = false) {
try {
const res = await fetch(url, { headers: { 'user-agent': 'Mnemazine/0.1 local knowledge ingest' } })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return await res.text()
} catch (err) {
if (optional) return ''
throw err
}
}
function links(html, base) {
const out = new Set()
for (const m of html.matchAll(/<a[^>]+href=["']([^"']+)["']/gi)) {
try {
const u = new URL(m[1], base)
if (u.origin === new URL(base).origin) out.add(u.href.replace(/#.*$/, ''))
} catch {}
}
return [...out]
}
async function discover(seedUrl) {
const origin = new URL(seedUrl).origin
const urls = new Set([seedUrl])
const robots = await fetchText(`${origin}/robots.txt`, true)
const sitemaps = [...robots.matchAll(/Sitemap:\s*(\S+)/gi)].map(m => m[1])
for (const sm of sitemaps.length ? sitemaps : [`${origin}/sitemap.xml`]) {
const xml = await fetchText(sm, true)
for (const m of xml.matchAll(/<loc>(.*?)<\/loc>/g)) {
try {
const u = new URL(m[1])
if (u.origin === origin) urls.add(u.href)
} catch {}
}
}
if (urls.size === 1) {
const html = await fetchText(seedUrl, true)
links(html, seedUrl).forEach(u => urls.add(u))
}
return [...urls].slice(0, maxPages)
}
function pageNote(url, html) {
const title = stripHtml(html.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i)?.[1] || html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] || url)
const text = stripHtml(html)
const github = [...html.matchAll(/https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+/g)].map(m => m[0])
return `# ${title}
## What This Is
This note was created from a public web page and should be refined into smaller durable notes if it contains several topics.
## Source
- URL: ${url}
## Extracted Knowledge
${escMd(text.slice(0, 6000))}
## Public Repositories Mentioned
${github.length ? [...new Set(github)].map(u => `- ${u}`).join('\n') : '- None found on this page.'}
## Verification
- Status: extracted from public page
- Needs: human or agent review before treating as final operational knowledge
`
}
const urls = await discover(seed)
const outDir = path.join(ROOT, '.mnemazine/cache/site-ingest', slug(seed))
await fs.mkdir(outDir, { recursive: true })
const notes = []
for (const url of urls) {
const html = await fetchText(url, true)
if (!html.trim()) continue
const note = pageNote(url, html)
const file = `${new Date().toISOString().slice(0, 10)}-${slug(url)}.md`
const target = apply ? path.join(VAULT, '01 Concepts', file) : path.join(outDir, file)
await fs.mkdir(path.dirname(target), { recursive: true })
await fs.writeFile(target, note, 'utf8')
notes.push(target)
}
if (graphify) {
await import('node:child_process').then(({ spawnSync }) => spawnSync('graphify', ['update', VAULT], { stdio: 'inherit' }))
}
console.log(JSON.stringify({ seed, pages: urls.length, notes: notes.length, applied: apply, output: apply ? VAULT : outDir }, null, 2))
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import { existsSync } from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
import { spawnSync } from 'node:child_process'
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')
async function ensureDir(dir) {
await fs.mkdir(dir, { recursive: true })
}
async function sha256(file) {
const hash = crypto.createHash('sha256')
hash.update(await fs.readFile(file))
return hash.digest('hex')
}
async function readJson(file, fallback) {
try { return JSON.parse(await fs.readFile(file, 'utf8')) } catch { return fallback }
}
function slugify(value) {
return String(value || 'note')
.toLowerCase()
.replace(/[^a-zа-я0-9]+/gi, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 80) || 'note'
}
async function extract(file) {
const ext = path.extname(file).toLowerCase()
if (['.md', '.txt', '.json', '.csv'].includes(ext)) return await fs.readFile(file, 'utf8')
const markitdown = spawnSync('markitdown', [file], { encoding: 'utf8' })
if (markitdown.status === 0 && markitdown.stdout.trim()) return markitdown.stdout
const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
if (existsSync(ocr) && ['.png', '.jpg', '.jpeg', '.heic', '.webp', '.tiff'].includes(ext)) {
const out = spawnSync(ocr, [file], { encoding: 'utf8' })
if (out.status === 0) return out.stdout
}
return ''
}
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}
## What This Is
${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.
## Source
- File: ${path.basename(source)}
- SHA-256: ${hash}
## Verification
- Status: needs review
- Evidence: local source file
## Reuse
- Turn stable procedures into skills.
- Turn repeated decisions into checklists.
- Link related notes after Graphify update.
`
}
async function main() {
await ensureDir(INBOX)
await ensureDir(VAULT)
await ensureDir(path.dirname(CACHE))
const cache = await readJson(CACHE, {})
const entries = (await fs.readdir(INBOX, { withFileTypes: true })).filter(d => d.isFile())
let processed = 0
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 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)
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 })
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))
}
main().catch(err => {
console.error(err)
process.exit(1)
})
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import path from 'node:path'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const argv = process.argv.slice(2)
function arg(name, fallback = '') {
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
if (!hit) return fallback
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
}
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')))
const badMarkers = [
/raw\s+ocr/i,
/сырой\s+ocr/i,
/распознанный\s+текст\s+без\s+обработки/i,
/lorem ipsum/i,
/TODO:\s*rewrite/i,
/скриншот\s+без\s+контекста/i
]
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()) out.push(...await walk(p))
else if (item.isFile() && p.endsWith('.md')) out.push(p)
}
return out
}
const files = await walk(VAULT)
const failures = []
for (const file of files) {
const text = await fs.readFile(file, 'utf8')
const hit = badMarkers.find(re => re.test(text))
const hasSource = /## Source|## Источник|source:/i.test(text)
const hasMeaning = /## What This Is|## Что это|## Суть/i.test(text)
if (hit || !hasSource || !hasMeaning) {
failures.push({ file: path.relative(VAULT, file), marker: hit ? String(hit) : 'missing required sections' })
}
}
if (failures.length) {
console.error(JSON.stringify({ ok: false, failures }, null, 2))
process.exit(1)
}
console.log(JSON.stringify({ ok: true, checked: files.length }, null, 2))
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import path from 'node:path'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
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()) out.push(...await walk(p))
else if (item.isFile() && p.endsWith('.md')) out.push(p)
}
return out
}
function esc(s) {
return String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
}
function titleOf(text, file) {
return text.match(/^#\s+(.+)$/m)?.[1]?.trim() || path.basename(file, '.md')
}
function summaryOf(text) {
const block = text.match(/## (?:What This Is|Что это|Суть)\s+([\s\S]*?)(\n## |$)/i)?.[1] || text
return block.replace(/[#*_`>-]/g, '').replace(/\s+/g, ' ').trim().slice(0, 520)
}
await fs.mkdir(REPORTS, { recursive: true })
await fs.mkdir(STATE, { recursive: true })
const files = await walk(VAULT)
const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
const cards = []
for (const file of files) {
const stat = await fs.stat(file)
if (stat.mtimeMs < weekAgo) continue
const text = await fs.readFile(file, 'utf8')
cards.push({ file: path.relative(VAULT, file), title: titleOf(text, file), summary: summaryOf(text) })
}
const html = `<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mnemazine Weekly</title>
<style>
:root{--blue:#0039a6;--red:#d52b1e;--ink:#111827;--muted:#667085;--line:#e5e7eb;--bg:#f8fafc}
*{box-sizing:border-box}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:var(--bg);color:var(--ink)}
header{min-height:48vh;padding:56px max(24px,8vw);background:linear-gradient(180deg,#fff 0 32%,var(--blue) 32% 66%,var(--red) 66%);color:white;display:flex;align-items:end}
.hero{max-width:980px;text-shadow:0 1px 24px rgba(0,0,0,.22)}h1{font-size:clamp(42px,7vw,92px);line-height:.95;margin:0 0 18px;letter-spacing:0}.lead{font-size:22px;max-width:760px;margin:0;color:#fff}
main{padding:34px max(18px,6vw) 70px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px}
.card{background:#fff;border:1px solid var(--line);border-radius:8px;padding:20px;box-shadow:0 10px 28px rgba(17,24,39,.06)}
.path{font-size:12px;color:var(--muted);margin-bottom:10px}.card h2{font-size:20px;line-height:1.18;margin:0 0 10px}.card p{font-size:15px;line-height:1.55;color:#344054}
.actions{display:flex;gap:8px;margin-top:16px}.actions button{border:1px solid var(--line);background:#fff;border-radius:7px;padding:9px 10px;font-weight:650;cursor:pointer}.actions button[data-v=read]{color:var(--blue)}.actions button[data-v=work]{color:var(--red)}.actions button[data-v=forget]{color:#475467}
.actions button.active{background:var(--ink);color:white;border-color:var(--ink)}
</style>
</head>
<body>
<header><section class="hero"><h1>Mnemazine Weekly</h1><p class="lead">Сводка знаний за последние 7 дней: что появилось, что стоит взять в работу, что можно забыть.</p></section></header>
<main><section class="grid">
${cards.map((c, i) => `<article class="card" data-id="${esc(c.file)}"><div class="path">${esc(c.file)}</div><h2>${esc(c.title)}</h2><p>${esc(c.summary)}</p><div class="actions"><button data-v="read">Прочитал</button><button data-v="work">В работу</button><button data-v="forget">Забыть</button></div></article>`).join('\n') || '<article class="card"><h2>За неделю новых заметок нет</h2><p>Положите материалы в inbox и запустите Mnemazine.</p></article>'}
</section></main>
<script>
const KEY='mnemazine-weekly-state';
const state=JSON.parse(localStorage.getItem(KEY)||'{}');
document.querySelectorAll('.card').forEach(card=>{
const id=card.dataset.id;
card.querySelectorAll('button').forEach(btn=>{
if(state[id]===btn.dataset.v) btn.classList.add('active');
btn.onclick=()=>{state[id]=btn.dataset.v;localStorage.setItem(KEY,JSON.stringify(state));card.querySelectorAll('button').forEach(b=>b.classList.remove('active'));btn.classList.add('active')}
})
})
</script>
</body></html>`
const out = path.join(REPORTS, `${new Date().toISOString().slice(0, 10)}-weekly-mnemazine.html`)
await fs.writeFile(out, html, 'utf8')
await fs.writeFile(path.join(STATE, 'weekly-state.example.json'), JSON.stringify({ note: 'Browser localStorage stores per-card state by default.' }, null, 2), 'utf8')
console.log(out)
+23
View File
@@ -0,0 +1,23 @@
---
name: local-doc-ops
description: Use when extracting, inspecting, splitting, or converting local PDFs, documents, and image-based files before they enter a knowledge pipeline.
---
# Local Document Operations
Use local deterministic tools before spending model context.
Preferred order:
1. Use structured parsers for PDFs and office documents.
2. Use Apple Vision OCR for images on macOS.
3. Use transcription for audio or video.
4. Only then ask a model to interpret unclear content.
Keep raw extracted text in cache or inbox. Write only refined knowledge into the vault.
Bundled helper:
```bash
python skills/local-doc-ops/pdf-kit.py --help
```
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""
pdf-kit — локальный PDF-тулкит для юрпрактики. $0, без Docker, на PyMuPDF (fitz).
OCR делает Apple Vision (vision-ocr) — здесь НЕ дублируется.
Команды:
merge OUT.pdf IN1 IN2 ... сшить файлы (PDF+картинки) в один PDF ПО ПОРЯДКУ
compress IN.pdf OUT.pdf сжать PDF (deflate + чистка мусора + сабсет шрифтов)
img2pdf OUT.pdf IMG1 IMG2 ... картинки → один PDF (по порядку)
sign IN.pdf OUT.pdf SIG.png наложить подпись-картинку: --page N (1-based, def посл.) --x --y (доля 0..1, def 0.62/0.78) --w (доля ширины, def 0.25)
extract IN.pdf [OUT.md] PDF → markdown (markitdown) для изучения в Мнемозине
pages IN.pdf инфо: число страниц, размер
Пути с пробелами/юникодом — в кавычках. Документы остаются ЛОКАЛЬНО (ничего не уходит наружу).
"""
import sys, os, subprocess
def _fitz():
import fitz
return fitz
IMG_EXT = (".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff", ".bmp", ".heic", ".heif", ".gif")
def _add_file_to_doc(doc, fitz, path):
ext = os.path.splitext(path)[1].lower()
if ext == ".pdf":
with fitz.open(path) as src:
doc.insert_pdf(src)
elif ext in IMG_EXT:
img = fitz.open(path)
rect = img[0].rect
pdfbytes = img.convert_to_pdf()
img.close()
with fitz.open("pdf", pdfbytes) as imgpdf:
doc.insert_pdf(imgpdf)
else:
raise SystemExit(f"merge: не поддержан тип {ext} ({os.path.basename(path)}). PDF/картинки.")
def cmd_merge(args):
fitz = _fitz()
out, ins = args[0], args[1:]
if not ins:
raise SystemExit("merge OUT.pdf IN1 IN2 ...")
doc = fitz.open()
for p in ins:
if not os.path.exists(p):
raise SystemExit(f"нет файла: {p}")
_add_file_to_doc(doc, fitz, p)
doc.save(out, garbage=4, deflate=True)
doc.close()
print(f"OK merge → {out} ({len(ins)} файлов по порядку)")
def cmd_img2pdf(args):
cmd_merge(args) # merge уже принимает картинки
def cmd_compress(args):
fitz = _fitz()
src, out = args[0], args[1]
before = os.path.getsize(src)
doc = fitz.open(src)
doc.save(out, garbage=4, deflate=True, deflate_images=True, deflate_fonts=True, clean=True)
doc.close()
after = os.path.getsize(out)
pct = round((1 - after / before) * 100) if before else 0
print(f"OK compress → {out} ({before//1024}KB → {after//1024}KB, -{pct}%)")
def cmd_sign(args):
fitz = _fitz()
opts = {a.split("=")[0]: a.split("=")[1] for a in args if a.startswith("--") and "=" in a}
pos = [a for a in args if not a.startswith("--")]
src, out, sig = pos[0], pos[1], pos[2]
doc = fitz.open(src)
page_n = int(opts.get("--page", len(doc))) # 1-based; def последняя
page = doc[page_n - 1]
pr = page.rect
fx = float(opts.get("--x", 0.62)); fy = float(opts.get("--y", 0.78)); fw = float(opts.get("--w", 0.25))
from PIL import Image
iw, ih = Image.open(sig).size
w = pr.width * fw
h = w * ih / iw
x0 = pr.width * fx; y0 = pr.height * fy
page.insert_image(fitz.Rect(x0, y0, x0 + w, y0 + h), filename=sig, keep_proportion=True, overlay=True)
doc.save(out, garbage=4, deflate=True)
doc.close()
print(f"OK sign → {out} (стр {page_n}, подпись {os.path.basename(sig)})")
def cmd_extract(args):
src = args[0]
out = args[1] if len(args) > 1 else os.path.splitext(src)[0] + ".md"
r = subprocess.run(["markitdown", src], capture_output=True, text=True)
if r.returncode != 0:
raise SystemExit("markitdown error: " + r.stderr[:300])
open(out, "w").write(r.stdout)
print(f"OK extract → {out} ({len(r.stdout)} симв, для Мнемозины)")
def cmd_pages(args):
fitz = _fitz()
doc = fitz.open(args[0])
print(f"{os.path.basename(args[0])}: {len(doc)} стр, {os.path.getsize(args[0])//1024}KB")
doc.close()
CMDS = {"merge": cmd_merge, "img2pdf": cmd_img2pdf, "compress": cmd_compress,
"sign": cmd_sign, "extract": cmd_extract, "pages": cmd_pages}
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] not in CMDS:
print(__doc__); sys.exit(0 if len(sys.argv) < 2 else 1)
CMDS[sys.argv[1]](sys.argv[2:])
+52
View File
@@ -0,0 +1,52 @@
---
name: mnemazine
description: Use when turning raw files, links, screenshots, transcripts, PDFs, guides, or repositories into verified reusable knowledge for an Obsidian-compatible vault.
---
# Mnemazine
Mnemazine is a knowledge refinery skill.
Use it when the user gives raw material and wants it preserved as durable knowledge, not as a dump.
## Contract
The vault stores final knowledge only.
Do not write raw OCR, copied fragments, noisy transcripts, or unverified paste dumps directly into the vault.
## Workflow
1. Identify what the source is: screenshot, PDF, site, code repo, video, transcript, guide, or inline text.
2. Extract locally when possible: text parser, PDF parser, Apple Vision OCR, or transcription.
3. Understand the topic before writing.
4. Research public sources when the claim depends on current or external facts.
5. Split one source into multiple notes when it contains multiple unrelated ideas.
6. Write clear notes with source links, verification status, practical use, and related concepts.
7. Run the vault quality gate.
8. Update Graphify when available.
9. Produce a short action brief when the new knowledge implies work.
## Note Shape
Every durable note should contain:
- `What This Is`;
- `Why It Matters`;
- `How To Use It`;
- `Source`;
- `Verification`;
- `Related Notes`;
- `Reuse`.
## Local Paths
Use environment variables:
- `MNEMAZINE_ROOT`;
- `MNEMAZINE_INBOX`;
- `MNEMAZINE_VAULT`;
- `MNEMAZINE_REPORTS`;
- `MNEMAZINE_STATE`.
Never assume a specific username, home path, private project, SSH host, or API key.
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""kb-embed — локальный семантический индекс vault для дедупа Мнемозины.
Без Ollama/облака: fastembed (onnxruntime) + multilingual-e5-small, CPU.
Ловит смысловые дубли, которые hash-cache (байтовый) пропускает —
пере-скриншот/пере-сейв того же знания с другим хэшем.
Запуск:
python skills/mnemazine/kb-embed.py <cmd> ...
Команды:
build <vault> <out.json> — эмбеддит все ноты → индекс
add <out.json> <note.md> [note.md...] — дозаписать ноты в индекс
query <idx.json> <text> [topk] [thr] — топ-похожих нот (cosine)
Все ответы — одна строка JSON (для парсинга агентом).
"""
import sys
import os
import json
import glob
import math
import warnings
warnings.filterwarnings("ignore") # чистый JSON-выхлоп для парсинга агентом
MODEL = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" # 384d, ~220MB, мультиязык RU
MAX_CHARS = 2000 # хвост ноты не нужен для темы
def _emb(texts, prefix):
from fastembed import TextEmbedding
model = TextEmbedding(MODEL)
return [v.tolist() for v in model.embed([prefix + t for t in texts])]
def _strip_fm(text):
"""Убрать YAML-frontmatter, оставить тело."""
t = text
if t.startswith("---"):
end = t.find("\n---", 3)
if end != -1:
t = t[end + 4:]
return t.strip()
def _is_content_note(p):
bad = ("/graphify-out/", "/.git/", "/.obsidian/")
if any(b in p for b in bad):
return False
return not os.path.basename(p).startswith("_")
def _read_body(p):
try:
return _strip_fm(open(p, encoding="utf-8").read())[:MAX_CHARS]
except Exception:
return ""
def _cos(a, b):
d = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return d / (na * nb) if na and nb else 0.0
def cmd_build(vault, out):
notes = [p for p in glob.glob(vault + "/**/*.md", recursive=True) if _is_content_note(p)]
bodies = [_read_body(p) for p in notes]
pairs = [(p, b) for p, b in zip(notes, bodies) if b]
vecs = _emb([b for _, b in pairs], "") if pairs else []
idx = {p: v for (p, _), v in zip(pairs, vecs)}
json.dump(idx, open(out, "w"), ensure_ascii=False)
print(json.dumps({"indexed": len(idx), "out": out}))
def cmd_add(out, notes):
idx = json.load(open(out)) if os.path.exists(out) else {}
bodies = [_read_body(p) for p in notes]
pairs = [(p, b) for p, b in zip(notes, bodies) if b]
if pairs:
vecs = _emb([b for _, b in pairs], "")
for (p, _), v in zip(pairs, vecs):
idx[p] = v
json.dump(idx, open(out, "w"), ensure_ascii=False)
print(json.dumps({"added": len(pairs), "total": len(idx)}))
def cmd_query(idxfile, text, topk=3, thr=0.0):
idx = json.load(open(idxfile)) if os.path.exists(idxfile) else {}
if not idx:
print(json.dumps({"matches": [], "top": 0.0, "note": "index empty"}))
return
qv = _emb([text[:MAX_CHARS]], "")[0]
scored = sorted(((_cos(qv, v), p) for p, v in idx.items()), reverse=True)[:topk]
matches = [{"note": p, "score": round(s, 4)} for s, p in scored if s >= thr]
print(json.dumps({"matches": matches, "top": round(scored[0][0], 4) if scored else 0.0},
ensure_ascii=False))
def main():
if len(sys.argv) < 2:
print(json.dumps({"error": "usage: build|add|query"}))
sys.exit(1)
cmd = sys.argv[1]
try:
if cmd == "build":
cmd_build(sys.argv[2], sys.argv[3])
elif cmd == "add":
cmd_add(sys.argv[2], sys.argv[3:])
elif cmd == "query":
topk = int(sys.argv[4]) if len(sys.argv) > 4 else 3
thr = float(sys.argv[5]) if len(sys.argv) > 5 else 0.0
cmd_query(sys.argv[2], sys.argv[3], topk, thr)
else:
print(json.dumps({"error": "unknown cmd: " + cmd}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
if __name__ == "__main__":
main()
+17
View File
@@ -0,0 +1,17 @@
import Foundation
import Vision
import AppKit
let args = CommandLine.arguments
guard args.count > 1, let img = NSImage(contentsOfFile: args[1]),
let cg = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
FileHandle.standardError.write("load fail\n".data(using:.utf8)!); exit(1)
}
let req = VNRecognizeTextRequest { r, _ in
guard let obs = r.results as? [VNRecognizedTextObservation] else { return }
for o in obs { if let t = o.topCandidates(1).first { print(t.string) } }
}
req.recognitionLevel = .accurate
req.recognitionLanguages = ["ru-RU","en-US"]
req.usesLanguageCorrection = true
try? VNImageRequestHandler(cgImage: cg, options: [:]).perform([req])
+1
View File
@@ -0,0 +1 @@
+7
View File
@@ -0,0 +1,7 @@
# Mnemazine KB Pipeline
```text
inbox -> census -> extraction -> understanding -> research -> verification -> atomization -> vault -> Graphify -> weekly brief
```
The pipeline is intentionally strict. A source is not done when text is extracted. It is done when a durable note exists or a clear rejection reason is recorded.