commit 5c59152c06e5710224507ad6bc7f132bfcf0643e Author: tv5171621-source Date: Mon Jun 15 02:47:14 2026 +0300 Initial open source release diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8557e2c --- /dev/null +++ b/.env.example @@ -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" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7d2f784 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c292901 --- /dev/null +++ b/CONTRIBUTING.md @@ -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. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7991a88 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..11cdb65 --- /dev/null +++ b/README.md @@ -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. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..40a9cc7 --- /dev/null +++ b/SECURITY.md @@ -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 +``` diff --git a/agents/kb-pipeline/kb-coordinator.md b/agents/kb-pipeline/kb-coordinator.md new file mode 100644 index 0000000..34331d3 --- /dev/null +++ b/agents/kb-pipeline/kb-coordinator.md @@ -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`. diff --git a/agents/kb-pipeline/kb-extract.md b/agents/kb-pipeline/kb-extract.md new file mode 100644 index 0000000..ef2bfc7 --- /dev/null +++ b/agents/kb-pipeline/kb-extract.md @@ -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. diff --git a/agents/kb-pipeline/kb-guard.md b/agents/kb-pipeline/kb-guard.md new file mode 100644 index 0000000..b149cc0 --- /dev/null +++ b/agents/kb-pipeline/kb-guard.md @@ -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. diff --git a/agents/kb-pipeline/kb-refine.md b/agents/kb-pipeline/kb-refine.md new file mode 100644 index 0000000..96599e5 --- /dev/null +++ b/agents/kb-pipeline/kb-refine.md @@ -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. diff --git a/agents/kb-pipeline/kb-verify.md b/agents/kb-pipeline/kb-verify.md new file mode 100644 index 0000000..d17ed5a --- /dev/null +++ b/agents/kb-pipeline/kb-verify.md @@ -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. diff --git a/demo/inbox/example-guide.md b/demo/inbox/example-guide.md new file mode 100644 index 0000000..f734fc6 --- /dev/null +++ b/demo/inbox/example-guide.md @@ -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. diff --git a/demo/vault/example-final-note.md b/demo/vault/example-final-note.md new file mode 100644 index 0000000..ac5936f --- /dev/null +++ b/demo/vault/example-final-note.md @@ -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. diff --git a/docs/apple-vision.md b/docs/apple-vision.md new file mode 100644 index 0000000..72b3b5d --- /dev/null +++ b/docs/apple-vision.md @@ -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. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..9ee93f2 --- /dev/null +++ b/docs/architecture.md @@ -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. diff --git a/docs/assets/screenshots/01-inbox-to-knowledge.svg b/docs/assets/screenshots/01-inbox-to-knowledge.svg new file mode 100644 index 0000000..1b146e6 --- /dev/null +++ b/docs/assets/screenshots/01-inbox-to-knowledge.svg @@ -0,0 +1,32 @@ + + + + Mnemazine: from raw input to memory + + + Inbox + screenshots, PDFs, + links, transcripts + + + + Extract + local OCR, parsers, + hash cache + + + + Verify + sources, GitHub, + official docs + + + + Vault + final + notes + + Rule + Raw OCR never becomes memory until it is understood, checked, and rewritten. + + diff --git a/docs/assets/screenshots/02-weekly-html-report.svg b/docs/assets/screenshots/02-weekly-html-report.svg new file mode 100644 index 0000000..92e2ecc --- /dev/null +++ b/docs/assets/screenshots/02-weekly-html-report.svg @@ -0,0 +1,24 @@ + + + + + + Mnemazine Weekly + Readable weekly memory, not a raw changelog + + + Local OCR before vision + Cheaper extraction. Stable cache. + Read + Work + Forget + + Graph after ingest + New notes become navigable context. + Read + + Split long guides + One source can become many notes. + Read + + diff --git a/docs/assets/screenshots/03-graphify-map.svg b/docs/assets/screenshots/03-graphify-map.svg new file mode 100644 index 0000000..e35595d --- /dev/null +++ b/docs/assets/screenshots/03-graphify-map.svg @@ -0,0 +1,16 @@ + + + Graphify memory map + + + + + OCR + Extraction + Atomization + Sources + Skills + Agents + + Graph context lets agents retrieve related knowledge without reading the whole vault. + diff --git a/docs/assets/screenshots/04-site-ingestion.svg b/docs/assets/screenshots/04-site-ingestion.svg new file mode 100644 index 0000000..351d9c1 --- /dev/null +++ b/docs/assets/screenshots/04-site-ingestion.svg @@ -0,0 +1,27 @@ + + + Website ingestion + + + Discover + robots.txt + sitemap.xml + same-origin links + + Extract + title + headings + visible text + GitHub links + + Refine + meaning + verification + atom notes + + Vault + final + knowledge + + + diff --git a/docs/graphify.md b/docs/graphify.md new file mode 100644 index 0000000..caed426 --- /dev/null +++ b/docs/graphify.md @@ -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. diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..31922bf --- /dev/null +++ b/docs/installation.md @@ -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. diff --git a/docs/obsidian.md b/docs/obsidian.md new file mode 100644 index 0000000..d3c279b --- /dev/null +++ b/docs/obsidian.md @@ -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. diff --git a/docs/site-ingestion.md b/docs/site-ingestion.md new file mode 100644 index 0000000..ff4bc88 --- /dev/null +++ b/docs/site-ingestion.md @@ -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. diff --git a/docs/token-economics.md b/docs/token-economics.md new file mode 100644 index 0000000..3cdd638 --- /dev/null +++ b/docs/token-economics.md @@ -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. diff --git a/docs/weekly-html.md b/docs/weekly-html.md new file mode 100644 index 0000000..f8969bf --- /dev/null +++ b/docs/weekly-html.md @@ -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. diff --git a/examples/knowledge-note.md b/examples/knowledge-note.md new file mode 100644 index 0000000..a0cbe2b --- /dev/null +++ b/examples/knowledge-note.md @@ -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. diff --git a/inbox/.gitkeep b/inbox/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/inbox/.gitkeep @@ -0,0 +1 @@ + diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..9ebbefb --- /dev/null +++ b/install.sh @@ -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" <=20" + } +} diff --git a/protocol/MNEMAZINE_PROTOCOL.md b/protocol/MNEMAZINE_PROTOCOL.md new file mode 100644 index 0000000..fb93275 --- /dev/null +++ b/protocol/MNEMAZINE_PROTOCOL.md @@ -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. diff --git a/reports/.gitkeep b/reports/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/reports/.gitkeep @@ -0,0 +1 @@ + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d291f83 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +markitdown +fastembed +pymupdf +pypdf +reportlab +pillow +openai-whisper +graphifyy diff --git a/scripts/check-public-release.sh b/scripts/check-public-release.sh new file mode 100755 index 0000000..43f99d7 --- /dev/null +++ b/scripts/check-public-release.sh @@ -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." diff --git a/scripts/mnemazine-ingest-site.mjs b/scripts/mnemazine-ingest-site.mjs new file mode 100755 index 0000000..de5ef08 --- /dev/null +++ b/scripts/mnemazine-ingest-site.mjs @@ -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(//gi, ' ') + .replace(//gi, ' ') + .replace(/<\/(h[1-4]|p|li|section|article|div)>/gi, '\n') + .replace(/]*>/gi, '\n### ') + .replace(/<[^>]+>/g, ' ') + .replace(/ /g, ' ') + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(/'|'/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(/]+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>/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(/]*>([\s\S]*?)<\/h1>/i)?.[1] || html.match(/]*>([\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)) diff --git a/scripts/mnemazine-run.mjs b/scripts/mnemazine-run.mjs new file mode 100755 index 0000000..3589a4d --- /dev/null +++ b/scripts/mnemazine-run.mjs @@ -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) +}) diff --git a/scripts/mnemazine-vault-quality-gate.mjs b/scripts/mnemazine-vault-quality-gate.mjs new file mode 100755 index 0000000..de13d35 --- /dev/null +++ b/scripts/mnemazine-vault-quality-gate.mjs @@ -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)) diff --git a/scripts/mnemazine-weekly-brief-html.mjs b/scripts/mnemazine-weekly-brief-html.mjs new file mode 100755 index 0000000..6be2838 --- /dev/null +++ b/scripts/mnemazine-weekly-brief-html.mjs @@ -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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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 = ` + + + + +Mnemazine Weekly + + + +

Mnemazine Weekly

Сводка знаний за последние 7 дней: что появилось, что стоит взять в работу, что можно забыть.

+
+${cards.map((c, i) => `
${esc(c.file)}

${esc(c.title)}

${esc(c.summary)}

`).join('\n') || '

За неделю новых заметок нет

Положите материалы в inbox и запустите Mnemazine.

'} +
+ +` + +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) diff --git a/skills/local-doc-ops/SKILL.md b/skills/local-doc-ops/SKILL.md new file mode 100644 index 0000000..3bb85ae --- /dev/null +++ b/skills/local-doc-ops/SKILL.md @@ -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 +``` diff --git a/skills/local-doc-ops/pdf-kit.py b/skills/local-doc-ops/pdf-kit.py new file mode 100644 index 0000000..dfb6894 --- /dev/null +++ b/skills/local-doc-ops/pdf-kit.py @@ -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:]) diff --git a/skills/mnemazine/SKILL.md b/skills/mnemazine/SKILL.md new file mode 100644 index 0000000..81cf0e6 --- /dev/null +++ b/skills/mnemazine/SKILL.md @@ -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. diff --git a/skills/mnemazine/kb-embed.py b/skills/mnemazine/kb-embed.py new file mode 100644 index 0000000..3443474 --- /dev/null +++ b/skills/mnemazine/kb-embed.py @@ -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 ... + +Команды: + build — эмбеддит все ноты → индекс + add [note.md...] — дозаписать ноты в индекс + query [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() diff --git a/skills/mnemazine/vision-ocr.swift b/skills/mnemazine/vision-ocr.swift new file mode 100644 index 0000000..723916a --- /dev/null +++ b/skills/mnemazine/vision-ocr.swift @@ -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]) diff --git a/vault/.gitkeep b/vault/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/vault/.gitkeep @@ -0,0 +1 @@ + diff --git a/workflows/kb-pipeline.md b/workflows/kb-pipeline.md new file mode 100644 index 0000000..3caf2d9 --- /dev/null +++ b/workflows/kb-pipeline.md @@ -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.